Skip to content

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

feat(google-translate): add Google Translate piece (#16232)

Fabio8248093862df
diff --git a/bun.lock b/bun.lock
index 5da09cc7e19..3aa33e2059c 100644
--- a/bun.lock
+++ b/bun.lock
@@ -4032,6 +4032,18 @@
"tslib": "2.6.2",
},
},
+ "packages/pieces/community/google-translate": {
+ "name": "@activepieces/piece-google-translate",
+ "version": "0.0.1",
+ "dependencies": {
+ "@activepieces/pieces-common": "workspace:*",
+ "@activepieces/pieces-framework": "workspace:*",
+ },
+ "devDependencies": {
+ "tslib": "2.6.2",
+ "vitest": "3.2.6",
+ },
+ },
"packages/pieces/community/google-vertexai": {
"name": "@activepieces/piece-google-vertexai",
"version": "0.1.7",
@@ -11850,6 +11862,8 @@
"@activepieces/piece-google-tasks": ["@activepieces/piece-google-tasks@workspace:packages/pieces/community/google-tasks"],
+ "@activepieces/piece-google-translate": ["@activepieces/piece-google-translate@workspace:packages/pieces/community/google-translate"],
+
"@activepieces/piece-google-vertexai": ["@activepieces/piece-google-vertexai@workspace:packages/pieces/community/google-vertexai"],
"@activepieces/piece-googlechat": ["@activepieces/piece-googlechat@workspace:packages/pieces/community/googlechat"],
diff --git a/packages/pieces/community/google-translate/.eslintrc.json b/packages/pieces/community/google-translate/.eslintrc.json
new file mode 100644
index 00000000000..9ee1a0770e8
--- /dev/null
+++ b/packages/pieces/community/google-translate/.eslintrc.json
@@ -0,0 +1,26 @@
+{
+ "extends": ["../../../../.eslintrc.json"],
+ "ignorePatterns": ["!**/*"],
+ "overrides": [
+ { "files": ["*.ts", "*.tsx", "*.js", "*.jsx"], "rules": {} },
+ {
+ "files": ["*.ts", "*.tsx"],
+ "rules": {
+ "no-restricted-imports": [
+ "error",
+ {
+ "patterns": [
+ "lodash",
+ "lodash/*",
+ "@activepieces/core-*",
+ "@activepieces/server*",
+ "@activepieces/engine",
+ "@activepieces/shared"
+ ]
+ }
+ ]
+ }
+ },
+ { "files": ["*.js", "*.jsx"], "rules": {} }
+ ]
+}
diff --git a/packages/pieces/community/google-translate/README.md b/packages/pieces/community/google-translate/README.md
new file mode 100644
index 00000000000..5833f9ab363
--- /dev/null
+++ b/packages/pieces/community/google-translate/README.md
@@ -0,0 +1,28 @@
+# Google Translate
+
+Translate text and detect languages with Google Cloud Translation (v2 Basic API).
+
+## Authentication
+
+OAuth2 with a client from your own Google Cloud project:
+
+1. Select or create a Google Cloud project with billing enabled (Cloud Translation has a free tier of 500,000 characters per month).
+2. Enable the **Cloud Translation API**.
+3. On the OAuth consent screen, add the scope `https://www.googleapis.com/auth/cloud-translation`.
+4. Create an OAuth client ID of type *Web application* and add the redirect URL shown in the connection dialog to *Authorized redirect URIs*.
+5. Paste the Client ID and Client Secret into the connection and sign in.
+
+Usage is billed per character on that Google Cloud project.
+
+## Actions
+
+| Action | Description |
+| --- | --- |
+| Translate Text | Translate text into a target language. The source language is detected automatically unless set. Supports plain text and HTML. |
+| Detect Language | Return the most likely language of a text (code and English name), with a confidence between 0 and 1. |
+| List Supported Languages | List the languages the API supports, with names in a chosen display language. |
+| Custom API call | Send a request to `https://translation.googleapis.com` with the connection's token. |
+
+## Triggers
+
+None.
diff --git a/packages/pieces/community/google-translate/package.json b/packages/pieces/community/google-translate/package.json
new file mode 100644
index 00000000000..4fa8bd0bc9a
--- /dev/null
+++ b/packages/pieces/community/google-translate/package.json
@@ -0,0 +1,20 @@
+{
+ "name": "@activepieces/piece-google-translate",
+ "version": "0.0.1",
+ "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'",
+ "test": "vitest run"
+ },
+ "dependencies": {
+ "@activepieces/pieces-common": "workspace:*",
+ "@activepieces/pieces-framework": "workspace:*"
+ },
+ "devDependencies": {
+ "tslib": "2.6.2",
+ "vitest": "3.2.6"
+ }
+}
diff --git a/packages/pieces/community/google-translate/src/i18n/translation.json b/packages/pieces/community/google-translate/src/i18n/translation.json
new file mode 100644
index 00000000000..0b4b97971d0
--- /dev/null
+++ b/packages/pieces/community/google-translate/src/i18n/translation.json
@@ -0,0 +1,46 @@
+{
+ "Translate text and detect languages with Google Cloud Translation.": "Translate text and detect languages with Google Cloud Translation.",
+ "Connect with an OAuth client from **your own** Google Cloud project:\n\n1. In [Google Cloud Console](https://console.cloud.google.com/), select or create a project with **billing enabled** (Cloud Translation has a free tier of 500,000 characters/month).\n2. **APIs & Services → Library**: enable **Cloud Translation API**.\n3. **APIs & Services → OAuth consent screen**: add the scope `https://www.googleapis.com/auth/cloud-translation`. While the app is in *Testing*, add the Google accounts that will connect as te": "Connect with an OAuth client from **your own** Google Cloud project:\n\n1. In [Google Cloud Console](https://console.cloud.google.com/), select or create a project with **billing enabled** (Cloud Translation has a free tier of 500,000 characters/month).\n2. **APIs & Services → Library**: enable **Cloud Translation API**.\n3. **APIs & Services → OAuth consent screen**: add the scope `https://www.googleapis.com/auth/cloud-translation`. While the app is in *Testing*, add the Google accounts that will connect as test users.\n4. **APIs & Services → Credentials → Create credentials → OAuth client ID**, type *Web application*. Add the **Redirect URL shown below** to *Authorized redirect URIs*.\n5. Paste the **Client ID** and **Client Secret** here, then sign in with a Google account of that project.",
+ "Translate Text": "Translate Text",
+ "Detect Language": "Detect Language",
+ "List Supported Languages": "List Supported Languages",
+ "Custom API Call": "Custom API Call",
+ "Translate text into a target language with Google Cloud Translation": "Translate text into a target language with Google Cloud Translation",
+ "Detect the language of a text with Google Cloud Translation": "Detect the language of a text with Google Cloud Translation",
+ "List the languages Google Cloud Translation supports, with their names": "List the languages Google Cloud Translation supports, with their names",
+ "Make a custom API call to a specific endpoint": "Make a custom API call to a specific endpoint",
+ "Text": "Text",
+ "Target Language": "Target Language",
+ "Source Language": "Source Language",
+ "Format": "Format",
+ "Display Language": "Display Language",
+ "Method": "Method",
+ "Headers": "Headers",
+ "Query Parameters": "Query Parameters",
+ "Body Type": "Body Type",
+ "Body": "Body",
+ "Response is Binary": "Response is Binary",
+ "Return Error as Output": "Return Error as Output",
+ "Timeout": "Timeout",
+ "Follow redirects": "Follow redirects",
+ "Text to translate. Pick HTML in Format to keep markup intact.": "Text to translate. Pick HTML in Format to keep markup intact.",
+ "Language to translate into.": "Language to translate into.",
+ "Leave empty to let Google detect the language of the text.": "Leave empty to let Google detect the language of the text.",
+ "How the text should be parsed.": "How the text should be parsed.",
+ "Text whose language should be detected.": "Text whose language should be detected.",
+ "ISO-639-1 code used to render the language names (e.g. en, pt, es).": "ISO-639-1 code used to render the language names (e.g. en, pt, es).",
+ "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.",
+ "On a failed request, output the error instead of failing the step.": "On a failed request, output the error instead of failing the step.",
+ "Seconds to wait for a response. Empty: up to the flow limit (10 min).": "Seconds to wait for a response. Empty: up to the flow limit (10 min).",
+ "Follow 3xx redirects instead of returning them as the response.": "Follow 3xx redirects instead of returning them as the response.",
+ "Plain text": "Plain text",
+ "HTML": "HTML",
+ "GET": "GET",
+ "POST": "POST",
+ "PATCH": "PATCH",
+ "PUT": "PUT",
+ "DELETE": "DELETE",
+ "HEAD": "HEAD"
+}
\ No newline at end of file
diff --git a/packages/pieces/community/google-translate/src/index.ts b/packages/pieces/community/google-translate/src/index.ts
new file mode 100644
index 00000000000..2d1a622bf15
--- /dev/null
+++ b/packages/pieces/community/google-translate/src/index.ts
@@ -0,0 +1,24 @@
+import { createPiece, PieceCategory } from '@activepieces/pieces-framework';
+
+import { customApiCallAction } from './lib/actions/custom-api-call';
+import { detectLanguageAction } from './lib/actions/detect-language';
+import { listLanguagesAction } from './lib/actions/list-languages';
+import { translateTextAction } from './lib/actions/translate-text';
+import { googleTranslateAuth } from './lib/auth';
+
+export const googleTranslate = createPiece({
+ displayName: 'Google Translate',
+ description: 'Translate text and detect languages with Google Cloud Translation.',
+ auth: googleTranslateAuth,
+ minimumSupportedRelease: '0.88.0',
+ logoUrl: 'https://cdn.activepieces.com/pieces/google-translate.png',
+ categories: [PieceCategory.ARTIFICIAL_INTELLIGENCE],
+ authors: ['fabio-kozlowski'],
+ actions: [
+ translateTextAction,
+ detectLanguageAction,
+ listLanguagesAction,
+ customApiCallAction,
+ ],
+ triggers: [],
+});
diff --git a/packages/pieces/community/google-translate/src/lib/actions/custom-api-call.ts b/packages/pieces/community/google-translate/src/lib/actions/custom-api-call.ts
new file mode 100644
index 00000000000..fe474bb2ff6
--- /dev/null
+++ b/packages/pieces/community/google-translate/src/lib/actions/custom-api-call.ts
@@ -0,0 +1,19 @@
+import { createCustomApiCallAction } from '@activepieces/pieces-common';
+
+import { googleTranslateAuth } from '../auth';
+import { googleTranslateClient } from '../common/client';
+
+export const customApiCallAction = createCustomApiCallAction({
+ auth: googleTranslateAuth,
+ baseUrl: () => googleTranslateClient.baseUrl(),
+ authMapping: async (auth, propsValue) => {
+ const url: string = propsValue['url']?.['url'] ?? '';
+ const baseUrl = googleTranslateClient.baseUrl();
+ if (/^https?:\/\//.test(url) && new URL(url).origin !== baseUrl) {
+ throw new Error(
+ `Custom API Call only sends your Google credentials to ${baseUrl}. Use a path relative to it (e.g. /language/translate/v2/languages) or a full URL on that host.`,
+ );
+ }
+ return { Authorization: `Bearer ${auth.access_token}` };
+ },
+});
diff --git a/packages/pieces/community/google-translate/src/lib/actions/detect-language.ts b/packages/pieces/community/google-translate/src/lib/actions/detect-language.ts
new file mode 100644
index 00000000000..f578fa4710f
--- /dev/null
+++ b/packages/pieces/community/google-translate/src/lib/actions/detect-language.ts
@@ -0,0 +1,46 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+
+import { googleTranslateAuth } from '../auth';
+import { googleTranslateApi } from '../common/api';
+import { detectLanguageOutputSchema } from '../output-schemas';
+
+export const detectLanguageAction = createAction({
+ name: 'detectLanguage',
+ classification: 'READ',
+ displayName: 'Detect Language',
+ description: 'Detect the language of a text with Google Cloud Translation',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ "Detects the language of a text and returns Google's top guess as a language code, its English name and a 0 to 1 confidence. Use before branching on language; to translate, call Translate text directly since it detects the source on its own. Read only, safe to retry.",
+ idempotent: true,
+ },
+ outputSchema: detectLanguageOutputSchema,
+ auth: googleTranslateAuth,
+ props: {
+ text: Property.LongText({
+ displayName: 'Text',
+ description: 'Text whose language should be detected.',
+ required: true,
+ }),
+ },
+ async run(context) {
+ const [[detection], languages] = await Promise.all([
+ googleTranslateApi.detect({
+ auth: context.auth,
+ q: context.propsValue.text,
+ }),
+ googleTranslateApi.listLanguages({ auth: context.auth, target: 'en' }),
+ ]);
+
+ if (!detection) {
+ throw new Error('Google Translate could not detect a language for the given text.');
+ }
+
+ return {
+ language: detection.language,
+ languageName: languages.find((language) => language.language === detection.language)?.name ?? null,
+ confidence: detection.confidence ?? null,
+ };
+ },
+});
diff --git a/packages/pieces/community/google-translate/src/lib/actions/list-languages.ts b/packages/pieces/community/google-translate/src/lib/actions/list-languages.ts
new file mode 100644
index 00000000000..877eb3bf4b5
--- /dev/null
+++ b/packages/pieces/community/google-translate/src/lib/actions/list-languages.ts
@@ -0,0 +1,36 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+
+import { googleTranslateAuth } from '../auth';
+import { googleTranslateApi } from '../common/api';
+import { listLanguagesOutputSchema } from '../output-schemas';
+
+export const listLanguagesAction = createAction({
+ name: 'listLanguages',
+ classification: 'SEARCH',
+ displayName: 'List Supported Languages',
+ description: 'List the languages Google Cloud Translation supports, with their names',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Lists every language code Google Cloud Translation supports, with names rendered in a chosen display language. Use to validate or look up a language code before translating. Read only, safe to retry.',
+ idempotent: true,
+ },
+ outputSchema: listLanguagesOutputSchema,
+ auth: googleTranslateAuth,
+ props: {
+ displayLanguage: Property.ShortText({
+ displayName: 'Display Language',
+ description: 'ISO-639-1 code used to render the language names (e.g. en, pt, es).',
+ required: false,
+ defaultValue: 'en',
+ }),
+ },
+ async run(context) {
+ const languages = await googleTranslateApi.listLanguages({
+ auth: context.auth,
+ target: context.propsValue.displayLanguage || 'en',
+ });
+
+ return { languages };
+ },
+});
diff --git a/packages/pieces/community/google-translate/src/lib/actions/translate-text.ts b/packages/pieces/community/google-translate/src/lib/actions/translate-text.ts
new file mode 100644
index 00000000000..662d39c09ec
--- /dev/null
+++ b/packages/pieces/community/google-translate/src/lib/actions/translate-text.ts
@@ -0,0 +1,74 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+
+import { googleTranslateAuth } from '../auth';
+import { googleTranslateApi } from '../common/api';
+import { googleTranslateProps } from '../common/props';
+import { translateTextOutputSchema } from '../output-schemas';
+
+import type { GoogleTranslateFormat } from '../common/types';
+
+export const translateTextAction = createAction({
+ name: 'translateText',
+ classification: 'READ',
+ displayName: 'Translate Text',
+ description: 'Translate text into a target language with Google Cloud Translation',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Translates a text into a target language code (e.g. pt, es) with Google Cloud Translation and returns the translated text and the source language. Leave the source language empty to auto-detect it; set format to html to keep markup intact. Changes nothing in Google, safe to retry, but every call is billed per character on the connected Google Cloud project.',
+ idempotent: true,
+ },
+ outputSchema: translateTextOutputSchema,
+ auth: googleTranslateAuth,
+ props: {
+ text: Property.LongText({
+ displayName: 'Text',
+ description: 'Text to translate. Pick HTML in Format to keep markup intact.',
+ required: true,
+ }),
+ targetLanguage: googleTranslateProps.language({
+ required: true,
+ displayName: 'Target Language',
+ description: 'Language to translate into.',
+ }),
+ sourceLanguage: googleTranslateProps.language({
+ required: false,
+ displayName: 'Source Language',
+ description: 'Leave empty to let Google detect the language of the text.',
+ }),
+ format: Property.StaticDropdown<GoogleTranslateFormat>({
+ displayName: 'Format',
+ description: 'How the text should be parsed.',
+ required: false,
+ defaultValue: 'text',
+ options: {
+ options: [
+ { label: 'Plain text', value: 'text' },
+ { label: 'HTML', value: 'html' },
+ ],
+ },
+ }),
+ },
+ async run(context) {
+ const { text, targetLanguage, sourceLanguage, format } = context.propsValue;
+
+ const translations = await googleTranslateApi.translate({
+ auth: context.auth,
+ q: text,
+ target: targetLanguage,
+ source: sourceLanguage || undefined,
+ format: format ?? 'text',
+ });
+
+ const [translation] = translations;
+ if (!translation) {
+ throw new Error('Google Translate returned no translation for the given text.');
+ }
+
+ return {
+ translatedText: translation.translatedText,
+ detectedSourceLanguage: translation.detectedSourceLanguage ?? sourceLanguage ?? null,
+ targetLanguage,
+ };
+ },
+});
diff --git a/packages/pieces/community/google-translate/src/lib/auth.ts b/packages/pieces/community/google-translate/src/lib/auth.ts
new file mode 100644
index 00000000000..987ccc7a41a
--- /dev/null
+++ b/packages/pieces/community/google-translate/src/lib/auth.ts
@@ -0,0 +1,21 @@
+import { PieceAuth } from '@activepieces/pieces-framework';
+
+const googleTranslateScopes = ['https://www.googleapis.com/auth/cloud-translation', 'email'];
+
+const connectionInstructions = `
+Connect with an OAuth client from **your own** Google Cloud project:
+
+1. In [Google Cloud Console](https://console.cloud.google.com/), select or create a project with **billing enabled** (Cloud Translation has a free tier of 500,000 characters/month).
+2. **APIs & Services → Library**: enable **Cloud Translation API**.
+3. **APIs & Services → OAuth consent screen**: add the scope \`https://www.googleapis.com/auth/cloud-translation\`. While the app is in *Testing*, add the Google accounts that will connect as test users.
+4. **APIs & Services → Credentials → Create credentials → OAuth client ID**, type *Web application*. Add the **Redirect URL shown below** to *Authorized redirect URIs*.
+5. Paste the **Client ID** and **Client Secret** here, then sign in with a Google account of that project.
+`.trim();
+
+export const googleTranslateAuth = PieceAuth.OAuth2({
+ description: connectionInstructions,
+ authUrl: 'https://accounts.google.com/o/oauth2/auth',
+ tokenUrl: 'https://oauth2.googleapis.com/token',
+ required: true,
+ scope: googleTranslateScopes,
+});
diff --git a/packages/pieces/community/google-translate/src/lib/common/api.ts b/packages/pieces/community/google-translate/src/lib/common/api.ts
new file mode 100644
index 00000000000..0114ac02b0e
--- /dev/null
+++ b/packages/pieces/community/google-translate/src/lib/common/api.ts
@@ -0,0 +1,76 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+
+import { googleTranslateClient } from './client';
+
+import type {
+ GoogleTranslateAuthValue,
+ GoogleTranslateDetection,
+ GoogleTranslateFormat,
+ GoogleTranslateLanguage,
+ GoogleTranslateTranslation,
+} from './types';
+
+async function translate({
+ auth,
+ q,
+ target,
+ source,
+ format,
+}: TranslateParams & { auth: GoogleTranslateAuthValue }): Promise<GoogleTranslateTranslation[]> {
+ const response = await googleTranslateClient.request<{
+ data: { translations: GoogleTranslateTranslation[] };
+ }>({
+ auth,
+ method: HttpMethod.POST,
+ path: V2_PATH,
+ body: { q, target, ...(source ? { source } : {}), format },
+ });
+ return response.data.translations;
+}
+
+async function detect({
+ auth,
+ q,
+}: {
+ auth: GoogleTranslateAuthValue;
+ q: string;
+}): Promise<GoogleTranslateDetection[]> {
+ const response = await googleTranslateClient.request<{
+ data: { detections: GoogleTranslateDetection[][] };
+ }>({
+ auth,
+ method: HttpMethod.POST,
+ path: `${V2_PATH}/detect`,
+ body: { q },
+ });
+ return response.data.detections.flatMap((candidates) => candidates.slice(0, 1));
+}
+
+async function listLanguages({
+ auth,
+ target,
+}: {
+ auth: GoogleTranslateAuthValue;
+ target: string;
+}): Promise<GoogleTranslateLanguage[]> {
+ const response = await googleTranslateClient.request<{
+ data: { languages: GoogleTranslateLanguage[] };
+ }>({
+ auth,
+ method: HttpMethod.GET,
+ path: `${V2_PATH}/languages`,
+ query: { target },
+ });
+ return response.data.languages;
+}
+
+export const googleTranslateApi = { translate, detect, listLanguages };
+
+const V2_PATH = '/language/translate/v2';
+
+type TranslateParams = {
+ q: string;
+ target: string;
+ source?: string;
+ format: GoogleTranslateFormat;
+};
diff --git a/packages/pieces/community/google-translate/src/lib/common/client.ts b/packages/pieces/community/google-translate/src/lib/common/client.ts
new file mode 100644
index 00000000000..fd7581f0f9e
--- /dev/null
+++ b/packages/pieces/community/google-translate/src/lib/common/client.ts
@@ -0,0 +1,33 @@
+import {
+ AuthenticationType,
+ HttpMethod,
+ httpClient,
+ QueryParams,
+} from '@activepieces/pieces-common';
+
+import type { GoogleTranslateAuthValue } from './types';
+
+function baseUrl(): string {
+ return 'https://translation.googleapis.com';
+}
+
+async function request<T>({
+ auth,
+ method,
+ path,
+ query,
+ body,
+}: RequestParams & { auth: GoogleTranslateAuthValue }): Promise<T> {
+ const response = await httpClient.sendRequest<T>({
+ method,
+ url: `${baseUrl()}${path}`,
+ authentication: { type: AuthenticationType.BEARER_TOKEN, token: auth.access_token },
+ queryParams: query,
+ body,
+ });
+ return response.body;
+}
+
+export const googleTranslateClient = { baseUrl, request };
+
+type RequestParams = { method: HttpMethod; path: string; query?: QueryParams; body?: unknown };
diff --git a/packages/pieces/community/google-translate/src/lib/common/props.ts b/packages/pieces/community/google-translate/src/lib/common/props.ts
new file mode 100644
index 00000000000..e406bc45038
--- /dev/null
+++ b/packages/pieces/community/google-translate/src/lib/common/props.ts
@@ -0,0 +1,54 @@
+import { DropdownState, Property } from '@activepieces/pieces-framework';
+
+import { googleTranslateAuth } from '../auth';
+import { googleTranslateApi } from './api';
+
+function language<R extends boolean>({
+ required,
+ displayName = 'Language',
+ description = 'A language supported by Google Translate.',
+}: PropParams<R>) {
+ return Property.Dropdown({
+ auth: googleTranslateAuth,
+ displayName,
+ description,
+ required,
+ refreshers: [],
+ options: async ({ auth }) => {
+ if (!auth) {
+ return disabledOptions({
+ placeholder: 'Please select an existing or create a new connection.',
+ });
+ }
+ try {
+ const languages = await googleTranslateApi.listLanguages({ auth, target: 'en' });
+ const options = languages
+ .filter((language) => !LEGACY_LANGUAGE_CODES.has(language.language))
+ .map((language) => ({
+ label: language.name ? `${language.name} (${language.language})` : language.language,
+ value: language.language,
+ }))
+ .sort((a, b) => a.label.localeCompare(b.label));
+ return { disabled: false, options };
+ } catch {
+ return disabledOptions({
+ placeholder: 'An error occurred while fetching the supported languages.',
+ });
+ }
+ },
+ });
+}
+
+function disabledOptions({ placeholder }: { placeholder: string }): DropdownState<never> {
+ return { disabled: true, options: [], placeholder };
+}
+
+export const googleTranslateProps = { language };
+
+const LEGACY_LANGUAGE_CODES = new Set(['iw', 'jw']);
+
+export type PropParams<R extends boolean> = {
+ required: R;
+ displayName?: string;
+ description?: string;
+};
diff --git a/packages/pieces/community/google-translate/src/lib/common/types.ts b/packages/pieces/community/google-translate/src/lib/common/types.ts
new file mode 100644
index 00000000000..2132ac953b7
--- /dev/null
+++ b/packages/pieces/community/google-translate/src/lib/common/types.ts
@@ -0,0 +1,20 @@
+export type GoogleTranslateAuthValue = { access_token: string };
+
+export type GoogleTranslateFormat = 'text' | 'html';
+
+export type GoogleTranslateTranslation = {
+ translatedText: string;
+ detectedSourceLanguage?: string;
+ model?: string;
+};
+
+export type GoogleTranslateDetection = {
+ language: string;
+ confidence?: number;
+ isReliable?: boolean;
+};
+
+export type GoogleTranslateLanguage = {
+ language: string;
+ name?: string;
+};
diff --git a/packages/pieces/community/google-translate/src/lib/output-schemas.ts b/packages/pieces/community/google-translate/src/lib/output-schemas.ts
new file mode 100644
index 00000000000..ce91febdac6
--- /dev/null
+++ b/packages/pieces/community/google-translate/src/lib/output-schemas.ts
@@ -0,0 +1,31 @@
+import { OutputSchema } from '@activepieces/pieces-framework';
+
+export const translateTextOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'translatedText', label: 'Translated Text' },
+ { key: 'detectedSourceLanguage', label: 'Source Language' },
+ { key: 'targetLanguage', label: 'Target Language' },
+ ],
+};
+
+export const detectLanguageOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'language', label: 'Language' },
+ { key: 'languageName', label: 'Language Name' },
+ { key: 'confidence', label: 'Confidence', format: 'number' },
+ ],
+};
+
+export const listLanguagesOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'languages',
+ label: 'Languages',
+ labelKey: 'name',
+ listItems: [
+ { key: 'language', label: 'Language Code' },
+ { key: 'name', label: 'Name' },
+ ],
+ },
+ ],
+};
diff --git a/packages/pieces/community/google-translate/test/lib/actions/actions.test.ts b/packages/pieces/community/google-translate/test/lib/actions/actions.test.ts
new file mode 100644
index 00000000000..2a1d9b1bf15
--- /dev/null
+++ b/packages/pieces/community/google-translate/test/lib/actions/actions.test.ts
@@ -0,0 +1,143 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const translate = vi.fn<() => Promise<unknown>>();
+const detect = vi.fn<() => Promise<unknown>>();
+const languages = vi.fn<() => Promise<unknown>>();
+
+vi.mock('../../../src/lib/common/api', () => ({
+ googleTranslateApi: { translate, detect, listLanguages: languages },
+}));
+
+const { translateTextAction } = await import('../../../src/lib/actions/translate-text');
+const { detectLanguageAction } = await import('../../../src/lib/actions/detect-language');
+const { listLanguagesAction } = await import('../../../src/lib/actions/list-languages');
+
+const AUTH = { access_token: 'ya29.test-token' };
+
+function actionContext(propsValue: Record<string, unknown>) {
+ return { auth: AUTH, propsValue } as never;
+}
+
+describe('translateTextAction', () => {
+ beforeEach(() => {
+ translate.mockReset();
+ });
+
+ it('should translate with the connection token and the selected languages', async () => {
+ translate.mockResolvedValue([{ translatedText: 'Olá mundo', detectedSourceLanguage: 'en' }]);
+
+ const output = await translateTextAction.run(
+ actionContext({ text: 'Hello world', targetLanguage: 'pt', sourceLanguage: '', format: undefined })
+ );
+
+ expect(translate).toHaveBeenCalledWith({
+ auth: AUTH,
+ q: 'Hello world',
+ target: 'pt',
+ source: undefined,
+ format: 'text',
+ });
+ expect(output).toEqual({
+ translatedText: 'Olá mundo',
+ detectedSourceLanguage: 'en',
+ targetLanguage: 'pt',
+ });
+ });
+
+ it('should pass an explicit source language and html format through', async () => {
+ translate.mockResolvedValue([{ translatedText: '<b>Hola</b>' }]);
+
+ const output = await translateTextAction.run(
+ actionContext({ text: '<b>Hi</b>', targetLanguage: 'es', sourceLanguage: 'en', format: 'html' })
+ );
+
+ expect(translate).toHaveBeenCalledWith({
+ auth: AUTH,
+ q: '<b>Hi</b>',
+ target: 'es',
+ source: 'en',
+ format: 'html',
+ });
+ expect(output).toEqual({
+ translatedText: '<b>Hola</b>',
+ detectedSourceLanguage: 'en',
+ targetLanguage: 'es',
+ });
+ });
+
+ it('should fail loudly when Google returns no translation', async () => {
+ translate.mockResolvedValue([]);
+
+ await expect(
+ translateTextAction.run(actionContext({ text: 'x', targetLanguage: 'pt' }))
+ ).rejects.toThrow('Google Translate returned no translation for the given text.');
+ });
+});
+
+describe('detectLanguageAction', () => {
+ beforeEach(() => {
+ detect.mockReset();
+ languages.mockReset();
+ languages.mockResolvedValue([
+ { language: 'pt', name: 'Portuguese' },
+ { language: 'en', name: 'English' },
+ ]);
+ });
+
+ it('should return the top detection with null confidence when Google omits it', async () => {
+ detect.mockResolvedValue([{ language: 'pt' }]);
+
+ const output = await detectLanguageAction.run(actionContext({ text: 'Olá' }));
+
+ expect(detect).toHaveBeenCalledWith({ auth: AUTH, q: 'Olá' });
+ expect(languages).toHaveBeenCalledWith({ auth: AUTH, target: 'en' });
+ expect(output).toEqual({ language: 'pt', languageName: 'Portuguese', confidence: null });
+ });
+
+ it('should drop the deprecated isReliable flag from the output', async () => {
+ detect.mockResolvedValue([{ language: 'en', confidence: 1, isReliable: false }]);
+
+ const output = await detectLanguageAction.run(actionContext({ text: 'Hello' }));
+
+ expect(output).toEqual({ language: 'en', languageName: 'English', confidence: 1 });
+ });
+
+ it('should return a null name for a code Google does not list, like und', async () => {
+ detect.mockResolvedValue([{ language: 'und', confidence: 0 }]);
+
+ const output = await detectLanguageAction.run(actionContext({ text: '12345' }));
+
+ expect(output).toEqual({ language: 'und', languageName: null, confidence: 0 });
+ });
+
+ it('should fail loudly when nothing was detected', async () => {
+ detect.mockResolvedValue([]);
+
+ await expect(detectLanguageAction.run(actionContext({ text: '' }))).rejects.toThrow(
+ 'Google Translate could not detect a language for the given text.'
+ );
+ });
+});
+
+describe('listLanguagesAction', () => {
+ beforeEach(() => {
+ languages.mockReset();
+ });
+
+ it('should default the display language to en', async () => {
+ languages.mockResolvedValue([{ language: 'pt', name: 'Portuguese' }]);
+
+ const output = await listLanguagesAction.run(actionContext({ displayLanguage: undefined }));
+
+ expect(languages).toHaveBeenCalledWith({ auth: AUTH, target: 'en' });
+ expect(output).toEqual({ languages: [{ language: 'pt', name: 'Portuguese' }] });
+ });
+
+ it('should render names in the requested display language', async () => {
+ languages.mockResolvedValue([]);
+
+ await listLanguagesAction.run(actionContext({ displayLanguage: 'pt' }));
+
+ expect(languages).toHaveBeenCalledWith({ auth: AUTH, target: 'pt' });
+ });
+});
diff --git a/packages/pieces/community/google-translate/test/lib/actions/custom-api-call.test.ts b/packages/pieces/community/google-translate/test/lib/actions/custom-api-call.test.ts
new file mode 100644
index 00000000000..5ebc5d5fc36
--- /dev/null
+++ b/packages/pieces/community/google-translate/test/lib/actions/custom-api-call.test.ts
@@ -0,0 +1,65 @@
+import { httpClient, HttpMethod } from '@activepieces/pieces-common';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { customApiCallAction } from '../../../src/lib/actions/custom-api-call';
+
+const TOKEN = 'ya29.test-token';
+
+function callContext(url: string) {
+ return {
+ auth: { access_token: TOKEN },
+ propsValue: { url: { url }, method: HttpMethod.GET, headers: {}, queryParams: {} },
+ } as never;
+}
+
+describe('customApiCallAction', () => {
+ const sendRequest = vi.spyOn(httpClient, 'sendRequest');
+
+ beforeEach(() => {
+ sendRequest.mockReset();
+ sendRequest.mockResolvedValue({ status: 200, headers: {}, body: { ok: true } });
+ });
+
+ afterEach(() => {
+ sendRequest.mockReset();
+ });
+
+ it('should send the bearer token to a path relative to the Translation API', async () => {
+ await customApiCallAction.run(callContext('/language/translate/v2/languages'));
+
+ expect(sendRequest).toHaveBeenCalledTimes(1);
+ expect(sendRequest.mock.calls[0]?.[0]).toMatchObject({
+ url: 'https://translation.googleapis.com/language/translate/v2/languages',
+ headers: { Authorization: `Bearer ${TOKEN}` },
+ });
+ });
+
+ it('should send the bearer token to an absolute URL on the Translation API host', async () => {
+ await customApiCallAction.run(
+ callContext('https://translation.googleapis.com/language/translate/v2/languages')
+ );
+
+ expect(sendRequest.mock.calls[0]?.[0]).toMatchObject({
+ url: 'https://translation.googleapis.com/language/translate/v2/languages',
+ headers: { Authorization: `Bearer ${TOKEN}` },
+ });
+ });
+
+ it.each([
+ 'https://attacker.example.com/collect',
+ 'https://translation.googleapis.com.attacker.example.com/v2',
+ 'https://[email protected]/v2',
+ 'http://translation.googleapis.com/language/translate/v2',
+ 'https://www.googleapis.com/drive/v3/files',
+ ])('should refuse to send the token to %s', async (url) => {
+ await expect(customApiCallAction.run(callContext(url))).rejects.toThrow(
+ 'Custom API Call only sends your Google credentials to https://translation.googleapis.com.'
+ );
+ expect(sendRequest).not.toHaveBeenCalled();
+ });
+
+ it('should refuse a malformed absolute URL', async () => {
+ await expect(customApiCallAction.run(callContext('https://'))).rejects.toThrow('Invalid URL');
+ expect(sendRequest).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/pieces/community/google-translate/tsconfig.json b/packages/pieces/community/google-translate/tsconfig.json
new file mode 100644
index 00000000000..71bc5814f5d
--- /dev/null
+++ b/packages/pieces/community/google-translate/tsconfig.json
@@ -0,0 +1,15 @@
+{
+ "extends": "../../../../tsconfig.base.json",
+ "compilerOptions": {
+ "module": "commonjs",
+ "forceConsistentCasingInFileNames": true,
+ "strict": true,
+ "noImplicitOverride": true,
+ "noPropertyAccessFromIndexSignature": true,
+ "noImplicitReturns": true,
+ "noFallthroughCasesInSwitch": true
+ },
+ "files": [],
+ "include": [],
+ "references": [{ "path": "./tsconfig.lib.json" }]
+}
diff --git a/packages/pieces/community/google-translate/tsconfig.lib.json b/packages/pieces/community/google-translate/tsconfig.lib.json
new file mode 100644
index 00000000000..a648eb45d7f
--- /dev/null
+++ b/packages/pieces/community/google-translate/tsconfig.lib.json
@@ -0,0 +1,13 @@
+{
+ "extends": "./tsconfig.json",
+ "compilerOptions": {
+ "rootDir": ".",
+ "baseUrl": ".",
+ "paths": {},
+ "outDir": "./dist",
+ "declaration": true,
+ "types": ["node"]
+ },
+ "include": ["src/**/*.ts"],
+ "exclude": ["jest.config.ts", "src/**/*.spec.ts", "src/**/*.test.ts"]
+}
diff --git a/packages/pieces/community/google-translate/vitest.config.ts b/packages/pieces/community/google-translate/vitest.config.ts
new file mode 100644
index 00000000000..79c97261904
--- /dev/null
+++ b/packages/pieces/community/google-translate/vitest.config.ts
@@ -0,0 +1,19 @@
+import path from 'path'
+import { defineConfig } from 'vitest/config'
+
+const repoRoot = path.resolve(__dirname, '../../../..')
+
+export default defineConfig({
+ root: __dirname,
+ test: {
+ globals: true,
+ environment: 'node',
+ include: ['test/**/*.test.ts'],
+ },
+ resolve: {
+ alias: {
+ '@activepieces/pieces-framework': path.resolve(repoRoot, 'packages/pieces/framework/src/index.ts'),
+ '@activepieces/pieces-common': path.resolve(repoRoot, 'packages/pieces/common/src/index.ts'),
+ },
+ },
+})
diff --git a/tsconfig.base.json b/tsconfig.base.json
index 148b2d26e13..5a9d5c6ffcc 100644
--- a/tsconfig.base.json
+++ b/tsconfig.base.json
@@ -223,6 +223,9 @@
"@activepieces/piece-calendly": [
"packages/pieces/community/calendly/src/index.ts"
],
+ "@activepieces/piece-google-translate": [
+ "packages/pieces/community/google-translate/src/index.ts"
+ ],
"@activepieces/piece-rounded-studio": [
"packages/pieces/community/rounded-studio/src/index.ts"
],