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(bannerbear): render images reliably with V5 keys, browse templates and images, and trigger on completed images (#16772)
Odai Ahmadec671707cd40
diff --git a/bun.lock b/bun.lockindex c8370890eb1..57f808b57e5 100644--- a/bun.lock+++ b/bun.lock@@ -1066,7 +1066,7 @@},"packages/pieces/community/bannerbear": {"name": "@activepieces/piece-bannerbear",- "version": "0.5.1",+ "version": "0.6.0","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -1075,6 +1075,7 @@},"devDependencies": {"tslib": "2.6.2",+ "vitest": "3.2.6",},},"packages/pieces/community/barcode-lookup": {diff --git a/docs/install/reference/breaking-changes-unreleased.mdx b/docs/install/reference/breaking-changes-unreleased.mdxindex a6177c16a5d..ba725293390 100644--- a/docs/install/reference/breaking-changes-unreleased.mdx+++ b/docs/install/reference/breaking-changes-unreleased.mdx@@ -8,6 +8,14 @@ Entries here move to [Breaking Changes](/install/reference/breaking-changes) aut## What has changed?+#### Bannerbear 0.6.0: Create Image is builder-only, returns the normalized image, and Custom API Call is asynchronous++From Bannerbear 0.6.0, **Create Image** is no longer offered as a tool to AI agents; it still works as a normal flow step. Agents use the new **Create Image from JSON** action instead. Create Image now returns the same normalized image as the other Bannerbear actions: the template ID is in `template_uid` instead of `template`, and `modifications`, `width` and `height` are no longer returned. **Custom API Call** no longer goes through `sync.api.bannerbear.com`; it now uses `api.bannerbear.com`, so a `POST /images` call returns the image while it is still `pending` instead of waiting for it to finish rendering.++#### What you need to do++Steps keep running on the version they were built with until you upgrade them. After upgrading, change any later step that reads `template` from Create Image to read `template_uid`, and stop reading `modifications`, `width` or `height`. Point Run Agent steps that used Create Image at **Create Image from JSON**. If a Custom API Call creates images, poll **Get Image** (or use the **New Image Completed** trigger) until the image is completed before using its URL.+#### Republishing no longer restarts polling triggersRepublishing a running flow without changing its polling trigger (same piece, version, trigger and inputs) now leaves the trigger running: `onDisable` and `onEnable` don't run and its stored state is kept, so events created around the republish are no longer lost. When a piece is upgraded to a newer version with the same inputs, only the new version's `onEnable` runs, with `context.isRepublish` set to `true`. The old version's `onDisable` doesn't run.diff --git a/packages/pieces/community/bannerbear/package.json b/packages/pieces/community/bannerbear/package.jsonindex 86c2b15d7a0..01344a6b819 100644--- a/packages/pieces/community/bannerbear/package.json+++ b/packages/pieces/community/bannerbear/package.json@@ -1,12 +1,13 @@{"name": "@activepieces/piece-bannerbear",- "version": "0.5.1",+ "version": "0.6.0","main": "./dist/src/index.js","types": "./dist/src/index.d.ts","scripts": {"build": "tsc -p tsconfig.lib.json && cp package.json dist/","bundle": "node ../../../../dist/packages/cli/src/index.js pieces bundle",- "lint": "eslint 'src/**/*.ts'"+ "lint": "eslint 'src/**/*.ts'",+ "test": "vitest run"},"dependencies": {"@activepieces/pieces-common": "workspace:*",@@ -15,6 +16,7 @@"@activepieces/core-utils": "workspace:*"},"devDependencies": {- "tslib": "2.6.2"+ "tslib": "2.6.2",+ "vitest": "3.2.6"}}diff --git a/packages/pieces/community/bannerbear/src/i18n/translation.json b/packages/pieces/community/bannerbear/src/i18n/translation.jsonindex 4dd60809565..6ed43c904ce 100644--- a/packages/pieces/community/bannerbear/src/i18n/translation.json+++ b/packages/pieces/community/bannerbear/src/i18n/translation.json@@ -1,9 +1,29 @@{"Automate image generation": "Automate image generation",- "Bannerbear API Key": "Bannerbear API Key",+ "Your Bannerbear API key. Both key types work:\n- **V5 key** (starts with `bb_ak_v5_`): in Bannerbear open **Settings → API Keys** and create a key.\n- **V2 project key** (older accounts): open your project, then **Settings → API Key**.\n\nMaster keys are not supported.": "Your Bannerbear API key. Both key types work:\n- **V5 key** (starts with `bb_ak_v5_`): in Bannerbear open **Settings → API Keys** and create a key.\n- **V2 project key** (older accounts): open your project, then **Settings → API Key**.\n\nMaster keys are not supported.","Create Image": "Create Image",+ "Create Image from JSON": "Create Image from JSON",+ "Get Image": "Get Image",+ "List Images": "List Images",+ "List Templates": "List Templates",+ "Get Template": "Get Template",+ "Update Template": "Update Template",+ "Create Screenshot": "Create Screenshot",+ "Create Collection": "Create Collection",+ "Create Animated GIF": "Create Animated GIF",+ "Get Account": "Get Account","Custom API Call": "Custom API Call","Create image from Bannerbear template": "Create image from Bannerbear template",+ "Render an image from a template ID and layer changes as JSON.": "Render an image from a template ID and layer changes as JSON.",+ "Get an image and its status by ID.": "Get an image and its status by ID.",+ "List images, one page at a time.": "List images, one page at a time.",+ "List image templates, optionally filtered by name or tag.": "List image templates, optionally filtered by name or tag.",+ "Get a template and its layer names.": "Get a template and its layer names.",+ "Rename a template or change its tags.": "Rename a template or change its tags.",+ "Take a screenshot of a web page (V2 API keys only).": "Take a screenshot of a web page (V2 API keys only).",+ "Render every template in a template set (V2 API keys only).": "Render every template in a template set (V2 API keys only).",+ "Render an animated GIF from frames (V2 API keys only).": "Render an animated GIF from frames (V2 API keys only).",+ "Get plan and credit usage for this API key.": "Get plan and credit usage for this API key.","Make a custom API call to a specific endpoint": "Make a custom API call to a specific endpoint","Template": "Template","Template version": "Template version",@@ -11,6 +31,28 @@"Transparent background": "Transparent background","Render a PDF": "Render a PDF","Metadata": "Metadata",+ "Wait for Completion": "Wait for Completion",+ "Template ID": "Template ID",+ "Layer Modifications": "Layer Modifications",+ "Transparent Background": "Transparent Background",+ "Image ID": "Image ID",+ "Page": "Page",+ "Per Page": "Per Page",+ "Name Contains": "Name Contains",+ "Tag": "Tag",+ "Name": "Name",+ "Tags": "Tags",+ "Metadata (V2 keys only)": "Metadata (V2 keys only)",+ "Description (V5 keys only)": "Description (V5 keys only)",+ "Page URL": "Page URL",+ "Width": "Width",+ "Height": "Height",+ "Mobile": "Mobile",+ "Language": "Language",+ "Template Set": "Template Set",+ "Frames": "Frames",+ "Frames per Second": "Frames per Second",+ "Loop": "Loop","Method": "Method","Headers": "Headers","Query Parameters": "Query Parameters",@@ -20,12 +62,35 @@"Return Error as Output": "Return Error as Output","Timeout": "Timeout","Follow redirects": "Follow redirects",- "The template to use in image creation.": "The template to use in image creation.",- "Create image based on a specific version of the template.": "Create image based on a specific version of the template.",- "A list of modifications you want to make on the template.": "A list of modifications you want to make on the template.",- "Render a PNG with a transparent background. Default is false.": "Render a PNG with a transparent background. Default is false.",- "Render a PDF instead of a PNG. Default is false.": "Render a PDF instead of a PNG. Default is false.",- "Any metadata that you need to store e.g. ID of a record in your DB.": "Any metadata that you need to store e.g. ID of a record in your DB.",+ "The Bannerbear template to use.": "The Bannerbear template to use.",+ "Render a specific template version. Leave empty for latest.": "Render a specific template version. Leave empty for latest.",+ "Values for each template layer. Empty fields are skipped.": "Values for each template layer. Empty fields are skipped.",+ "Render a PNG with a transparent background.": "Render a PNG with a transparent background.",+ "Also render a PDF (uses extra credits).": "Also render a PDF (uses extra credits).",+ "Any text to store with the image, e.g. a record ID.": "Any text to store with the image, e.g. a record ID.",+ "Wait up to 2 minutes for the render; else return pending.": "Wait up to 2 minutes for the render; else return pending.",+ "The template UID, from List Templates.": "The template UID, from List Templates.",+ "JSON array, one object per layer, each with \"name\".": "JSON array, one object per layer, each with \"name\".",+ "The image UID returned by Create Image.": "The image UID returned by Create Image.",+ "Page number, starting at 1.": "Page number, starting at 1.",+ "Images per page, 1 to 100. V5 keys always get 25.": "Images per page, 1 to 100. V5 keys always get 25.",+ "Only templates whose name contains this text.": "Only templates whose name contains this text.",+ "Only templates with this tag.": "Only templates with this tag.",+ "New template name.": "New template name.",+ "Replaces all tags. Leave empty to keep current tags.": "Replaces all tags. Leave empty to keep current tags.",+ "Text stored with the template.": "Text stored with the template.",+ "Template description.": "Template description.",+ "The web page to capture.": "The web page to capture.",+ "Browser width in pixels. Default 1200.": "Browser width in pixels. Default 1200.",+ "Browser height in pixels. Empty = full page.": "Browser height in pixels. Empty = full page.",+ "Use a mobile user agent.": "Use a mobile user agent.",+ "Browser language code.": "Browser language code.",+ "The template set to render as a collection.": "The template set to render as a collection.",+ "Any text to store with the collection.": "Any text to store with the collection.",+ "JSON array of frames; each frame is an array of layers.": "JSON array of frames; each frame is an array of layers.",+ "Playback speed, e.g. 1.": "Playback speed, e.g. 1.",+ "Loop the GIF forever.": "Loop the GIF forever.",+ "Any text to store with the GIF.": "Any text to store with the GIF.","Authorization headers are injected automatically from your connection.": "Authorization headers are injected automatically from your connection.","Appended to the URL as ?key=value.": "Appended to the URL as ?key=value.","Enable for files like PDFs, images, etc.": "Enable for files like PDFs, images, etc.",@@ -39,5 +104,7 @@"DELETE": "DELETE","HEAD": "HEAD","Request": "Request",- "Data to send": "Data to send"+ "Data to send": "Data to send",+ "New Image Completed": "New Image Completed",+ "Triggers when an image finishes rendering.": "Triggers when an image finishes rendering."}\ No newline at end of filediff --git a/packages/pieces/community/bannerbear/src/index.ts b/packages/pieces/community/bannerbear/src/index.tsindex 0de5da8ed8c..aa0e6839856 100644--- a/packages/pieces/community/bannerbear/src/index.ts+++ b/packages/pieces/community/bannerbear/src/index.ts@@ -1,27 +1,49 @@import { createCustomApiCallAction } from '@activepieces/pieces-common';-import { PieceAuth, createPiece } from '@activepieces/pieces-framework';-import { PieceCategory } from '@activepieces/pieces-framework';+import { createPiece, PieceCategory } from '@activepieces/pieces-framework';import { bannerbearCreateImageAction } from './lib/actions/create-image';+import { createImageFromJsonAction } from './lib/actions/create-image-from-json';+import { getImageAction } from './lib/actions/get-image';+import { listImagesAction } from './lib/actions/list-images';+import { listTemplatesAction } from './lib/actions/list-templates';+import { getTemplateAction } from './lib/actions/get-template';+import { updateTemplateAction } from './lib/actions/update-template';+import { createScreenshotAction } from './lib/actions/create-screenshot';+import { createCollectionAction } from './lib/actions/create-collection';+import { createAnimatedGifAction } from './lib/actions/create-animated-gif';+import { getAccountAction } from './lib/actions/get-account';+import { newImageCompletedTrigger } from './lib/triggers/new-image-completed';import { bannerbearAuth } from './lib/auth';+import { bannerbearClient } from './lib/common/client';export const bannerbear = createPiece({displayName: 'Bannerbear',description: 'Automate image generation',- minimumSupportedRelease: '0.30.0',+ minimumSupportedRelease: '0.88.2',logoUrl: 'https://cdn.activepieces.com/pieces/bannerbear.png',categories: [PieceCategory.MARKETING],- authors: ["kishanprmr","MoShizzle","khaledmashaly","abuaboud"],+ authors: ["kishanprmr","MoShizzle","khaledmashaly","abuaboud","OdaiAhmed99"],auth: bannerbearAuth,actions: [bannerbearCreateImageAction,+ createImageFromJsonAction,+ getImageAction,+ listImagesAction,+ listTemplatesAction,+ getTemplateAction,+ updateTemplateAction,+ createScreenshotAction,+ createCollectionAction,+ createAnimatedGifAction,+ getAccountAction,createCustomApiCallAction({- baseUrl: () => 'https://sync.api.bannerbear.com/v2',+ baseUrl: (auth) =>+ auth ? bannerbearClient.getBaseUrl(auth.secret_text) : 'https://api.bannerbear.com/v2',auth: bannerbearAuth,authMapping: async (auth) => ({- Authorization: `Bearer ${auth.secret_text}`,+ Authorization: `Bearer ${auth.secret_text.trim()}`,}),}),],- triggers: [],+ triggers: [newImageCompletedTrigger],});diff --git a/packages/pieces/community/bannerbear/src/lib/actions/create-animated-gif.ts b/packages/pieces/community/bannerbear/src/lib/actions/create-animated-gif.tsnew file mode 100644index 00000000000..164ccd51ebf--- /dev/null+++ b/packages/pieces/community/bannerbear/src/lib/actions/create-animated-gif.ts@@ -0,0 +1,122 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { bannerbearAuth } from '../auth';+import { bannerbearClient } from '../common/client';+import { bannerbearProps } from '../common/props';+import { bannerbearOutputSchemas } from '../output-schemas';++export const createAnimatedGifAction = createAction({+ auth: bannerbearAuth,+ name: 'create_animated_gif',+ classification: 'WRITE',+ displayName: 'Create Animated GIF',+ description: 'Render an animated GIF from frames (V2 API keys only).',+ audience: 'both',+ aiMetadata: {+ description:+ 'Render an animated GIF from a Bannerbear template where each frame is its own list of layer modifications. Only works with V2 API keys. Each call starts a new render and uses credits.',+ idempotent: false,+ },+ outputSchema: bannerbearOutputSchemas['animatedGif'],+ props: {+ template_uid: Property.ShortText({+ displayName: 'Template ID',+ description: 'The template UID, from List Templates.',+ required: true,+ }),+ frames: Property.Json({+ displayName: 'Frames',+ description: 'JSON array of frames; each frame is an array of layers.',+ required: true,+ defaultValue: [[{ name: 'title', text: 'Frame 1' }], [{ name: 'title', text: 'Frame 2' }]],+ }),+ fps: Property.Number({+ displayName: 'Frames per Second',+ description: 'Playback speed, e.g. 1.',+ required: false,+ }),+ loop: Property.Checkbox({+ displayName: 'Loop',+ description: 'Loop the GIF forever.',+ required: false,+ defaultValue: true,+ }),+ metadata: Property.ShortText({+ displayName: 'Metadata',+ description: 'Any text to store with the GIF.',+ required: false,+ }),+ wait_for_completion: bannerbearProps.waitForCompletion,+ },+ async run({ auth, propsValue }) {+ const apiKey = auth.secret_text;+ bannerbearClient.requireVersion({ apiKey, version: 'v2', feature: 'Create Animated GIF' });+ const template = propsValue.template_uid.trim();+ if (template === '') throw new Error('Template ID is required.');+ const rawFrames = parseFrames(propsValue.frames);+ if (!Array.isArray(rawFrames) || rawFrames.length === 0) {+ throw new Error('Frames must be a non-empty JSON array of frames.');+ }+ const frames = rawFrames.map((frame) => bannerbearClient.parseModificationsJson(frame));+ const body: Record<string, unknown> = { template, frames };+ if (propsValue.fps !== undefined && propsValue.fps !== null) {+ const fps = Number(propsValue.fps);+ if (!Number.isFinite(fps) || fps <= 0) {+ throw new Error('Frames per Second must be a positive number.');+ }+ body['fps'] = fps;+ }+ if (propsValue.loop !== undefined) body['loop'] = propsValue.loop;+ if (propsValue.metadata) body['metadata'] = propsValue.metadata;+ const created = await bannerbearClient.request<RawGif>({+ apiKey,+ method: HttpMethod.POST,+ path: '/animated_gifs',+ body,+ });+ const { record, timedOut } = await bannerbearClient.waitFor({+ initial: created,+ wait: propsValue.wait_for_completion !== false,+ doneStatuses: bannerbearClient.IMAGE_DONE_STATUSES,+ failedStatuses: bannerbearClient.IMAGE_FAILED_STATUSES,+ fetchLatest: () =>+ bannerbearClient.request<RawGif>({+ apiKey,+ method: HttpMethod.GET,+ path: `/animated_gifs/${encodeURIComponent(created.uid)}`,+ }),+ });+ bannerbearClient.throwIfFailed({ status: record.status, uid: record.uid });+ return {+ uid: record.uid,+ status: record.status ?? null,+ template_uid: bannerbearClient.readTemplateUid(record.template) ?? template,+ image_url: record.image_url ?? null,+ fps: record.fps ?? null,+ metadata: record.metadata ?? null,+ self: record.self ?? null,+ created_at: record.created_at ?? null,+ timed_out: timedOut,+ };+ },+});++function parseFrames(value: unknown): unknown {+ if (typeof value !== 'string') return value;+ try {+ return JSON.parse(value);+ } catch {+ throw new Error('Frames is not valid JSON.');+ }+}++type RawGif = {+ uid: string;+ status?: string | null;+ template?: unknown;+ image_url?: string | null;+ fps?: number | null;+ metadata?: string | null;+ self?: string | null;+ created_at?: string | null;+};diff --git a/packages/pieces/community/bannerbear/src/lib/actions/create-collection.ts b/packages/pieces/community/bannerbear/src/lib/actions/create-collection.tsnew file mode 100644index 00000000000..8078a9f5e80--- /dev/null+++ b/packages/pieces/community/bannerbear/src/lib/actions/create-collection.ts@@ -0,0 +1,94 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { bannerbearAuth } from '../auth';+import { bannerbearClient, RawImage } from '../common/client';+import { bannerbearProps } from '../common/props';+import { bannerbearOutputSchemas } from '../output-schemas';++export const createCollectionAction = createAction({+ auth: bannerbearAuth,+ name: 'create_collection',+ classification: 'WRITE',+ displayName: 'Create Collection',+ description: 'Render every template in a template set (V2 API keys only).',+ audience: 'both',+ aiMetadata: {+ description:+ 'Render one image per template in a Bannerbear template set, applying the same layer modifications to all. Only works with V2 API keys. Each call starts new renders and uses one credit per template.',+ idempotent: false,+ },+ outputSchema: bannerbearOutputSchemas['collection'],+ props: {+ template_set: bannerbearProps.templateSet,+ modifications: Property.Json({+ displayName: 'Layer Modifications',+ description: 'JSON array, one object per layer, each with "name".',+ required: true,+ defaultValue: [{ name: 'title', text: 'Hello world' }],+ }),+ metadata: Property.ShortText({+ displayName: 'Metadata',+ description: 'Any text to store with the collection.',+ required: false,+ }),+ wait_for_completion: bannerbearProps.waitForCompletion,+ },+ async run({ auth, propsValue }) {+ const apiKey = auth.secret_text;+ bannerbearClient.requireVersion({ apiKey, version: 'v2', feature: 'Create Collection' });+ const templateSet = String(propsValue.template_set ?? '').trim();+ if (templateSet === '') throw new Error('Template Set is required.');+ const body: Record<string, unknown> = {+ template_set: templateSet,+ modifications: bannerbearClient.parseModificationsJson(propsValue.modifications),+ };+ if (propsValue.metadata) body['metadata'] = propsValue.metadata;+ const created = await bannerbearClient.request<RawCollection>({+ apiKey,+ method: HttpMethod.POST,+ path: '/collections',+ body,+ });+ const { record, timedOut } = await bannerbearClient.waitFor({+ initial: created,+ wait: propsValue.wait_for_completion !== false,+ doneStatuses: bannerbearClient.IMAGE_DONE_STATUSES,+ failedStatuses: bannerbearClient.IMAGE_FAILED_STATUSES,+ fetchLatest: () =>+ bannerbearClient.request<RawCollection>({+ apiKey,+ method: HttpMethod.GET,+ path: `/collections/${encodeURIComponent(created.uid)}`,+ }),+ });+ bannerbearClient.throwIfFailed({ status: record.status, uid: record.uid });+ return {+ uid: record.uid,+ status: record.status ?? null,+ template_set: record.template_set ?? templateSet,+ images: (record.images ?? []).map((image) => {+ const n = bannerbearClient.normalizeImage(image);+ return {+ uid: n.uid,+ status: n.status,+ template_uid: n.template_uid,+ image_url: n.image_url,+ };+ }),+ metadata: record.metadata ?? null,+ self: record.self ?? null,+ created_at: record.created_at ?? null,+ timed_out: timedOut,+ };+ },+});++type RawCollection = {+ uid: string;+ status?: string | null;+ template_set?: string | null;+ images?: RawImage[];+ metadata?: string | null;+ self?: string | null;+ created_at?: string | null;+};diff --git a/packages/pieces/community/bannerbear/src/lib/actions/create-image-from-json.ts b/packages/pieces/community/bannerbear/src/lib/actions/create-image-from-json.tsnew file mode 100644index 00000000000..30b9a145ce7--- /dev/null+++ b/packages/pieces/community/bannerbear/src/lib/actions/create-image-from-json.ts@@ -0,0 +1,72 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { bannerbearAuth } from '../auth';+import { bannerbearClient } from '../common/client';+import { bannerbearProps } from '../common/props';+import { bannerbearOutputSchemas } from '../output-schemas';++export const createImageFromJsonAction = createAction({+ auth: bannerbearAuth,+ name: 'create_image_from_json',+ classification: 'WRITE',+ displayName: 'Create Image from JSON',+ description: 'Render an image from a template ID and layer changes as JSON.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Render an image from a Bannerbear template ID and a JSON array of layer modifications. Call Get Template first to learn the layer names. Each call starts a new render and uses a credit, so retries create duplicates.',+ idempotent: false,+ },+ outputSchema: bannerbearOutputSchemas['createImage'],+ props: {+ template_uid: Property.ShortText({+ displayName: 'Template ID',+ description: 'The template UID, from List Templates.',+ required: true,+ }),+ modifications: Property.Json({+ displayName: 'Layer Modifications',+ description: 'JSON array, one object per layer, each with "name".',+ required: true,+ defaultValue: [{ name: 'title', text: 'Hello world' }],+ }),+ transparent: Property.Checkbox({+ displayName: 'Transparent Background',+ description: 'Render a PNG with a transparent background.',+ required: false,+ }),+ render_pdf: Property.Checkbox({+ displayName: 'Render a PDF',+ description: 'Also render a PDF (uses extra credits).',+ required: false,+ }),+ metadata: Property.ShortText({+ displayName: 'Metadata',+ description: 'Any text to store with the image, e.g. a record ID.',+ required: false,+ }),+ wait_for_completion: bannerbearProps.waitForCompletion,+ },+ async run({ auth, propsValue }) {+ const apiKey = auth.secret_text;+ const templateUid = propsValue.template_uid.trim();+ if (templateUid === '') {+ throw new Error('Template ID is required.');+ }+ const modifications = bannerbearClient.parseModificationsJson(+ propsValue.modifications+ );+ const body = bannerbearClient.buildImageRequest({+ apiKey,+ templateUid,+ modifications,+ transparent: propsValue.transparent,+ renderPdf: propsValue.render_pdf,+ metadata: propsValue.metadata,+ });+ return bannerbearClient.createImageAndWait({+ apiKey,+ body,+ wait: propsValue.wait_for_completion !== false,+ });+ },+});diff --git a/packages/pieces/community/bannerbear/src/lib/actions/create-image.ts b/packages/pieces/community/bannerbear/src/lib/actions/create-image.tsindex 804f80e75d2..87a46418f25 100644--- a/packages/pieces/community/bannerbear/src/lib/actions/create-image.ts+++ b/packages/pieces/community/bannerbear/src/lib/actions/create-image.ts@@ -1,351 +1,264 @@import {- Property,- DynamicPropsValue,createAction,+ InputPropertyMap,+ Property,} from '@activepieces/pieces-framework';-import {- AuthenticationType,- httpClient,- HttpMethod,- HttpRequest,-} from '@activepieces/pieces-common';+import { HttpMethod } from '@activepieces/pieces-common';import { bannerbearAuth } from '../auth';+import {+ bannerbearClient,+ RawTemplate,+ V2Modification,+} from '../common/client';+import { bannerbearProps } from '../common/props';+import { bannerbearOutputSchemas } from '../output-schemas';export const bannerbearCreateImageAction = createAction({auth: bannerbearAuth,- name: 'bannerbear_create_image', // Must be a unique across the piece, this shouldn't be changed.+ name: 'bannerbear_create_image',classification: 'WRITE',displayName: 'Create Image',description: 'Create image from Bannerbear template',- audience: 'both',+ audience: 'human',aiMetadata: {description:- 'Renders a new image (or PDF) from a Bannerbear template by applying layer modifications (text, image URLs, ratings, charts, bar codes, colors). Choose this to programmatically generate branded graphics; requires a valid template UID and modifications matching that template\'s available layers. Not idempotent — each call submits a new render and produces a new image.',+ 'Renders a new image (or PDF) from a Bannerbear template picked from a dropdown, with one input group per template layer. Agents should use Create Image from JSON instead. Each call submits a new render and uses a credit.',idempotent: false,},+ outputSchema: bannerbearOutputSchemas['createImage'],props: {- template: Property.Dropdown({- auth: bannerbearAuth,- displayName: 'Template',- description: 'The template to use in image creation.',- required: true,- refreshers: [],- options: async ({ auth }) => {- if (!auth) {- return {- disabled: true,- options: [],- placeholder: 'Please enter your API key first.',- };- }-- const response = await httpClient.sendRequest<BannerbearTemplate[]>({- method: HttpMethod.GET,- url: `https://api.bannerbear.com/v2/templates`,- authentication: {- type: AuthenticationType.BEARER_TOKEN,- token: auth.secret_text,- },- });-- if (response.status === 200) {- return {- disabled: false,- options: response.body.map((template) => {- return {- label: template.name,- value: template,- };- }),- };- }-- return {- disabled: true,- options: [],- placeholder: 'Error processing templates',- };- },- }),+ template: bannerbearProps.template({ required: true }),template_version: Property.Number({displayName: 'Template version',- description: 'Create image based on a specific version of the template.',+ description: 'Render a specific template version. Leave empty for latest.',required: false,}),modifications: Property.DynamicProperties({auth: bannerbearAuth,displayName: 'Template modifications',- description: 'A list of modifications you want to make on the template.',+ description: 'Values for each template layer. Empty fields are skipped.',required: true,refreshers: ['template'],props: async ({ auth, template }) => {- if (!auth) return {};- if (!template) return {};-- let fields: DynamicPropsValue = {};-- (template as BannerbearTemplate).available_modifications.map(- (modification) => {- if ('text' in modification) {- fields = {- ...BannerbearModificationsMapping.main,- ...BannerbearModificationsMapping.text,- ...BannerbearModificationsMapping.common,- };- } else if ('rating' in modification) {- fields = {- ...BannerbearModificationsMapping.main,- ...BannerbearModificationsMapping.star_rating,- ...BannerbearModificationsMapping.common,- };- } else if ('image_url' in modification) {- fields = {- ...BannerbearModificationsMapping.main,- ...BannerbearModificationsMapping.image,- ...BannerbearModificationsMapping.common,- };- } else if ('chart_data' in modification) {- fields = {- ...BannerbearModificationsMapping.main,- ...BannerbearModificationsMapping.barline_chart,- ...BannerbearModificationsMapping.common,- };- } else if ('bar_code_data' in modification) {- fields = {- ...BannerbearModificationsMapping.main,- ...BannerbearModificationsMapping.bar_code,- ...BannerbearModificationsMapping.common,- };- }+ const templateUid = bannerbearClient.readTemplateUid(template);+ if (!auth || !templateUid) return {};+ const apiKey = auth.secret_text;+ const raw = await bannerbearClient.request<RawTemplate>({+ apiKey,+ method: HttpMethod.GET,+ path: bannerbearClient.templatePath({ apiKey, uid: templateUid }),+ });+ const normalized = bannerbearClient.normalizeTemplate(raw);+ const fields: InputPropertyMap = {};+ for (const layer of normalized.layers) {+ if (!layer.name) continue;+ for (const field of fieldsForLayer(layer.type)) {+ fields[`${layer.name}${SEPARATOR}${field.key}`] = buildFieldProp({+ layerName: layer.name,+ field,+ });}- );-+ }return fields;},}),transparent: Property.Checkbox({displayName: 'Transparent background',- description:- 'Render a PNG with a transparent background. Default is false.',+ description: 'Render a PNG with a transparent background.',required: false,}),render_pdf: Property.Checkbox({displayName: 'Render a PDF',- description: 'Render a PDF instead of a PNG. Default is false.',+ description: 'Also render a PDF (uses extra credits).',required: false,}),metadata: Property.LongText({displayName: 'Metadata',- description:- 'Any metadata that you need to store e.g. ID of a record in your DB.',+ description: 'Any text to store with the image, e.g. a record ID.',required: false,}),+ wait_for_completion: bannerbearProps.waitForCompletion,},async run({ auth, propsValue }) {- const body = {- modifications:- Object.keys(propsValue.modifications).length === 0- ? []- : [propsValue.modifications],- template_version: propsValue.template_version,+ const apiKey = auth.secret_text;+ const templateUid = bannerbearClient.readTemplateUid(propsValue.template);+ if (!templateUid) {+ throw new Error('Please select a template.');+ }+ const templateVersion = toOptionalInteger(propsValue.template_version);+ const body = bannerbearClient.buildImageRequest({+ apiKey,+ templateUid,+ modifications: toModifications(propsValue.modifications ?? {}),transparent: propsValue.transparent,- render_pdf: propsValue.render_pdf,- template: propsValue.template.uid,+ renderPdf: propsValue.render_pdf,metadata: propsValue.metadata,- };-- const request: HttpRequest = {- method: HttpMethod.POST,- url: `https://sync.api.bannerbear.com/v2/images`,+ templateVersion,+ });+ return bannerbearClient.createImageAndWait({+ apiKey,body,- authentication: {- type: AuthenticationType.BEARER_TOKEN,- token: auth.secret_text,- },- };+ wait: propsValue.wait_for_completion !== false,+ });+ },+});- const result = await httpClient.sendRequest<BannerbearTemplate>(request);+function toModifications(values: Record<string, unknown>): V2Modification[] {+ const legacyName = values['name'];+ if (typeof legacyName === 'string' && legacyName.trim() !== '') {+ return [cleanLegacy(values)];+ }+ const byLayer = new Map<string, V2Modification>();+ for (const [key, value] of Object.entries(values)) {+ const index = key.lastIndexOf(SEPARATOR);+ if (index < 0 || isEmptyValue(value)) {+ continue;+ }+ const layer = key.slice(0, index);+ const field = key.slice(index + SEPARATOR.length);+ const current = byLayer.get(layer) ?? { name: layer };+ byLayer.set(layer, { ...current, [field]: coerceField({ field, value }) });+ }+ return Array.from(byLayer.values());+}- if (result.status === 200 || result.status === 202) {- return result.body;- } else {- return result;+function cleanLegacy(values: Record<string, unknown>): V2Modification {+ const result: V2Modification = {};+ for (const [key, value] of Object.entries(values)) {+ if (isEmptyValue(value)) continue;+ result[key] = coerceField({ field: key, value });+ }+ return result;+}++function coerceField({+ field,+ value,+}: {+ field: string;+ value: unknown;+}): unknown {+ if (NUMBER_FIELDS.includes(field)) {+ const n = Number(value);+ if (!Number.isFinite(n)) {+ throw new Error(`"${field}" must be a number, got "${String(value)}".`);}- },-});+ return n;+ }+ if (field === 'gradient' && typeof value === 'string') {+ const trimmed = value.trim();+ if (trimmed.startsWith('[')) {+ try {+ const parsed: unknown = JSON.parse(trimmed);+ if (Array.isArray(parsed)) return parsed;+ } catch {+ throw new Error('Gradient must be a list like ["#000","#FFF"].');+ }+ }+ return trimmed.split(',').map((c) => c.trim()).filter((c) => c !== '');+ }+ return value;+}-interface BannerbearTemplate {- created_at: string;- name: string;- self: string;- uid: string;- preview_url: number;- width: number;- height: number;- available_modifications: {- name: string;- image_url?: string;- text?: string;- chart_data: string;- bar_code_data: number;- rating: number;- }[];- tags: string[];+function toOptionalInteger(value: unknown): number | undefined {+ if (value === undefined || value === null || value === '') return undefined;+ const n = Number(value);+ if (!Number.isInteger(n) || n < 1) {+ throw new Error('Template version must be a whole number of 1 or more.');+ }+ return n;}-const BannerbearModificationsMapping = {- main: {- name: Property.ShortText({- displayName: 'Name',- required: true,- description: 'The name of the layer you want to change.',- }),- color: Property.ShortText({- displayName: 'Color',- required: false,- description: 'Color in hex format e.g. "#FF0000".',- }),- },- common: {- gradient: Property.ShortText({- displayName: 'Gradient',- required: false,- description: 'Fill with gradient e.g. ["#000", "#FFF"]',- }),- border_width: Property.Number({- displayName: 'Border width',- required: false,- description: 'Width of the object border.',- }),- border_color: Property.ShortText({- displayName: 'Border color',- required: false,- description: 'Border color in hex format e.g. "#FF0000".',- }),- shift_x: Property.Number({- displayName: 'Shift x',- required: false,- description: 'Shift layer along the x axis.',- }),- shift_y: Property.Number({- displayName: 'Shift y',- required: false,- description: 'Shift layer along the y axis.',- }),- target: Property.ShortText({- displayName: 'Target',- required: false,- description:- 'Add a clickable link to a URL on this object when rendering a PDF.',- }),- hide: Property.Checkbox({- displayName: 'Hide',- required: false,- description: 'Set to true to hide a layer.',- }),- },- text: {- text: Property.ShortText({- displayName: 'Text',- required: false,- description: 'Replacement text you want to use.',- }),- background: Property.ShortText({- displayName: 'Background',- required: false,- description: 'Background color in hex format e.g. "#FF0000".',- }),- font_family: Property.ShortText({- displayName: 'Font family',- required: false,- description: 'Change the font.',- }),- text_align_h: Property.ShortText({- displayName: 'Text align H',- required: false,- description: 'Horizontal alignment (left, center, right)',- }),- text_align_v: Property.ShortText({- displayName: 'Text align V',- required: false,- description: 'Vertical alignment (top, center, bottom)',- }),- font_family_2: Property.ShortText({- displayName: 'Font family 2',- required: false,- description: 'Change the secondary font.',- }),- color_2: Property.ShortText({- displayName: 'Color 2',- required: false,- description: 'Change the secondary font color.',- }),- },- image: {- image_url: Property.ShortText({- displayName: 'Image url',- required: false,- description: 'Change the image.',- }),- effect: Property.ShortText({- displayName: 'Effect',- required: false,- description: 'Change the effect.',- }),- anchor_x: Property.ShortText({- displayName: 'Anchor x',- required: false,- description: 'Change the anchor point (left, center, right)',- }),- anchor_y: Property.ShortText({- displayName: 'Anchor y',- required: false,- description: 'Change the anchor point (top, center, bottom).',- }),- fill_type: Property.ShortText({- displayName: 'Fill type',- required: false,- description: 'Change the fill type (fill, fit).',- }),- disable_face_detect: Property.Checkbox({- displayName: 'Disable face detect',- required: false,- description:- 'Set to true to disable face detect for this request (if the image container is using face detect).',- }),- disable_smart_crop: Property.Checkbox({- displayName: 'Disable smart crop',- required: false,- description:- 'Set to true to disable smart crop for this request (if the image container is using smart crop)',- }),- },- barline_chart: {- chart_data: Property.ShortText({- displayName: 'Chart data',- required: false,- description: 'Comma-delimited list of numbers to use as data.',- }),- },- star_rating: {- rating: Property.Number({- displayName: 'Rating',- required: false,- description: 'Number from 0 to 100 to use as the rating.',- }),- },- qr_code: {- target: Property.ShortText({- displayName: 'Target',- required: false,- description: 'URL or text to use as the code target.',- }),- },- bar_code: {- bar_code_data: Property.ShortText({- displayName: 'Barcode data',- required: false,- description: 'Text to encode as a bar code.',- }),- },+function isEmptyValue(value: unknown): boolean {+ return value === undefined || value === null || value === '';+}++function fieldsForLayer(type: string): LayerField[] {+ const result: LayerField[] = [];+ const keys = new Set<string>();+ for (const field of [...(LAYER_FIELDS[type] ?? []), ...COMMON_FIELDS]) {+ if (keys.has(field.key)) continue;+ keys.add(field.key);+ result.push(field);+ }+ return result;+}++function buildFieldProp({+ layerName,+ field,+}: {+ layerName: string;+ field: LayerField;+}) {+ const options = {+ displayName: `${layerName}: ${field.label}`,+ description: field.description,+ required: false,+ };+ if (field.kind === 'checkbox') return Property.Checkbox(options);+ if (field.kind === 'number') return Property.Number(options);+ return Property.ShortText(options);+}++const SEPARATOR = '::';++const NUMBER_FIELDS = ['rating', 'border_width', 'shift_x', 'shift_y'];++const COMMON_FIELDS: LayerField[] = [+ { key: 'color', label: 'Color', description: 'Hex color, e.g. #FF0000.' },+ { key: 'gradient', label: 'Gradient', description: 'Fill with a gradient, e.g. ["#000","#FFF"] or #000,#FFF.' },+ { key: 'border_width', label: 'Border Width', description: 'Width of the layer border.', kind: 'number' },+ { key: 'border_color', label: 'Border Color', description: 'Hex color, e.g. #FF0000.' },+ { key: 'shift_x', label: 'Shift X', description: 'Move the layer along the x axis (pixels).', kind: 'number' },+ { key: 'shift_y', label: 'Shift Y', description: 'Move the layer along the y axis (pixels).', kind: 'number' },+ { key: 'target', label: 'Link Target', description: 'Clickable link URL on this layer when rendering a PDF.' },+ { key: 'hide', label: 'Hide', description: 'Hide this layer.', kind: 'checkbox' },+];++const TEXT_FIELDS: LayerField[] = [+ { key: 'text', label: 'Text', description: 'Replacement text.' },+ { key: 'color', label: 'Text Color', description: 'Hex color, e.g. #FF0000.' },+ { key: 'background', label: 'Background', description: 'Hex color, e.g. #000000.' },+ { key: 'font_family', label: 'Font', description: 'Font family name.' },+ { key: 'text_align_h', label: 'Horizontal Align', description: 'left, center or right.' },+ { key: 'text_align_v', label: 'Vertical Align', description: 'top, center or bottom.' },+ { key: 'font_family_2', label: 'Secondary Font', description: 'Secondary font family name.' },+ { key: 'color_2', label: 'Secondary Text Color', description: 'Hex color for the secondary font.' },+];++const IMAGE_FIELDS: LayerField[] = [+ { key: 'image_url', label: 'Image URL', description: 'Public URL of the image.' },+ { key: 'effect', label: 'Effect', description: 'Image effect name, e.g. Grayscale.' },+ { key: 'anchor_x', label: 'Anchor X', description: 'left, center or right.' },+ { key: 'anchor_y', label: 'Anchor Y', description: 'top, center or bottom.' },+ { key: 'fill_type', label: 'Fill Type', description: 'fill or fit.' },+ { key: 'disable_face_detect', label: 'Disable Face Detect', description: 'Turn off face detection for this render.', kind: 'checkbox' },+ { key: 'disable_smart_crop', label: 'Disable Smart Crop', description: 'Turn off smart crop for this render.', kind: 'checkbox' },+];++const LAYER_FIELDS: Record<string, LayerField[]> = {+ text: TEXT_FIELDS,+ image: IMAGE_FIELDS,+ rectangle_image_container: IMAGE_FIELDS,+ circle_image_container: IMAGE_FIELDS,+ rating: [+ { key: 'rating', label: 'Rating', description: 'Number from 0 to 100.', kind: 'number' },+ ],+ chart: [+ { key: 'chart_data', label: 'Chart Data', description: 'Comma-separated numbers, e.g. 10,20,30.' },+ ],+ bar_code: [+ { key: 'bar_code_data', label: 'Bar Code Data', description: 'Text to encode as a bar code.' },+ ],+ qr_code: [+ { key: 'target', label: 'QR Code Target', description: 'URL or text to encode in the QR code.' },+ ],+};++type LayerField = {+ key: string;+ label: string;+ description: string;+ kind?: 'text' | 'number' | 'checkbox';};diff --git a/packages/pieces/community/bannerbear/src/lib/actions/create-screenshot.ts b/packages/pieces/community/bannerbear/src/lib/actions/create-screenshot.tsnew file mode 100644index 00000000000..028f54ee935--- /dev/null+++ b/packages/pieces/community/bannerbear/src/lib/actions/create-screenshot.ts@@ -0,0 +1,122 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { bannerbearAuth } from '../auth';+import { bannerbearClient } from '../common/client';+import { bannerbearProps } from '../common/props';+import { bannerbearOutputSchemas } from '../output-schemas';++export const createScreenshotAction = createAction({+ auth: bannerbearAuth,+ name: 'create_screenshot',+ classification: 'WRITE',+ displayName: 'Create Screenshot',+ description: 'Take a screenshot of a web page (V2 API keys only).',+ audience: 'both',+ aiMetadata: {+ description:+ 'Capture a screenshot of a public web page with Bannerbear. Only works with V2 API keys; V5 keys get an error. Each call starts a new capture and uses a credit.',+ idempotent: false,+ },+ outputSchema: bannerbearOutputSchemas['screenshot'],+ props: {+ url: Property.ShortText({+ displayName: 'Page URL',+ description: 'The web page to capture.',+ required: true,+ }),+ width: Property.Number({+ displayName: 'Width',+ description: 'Browser width in pixels. Default 1200.',+ required: false,+ }),+ height: Property.Number({+ displayName: 'Height',+ description: 'Browser height in pixels. Empty = full page.',+ required: false,+ }),+ mobile: Property.Checkbox({+ displayName: 'Mobile',+ description: 'Use a mobile user agent.',+ required: false,+ }),+ language: Property.ShortText({+ displayName: 'Language',+ description: 'Browser language code.',+ required: false,+ }),+ wait_for_completion: bannerbearProps.waitForCompletion,+ },+ async run({ auth, propsValue }) {+ const apiKey = auth.secret_text;+ bannerbearClient.requireVersion({ apiKey, version: 'v2', feature: 'Create Screenshot' });+ const url = propsValue.url.trim();+ if (!/^https?:\/\//i.test(url)) {+ throw new Error('Page URL must start with http:// or https://.');+ }+ const body: Record<string, unknown> = { url };+ const width = toPositiveInt({ value: propsValue.width, label: 'Width' });+ const height = toPositiveInt({ value: propsValue.height, label: 'Height' });+ if (width !== undefined) body['width'] = width;+ if (height !== undefined) body['height'] = height;+ if (propsValue.mobile !== undefined) body['mobile'] = propsValue.mobile;+ if (propsValue.language) body['language'] = propsValue.language;+ const created = await bannerbearClient.request<RawScreenshot>({+ apiKey,+ method: HttpMethod.POST,+ path: '/screenshots',+ body,+ });+ const { record, timedOut } = await bannerbearClient.waitFor({+ initial: created,+ wait: propsValue.wait_for_completion !== false,+ doneStatuses: bannerbearClient.IMAGE_DONE_STATUSES,+ failedStatuses: bannerbearClient.IMAGE_FAILED_STATUSES,+ fetchLatest: () =>+ bannerbearClient.request<RawScreenshot>({+ apiKey,+ method: HttpMethod.GET,+ path: `/screenshots/${encodeURIComponent(created.uid)}`,+ }),+ });+ bannerbearClient.throwIfFailed({ status: record.status, uid: record.uid });+ return {+ uid: record.uid,+ status: record.status ?? null,+ url: record.url ?? url,+ screenshot_image_url: record.screenshot_image_url ?? null,+ width: record.width ?? null,+ height: record.height ?? null,+ mobile: record.mobile ?? null,+ self: record.self ?? null,+ created_at: record.created_at ?? null,+ timed_out: timedOut,+ };+ },+});++function toPositiveInt({+ value,+ label,+}: {+ value: unknown;+ label: string;+}): number | undefined {+ if (value === undefined || value === null || value === '') return undefined;+ const n = Number(value);+ if (!Number.isInteger(n) || n < 1) {+ throw new Error(`${label} must be a whole number of 1 or more.`);+ }+ return n;+}++type RawScreenshot = {+ uid: string;+ status?: string | null;+ url?: string | null;+ screenshot_image_url?: string | null;+ width?: number | null;+ height?: number | null;+ mobile?: boolean | null;+ self?: string | null;+ created_at?: string | null;+};diff --git a/packages/pieces/community/bannerbear/src/lib/actions/get-account.ts b/packages/pieces/community/bannerbear/src/lib/actions/get-account.tsnew file mode 100644index 00000000000..68a233a5de6--- /dev/null+++ b/packages/pieces/community/bannerbear/src/lib/actions/get-account.ts@@ -0,0 +1,65 @@+import { createAction } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { bannerbearAuth } from '../auth';+import { bannerbearClient } from '../common/client';+import { bannerbearOutputSchemas } from '../output-schemas';++export const getAccountAction = createAction({+ auth: bannerbearAuth,+ name: 'get_account',+ classification: 'READ',+ displayName: 'Get Account',+ description: 'Get plan and credit usage for this API key.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Read the Bannerbear plan, credit quota and usage for the connected key. Use to check remaining credits before rendering. Read-only.',+ idempotent: true,+ },+ outputSchema: bannerbearOutputSchemas['account'],+ props: {},+ async run({ auth }) {+ const apiKey = auth.secret_text;+ const raw = await bannerbearClient.request<RawAccount>({+ apiKey,+ method: HttpMethod.GET,+ path: '/account',+ });+ if (bannerbearClient.getVersion(apiKey) === 'v5') {+ return {+ uid: raw.uid ?? null,+ api_version: 'v5',+ plan: raw.plan ?? null,+ project_name: raw.workspace ?? null,+ api_usage: raw.quota?.current ?? null,+ api_quota: raw.quota?.max ?? null,+ api_remaining: raw.quota?.remaining ?? null,+ created_at: raw.created_at ?? null,+ };+ }+ const usage = raw.api_usage ?? null;+ const quota = raw.api_quota ?? null;+ return {+ uid: raw.uid ?? null,+ api_version: 'v2',+ plan: raw.paid_plan_name ?? null,+ project_name: raw.current_project?.name ?? null,+ api_usage: usage,+ api_quota: quota,+ api_remaining: usage !== null && quota !== null ? quota - usage : null,+ created_at: raw.created_at ?? null,+ };+ },+});++type RawAccount = {+ uid?: string;+ created_at?: string;+ plan?: string;+ workspace?: string;+ quota?: { max?: number; current?: number; remaining?: number };+ paid_plan_name?: string;+ api_usage?: number;+ api_quota?: number;+ current_project?: { name?: string };+};diff --git a/packages/pieces/community/bannerbear/src/lib/actions/get-image.ts b/packages/pieces/community/bannerbear/src/lib/actions/get-image.tsnew file mode 100644index 00000000000..a458c2b2006--- /dev/null+++ b/packages/pieces/community/bannerbear/src/lib/actions/get-image.ts@@ -0,0 +1,37 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { bannerbearAuth } from '../auth';+import { bannerbearClient, RawImage } from '../common/client';+import { bannerbearOutputSchemas } from '../output-schemas';++export const getImageAction = createAction({+ auth: bannerbearAuth,+ name: 'get_image',+ classification: 'READ',+ displayName: 'Get Image',+ description: 'Get an image and its status by ID.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Fetch one Bannerbear image by its ID to read its status and file URLs. Use after a create action returned status "pending". Read-only and safe to retry.',+ idempotent: true,+ },+ outputSchema: bannerbearOutputSchemas['image'],+ props: {+ image_uid: Property.ShortText({+ displayName: 'Image ID',+ description: 'The image UID returned by Create Image.',+ required: true,+ }),+ },+ async run({ auth, propsValue }) {+ const uid = propsValue.image_uid.trim();+ if (uid === '') throw new Error('Image ID is required.');+ const raw = await bannerbearClient.request<RawImage>({+ apiKey: auth.secret_text,+ method: HttpMethod.GET,+ path: `/images/${encodeURIComponent(uid)}`,+ });+ return bannerbearClient.normalizeImage(raw);+ },+});diff --git a/packages/pieces/community/bannerbear/src/lib/actions/get-template.ts b/packages/pieces/community/bannerbear/src/lib/actions/get-template.tsnew file mode 100644index 00000000000..1d3d29d9a57--- /dev/null+++ b/packages/pieces/community/bannerbear/src/lib/actions/get-template.ts@@ -0,0 +1,38 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { bannerbearAuth } from '../auth';+import { bannerbearClient, RawTemplate } from '../common/client';+import { bannerbearOutputSchemas } from '../output-schemas';++export const getTemplateAction = createAction({+ auth: bannerbearAuth,+ name: 'get_template',+ classification: 'READ',+ displayName: 'Get Template',+ description: 'Get a template and its layer names.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Fetch one Bannerbear image template by ID, including its layers (name and type). Call this before Create Image from JSON to know which layer names to modify. Read-only.',+ idempotent: true,+ },+ outputSchema: bannerbearOutputSchemas['template'],+ props: {+ template_uid: Property.ShortText({+ displayName: 'Template ID',+ description: 'The template UID, from List Templates.',+ required: true,+ }),+ },+ async run({ auth, propsValue }) {+ const apiKey = auth.secret_text;+ const uid = propsValue.template_uid.trim();+ if (uid === '') throw new Error('Template ID is required.');+ const raw = await bannerbearClient.request<RawTemplate>({+ apiKey,+ method: HttpMethod.GET,+ path: bannerbearClient.templatePath({ apiKey, uid }),+ });+ return bannerbearClient.normalizeTemplate(raw);+ },+});diff --git a/packages/pieces/community/bannerbear/src/lib/actions/list-images.test.ts b/packages/pieces/community/bannerbear/src/lib/actions/list-images.test.tsnew file mode 100644index 00000000000..fc89348d7bd--- /dev/null+++ b/packages/pieces/community/bannerbear/src/lib/actions/list-images.test.ts@@ -0,0 +1,14 @@+import { describe, expect, it } from 'vitest';+import { fullPageSize } from './list-images';++describe('fullPageSize', () => {+ it('uses the requested limit for v2 keys', () => {+ expect(fullPageSize({ apiKey: 'abc', limit: 100 })).toBe(100);+ expect(fullPageSize({ apiKey: 'abc', limit: 10 })).toBe(10);+ });++ it('caps at 25 for v5 keys but keeps smaller limits', () => {+ expect(fullPageSize({ apiKey: 'bb_ak_v5_x', limit: 100 })).toBe(25);+ expect(fullPageSize({ apiKey: 'bb_ak_v5_x', limit: 10 })).toBe(10);+ });+});diff --git a/packages/pieces/community/bannerbear/src/lib/actions/list-images.ts b/packages/pieces/community/bannerbear/src/lib/actions/list-images.tsnew file mode 100644index 00000000000..69c499a2dde--- /dev/null+++ b/packages/pieces/community/bannerbear/src/lib/actions/list-images.ts@@ -0,0 +1,67 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod, QueryParams } from '@activepieces/pieces-common';+import { bannerbearAuth } from '../auth';+import { bannerbearClient, RawImage } from '../common/client';+import { bannerbearOutputSchemas } from '../output-schemas';++export const listImagesAction = createAction({+ auth: bannerbearAuth,+ name: 'list_images',+ classification: 'SEARCH',+ displayName: 'List Images',+ description: 'List images, one page at a time.',+ audience: 'both',+ aiMetadata: {+ description:+ 'List Bannerbear images page by page (1-100 per page). Use Get Image when you already have an ID. Check has_more and raise page to read further. Read-only.',+ idempotent: true,+ },+ outputSchema: bannerbearOutputSchemas['listImages'],+ props: {+ page: Property.Number({+ displayName: 'Page',+ description: 'Page number, starting at 1.',+ required: false,+ defaultValue: 1,+ }),+ limit: Property.Number({+ displayName: 'Per Page',+ description: 'Images per page, 1 to 100.',+ required: false,+ defaultValue: 25,+ }),+ },+ async run({ auth, propsValue }) {+ const apiKey = auth.secret_text;+ const page = bannerbearClient.clampPage(propsValue.page);+ const limit = bannerbearClient.clampLimit(propsValue.limit);+ const queryParams: QueryParams = { page: String(page), limit: String(limit) };+ const raw = await bannerbearClient.request<RawImage[]>({+ apiKey,+ method: HttpMethod.GET,+ path: '/images',+ queryParams,+ });+ return {+ items: raw.map((i) => bannerbearClient.normalizeImage(i)),+ page,+ has_more: raw.length >= fullPageSize({ apiKey, limit }),+ };+ },+});++// V5 honours `limit`, but if the server ever caps pages at 25 a short page+// must still count as full, otherwise has_more would stop agents early.+export function fullPageSize({+ apiKey,+ limit,+}: {+ apiKey: string;+ limit: number;+}): number {+ return bannerbearClient.getVersion(apiKey) === 'v5'+ ? Math.min(limit, V5_MAX_SERVER_PAGE)+ : limit;+}++const V5_MAX_SERVER_PAGE = 25;diff --git a/packages/pieces/community/bannerbear/src/lib/actions/list-templates.ts b/packages/pieces/community/bannerbear/src/lib/actions/list-templates.tsnew file mode 100644index 00000000000..6d1576d29a7--- /dev/null+++ b/packages/pieces/community/bannerbear/src/lib/actions/list-templates.ts@@ -0,0 +1,111 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod, QueryParams } from '@activepieces/pieces-common';+import { bannerbearAuth } from '../auth';+import { bannerbearClient, RawTemplate } from '../common/client';+import { bannerbearOutputSchemas } from '../output-schemas';++export const listTemplatesAction = createAction({+ auth: bannerbearAuth,+ name: 'list_templates',+ classification: 'SEARCH',+ displayName: 'List Templates',+ description: 'List image templates, optionally filtered by name or tag.',+ audience: 'both',+ aiMetadata: {+ description:+ 'List Bannerbear image templates with their IDs, optionally filtered by name or tag. Use it to find a template ID for Create Image from JSON, then Get Template for its layers. Read-only.',+ idempotent: true,+ },+ outputSchema: bannerbearOutputSchemas['listTemplates'],+ props: {+ name: Property.ShortText({+ displayName: 'Name Contains',+ description: 'Only templates whose name contains this text.',+ required: false,+ }),+ tag: Property.ShortText({+ displayName: 'Tag',+ description: 'Only templates with this tag.',+ required: false,+ }),+ page: Property.Number({+ displayName: 'Page',+ description: 'Page number, starting at 1.',+ required: false,+ defaultValue: 1,+ }),+ },+ async run({ auth, propsValue }) {+ const apiKey = auth.secret_text;+ const page = bannerbearClient.clampPage(propsValue.page);+ const name = propsValue.name?.trim() ?? '';+ const tag = propsValue.tag?.trim() ?? '';+ if (bannerbearClient.getVersion(apiKey) === 'v5') {+ if (name === '' && tag === '') {+ const raw = await bannerbearClient.request<RawTemplate[]>({+ apiKey,+ method: HttpMethod.GET,+ path: '/image_templates',+ queryParams: { page: String(page) },+ });+ return {+ items: raw.map((t) => toListItem(bannerbearClient.normalizeTemplate(t))),+ page,+ has_more: raw.length >= V5_PAGE_SIZE,+ };+ }+ const all = await bannerbearClient.listAllTemplates(apiKey);+ const filtered = all.filter(+ (t) =>+ (name === '' ||+ (t.name ?? '').toLowerCase().includes(name.toLowerCase())) &&+ (tag === '' || t.tags.includes(tag))+ );+ const start = (page - 1) * V5_PAGE_SIZE;+ return {+ items: filtered.slice(start, start + V5_PAGE_SIZE).map((t) => toListItem(t)),+ page,+ has_more: filtered.length > start + V5_PAGE_SIZE,+ };+ }+ const queryParams: QueryParams = {+ page: String(page),+ limit: String(bannerbearClient.MAX_LIMIT),+ };+ if (name !== '') queryParams['name'] = name;+ if (tag !== '') queryParams['tag'] = tag;+ const raw = await bannerbearClient.request<RawTemplate[]>({+ apiKey,+ method: HttpMethod.GET,+ path: '/templates',+ queryParams,+ });+ return {+ items: raw.map((t) => toListItem(bannerbearClient.normalizeTemplate(t))),+ page,+ has_more: raw.length >= bannerbearClient.MAX_LIMIT,+ };+ },+});++function toListItem(t: {+ uid: string;+ name: string | null;+ width: number | null;+ height: number | null;+ preview_url: string | null;+ tags: string[];+ created_at: string | null;+}) {+ return {+ uid: t.uid,+ name: t.name,+ width: t.width,+ height: t.height,+ preview_url: t.preview_url,+ tags: t.tags,+ created_at: t.created_at,+ };+}++const V5_PAGE_SIZE = 25;diff --git a/packages/pieces/community/bannerbear/src/lib/actions/update-template.ts b/packages/pieces/community/bannerbear/src/lib/actions/update-template.tsnew file mode 100644index 00000000000..e8a2342bdac--- /dev/null+++ b/packages/pieces/community/bannerbear/src/lib/actions/update-template.ts@@ -0,0 +1,77 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { bannerbearAuth } from '../auth';+import { bannerbearClient, RawTemplate } from '../common/client';+import { bannerbearOutputSchemas } from '../output-schemas';++export const updateTemplateAction = createAction({+ auth: bannerbearAuth,+ name: 'update_template',+ classification: 'WRITE',+ displayName: 'Update Template',+ description: 'Rename a template or change its tags.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Update a Bannerbear template name, tags, or metadata (V2) / description (V5). Fields left empty are not changed; tags replace the full list. Setting the same values again changes nothing.',+ idempotent: true,+ },+ outputSchema: bannerbearOutputSchemas['template'],+ props: {+ template_uid: Property.ShortText({+ displayName: 'Template ID',+ description: 'The template UID, from List Templates.',+ required: true,+ }),+ name: Property.ShortText({+ displayName: 'Name',+ description: 'New template name.',+ required: false,+ }),+ tags: Property.Array({+ displayName: 'Tags',+ description: 'Replaces all tags. Leave empty to keep current tags.',+ required: false,+ }),+ metadata: Property.ShortText({+ displayName: 'Metadata (V2 keys only)',+ description: 'Text stored with the template.',+ required: false,+ }),+ description: Property.ShortText({+ displayName: 'Description (V5 keys only)',+ description: 'Template description.',+ required: false,+ }),+ },+ async run({ auth, propsValue }) {+ const apiKey = auth.secret_text;+ const uid = propsValue.template_uid.trim();+ if (uid === '') throw new Error('Template ID is required.');+ const body: Record<string, unknown> = {};+ if (propsValue.name !== undefined && propsValue.name !== '') {+ body['name'] = propsValue.name;+ }+ if (Array.isArray(propsValue.tags) && propsValue.tags.length > 0) {+ body['tags'] = propsValue.tags.map((t) => String(t));+ }+ if (propsValue.metadata !== undefined && propsValue.metadata !== '') {+ bannerbearClient.requireVersion({ apiKey, version: 'v2', feature: 'Template metadata' });+ body['metadata'] = propsValue.metadata;+ }+ if (propsValue.description !== undefined && propsValue.description !== '') {+ bannerbearClient.requireVersion({ apiKey, version: 'v5', feature: 'Template description' });+ body['description'] = propsValue.description;+ }+ if (Object.keys(body).length === 0) {+ throw new Error('Set at least one field to update.');+ }+ const raw = await bannerbearClient.request<RawTemplate>({+ apiKey,+ method: HttpMethod.PATCH,+ path: bannerbearClient.templatePath({ apiKey, uid }),+ body,+ });+ return bannerbearClient.normalizeTemplate(raw);+ },+});diff --git a/packages/pieces/community/bannerbear/src/lib/auth.ts b/packages/pieces/community/bannerbear/src/lib/auth.tsindex 3b12ac5a0f1..005f61c8de2 100644--- a/packages/pieces/community/bannerbear/src/lib/auth.ts+++ b/packages/pieces/community/bannerbear/src/lib/auth.ts@@ -1,7 +1,27 @@import { PieceAuth } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { bannerbearClient } from './common/client';export const bannerbearAuth = PieceAuth.SecretText({displayName: 'API Key',- description: 'Bannerbear API Key',+ description: `Your Bannerbear API key. Both key types work:+- **V5 key** (starts with \`bb_ak_v5_\`): in Bannerbear open **Settings → API Keys** and create a key.+- **V2 project key** (older accounts): open your project, then **Settings → API Key**.++Master keys are not supported.`,required: true,+ validate: async ({ auth }) => {+ const apiKey = auth.trim();+ const path =+ bannerbearClient.getVersion(apiKey) === 'v5' ? '/account' : '/auth';+ try {+ await bannerbearClient.request({ apiKey, method: HttpMethod.GET, path });+ return { valid: true };+ } catch (error) {+ return {+ valid: false,+ error: error instanceof Error ? error.message : 'Invalid API key.',+ };+ }+ },});diff --git a/packages/pieces/community/bannerbear/src/lib/common/client.ts b/packages/pieces/community/bannerbear/src/lib/common/client.tsnew file mode 100644index 00000000000..6c4014a74fe--- /dev/null+++ b/packages/pieces/community/bannerbear/src/lib/common/client.ts@@ -0,0 +1,544 @@+import {+ AuthenticationType,+ httpClient,+ HttpMethod,+ QueryParams,+} from '@activepieces/pieces-common';++export const bannerbearClient = {+ getVersion(apiKey: string): BannerbearApiVersion {+ return apiKey.trim().startsWith(V5_KEY_PREFIX) ? 'v5' : 'v2';+ },+ templatePath({ apiKey, uid }: { apiKey: string; uid: string }): string {+ const base =+ bannerbearClient.getVersion(apiKey) === 'v5'+ ? '/image_templates'+ : '/templates';+ return `${base}/${encodeURIComponent(uid)}`;+ },+ getBaseUrl(apiKey: string): string {+ return `https://api.bannerbear.com/${bannerbearClient.getVersion(apiKey)}`;+ },+ async request<T>({+ apiKey,+ method,+ path,+ body,+ queryParams,+ }: {+ apiKey: string;+ method: HttpMethod;+ path: string;+ body?: unknown;+ queryParams?: QueryParams;+ }): Promise<T> {+ try {+ const response = await httpClient.sendRequest<T>({+ method,+ url: `${bannerbearClient.getBaseUrl(apiKey)}${path}`,+ body,+ queryParams,+ authentication: {+ type: AuthenticationType.BEARER_TOKEN,+ token: apiKey.trim(),+ },+ });+ return response.body;+ } catch (error) {+ throw new Error(describeError(error));+ }+ },+ requireVersion({+ apiKey,+ version,+ feature,+ }: {+ apiKey: string;+ version: BannerbearApiVersion;+ feature: string;+ }): void {+ const current = bannerbearClient.getVersion(apiKey);+ if (current !== version) {+ throw new Error(+ `${feature} is not available with ${current.toUpperCase()} API keys. Bannerbear only offers it on the ${version.toUpperCase()} API.`+ );+ }+ },+ async waitFor<T extends { status?: string | null }>({+ fetchLatest,+ initial,+ wait,+ doneStatuses,+ failedStatuses,+ }: {+ fetchLatest: () => Promise<T>;+ initial: T;+ wait: boolean;+ doneStatuses: string[];+ failedStatuses: string[];+ }): Promise<{ record: T; timedOut: boolean }> {+ let record = initial;+ if (!wait) {+ return { record, timedOut: false };+ }+ const deadline = Date.now() + MAX_WAIT_MS;+ while (+ !isFinished({ status: record.status, doneStatuses, failedStatuses })+ ) {+ if (Date.now() + POLL_INTERVAL_MS > deadline) {+ return { record, timedOut: true };+ }+ await sleep(POLL_INTERVAL_MS);+ record = await fetchLatest();+ }+ return { record, timedOut: false };+ },+ async listAllTemplates(apiKey: string): Promise<NormalizedTemplate[]> {+ const version = bannerbearClient.getVersion(apiKey);+ const path = version === 'v5' ? '/image_templates' : '/templates';+ const pageSize =+ version === 'v5' ? V5_TEMPLATE_PAGE_SIZE : bannerbearClient.MAX_LIMIT;+ const templates: NormalizedTemplate[] = [];+ for (let page = 1; ; page++) {+ if (page > MAX_TEMPLATE_PAGES) {+ throw new Error(+ `This Bannerbear account has more than ${MAX_TEMPLATE_PAGES * pageSize} templates, which is more than can be listed in one step. Use Get Template with a template UID instead.`+ );+ }+ const queryParams: QueryParams = { page: String(page) };+ if (version === 'v2') {+ queryParams['limit'] = String(bannerbearClient.MAX_LIMIT);+ }+ const batch = await bannerbearClient.request<RawTemplate[]>({+ apiKey,+ method: HttpMethod.GET,+ path,+ queryParams,+ });+ templates.push(...batch.map((t) => normalizeTemplate(t)));+ if (batch.length < pageSize) {+ break;+ }+ }+ return templates;+ },+ normalizeImage,+ normalizeTemplate,+ readTemplateUid,+ buildImageRequest,+ createImageAndWait,+ throwIfFailed,+ parseModificationsJson,+ clampLimit,+ clampPage,+ MAX_LIMIT: 100,+ IMAGE_DONE_STATUSES: ['completed'],+ IMAGE_FAILED_STATUSES: ['failed'],+};++const V5_KEY_PREFIX = 'bb_ak_v5_';+const POLL_INTERVAL_MS = 2000;+const MAX_WAIT_MS = 120000;++const MAX_TEMPLATE_PAGES = 400;+const V5_TEMPLATE_PAGE_SIZE = 25;++function normalizeImage(raw: RawImage): NormalizedImage {+ const files = raw.files ?? {};+ const png = raw.image_url_png ?? files['png'] ?? null;+ const jpg = raw.image_url_jpg ?? files['jpg'] ?? null;+ const pdf = raw.pdf_url ?? files['pdf'] ?? null;+ const firstFile = Object.values(files).find((f) => typeof f === 'string');+ return {+ uid: raw.uid,+ status: raw.status ?? null,+ template_uid: readTemplateUid(raw.template),+ image_url: raw.image_url ?? png ?? jpg ?? firstFile ?? null,+ image_url_png: png,+ image_url_jpg: jpg,+ pdf_url: pdf,+ metadata: raw.metadata ?? null,+ error: raw.error ?? null,+ self: raw.self ?? null,+ created_at: raw.created_at ?? null,+ completed_at: raw.completed_at ?? null,+ };+}++function normalizeTemplate(raw: RawTemplate): NormalizedTemplate {+ const v5Layers = raw.config?.objects ?? [];+ const v2Layers = raw.available_modifications ?? [];+ const layers: NormalizedLayer[] =+ v5Layers.length > 0+ ? v5Layers.map((layer) => ({+ name: layer.name ?? null,+ id: layer.id ?? null,+ type: layer.type ?? 'unknown',+ }))+ : v2Layers.map((layer) => ({+ name: layer.name,+ id: null,+ type: detectV2LayerType(layer),+ }));+ return {+ uid: raw.uid,+ name: raw.name ?? null,+ width: raw.width ?? null,+ height: raw.height ?? null,+ preview_url: raw.preview_url ?? raw.preview ?? null,+ tags: raw.tags ?? [],+ created_at: raw.created_at ?? null,+ layers,+ };+}++function readTemplateUid(template: unknown): string | null {+ if (typeof template === 'string') {+ return template;+ }+ if (+ template !== null &&+ typeof template === 'object' &&+ 'uid' in template &&+ typeof template.uid === 'string'+ ) {+ return template.uid;+ }+ return null;+}++function toV5Object(mod: V2Modification): Record<string, unknown> {+ const result: Record<string, unknown> = {};+ for (const [key, value] of Object.entries(mod)) {+ if (value === undefined || value === null || value === '') {+ continue;+ }+ const mapped = V2_TO_V5_KEYS[key];+ if (mapped) {+ result[mapped] = value;+ } else {+ result[key] = value;+ }+ }+ return result;+}++function buildImageRequest({+ apiKey,+ templateUid,+ modifications,+ transparent,+ renderPdf,+ metadata,+ templateVersion,+}: {+ apiKey: string;+ templateUid: string;+ modifications: V2Modification[];+ transparent?: boolean;+ renderPdf?: boolean;+ metadata?: string;+ templateVersion?: number;+}): Record<string, unknown> {+ if (bannerbearClient.getVersion(apiKey) === 'v5') {+ const formats = ['png'];+ if (renderPdf) {+ formats.push('pdf');+ }+ const body: Record<string, unknown> = {+ template: templateUid,+ modifications: {+ objects: modifications.map((m) => toV5Object(m)),+ template: transparent ? { transparent: true } : undefined,+ },+ formats,+ };+ if (metadata) body['metadata'] = metadata;+ if (templateVersion !== undefined) body['version'] = templateVersion;+ return body;+ }+ const body: Record<string, unknown> = {+ template: templateUid,+ modifications,+ };+ if (transparent !== undefined) body['transparent'] = transparent;+ if (renderPdf !== undefined) body['render_pdf'] = renderPdf;+ if (metadata) body['metadata'] = metadata;+ if (templateVersion !== undefined) body['template_version'] = templateVersion;+ return body;+}++async function createImageAndWait({+ apiKey,+ body,+ wait,+}: {+ apiKey: string;+ body: Record<string, unknown>;+ wait: boolean;+}): Promise<NormalizedImage & { timed_out: boolean }> {+ const created = await bannerbearClient.request<RawImage>({+ apiKey,+ method: HttpMethod.POST,+ path: '/images',+ body,+ });+ const { record, timedOut } = await bannerbearClient.waitFor({+ initial: created,+ wait,+ doneStatuses: bannerbearClient.IMAGE_DONE_STATUSES,+ failedStatuses: bannerbearClient.IMAGE_FAILED_STATUSES,+ fetchLatest: () =>+ bannerbearClient.request<RawImage>({+ apiKey,+ method: HttpMethod.GET,+ path: `/images/${encodeURIComponent(created.uid)}`,+ }),+ });+ throwIfFailed({+ status: record.status,+ error: record.error,+ uid: record.uid,+ });+ return { ...normalizeImage(record), timed_out: timedOut };+}++function throwIfFailed({+ status,+ error,+ uid,+}: {+ status?: string | null;+ error?: string | null;+ uid: string;+}): void {+ if (status === 'failed') {+ throw new Error(+ `Bannerbear render ${uid} failed${error ? `: ${error}` : '.'}`+ );+ }+}++function parseModificationsJson(value: unknown): V2Modification[] {+ const parsed = typeof value === 'string' ? safeJsonParse(value) : value;+ if (!Array.isArray(parsed)) {+ throw new Error(+ 'Modifications must be a JSON array of objects, e.g. [{"name":"title","text":"Hi"}].'+ );+ }+ return parsed.map((item, index) => {+ if (item === null || typeof item !== 'object' || Array.isArray(item)) {+ throw new Error(`Modification #${index + 1} must be an object.`);+ }+ const entries: Record<string, unknown> = Object.fromEntries(+ Object.entries(item)+ );+ const name = entries['name'];+ const id = entries['id'];+ if (+ (typeof name !== 'string' || name.trim() === '') &&+ (typeof id !== 'string' || id.trim() === '')+ ) {+ throw new Error(+ `Modification #${index + 1} needs a "name" (the layer name).`+ );+ }+ return entries;+ });+}++function clampLimit(limit: unknown): number {+ const n = Number(limit ?? 25);+ if (!Number.isFinite(n) || n < 1) return 25;+ return Math.min(Math.floor(n), bannerbearClient.MAX_LIMIT);+}++function clampPage(page: unknown): number {+ const n = Number(page ?? 1);+ if (!Number.isFinite(n) || n < 1) return 1;+ return Math.floor(n);+}++function safeJsonParse(value: string): unknown {+ try {+ return JSON.parse(value);+ } catch {+ throw new Error('Modifications is not valid JSON.');+ }+}++function isFinished({+ status,+ doneStatuses,+ failedStatuses,+}: {+ status?: string | null;+ doneStatuses: string[];+ failedStatuses: string[];+}): boolean {+ if (!status) return true;+ return doneStatuses.includes(status) || failedStatuses.includes(status);+}++function sleep(ms: number): Promise<void> {+ return new Promise((resolve) => setTimeout(resolve, ms));+}++function detectV2LayerType(layer: Record<string, unknown>): string {+ if ('text' in layer) return 'text';+ if ('image_url' in layer) return 'image';+ if ('rating' in layer) return 'rating';+ if ('chart_data' in layer) return 'chart';+ if ('bar_code_data' in layer) return 'bar_code';+ if ('target' in layer) return 'qr_code';+ return 'shape';+}++function describeError(error: unknown): string {+ const status = readStatus(error);+ const vendorMessage = readVendorMessage(error);+ if (status === undefined) {+ return error instanceof Error ? error.message : String(error);+ }+ const hint = STATUS_HINTS[status] ?? 'Bannerbear request failed';+ return vendorMessage+ ? `${hint} (HTTP ${status}): ${vendorMessage}`+ : `${hint} (HTTP ${status}).`;+}++function readStatus(error: unknown): number | undefined {+ if (error === null || typeof error !== 'object' || !('response' in error)) {+ return undefined;+ }+ const response = error.response;+ if (+ response !== null &&+ typeof response === 'object' &&+ 'status' in response &&+ typeof response.status === 'number'+ ) {+ return response.status;+ }+ return undefined;+}++function readVendorMessage(error: unknown): string | undefined {+ if (error === null || typeof error !== 'object' || !('response' in error)) {+ return undefined;+ }+ const response = error.response;+ if (+ response === null ||+ typeof response !== 'object' ||+ !('body' in response)+ ) {+ return undefined;+ }+ const body = response.body;+ if (typeof body === 'string') {+ return body.slice(0, 500);+ }+ if (body !== null && typeof body === 'object') {+ if ('message' in body && typeof body.message === 'string') {+ return body.message;+ }+ if ('error' in body && typeof body.error === 'string') {+ return body.error;+ }+ return JSON.stringify(body).slice(0, 500);+ }+ return undefined;+}++const STATUS_HINTS: Record<number, string> = {+ 400: 'Bannerbear rejected the request',+ 401: 'Invalid Bannerbear API key',+ 402: 'Bannerbear API quota is used up',+ 403: 'This API key has no access to that resource',+ 404: 'Bannerbear could not find that resource',+ 408: 'Bannerbear render timed out',+ 422: 'Bannerbear could not process the request',+ 429: 'Bannerbear rate limit hit, try again shortly',+ 500: 'Bannerbear server error',+ 503: 'Bannerbear is temporarily unavailable',+};++const V2_TO_V5_KEYS: Record<string, string> = {+ image_url: 'background-image',+ background: 'background-color',+ font_family: 'font-family',+ font_family_2: 'font-family-secondary',+ color_2: 'color-secondary',+ border_width: 'border-width',+ border_color: 'border-color',+ hide: 'hidden',+ rating: 'rating-score',+ bar_code_data: 'barcode-data',+ target: 'qr-target',+ shadow: 'box-shadow',+};++export type BannerbearApiVersion = 'v2' | 'v5';++export type V2Modification = Record<string, unknown>;++export type RawImage = {+ uid: string;+ status?: string | null;+ template?: unknown;+ image_url?: string | null;+ image_url_png?: string | null;+ image_url_jpg?: string | null;+ pdf_url?: string | null;+ files?: Record<string, string>;+ metadata?: string | null;+ error?: string | null;+ self?: string | null;+ created_at?: string | null;+ completed_at?: string | null;+};++export type NormalizedImage = {+ uid: string;+ status: string | null;+ template_uid: string | null;+ image_url: string | null;+ image_url_png: string | null;+ image_url_jpg: string | null;+ pdf_url: string | null;+ metadata: string | null;+ error: string | null;+ self: string | null;+ created_at: string | null;+ completed_at: string | null;+};++export type RawTemplate = {+ uid: string;+ name?: string | null;+ width?: number | null;+ height?: number | null;+ preview_url?: string | null;+ preview?: string | null;+ tags?: string[];+ created_at?: string | null;+ available_modifications?: (Record<string, unknown> & { name: string })[];+ config?: { objects?: { name?: string; id?: string; type?: string }[] };+};++export type NormalizedLayer = {+ name: string | null;+ id: string | null;+ type: string;+};++export type NormalizedTemplate = {+ uid: string;+ name: string | null;+ width: number | null;+ height: number | null;+ preview_url: string | null;+ tags: string[];+ created_at: string | null;+ layers: NormalizedLayer[];+};diff --git a/packages/pieces/community/bannerbear/src/lib/common/props.ts b/packages/pieces/community/bannerbear/src/lib/common/props.tsnew file mode 100644index 00000000000..9a3b87e6bd7--- /dev/null+++ b/packages/pieces/community/bannerbear/src/lib/common/props.ts@@ -0,0 +1,112 @@+import { Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { bannerbearAuth } from '../auth';+import { bannerbearClient } from './client';++const TEMPLATE_SET_MAX_PAGES = 40;++export const bannerbearProps = {+ template: ({ required }: { required: boolean }) =>+ Property.Dropdown({+ auth: bannerbearAuth,+ displayName: 'Template',+ description: 'The Bannerbear template to use.',+ required,+ refreshers: [],+ options: async ({ auth }) => {+ if (!auth) {+ return {+ disabled: true,+ options: [],+ placeholder: 'Please connect your Bannerbear account first.',+ };+ }+ try {+ const templates = await bannerbearClient.listAllTemplates(+ auth.secret_text+ );+ return {+ disabled: false,+ options: templates.map((t) => ({+ label: t.name ?? t.uid,+ value: t.uid,+ })),+ };+ } catch (error) {+ return {+ disabled: true,+ options: [],+ placeholder: `Could not load templates: ${+ error instanceof Error ? error.message : String(error)+ }`,+ };+ }+ },+ }),+ templateSet: Property.Dropdown({+ auth: bannerbearAuth,+ displayName: 'Template Set',+ description: 'The template set to render as a collection.',+ required: true,+ refreshers: [],+ options: async ({ auth }) => {+ if (!auth) {+ return {+ disabled: true,+ options: [],+ placeholder: 'Please connect your Bannerbear account first.',+ };+ }+ if (bannerbearClient.getVersion(auth.secret_text) === 'v5') {+ return {+ disabled: true,+ options: [],+ placeholder: 'Template sets are not available with V5 API keys.',+ };+ }+ try {+ const options: { label: string; value: string }[] = [];+ let truncated = true;+ for (let page = 1; page <= TEMPLATE_SET_MAX_PAGES; page++) {+ const batch = await bannerbearClient.request<+ { uid: string; name?: string }[]+ >({+ apiKey: auth.secret_text,+ method: HttpMethod.GET,+ path: '/template_sets',+ queryParams: { page: String(page) },+ });+ options.push(+ ...batch.map((s) => ({ label: s.name ?? s.uid, value: s.uid }))+ );+ if (batch.length < 25) {+ truncated = false;+ break;+ }+ }+ if (truncated) {+ return {+ disabled: false,+ options,+ placeholder: `Showing the first ${options.length} template sets only; use the Bannerbear dashboard to find others.`,+ };+ }+ return { disabled: false, options };+ } catch (error) {+ return {+ disabled: true,+ options: [],+ placeholder: `Could not load template sets: ${+ error instanceof Error ? error.message : String(error)+ }`,+ };+ }+ },+ }),+ waitForCompletion: Property.Checkbox({+ displayName: 'Wait for Completion',+ description: 'Wait up to 2 minutes for the render; else return pending.',+ required: false,+ defaultValue: true,+ }),+};diff --git a/packages/pieces/community/bannerbear/src/lib/output-schemas.ts b/packages/pieces/community/bannerbear/src/lib/output-schemas.tsnew file mode 100644index 00000000000..cc605d02a3e--- /dev/null+++ b/packages/pieces/community/bannerbear/src/lib/output-schemas.ts@@ -0,0 +1,139 @@+import { OutputSchema } from '@activepieces/pieces-framework';++export const bannerbearOutputSchemas: Record<string, OutputSchema> = {+ createImage: { fields: [...imageFields(), timedOutField()] },+ image: { fields: imageFields() },+ listImages: {+ fields: [+ {+ key: 'items',+ label: 'Images',+ labelKey: 'uid',+ listItems: imageFields(),+ },+ { key: 'page', label: 'Page', format: 'number' },+ { key: 'has_more', label: 'Has More', format: 'boolean' },+ ],+ },+ template: { fields: templateFields() },+ listTemplates: {+ fields: [+ {+ key: 'items',+ label: 'Templates',+ labelKey: 'name',+ listItems: templateFields().filter((f) => f.key !== 'layers'),+ },+ { key: 'page', label: 'Page', format: 'number' },+ { key: 'has_more', label: 'Has More', format: 'boolean' },+ ],+ },+ screenshot: {+ fields: [+ { key: 'uid', label: 'Screenshot ID' },+ { key: 'status', label: 'Status' },+ { key: 'url', label: 'Page URL', format: 'url' },+ { key: 'screenshot_image_url', label: 'Screenshot URL', format: 'url' },+ { key: 'width', label: 'Width', format: 'number' },+ { key: 'height', label: 'Height', format: 'number' },+ { key: 'mobile', label: 'Mobile', format: 'boolean' },+ { key: 'self', label: 'API URL', format: 'url' },+ { key: 'created_at', label: 'Created At', format: 'datetime' },+ timedOutField(),+ ],+ },+ collection: {+ fields: [+ { key: 'uid', label: 'Collection ID' },+ { key: 'status', label: 'Status' },+ { key: 'template_set', label: 'Template Set ID' },+ {+ key: 'images',+ label: 'Images',+ labelKey: 'template_uid',+ listItems: [+ { key: 'uid', label: 'Image ID' },+ { key: 'status', label: 'Status' },+ { key: 'template_uid', label: 'Template ID' },+ { key: 'image_url', label: 'Image URL', format: 'url' },+ ],+ },+ { key: 'metadata', label: 'Metadata' },+ { key: 'self', label: 'API URL', format: 'url' },+ { key: 'created_at', label: 'Created At', format: 'datetime' },+ timedOutField(),+ ],+ },+ animatedGif: {+ fields: [+ { key: 'uid', label: 'GIF ID' },+ { key: 'status', label: 'Status' },+ { key: 'template_uid', label: 'Template ID' },+ { key: 'image_url', label: 'GIF URL', format: 'url' },+ { key: 'fps', label: 'Frames per Second', format: 'number' },+ { key: 'metadata', label: 'Metadata' },+ { key: 'self', label: 'API URL', format: 'url' },+ { key: 'created_at', label: 'Created At', format: 'datetime' },+ timedOutField(),+ ],+ },+ account: {+ fields: [+ { key: 'uid', label: 'Account ID' },+ { key: 'api_version', label: 'API Version' },+ { key: 'plan', label: 'Plan' },+ { key: 'project_name', label: 'Project / Workspace' },+ { key: 'api_usage', label: 'Credits Used', format: 'number' },+ { key: 'api_quota', label: 'Credit Quota', format: 'number' },+ { key: 'api_remaining', label: 'Credits Remaining', format: 'number' },+ { key: 'created_at', label: 'Created At', format: 'datetime' },+ ],+ },+};++function imageFields(): OutputSchema['fields'] {+ return [+ { key: 'uid', label: 'Image ID' },+ { key: 'status', label: 'Status' },+ { key: 'template_uid', label: 'Template ID' },+ { key: 'image_url', label: 'Image URL', format: 'url' },+ { key: 'image_url_png', label: 'PNG URL', format: 'url' },+ { key: 'image_url_jpg', label: 'JPG URL', format: 'url' },+ { key: 'pdf_url', label: 'PDF URL', format: 'url' },+ { key: 'metadata', label: 'Metadata' },+ { key: 'error', label: 'Error' },+ { key: 'self', label: 'API URL', format: 'url' },+ { key: 'created_at', label: 'Created At', format: 'datetime' },+ { key: 'completed_at', label: 'Completed At', format: 'datetime' },+ ];+}++function templateFields(): OutputSchema['fields'] {+ return [+ { key: 'uid', label: 'Template ID' },+ { key: 'name', label: 'Name' },+ { key: 'width', label: 'Width', format: 'number' },+ { key: 'height', label: 'Height', format: 'number' },+ { key: 'preview_url', label: 'Preview', format: 'image' },+ { key: 'tags', label: 'Tags' },+ { key: 'created_at', label: 'Created At', format: 'datetime' },+ {+ key: 'layers',+ label: 'Layers',+ labelKey: 'name',+ listItems: [+ { key: 'name', label: 'Layer Name' },+ { key: 'id', label: 'Layer ID' },+ { key: 'type', label: 'Layer Type' },+ ],+ },+ ];+}++function timedOutField(): OutputSchema['fields'][number] {+ return {+ key: 'timed_out',+ label: 'Still Rendering (Wait Timed Out)',+ format: 'boolean',+ };+}diff --git a/packages/pieces/community/bannerbear/src/lib/triggers/new-image-completed.test.ts b/packages/pieces/community/bannerbear/src/lib/triggers/new-image-completed.test.tsnew file mode 100644index 00000000000..61dd4cf60b1--- /dev/null+++ b/packages/pieces/community/bannerbear/src/lib/triggers/new-image-completed.test.ts@@ -0,0 +1,207 @@+/// <reference types="vitest/globals" />++import { bannerbearClient, RawImage } from '../common/client';+import { newImageCompletedTrigger } from './new-image-completed';++describe('bannerbear new-image-completed', () => {+ let feed: RawImage[];+ let store: Map<string, unknown>;+ let clock: number;++ beforeEach(() => {+ feed = [];+ store = new Map();+ clock = Date.parse('2030-01-01T00:00:00.000Z');+ vi.spyOn(bannerbearClient, 'request').mockImplementation(+ async ({ path, queryParams }) => fakeRequest({ feed, path, queryParams })+ );+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ const addImages = ({ count, status }: { count: number; status: string }) => {+ const added: RawImage[] = [];+ for (let i = 0; i < count; i++) {+ clock += 1000;+ added.push({+ uid: `img-${clock}`,+ status,+ created_at: new Date(clock).toISOString(),+ completed_at: status === 'completed' ? new Date().toISOString() : null,+ });+ }+ feed = [...added.reverse(), ...feed];+ return added;+ };++ const context = ({ isRepublish }: { isRepublish: boolean }) => ({+ auth: { secret_text: 'v2-key' },+ propsValue: {},+ isRepublish,+ store: {+ get: async (key: string) => store.get(key) ?? null,+ put: async (key: string, value: unknown) => {+ store.set(key, value);+ return value;+ },+ delete: async (key: string) => {+ store.delete(key);+ },+ },+ });++ const call = async ({ hook, isRepublish = false }: { hook: 'onEnable' | 'onDisable' | 'run'; isRepublish?: boolean }) =>+ Reflect.apply(newImageCompletedTrigger[hook], newImageCompletedTrigger, [context({ isRepublish })]);++ const runUntilQuiet = async () => {+ const emitted: string[] = [];+ for (let i = 0; i < 60; i++) {+ const batch: { uid: string }[] = await call({ hook: 'run' });+ emitted.push(...batch.map((image) => image.uid));+ }+ return emitted;+ };++ test('delivers every image of a burst longer than ten pages exactly once', async () => {+ addImages({ count: 5, status: 'completed' });+ await call({ hook: 'onEnable' });+ const burst = addImages({ count: 1250, status: 'completed' });++ const emitted = await runUntilQuiet();++ expect(emitted).toHaveLength(burst.length);+ expect(new Set(emitted)).toEqual(new Set(burst.map((image) => image.uid)));+ });++ test('keeps paging when the server returns fewer items than the requested limit', async () => {+ addImages({ count: 5, status: 'completed' });+ await call({ hook: 'onEnable' });+ const burst = addImages({ count: 120, status: 'completed' });+ vi.spyOn(bannerbearClient, 'request').mockImplementation(async ({ path, queryParams }) =>+ fakeRequest({ feed, path, queryParams: { ...queryParams, limit: '25' } })+ );++ const emitted = await runUntilQuiet();++ expect(new Set(emitted)).toEqual(new Set(burst.map((image) => image.uid)));+ expect(emitted).toHaveLength(burst.length);+ });++ test('recovers pending images that overflow the pending list', async () => {+ await call({ hook: 'onEnable' });+ const pending = addImages({ count: 2100, status: 'pending' });+ await runUntilQuiet();+ for (const image of feed) {+ image.status = 'completed';+ image.completed_at = new Date().toISOString();+ }++ const emitted = await runUntilQuiet();++ expect(emitted).toHaveLength(pending.length);+ expect(new Set(emitted)).toEqual(new Set(pending.map((image) => image.uid)));+ });++ test('does not fire completed images from before enable that sit beyond page 1', async () => {+ addImages({ count: 60, status: 'completed' });+ vi.spyOn(bannerbearClient, 'request').mockImplementation(async ({ path, queryParams }) =>+ fakeRequest({ feed, path, queryParams: { ...queryParams, limit: '25' } })+ );+ await call({ hook: 'onEnable' });+ const fresh = addImages({ count: 24, status: 'completed' });++ const emitted = await runUntilQuiet();++ expect(new Set(emitted)).toEqual(new Set(fresh.map((image) => image.uid)));+ expect(emitted).toHaveLength(fresh.length);+ });++ test('fires images from before enable that were still rendering and finish later', async () => {+ const old = addImages({ count: 26, status: 'pending' });+ vi.spyOn(bannerbearClient, 'request').mockImplementation(async ({ path, queryParams }) =>+ fakeRequest({ feed, path, queryParams: { ...queryParams, limit: '25' } })+ );+ await call({ hook: 'onEnable' });+ const fresh = addImages({ count: 24, status: 'completed' });+ await new Promise((resolve) => setTimeout(resolve, 5));+ const first = await runUntilQuiet();+ for (const image of feed) {+ if (image.status === 'pending') {+ image.status = 'completed';+ image.completed_at = new Date().toISOString();+ }+ }++ const emitted = [...first, ...(await runUntilQuiet())];++ expect(new Set(emitted)).toEqual(new Set([...fresh, ...old].map((image) => image.uid)));+ expect(emitted).toHaveLength(fresh.length + old.length);+ });++ test('rotates the pending queue so slow renders do not block later images', async () => {+ await call({ hook: 'onEnable' });+ const later = addImages({ count: 30, status: 'pending' });+ const slow = addImages({ count: 25, status: 'pending' });+ await call({ hook: 'run' });+ addImages({ count: 150, status: 'completed' });+ await runUntilQuiet();+ const laterUids = new Set(later.map((image) => image.uid));+ for (const image of feed) {+ if (laterUids.has(image.uid)) {+ image.status = 'completed';+ image.completed_at = new Date().toISOString();+ }+ }+ expect(slow).toHaveLength(25);++ const emitted: string[] = [];+ for (let i = 0; i < 4; i++) {+ const batch: { uid: string }[] = await call({ hook: 'run' });+ emitted.push(...batch.map((image) => image.uid));+ }++ expect(new Set(emitted)).toEqual(laterUids);+ });++ test('republish keeps the stored state and disable leaves it in place', async () => {+ addImages({ count: 3, status: 'completed' });+ await call({ hook: 'onEnable' });+ const before = structuredClone(store.get(STORE_KEY));+ addImages({ count: 4, status: 'completed' });++ await call({ hook: 'onDisable' });+ await call({ hook: 'onEnable', isRepublish: true });++ expect(store.get(STORE_KEY)).toEqual(before);+ const emitted = await runUntilQuiet();+ expect(emitted).toHaveLength(4);+ });+});++async function fakeRequest({+ feed,+ path,+ queryParams,+}: {+ feed: RawImage[];+ path: string;+ queryParams?: Record<string, string>;+}): Promise<never> {+ if (path === '/images') {+ const page = Number(queryParams?.['page'] ?? '1');+ const limit = Number(queryParams?.['limit'] ?? '25');+ return Reflect.apply(identity, null, [feed.slice((page - 1) * limit, page * limit).map((image) => ({ ...image }))]);+ }+ const uid = decodeURIComponent(path.replace('/images/', ''));+ const image = feed.find((i) => i.uid === uid);+ if (!image) throw new Error('HTTP 404');+ return Reflect.apply(identity, null, [{ ...image }]);+}++function identity(value: unknown): unknown {+ return value;+}++const STORE_KEY = 'bannerbear_new_image_completed_state';diff --git a/packages/pieces/community/bannerbear/src/lib/triggers/new-image-completed.ts b/packages/pieces/community/bannerbear/src/lib/triggers/new-image-completed.tsnew file mode 100644index 00000000000..9afd1059939--- /dev/null+++ b/packages/pieces/community/bannerbear/src/lib/triggers/new-image-completed.ts@@ -0,0 +1,312 @@+import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { bannerbearAuth } from '../auth';+import {+ bannerbearClient,+ NormalizedImage,+ RawImage,+} from '../common/client';+import { bannerbearOutputSchemas } from '../output-schemas';++export const newImageCompletedTrigger = createTrigger({+ auth: bannerbearAuth,+ name: 'new_image_completed',+ classification: 'READ',+ displayName: 'New Image Completed',+ description: 'Triggers when an image finishes rendering.',+ aiMetadata: {+ description:+ 'Fires once per Bannerbear image that reaches status "completed", including images that were still pending on an earlier check.',+ },+ outputSchema: bannerbearOutputSchemas['image'],+ props: {},+ type: TriggerStrategy.POLLING,+ sampleData: {+ uid: 'kG39R5XbvPQpLENKBWJj',+ status: 'completed',+ template_uid: '6A37YJe5qNDmpvWKP0',+ image_url: 'https://images.bannerbear.com/direct/example.png',+ image_url_png: 'https://images.bannerbear.com/direct/example.png',+ image_url_jpg: 'https://images.bannerbear.com/direct/example.jpg',+ pdf_url: null,+ metadata: null,+ error: null,+ self: 'https://api.bannerbear.com/v2/images/kG39R5XbvPQpLENKBWJj',+ created_at: '2026-10-22T10:00:00.000Z',+ completed_at: null,+ },+ async onEnable(context) {+ if (context.isRepublish && (await context.store.get(STORE_KEY))) return;+ const { images } = await scanPages({+ apiKey: context.auth.secret_text,+ startPage: 1,+ stopAt: null,+ maxPages: 1,+ });+ await context.store.put<PollState>(STORE_KEY, {+ seen: images.filter((i) => i.status === 'completed').map((i) => i.uid).slice(0, MAX_SEEN),+ pending: images.filter((i) => i.status === 'pending').map((i) => toPendingEntry(i)).slice(0, MAX_PENDING),+ head: newestCreatedAt(images) ?? new Date().toISOString(),+ floor: oldestCreatedAt(images.map((i) => toPendingEntry(i))) ?? new Date().toISOString(),+ enabledAt: new Date().toISOString(),+ backfill: null,+ recovery: null,+ });+ },+ async onDisable() {+ return;+ },+ async test(context) {+ const { images } = await scanPages({+ apiKey: context.auth.secret_text,+ startPage: 1,+ stopAt: null,+ maxPages: 1,+ });+ return images.filter((i) => i.status === 'completed').slice(0, 5);+ },+ async run(context) {+ const apiKey = context.auth.secret_text;+ const pollStartedAt = Date.now() - CLOCK_SKEW_MS;+ const stored = await context.store.get<StoredPollState>(STORE_KEY);+ const state: PollState = {+ seen: stored?.seen ?? [],+ pending: (stored?.pending ?? []).map((entry) =>+ typeof entry === 'string' ? { uid: entry, created_at: null } : entry+ ),+ head: stored?.head ?? null,+ floor: stored?.floor ?? null,+ enabledAt: stored?.enabledAt ?? null,+ backfill: stored?.backfill ?? null,+ recovery: stored?.recovery ?? null,+ };+ const seen = new Set(state.seen);+ const fresh = await scanPages({+ apiKey,+ startPage: 1,+ stopAt: state.head,+ maxPages: state.head === null ? 1 : MAX_PAGES_PER_SCAN,+ });+ let backfill = state.backfill;+ if (!fresh.reachedStop) {+ backfill = backfill+ ? { page: Math.min(backfill.page, fresh.nextPage), until: backfill.until }+ : { page: fresh.nextPage, until: state.head };+ }+ const backfillImages: NormalizedImage[] = [];+ if (backfill && fresh.reachedStop) {+ const older = await scanPages({+ apiKey,+ startPage: backfill.page,+ stopAt: backfill.until,+ maxPages: MAX_PAGES_PER_SCAN,+ });+ backfillImages.push(...older.images);+ backfill = older.reachedStop+ ? null+ : { page: older.nextPage, until: backfill.until };+ }+ let recovery = state.recovery;+ const recoveredImages: NormalizedImage[] = [];+ if (recovery && fresh.reachedStop) {+ const since = Date.parse(recovery.since);+ const scanned = await scanPages({+ apiKey,+ startPage: recovery.page,+ stopAt: recovery.until,+ maxPages: MAX_PAGES_PER_SCAN,+ });+ recoveredImages.push(+ ...scanned.images.filter(+ (i) =>+ i.status !== 'completed' ||+ (i.completed_at !== null && Date.parse(i.completed_at) >= since)+ )+ );+ recovery = scanned.reachedStop+ ? null+ : { page: scanned.nextPage, until: recovery.until, since: recovery.since };+ }+ // Images created at or before the enable-time floor existed before the trigger was+ // enabled. Only the ones that had already completed by then are dropped; unfinished+ // ones stay eligible so their later completion still fires.+ const floorTime = state.floor === null ? NaN : Date.parse(state.floor);+ const enabledTime = state.enabledAt === null ? NaN : Date.parse(state.enabledAt);+ const recent = dedupe([...fresh.images, ...backfillImages, ...recoveredImages]).filter(+ (i) =>+ Number.isNaN(floorTime) ||+ i.created_at === null ||+ Date.parse(i.created_at) > floorTime ||+ i.status !== 'completed' ||+ (!Number.isNaN(enabledTime) &&+ i.completed_at !== null &&+ Date.parse(i.completed_at) > enabledTime)+ );+ const recentByUid = new Map(recent.map((i) => [i.uid, i]));+ const pendingToCheck = state.pending.filter((entry) => !recentByUid.has(entry.uid));+ const pendingChecks = (+ await Promise.all(+ pendingToCheck+ .slice(0, MAX_PENDING_CHECKS)+ .map((entry) => fetchImage({ apiKey, uid: entry.uid }))+ )+ ).filter((i): i is NormalizedImage => i !== null);+ const candidates = [...recent, ...pendingChecks];+ const emitted = candidates.filter((i) => i.status === 'completed' && !seen.has(i.uid));+ // Rotate: entries checked this poll and still pending go behind the unchecked ones,+ // so a slow render never blocks the rest of the queue from being checked.+ const stillPending = dedupePending([+ ...recent.filter((i) => i.status === 'pending').map((i) => toPendingEntry(i)),+ ...pendingToCheck.slice(MAX_PENDING_CHECKS),+ ...pendingChecks.filter((i) => i.status === 'pending').map((i) => toPendingEntry(i)),+ ]);+ const overflowFloor = oldestCreatedAt(stillPending.slice(MAX_PENDING));+ if (overflowFloor !== null) {+ recovery = {+ page: 1,+ until: recovery ? olderOf({ current: recovery.until, other: overflowFloor }) : overflowFloor,+ since: recovery ? recovery.since : new Date(pollStartedAt).toISOString(),+ };+ }+ await context.store.put<PollState>(STORE_KEY, {+ seen: [...emitted.map((i) => i.uid), ...state.seen].slice(0, MAX_SEEN),+ pending: stillPending.slice(0, MAX_PENDING),+ head: newestCreatedAt(fresh.images) ?? state.head,+ floor: state.floor,+ enabledAt: state.enabledAt,+ backfill,+ recovery,+ });+ return emitted.reverse();+ },+});++async function scanPages({+ apiKey,+ startPage,+ stopAt,+ maxPages,+}: {+ apiKey: string;+ startPage: number;+ stopAt: string | null;+ maxPages: number;+}): Promise<{ images: NormalizedImage[]; reachedStop: boolean; nextPage: number }> {+ const stopTime = stopAt ? Date.parse(stopAt) : NaN;+ const images: NormalizedImage[] = [];+ for (let page = startPage; page < startPage + maxPages; page++) {+ const raw = await bannerbearClient.request<RawImage[]>({+ apiKey,+ method: HttpMethod.GET,+ path: '/images',+ queryParams: { page: String(page), limit: String(bannerbearClient.MAX_LIMIT) },+ });+ const batch = raw.map((i) => bannerbearClient.normalizeImage(i));+ images.push(...batch);+ const reachedCheckpoint =+ !Number.isNaN(stopTime) &&+ batch.some((i) => i.created_at !== null && Date.parse(i.created_at) < stopTime);+ if (raw.length < SERVER_DEFAULT_PAGE_SIZE || reachedCheckpoint) {+ return { images: dedupe(images), reachedStop: true, nextPage: page + 1 };+ }+ }+ return {+ images: dedupe(images),+ reachedStop: stopAt === null && maxPages === 1,+ nextPage: startPage + maxPages,+ };+}++function toPendingEntry(image: NormalizedImage): PendingEntry {+ return { uid: image.uid, created_at: image.created_at };+}++function dedupePending(entries: PendingEntry[]): PendingEntry[] {+ const unique = new Map<string, PendingEntry>();+ for (const entry of entries) {+ if (!unique.has(entry.uid)) unique.set(entry.uid, entry);+ }+ return Array.from(unique.values());+}++function oldestCreatedAt(entries: PendingEntry[]): string | null {+ let oldest: string | null = null;+ for (const entry of entries) {+ if (entry.created_at === null) continue;+ oldest = oldest === null ? entry.created_at : olderOf({ current: oldest, other: entry.created_at });+ }+ return oldest;+}++function olderOf({ current, other }: { current: string | null; other: string }): string | null {+ if (current === null) return null;+ return Date.parse(other) < Date.parse(current) ? other : current;+}++function dedupe(images: NormalizedImage[]): NormalizedImage[] {+ const unique = new Map<string, NormalizedImage>();+ for (const image of images) {+ if (!unique.has(image.uid)) unique.set(image.uid, image);+ }+ return Array.from(unique.values());+}++function newestCreatedAt(images: NormalizedImage[]): string | null {+ let newest: string | null = null;+ let newestTime = -Infinity;+ for (const image of images) {+ if (image.created_at === null) continue;+ const time = Date.parse(image.created_at);+ if (!Number.isNaN(time) && time > newestTime) {+ newestTime = time;+ newest = image.created_at;+ }+ }+ return newest;+}++async function fetchImage({+ apiKey,+ uid,+}: {+ apiKey: string;+ uid: string;+}): Promise<NormalizedImage | null> {+ try {+ const raw = await bannerbearClient.request<RawImage>({+ apiKey,+ method: HttpMethod.GET,+ path: `/images/${encodeURIComponent(uid)}`,+ });+ return bannerbearClient.normalizeImage(raw);+ } catch (error) {+ if (error instanceof Error && error.message.includes('HTTP 404')) {+ return null;+ }+ throw error;+ }+}++const STORE_KEY = 'bannerbear_new_image_completed_state';+const MAX_PAGES_PER_SCAN = 10;+const SERVER_DEFAULT_PAGE_SIZE = 25;+const MAX_SEEN = 5000;+const MAX_PENDING = 2000;+const CLOCK_SKEW_MS = 5 * 60 * 1000;+const MAX_PENDING_CHECKS = 25;++type PollState = {+ seen: string[];+ pending: PendingEntry[];+ head: string | null;+ floor: string | null;+ enabledAt: string | null;+ backfill: { page: number; until: string | null } | null;+ recovery: { page: number; until: string | null; since: string } | null;+};++type PendingEntry = { uid: string; created_at: string | null };++type StoredPollState = Partial<Omit<PollState, 'pending'>> & {+ pending?: (string | PendingEntry)[];+};diff --git a/packages/pieces/community/bannerbear/vitest.config.ts b/packages/pieces/community/bannerbear/vitest.config.tsnew file mode 100644index 00000000000..1bd3d1e5fe7--- /dev/null+++ b/packages/pieces/community/bannerbear/vitest.config.ts@@ -0,0 +1,19 @@+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'),+ '@activepieces/core-piece-types': path.resolve(repoRoot, 'packages/core/piece-types/src/index.ts'),+ '@activepieces/core-utils': path.resolve(repoRoot, 'packages/core/utils/src/index.ts'),+ },+ },+})