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(google-search-console): query performance, inspect URLs and manage sitemaps from AI agents (#16227)
Odai Ahmada9774ae6f637
diff --git a/bun.lock b/bun.lockindex 490b131eec8..156dd47689a 100644--- a/bun.lock+++ b/bun.lock@@ -3965,18 +3965,17 @@},"packages/pieces/community/google-search-console": {"name": "@activepieces/piece-google-search-console",- "version": "0.3.0",+ "version": "0.4.0","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*","@activepieces/pieces-common": "workspace:*","@activepieces/pieces-framework": "workspace:*",- "@googleapis/webmasters": "2.0.1",- "dayjs": "1.11.9",- "google-auth-library": "10.5.0",+ "undici": "7.29.1",},"devDependencies": {"tslib": "2.6.2",+ "vitest": "3.2.6",},},"packages/pieces/community/google-sheets": {@@ -13466,8 +13465,6 @@"@googleapis/sheets": ["@googleapis/[email protected]", "", { "dependencies": { "googleapis-common": "^8.0.0" } }, "sha512-b1tBlMcfvNEziM4DZCikLOc9iqSlgCK1e5bMKtNQIADRXr1CQmbkHV3ZBVvTsFsjLErgihqO58Itn/kzCnSZ0A=="],- "@googleapis/webmasters": ["@googleapis/[email protected]", "", { "dependencies": { "googleapis-common": "^8.0.2-rc.0" } }, "sha512-eW/snHjAKakxoqcrsLYpJOVJIo8h2Ikgrv1SdS8lYLmFy9TGSf/W4MiCpkG3qQlcbVMA1cMviOBZUkliCo3EfA=="],-"@graphql-typed-document-node/core": ["@graphql-typed-document-node/[email protected]", "", { "peerDependencies": { "graphql": "^0.8.0 || ^0.9.0 || ^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^14.0.0 || ^15.0.0 || ^16.0.0 || ^17.0.0" } }, "sha512-mB9oAsNCm9aM3/SOv4YtBMqZbYj10R7dkq8byBqxGY/ncFwhf2oQzMV+LCRlWoDSEBJ3COiR1yeDvMtsoOsuFQ=="],"@grpc/grpc-js": ["@grpc/[email protected]", "", { "dependencies": { "@grpc/proto-loader": "^0.8.0", "@js-sdsl/ordered-map": "^4.4.2" } }, "sha512-Iq8QQQ/7X3Sac15oB6p0FmUg/klxQvXLeileoqrTRGJYLV+/9tubbr9ipz0GKHjmXVsgFPo/+W+2cA8eNcR+XA=="],@@ -18496,8 +18493,6 @@"@activepieces/piece-google-search/tslib": ["[email protected]", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],- "@activepieces/piece-google-search-console/google-auth-library": ["[email protected]", "", { "dependencies": { "base64-js": "^1.3.0", "ecdsa-sig-formatter": "^1.0.11", "gaxios": "^7.0.0", "gcp-metadata": "^8.0.0", "google-logging-utils": "^1.0.0", "gtoken": "^8.0.0", "jws": "^4.0.0" } }, "sha512-7ABviyMOlX5hIVD60YOfHw4/CxOfBhyduaYB+wbFWCWoni4N7SLcV46hrVRktuBbZjFC9ONyqamZITN7q3n32w=="],-"@activepieces/piece-google-sheets/google-auth-library": ["[email protected]", "", { "dependencies": { "base64-js": "^1.3.0", "ecdsa-sig-formatter": "^1.0.11", "gaxios": "^7.0.0", "gcp-metadata": "^8.0.0", "google-logging-utils": "^1.0.0", "gtoken": "^8.0.0", "jws": "^4.0.0" } }, "sha512-7ABviyMOlX5hIVD60YOfHw4/CxOfBhyduaYB+wbFWCWoni4N7SLcV46hrVRktuBbZjFC9ONyqamZITN7q3n32w=="],"@activepieces/piece-google-slides/google-auth-library": ["[email protected]", "", { "dependencies": { "base64-js": "^1.3.0", "ecdsa-sig-formatter": "^1.0.11", "gaxios": "^7.0.0", "gcp-metadata": "^8.0.0", "google-logging-utils": "^1.0.0", "gtoken": "^8.0.0", "jws": "^4.0.0" } }, "sha512-7ABviyMOlX5hIVD60YOfHw4/CxOfBhyduaYB+wbFWCWoni4N7SLcV46hrVRktuBbZjFC9ONyqamZITN7q3n32w=="],@@ -21034,14 +21029,6 @@"@activepieces/piece-google-forms/google-auth-library/jws": ["[email protected]", "", { "dependencies": { "jwa": "^2.0.1", "safe-buffer": "^5.0.1" } }, "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA=="],- "@activepieces/piece-google-search-console/google-auth-library/gaxios": ["[email protected]", "", { "dependencies": { "extend": "^3.0.2", "https-proxy-agent": "^7.0.1", "node-fetch": "^3.3.2", "rimraf": "^5.0.1" } }, "sha512-YGGyuEdVIjqxkxVH1pUTMY/XtmmsApXrCVv5EU25iX6inEPbV+VakJfLealkBtJN69AQmh1eGOdCl9Sm1UP6XQ=="],-- "@activepieces/piece-google-search-console/google-auth-library/gcp-metadata": ["[email protected]", "", { "dependencies": { "gaxios": "^7.0.0", "google-logging-utils": "^1.0.0", "json-bigint": "^1.0.0" } }, "sha512-zV/5HKTfCeKWnxG0Dmrw51hEWFGfcF2xiXqcA3+J90WDuP0SvoiSO5ORvcBsifmx/FoIjgQN3oNOGaQ5PhLFkg=="],-- "@activepieces/piece-google-search-console/google-auth-library/gtoken": ["[email protected]", "", { "dependencies": { "gaxios": "^7.0.0", "jws": "^4.0.0" } }, "sha512-+CqsMbHPiSTdtSO14O51eMNlrp9N79gmeqmXeouJOhfucAedHw9noVe/n5uJk3tbKE6a+6ZCQg3RPhVhHByAIw=="],-- "@activepieces/piece-google-search-console/google-auth-library/jws": ["[email protected]", "", { "dependencies": { "jwa": "^2.0.1", "safe-buffer": "^5.0.1" } }, "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA=="],-"@activepieces/piece-google-sheets/google-auth-library/gaxios": ["[email protected]", "", { "dependencies": { "extend": "^3.0.2", "https-proxy-agent": "^7.0.1", "node-fetch": "^3.3.2", "rimraf": "^5.0.1" } }, "sha512-YGGyuEdVIjqxkxVH1pUTMY/XtmmsApXrCVv5EU25iX6inEPbV+VakJfLealkBtJN69AQmh1eGOdCl9Sm1UP6XQ=="],"@activepieces/piece-google-sheets/google-auth-library/gcp-metadata": ["[email protected]", "", { "dependencies": { "gaxios": "^7.0.0", "google-logging-utils": "^1.0.0", "json-bigint": "^1.0.0" } }, "sha512-zV/5HKTfCeKWnxG0Dmrw51hEWFGfcF2xiXqcA3+J90WDuP0SvoiSO5ORvcBsifmx/FoIjgQN3oNOGaQ5PhLFkg=="],@@ -22208,10 +22195,6 @@"@activepieces/piece-google-forms/google-auth-library/jws/jwa": ["[email protected]", "", { "dependencies": { "buffer-equal-constant-time": "^1.0.1", "ecdsa-sig-formatter": "1.0.11", "safe-buffer": "^5.0.1" } }, "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg=="],- "@activepieces/piece-google-search-console/google-auth-library/gaxios/node-fetch": ["[email protected]", "", { "dependencies": { "data-uri-to-buffer": "^4.0.0", "fetch-blob": "^3.1.4", "formdata-polyfill": "^4.0.10" } }, "sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA=="],-- "@activepieces/piece-google-search-console/google-auth-library/jws/jwa": ["[email protected]", "", { "dependencies": { "buffer-equal-constant-time": "^1.0.1", "ecdsa-sig-formatter": "1.0.11", "safe-buffer": "^5.0.1" } }, "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg=="],-"@activepieces/piece-google-sheets/google-auth-library/gaxios/node-fetch": ["[email protected]", "", { "dependencies": { "data-uri-to-buffer": "^4.0.0", "fetch-blob": "^3.1.4", "formdata-polyfill": "^4.0.10" } }, "sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA=="],"@activepieces/piece-google-sheets/google-auth-library/jws/jwa": ["[email protected]", "", { "dependencies": { "buffer-equal-constant-time": "^1.0.1", "ecdsa-sig-formatter": "1.0.11", "safe-buffer": "^5.0.1" } }, "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg=="],diff --git a/packages/pieces/community/google-search-console/package.json b/packages/pieces/community/google-search-console/package.jsonindex 29283107936..56b2da736be 100644--- a/packages/pieces/community/google-search-console/package.json+++ b/packages/pieces/community/google-search-console/package.json@@ -1,23 +1,23 @@{"name": "@activepieces/piece-google-search-console",- "version": "0.3.1",+ "version": "0.4.0","main": "./dist/src/index.js","types": "./dist/src/index.d.ts","dependencies": {"@activepieces/pieces-common": "workspace:*","@activepieces/pieces-framework": "workspace:*",- "@googleapis/webmasters": "2.0.1",- "dayjs": "1.11.9",- "google-auth-library": "10.5.0","@activepieces/core-piece-types": "workspace:*",- "@activepieces/core-utils": "workspace:*"+ "@activepieces/core-utils": "workspace:*",+ "undici": "7.29.1"},"devDependencies": {- "tslib": "2.6.2"+ "tslib": "2.6.2",+ "vitest": "3.2.6"},"scripts": {"build": "tsc -p tsconfig.lib.json && cp package.json dist/","bundle": "node ../../../../dist/packages/cli/src/index.js pieces bundle",- "lint": "eslint 'src/**/*.ts'"+ "lint": "eslint 'src/**/*.ts'",+ "test": "vitest run"}}diff --git a/packages/pieces/community/google-search-console/src/i18n/translation.json b/packages/pieces/community/google-search-console/src/i18n/translation.jsonindex 935037e1eff..58c0b8cf6f5 100644--- a/packages/pieces/community/google-search-console/src/i18n/translation.json+++ b/packages/pieces/community/google-search-console/src/i18n/translation.json@@ -1,20 +1,39 @@{- "\n 1. Sign in to [Google Cloud Console](https://console.cloud.google.com/).\n 2. Create a new project or you can use existing one.\n 3. Go to **APIs & Services** and click **Enable APIs & Services**.\n 4. Search for **Google Search Console API** in the search bar and enable it.\n 5. Go to **OAuth consent screen** and select **External** type and click create.\n 6. Fill App Name, User Support Email, and Developer Contact Information. Click on the Save and Continue button.\n 7. Click on **Add or Remove Scopes": "\n 1. Sign in to [Google Cloud Console](https://console.cloud.google.com/).\n 2. Create a new project or you can use existing one.\n 3. Go to **APIs & Services** and click **Enable APIs & Services**.\n 4. Search for **Google Search Console API** in the search bar and enable it.\n 5. Go to **OAuth consent screen** and select **External** type and click create.\n 6. Fill App Name, User Support Email, and Developer Contact Information. Click on the Save and Continue button.\n 7. Click on **Add or Remove Scopes** and add following scopes and click update.\n - https://www.googleapis.com/auth/webmasters\n 8. Click Save and Continue to finish the Scopes step.\n 9. Click on the Add Users button and add a test email You can add your own email)\n.Then finally click Save and Continue to finish the Test Users portion.\n 10. Go to **Credentials**. Click on the **Create Credentials** button and select the **OAuth client ID** option.\n 11. Select the application type as **Web Application** and fill the Name field.\n 12. Add https://cloud.activepieces.com/redirect in **Authorized redirect URIs** field, and click on the Create button.\n 13. Copy **Client ID** and **Client Secret**.",+ "Monitor your site's Google Search traffic, sitemaps and index status.": "Monitor your site's Google Search traffic, sitemaps and index status.",+ "\n 1. Sign in to [Google Cloud Console](https://console.cloud.google.com/) and create a project, or pick an existing one.\n 2. Go to **APIs & Services > Library**, search for **Google Search Console API** and click **Enable**. It must be enabled in the same project as the OAuth client you create below.\n 3. Go to **OAuth consent screen**, choose **External**, fill in the app name and the support and developer emails, and save.\n 4. In **Scopes** (Data access), add `https://www.googleapis.com/auth/webmasters": "\n 1. Sign in to [Google Cloud Console](https://console.cloud.google.com/) and create a project, or pick an existing one.\n 2. Go to **APIs & Services > Library**, search for **Google Search Console API** and click **Enable**. It must be enabled in the same project as the OAuth client you create below.\n 3. Go to **OAuth consent screen**, choose **External**, fill in the app name and the support and developer emails, and save.\n 4. In **Scopes** (Data access), add `https://www.googleapis.com/auth/webmasters` and `email`, then save.\n 5. While the app is in **Testing**, add the Google account you will connect under **Test users**. Tokens of apps in Testing expire after 7 days; publish the app to avoid reconnecting.\n 6. Go to **Credentials > Create Credentials > OAuth client ID** and choose **Web application**.\n 7. Under **Authorized redirect URIs**, add the Redirect URL shown in this dialog, then click **Create**.\n 8. Copy the **Client ID** and **Client Secret** into the fields below.","Search Analytics": "Search Analytics",+ "Search Analytics (by Site URL)": "Search Analytics (by Site URL)","List Sitemaps": "List Sitemaps",+ "List Sitemaps (by Site URL)": "List Sitemaps (by Site URL)",+ "Get Sitemap": "Get Sitemap","Submit a Sitemap": "Submit a Sitemap",+ "Submit Sitemap (by Site URL)": "Submit Sitemap (by Site URL)",+ "Delete a Sitemap": "Delete a Sitemap",+ "Delete Sitemap (by Site URL)": "Delete Sitemap (by Site URL)","List Sites": "List Sites",+ "Get Site": "Get Site","Add a Site": "Add a Site","Delete a Site": "Delete a Site",+ "Delete Site (by Site URL)": "Delete Site (by Site URL)","URL Inspection": "URL Inspection",+ "Inspect URL (by Site URL)": "Inspect URL (by Site URL)","Custom API Call": "Custom API Call","Query traffic data for your site using the Google Search Console API.": "Query traffic data for your site using the Google Search Console API.",+ "Queries search traffic (clicks, impressions, CTR, position) for a property.": "Queries search traffic (clicks, impressions, CTR, position) for a property.","List all your sitemaps for a given site": "List all your sitemaps for a given site",+ "Lists the sitemaps submitted for a property.": "Lists the sitemaps submitted for a property.",+ "Gets the status of one submitted sitemap.": "Gets the status of one submitted sitemap.","Submits a sitemap for a site.": "Submits a sitemap for a site.",+ "Submits a sitemap for a property.": "Submits a sitemap for a property.",+ "Removes a sitemap from the Sitemaps report of a site.": "Removes a sitemap from the Sitemaps report of a site.",+ "Removes a sitemap from the Sitemaps report of a property.": "Removes a sitemap from the Sitemaps report of a property.","Lists the user's Search Console sites.": "Lists the user's Search Console sites.",+ "Gets the permission level of one Search Console property.": "Gets the permission level of one Search Console property.","Adds a site to the set of the user's sites in Search Console.": "Adds a site to the set of the user's sites in Search Console.","Removes a site from the set of the user's Search Console sites.": "Removes a site from the set of the user's Search Console sites.",+ "Removes a property from the user's Search Console sites.": "Removes a property from the user's Search Console sites.","Use the URL Inspection action to check the status and presence of a specific page within Google's index.": "Use the URL Inspection action to check the status and presence of a specific page within Google's index.",+ "Checks the status of one page in Google's index.": "Checks the status of one page in Google's index.","Make a custom API call to a specific endpoint": "Make a custom API call to a specific endpoint","Site URL": "Site URL","Start Date": "Start Date",@@ -23,29 +42,58 @@"Search Type": "Search Type","Filters": "Filters","Aggregation Type": "Aggregation Type",+ "Data State": "Data State","Row Limit": "Row Limit","Start Row": "Start Row",+ "Last N Days": "Last N Days",+ "Sitemap Index URL": "Sitemap Index URL",+ "Sitemap URL": "Sitemap URL","Sitemap Path": "Sitemap Path",+ "Sitemap": "Sitemap","URL to Inspect": "URL to Inspect",+ "Language Code": "Language Code","Method": "Method","Headers": "Headers","Query Parameters": "Query Parameters","Body Type": "Body Type","Body": "Body",- "Response is Binary ?": "Response is Binary ?",- "No Error on Failure": "No Error on Failure",- "Timeout (in seconds)": "Timeout (in seconds)",+ "Response is Binary": "Response is Binary",+ "Return Error as Output": "Return Error as Output",+ "Timeout": "Timeout","Follow redirects": "Follow redirects",- "The start date of the date range to query (in YYYY-MM-DD format).": "The start date of the date range to query (in YYYY-MM-DD format).",- "The end date of the date range to query (in YYYY-MM-DD format).": "The end date of the date range to query (in YYYY-MM-DD format).",- "The dimensions to group results by. Valid values: \"query\", \"page\", \"country\", \"device\", \"searchAppearance\", \"date\", \"hour\".": "The dimensions to group results by. Valid values: \"query\", \"page\", \"country\", \"device\", \"searchAppearance\", \"date\", \"hour\".",- "Filter results by search type. Defaults to \"web\".": "Filter results by search type. Defaults to \"web\".",- "Optional filters to apply to the data. All filters are AND-ed together.": "Optional filters to apply to the data. All filters are AND-ed together.",- "How data is aggregated. Defaults to \"auto\".": "How data is aggregated. Defaults to \"auto\".",- "The maximum number of rows to return. Min: 1, Max: 5,000. Defaults to 1,000.": "The maximum number of rows to return. Min: 1, Max: 5,000. Defaults to 1,000.",- "Zero-based index of the first row to return. Use with Row Limit to paginate results. Defaults to 0.": "Zero-based index of the first row to return. Use with Row Limit to paginate results. Defaults to 0.",+ "The Search Console property. Only properties you have verified access to are listed.": "The Search Console property. Only properties you have verified access to are listed.",+ "First day of the range (YYYY-MM-DD), in Pacific Time. Search Console data lags 2-3 days and is kept for about 16 months.": "First day of the range (YYYY-MM-DD), in Pacific Time. Search Console data lags 2-3 days and is kept for about 16 months.",+ "Last day of the range (YYYY-MM-DD, inclusive), in Pacific Time. A range that covers only today or yesterday usually has no data yet.": "Last day of the range (YYYY-MM-DD, inclusive), in Pacific Time. A range that covers only today or yesterday usually has no data yet.",+ "The dimensions to group results by, in order. Valid values: \"query\", \"page\", \"country\", \"device\", \"searchAppearance\", \"date\", \"hour\". Each row of the output gets one column per dimension.": "The dimensions to group results by, in order. Valid values: \"query\", \"page\", \"country\", \"device\", \"searchAppearance\", \"date\", \"hour\". Each row of the output gets one column per dimension.",+ "The Google surface to report on. Defaults to \"web\". Discover and Google News have no search queries.": "The Google surface to report on. Defaults to \"web\". Discover and Google News have no search queries.",+ "Optional filters. All filters are combined with AND.": "Optional filters. All filters are combined with AND.",+ "How results are aggregated. Defaults to \"auto\". \"byProperty\" cannot be used with the page dimension or a page filter.": "How results are aggregated. Defaults to \"auto\". \"byProperty\" cannot be used with the page dimension or a page filter.",+ "Which data to include. \"final\" (default) has only finalized data; \"all\" adds fresh, still-changing data from the last days; \"hourly_all\" is required for the hour dimension and is selected automatically when you group by hour.": "Which data to include. \"final\" (default) has only finalized data; \"all\" adds fresh, still-changing data from the last days; \"hourly_all\" is required for the hour dimension and is selected automatically when you group by hour.",+ "The maximum number of rows to return, from 1 to 25,000. Defaults to 1,000.": "The maximum number of rows to return, from 1 to 25,000. Defaults to 1,000.",+ "Zero-based index of the first row to return. Use with Row Limit to page through results. Defaults to 0.": "Zero-based index of the first row to return. Use with Row Limit to page through results. Defaults to 0.",+ "The Search Console property exactly as List Sites returns it: a URL-prefix property ends with \"/\" (e.g. \"https://www.example.com/\"), a domain property starts with \"sc-domain:\" (e.g. \"sc-domain:example.com\").": "The Search Console property exactly as List Sites returns it: a URL-prefix property ends with \"/\" (e.g. \"https://www.example.com/\"), a domain property starts with \"sc-domain:\" (e.g. \"sc-domain:example.com\").",+ "Number of days ending yesterday (Pacific Time), from 1 to 500. Used when Start Date is empty; defaults to 28. Do not combine with Start Date/End Date.": "Number of days ending yesterday (Pacific Time), from 1 to 500. Used when Start Date is empty; defaults to 28. Do not combine with Start Date/End Date.",+ "First day of the range, YYYY-MM-DD (Pacific Time). Leave empty to use Last N Days.": "First day of the range, YYYY-MM-DD (Pacific Time). Leave empty to use Last N Days.",+ "Last day of the range (inclusive), YYYY-MM-DD (Pacific Time). Defaults to yesterday when Start Date is set.": "Last day of the range (inclusive), YYYY-MM-DD (Pacific Time). Defaults to yesterday when Start Date is set.",+ "Group results by these dimensions, in this order. Leave empty for one totals row. \"hour\" covers only the last few days.": "Group results by these dimensions, in this order. Leave empty for one totals row. \"hour\" covers only the last few days.",+ "Maximum rows to return, from 1 to 1000. Defaults to 100.": "Maximum rows to return, from 1 to 1000. Defaults to 100.",+ "Zero-based index of the first row; pass next_start_row from the previous call to get the next page. Defaults to 0.": "Zero-based index of the first row; pass next_start_row from the previous call to get the next page. Defaults to 0.",+ "Optional. The full URL of a sitemap index to list only the sitemaps inside it.": "Optional. The full URL of a sitemap index to list only the sitemaps inside it.",+ "Optional. The full URL of a sitemap index; only the sitemaps inside it are listed.": "Optional. The full URL of a sitemap index; only the sitemaps inside it are listed.",+ "The full URL of the sitemap, e.g. \"https://www.example.com/sitemap.xml\".": "The full URL of the sitemap, e.g. \"https://www.example.com/sitemap.xml\".",+ "A sitemap submitted to the selected property.": "A sitemap submitted to the selected property.",+ "A URL-prefix property such as \"https://www.example.com/\" (a missing trailing slash is added) or a domain property such as \"sc-domain:example.com\".": "A URL-prefix property such as \"https://www.example.com/\" (a missing trailing slash is added) or a domain property such as \"sc-domain:example.com\".",+ "The Search Console property. Unverified properties are listed too.": "The Search Console property. Unverified properties are listed too.",+ "The full URL of the page. It must belong to the selected property.": "The full URL of the page. It must belong to the selected property.",+ "Optional language for the issue messages, as a BCP-47 code such as \"en-US\" or \"de\". Defaults to English.": "Optional language for the issue messages, as a BCP-47 code such as \"en-US\" or \"de\". Defaults to English.",+ "The full URL of the page. It must belong to the property (same protocol and host, under the property path, or any subdomain of a domain property).": "The full URL of the page. It must belong to the property (same protocol and host, under the property path, or any subdomain of a domain property).",+ "Optional BCP-47 language for issue messages, e.g. \"en-US\". Defaults to English.": "Optional BCP-47 language for issue messages, e.g. \"en-US\". Defaults to English.","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.","Web": "Web","Discover": "Discover","Google News": "Google News",@@ -56,14 +104,20 @@"By Page": "By Page","By Property": "By Property","By News Showcase Panel": "By News Showcase Panel",+ "final": "final",+ "all": "all",+ "hourly_all": "hourly_all",+ "date": "date",+ "hour": "hour",+ "query": "query",+ "page": "page",+ "country": "country",+ "device": "device",+ "searchAppearance": "searchAppearance","GET": "GET","POST": "POST","PATCH": "PATCH","PUT": "PUT","DELETE": "DELETE",- "HEAD": "HEAD",- "None": "None",- "JSON": "JSON",- "Form Data": "Form Data",- "Raw": "Raw"+ "HEAD": "HEAD"}\ No newline at end of filediff --git a/packages/pieces/community/google-search-console/src/index.ts b/packages/pieces/community/google-search-console/src/index.tsindex 7731dc00063..5e4c1d73718 100644--- a/packages/pieces/community/google-search-console/src/index.ts+++ b/packages/pieces/community/google-search-console/src/index.ts@@ -1,43 +1,55 @@-import { createPiece, OAuth2PropertyValue, PieceAuth } from '@activepieces/pieces-framework';-import { webmasters as googleWebmasters } from '@googleapis/webmasters';-import { OAuth2Client } from 'google-auth-library';-import { urlInspection } from './lib/actions/url-inspection';-import { searchAnalytics } from './lib/actions/search-analytics';-import { listSitemaps } from './lib/actions/list-sitemaps';-import { submitSitemap } from './lib/actions/submit-a-sitemap';-import { listSites } from './lib/actions/list-sites';+import { createCustomApiCallAction } from '@activepieces/pieces-common';+import { createPiece, PieceCategory } from '@activepieces/pieces-framework';import { addSite } from './lib/actions/add-a-site';+import { deleteSiteBySiteUrl } from './lib/actions/ai/delete-site-by-site-url';+import { deleteSitemapBySiteUrl } from './lib/actions/ai/delete-sitemap-by-site-url';+import { getSite } from './lib/actions/ai/get-site';+import { getSitemap } from './lib/actions/ai/get-sitemap';+import { inspectUrlBySiteUrl } from './lib/actions/ai/inspect-url-by-site-url';+import { listSitemapsBySiteUrl } from './lib/actions/ai/list-sitemaps-by-site-url';+import { searchAnalyticsBySiteUrl } from './lib/actions/ai/search-analytics-by-site-url';+import { submitSitemapBySiteUrl } from './lib/actions/ai/submit-sitemap-by-site-url';import { deleteSite } from './lib/actions/delete-a-site';-import { createCustomApiCallAction } from '@activepieces/pieces-common';+import { deleteSitemap } from './lib/actions/delete-a-sitemap';+import { listSitemaps } from './lib/actions/list-sitemaps';+import { listSites } from './lib/actions/list-sites';+import { searchAnalytics } from './lib/actions/search-analytics';+import { submitSitemap } from './lib/actions/submit-a-sitemap';+import { urlInspection } from './lib/actions/url-inspection';import { googleSearchConsoleAuth } from './lib/auth';-export const createAuthClient = (accessToken: string) => {- const auth = new OAuth2Client();- auth.setCredentials({ access_token: accessToken });- return googleWebmasters({ version: 'v3', auth });-};-export const googleSearchConsolePiece = createPiece({displayName: 'Google Search Console',- minimumSupportedRelease: '0.30.0',+ description: "Monitor your site's Google Search traffic, sitemaps and index status.",+ minimumSupportedRelease: '0.88.2',auth: googleSearchConsoleAuth,logoUrl: 'https://cdn.activepieces.com/pieces/google-search-console.png',- authors: ['Gushkool','kishanprmr','itsishant','sanket-a11y'],+ categories: [PieceCategory.MARKETING],+ authors: ['Gushkool', 'kishanprmr', 'itsishant', 'sanket-a11y'],triggers: [],actions: [searchAnalytics,+ searchAnalyticsBySiteUrl,listSitemaps,+ listSitemapsBySiteUrl,+ getSitemap,submitSitemap,+ submitSitemapBySiteUrl,+ deleteSitemap,+ deleteSitemapBySiteUrl,listSites,+ getSite,addSite,deleteSite,+ deleteSiteBySiteUrl,urlInspection,+ inspectUrlBySiteUrl,createCustomApiCallAction({baseUrl: () => 'https://www.googleapis.com/webmasters/v3',auth: googleSearchConsoleAuth,authMapping: async (auth) => ({- Authorization: `Bearer ${(auth).access_token}`,+ Authorization: `Bearer ${auth.access_token}`,}),}),],-});\ No newline at end of file+});diff --git a/packages/pieces/community/google-search-console/src/lib/actions/add-a-site.ts b/packages/pieces/community/google-search-console/src/lib/actions/add-a-site.tsindex 062e0165081..83f7500698c 100644--- a/packages/pieces/community/google-search-console/src/lib/actions/add-a-site.ts+++ b/packages/pieces/community/google-search-console/src/lib/actions/add-a-site.ts@@ -1,6 +1,8 @@import { createAction, Property } from '@activepieces/pieces-framework';import { googleSearchConsoleAuth } from '../auth';-import { createAuthClient } from '../../';+import { gscInputs } from '../common/inputs';+import { gscOps } from '../common/operations';+import { gscOutputSchemas } from '../output-schemas';export const addSite = createAction({auth: googleSearchConsoleAuth,@@ -9,18 +11,22 @@ export const addSite = createAction({displayName: 'Add a Site',description: "Adds a site to the set of the user's sites in Search Console.",audience: 'both',- aiMetadata: { description: "Add a site to the authenticated user's Google Search Console account so it can be managed and (after separate verification) monitored. Choose this when onboarding a new property. Requires the exact siteUrl (a URL-prefix property like 'https://example.com/' or a 'sc-domain:' property). Mutating, but adding an already-present site is effectively a no-op rather than a duplicate.", idempotent: false },+ aiMetadata: {+ description:+ "Adds a property to the connected account's Search Console. The property stays unverified (permission siteUnverifiedUser) until someone verifies ownership in the Search Console UI; the API cannot verify it, and unverified properties return no data. Adding a property that is already there changes nothing, so it is safe to retry.",+ idempotent: true,+ },props: {siteUrl: Property.ShortText({displayName: 'Site URL',+ description:+ 'A URL-prefix property such as "https://www.example.com/" (a missing trailing slash is added) or a domain property such as "sc-domain:example.com".',required: true,}),},+ outputSchema: gscOutputSchemas.addSite,async run(context) {- const webmasters = createAuthClient(context.auth.access_token);- await webmasters.sites.add({- siteUrl: context.propsValue.siteUrl,- });- return { success: true };+ const siteUrl = gscInputs.siteUrl({ value: context.propsValue.siteUrl });+ return gscOps.addSite({ auth: context.auth, siteUrl });},});diff --git a/packages/pieces/community/google-search-console/src/lib/actions/ai/delete-site-by-site-url.ts b/packages/pieces/community/google-search-console/src/lib/actions/ai/delete-site-by-site-url.tsnew file mode 100644index 00000000000..257adc1dc1d--- /dev/null+++ b/packages/pieces/community/google-search-console/src/lib/actions/ai/delete-site-by-site-url.ts@@ -0,0 +1,29 @@+import { createAction } from '@activepieces/pieces-framework';+import { googleSearchConsoleAuth } from '../../auth';+import { commonProps } from '../../common';+import { gscInputs } from '../../common/inputs';+import { gscOps } from '../../common/operations';+import { gscOutputSchemas } from '../../output-schemas';++export const deleteSiteBySiteUrl = createAction({+ auth: googleSearchConsoleAuth,+ name: 'delete_site_by_site_url',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete Site (by Site URL)',+ description: "Removes a property from the user's Search Console sites.",+ audience: 'ai',+ aiMetadata: {+ description:+ "Removes a property from the connected account's Search Console list. Only this account loses it; other owners and the collected data are not affected, but a verified property must be verified again to come back. Confirm with the user first. A second call for the same property fails.",+ idempotent: false,+ },+ props: {+ site_url: commonProps.aiSiteUrl(),+ },+ outputSchema: gscOutputSchemas.deleteSiteAi,+ async run(context) {+ const siteUrl = gscInputs.siteUrl({ value: context.propsValue.site_url });+ await gscOps.deleteSite({ auth: context.auth, siteUrl });+ return { success: true, site_url: siteUrl };+ },+});diff --git a/packages/pieces/community/google-search-console/src/lib/actions/ai/delete-sitemap-by-site-url.ts b/packages/pieces/community/google-search-console/src/lib/actions/ai/delete-sitemap-by-site-url.tsnew file mode 100644index 00000000000..1f8cc3e2e26--- /dev/null+++ b/packages/pieces/community/google-search-console/src/lib/actions/ai/delete-sitemap-by-site-url.ts@@ -0,0 +1,31 @@+import { createAction } from '@activepieces/pieces-framework';+import { googleSearchConsoleAuth } from '../../auth';+import { commonProps } from '../../common';+import { gscInputs } from '../../common/inputs';+import { gscOps } from '../../common/operations';+import { gscOutputSchemas } from '../../output-schemas';++export const deleteSitemapBySiteUrl = createAction({+ auth: googleSearchConsoleAuth,+ name: 'delete_sitemap_by_site_url',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete Sitemap (by Site URL)',+ description: 'Removes a sitemap from the Sitemaps report of a property.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Removes a submitted sitemap from the Sitemaps report of a property. Google may keep crawling the sitemap and its URLs; resubmitting restores the entry. Needs siteOwner or siteFullUser permission; confirm with the user first. Deleting a sitemap that is already gone also succeeds, so it is safe to retry.',+ idempotent: true,+ },+ props: {+ site_url: commonProps.aiSiteUrl(),+ feedpath: commonProps.feedpathText(),+ },+ outputSchema: gscOutputSchemas.sitemapChangeAi,+ async run(context) {+ const siteUrl = gscInputs.siteUrl({ value: context.propsValue.site_url });+ const feedpath = gscInputs.absoluteUrl({ value: context.propsValue.feedpath, label: 'Sitemap URL' });+ await gscOps.deleteSitemap({ auth: context.auth, siteUrl, feedpath });+ return { success: true, site_url: siteUrl, feedpath };+ },+});diff --git a/packages/pieces/community/google-search-console/src/lib/actions/ai/get-site.ts b/packages/pieces/community/google-search-console/src/lib/actions/ai/get-site.tsnew file mode 100644index 00000000000..a291465272c--- /dev/null+++ b/packages/pieces/community/google-search-console/src/lib/actions/ai/get-site.ts@@ -0,0 +1,30 @@+import { createAction } from '@activepieces/pieces-framework';+import { googleSearchConsoleAuth } from '../../auth';+import { commonProps } from '../../common';+import { gscInputs } from '../../common/inputs';+import { gscOps } from '../../common/operations';+import { gscShape } from '../../common/shape';+import { gscOutputSchemas } from '../../output-schemas';++export const getSite = createAction({+ auth: googleSearchConsoleAuth,+ name: 'get_site',+ classification: 'READ',+ displayName: 'Get Site',+ description: 'Gets the permission level of one Search Console property.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Reads one Search Console property by its exact Site URL and reports the permission level and whether it is verified. Use it to check access before reading data or changing sitemaps (that needs siteOwner or siteFullUser); use List Sites to discover properties. Read-only and safe to retry.',+ idempotent: true,+ },+ props: {+ site_url: commonProps.aiSiteUrl(),+ },+ outputSchema: gscOutputSchemas.getSite,+ async run(context) {+ const siteUrl = gscInputs.siteUrl({ value: context.propsValue.site_url });+ const site = await gscOps.getSite({ auth: context.auth, siteUrl });+ return gscShape.siteFlat(site);+ },+});diff --git a/packages/pieces/community/google-search-console/src/lib/actions/ai/get-sitemap.ts b/packages/pieces/community/google-search-console/src/lib/actions/ai/get-sitemap.tsnew file mode 100644index 00000000000..be313e8d1b3--- /dev/null+++ b/packages/pieces/community/google-search-console/src/lib/actions/ai/get-sitemap.ts@@ -0,0 +1,31 @@+import { createAction } from '@activepieces/pieces-framework';+import { googleSearchConsoleAuth } from '../../auth';+import { commonProps } from '../../common';+import { gscInputs } from '../../common/inputs';+import { gscOps } from '../../common/operations';+import { gscShape } from '../../common/shape';+import { gscOutputSchemas } from '../../output-schemas';++export const getSitemap = createAction({+ auth: googleSearchConsoleAuth,+ name: 'get_sitemap',+ classification: 'READ',+ displayName: 'Get Sitemap',+ description: 'Gets the status of one submitted sitemap.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Reads the health of one submitted sitemap by its URL: errors, warnings, pending state, last submitted and downloaded times, and submitted URL counts. Use List Sitemaps (by Site URL) when the sitemap URL is unknown. Read-only and safe to retry.',+ idempotent: true,+ },+ props: {+ site_url: commonProps.aiSiteUrl(),+ feedpath: commonProps.feedpathText(),+ },+ outputSchema: gscOutputSchemas.getSitemap,+ async run(context) {+ const siteUrl = gscInputs.siteUrl({ value: context.propsValue.site_url });+ const feedpath = gscInputs.absoluteUrl({ value: context.propsValue.feedpath, label: 'Sitemap URL' });+ return gscShape.sitemapFlat(await gscOps.getSitemap({ auth: context.auth, siteUrl, feedpath }));+ },+});diff --git a/packages/pieces/community/google-search-console/src/lib/actions/ai/inspect-url-by-site-url.ts b/packages/pieces/community/google-search-console/src/lib/actions/ai/inspect-url-by-site-url.tsnew file mode 100644index 00000000000..ecc3758b948--- /dev/null+++ b/packages/pieces/community/google-search-console/src/lib/actions/ai/inspect-url-by-site-url.ts@@ -0,0 +1,42 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { googleSearchConsoleAuth } from '../../auth';+import { commonProps } from '../../common';+import { gscInputs } from '../../common/inputs';+import { gscOps } from '../../common/operations';+import { gscShape } from '../../common/shape';+import { gscOutputSchemas } from '../../output-schemas';++export const inspectUrlBySiteUrl = createAction({+ auth: googleSearchConsoleAuth,+ name: 'inspect_url_by_site_url',+ classification: 'READ',+ displayName: 'Inspect URL (by Site URL)',+ description: "Checks the status of one page in Google's index.",+ audience: 'ai',+ aiMetadata: {+ description:+ "Reports Google's index status of one page in a property: verdict, coverage, last crawl, canonicals, robots.txt and rich result issues. Use it to diagnose why a specific page is or is not indexed. Limited to 2,000 inspections per property per day, so do not loop over a whole site. Read-only and safe to retry.",+ idempotent: true,+ },+ props: {+ site_url: commonProps.aiSiteUrl(),+ inspection_url: Property.ShortText({+ displayName: 'URL to Inspect',+ description: 'The full URL of the page. It must belong to the property (same protocol and host, under the property path, or any subdomain of a domain property).',+ required: true,+ }),+ language_code: Property.ShortText({+ displayName: 'Language Code',+ description: 'Optional BCP-47 language for issue messages, e.g. "en-US". Defaults to English.',+ required: false,+ }),+ },+ outputSchema: gscOutputSchemas.inspectUrlAi,+ async run(context) {+ const siteUrl = gscInputs.siteUrl({ value: context.propsValue.site_url });+ const inspectionUrl = gscInputs.urlInProperty({ value: context.propsValue.inspection_url, label: 'URL to Inspect', site: siteUrl });+ const languageCode = gscInputs.languageCode({ value: context.propsValue.language_code });+ const body = await gscOps.inspectUrl({ auth: context.auth, siteUrl, inspectionUrl, languageCode });+ return gscShape.inspection({ body, inspectedUrl: inspectionUrl });+ },+});diff --git a/packages/pieces/community/google-search-console/src/lib/actions/ai/list-sitemaps-by-site-url.ts b/packages/pieces/community/google-search-console/src/lib/actions/ai/list-sitemaps-by-site-url.tsnew file mode 100644index 00000000000..ac7be0846ef--- /dev/null+++ b/packages/pieces/community/google-search-console/src/lib/actions/ai/list-sitemaps-by-site-url.ts@@ -0,0 +1,36 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { googleSearchConsoleAuth } from '../../auth';+import { commonProps } from '../../common';+import { gscInputs } from '../../common/inputs';+import { gscOps } from '../../common/operations';+import { gscShape } from '../../common/shape';+import { gscOutputSchemas } from '../../output-schemas';++export const listSitemapsBySiteUrl = createAction({+ auth: googleSearchConsoleAuth,+ name: 'list_sitemaps_by_site_url',+ classification: 'SEARCH',+ displayName: 'List Sitemaps (by Site URL)',+ description: 'Lists the sitemaps submitted for a property.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists the sitemaps submitted for a property with their health: errors, warnings, pending state, last download and submitted URL counts. Use Get Sitemap when you already know the sitemap URL; pass sitemap_index to list the children of a sitemap index. Read-only and safe to retry.',+ idempotent: true,+ },+ props: {+ site_url: commonProps.aiSiteUrl(),+ sitemap_index: Property.ShortText({+ displayName: 'Sitemap Index URL',+ description: 'Optional. The full URL of a sitemap index; only the sitemaps inside it are listed.',+ required: false,+ }),+ },+ outputSchema: gscOutputSchemas.listSitemapsAi,+ async run(context) {+ const siteUrl = gscInputs.siteUrl({ value: context.propsValue.site_url });+ const sitemapIndex = context.propsValue.sitemap_index ? gscInputs.absoluteUrl({ value: context.propsValue.sitemap_index, label: 'Sitemap Index URL' }) : undefined;+ const sitemaps = (await gscOps.listSitemaps({ auth: context.auth, siteUrl, sitemapIndex })).map(gscShape.sitemapFlat);+ return { sitemaps, count: sitemaps.length };+ },+});diff --git a/packages/pieces/community/google-search-console/src/lib/actions/ai/search-analytics-by-site-url.ts b/packages/pieces/community/google-search-console/src/lib/actions/ai/search-analytics-by-site-url.tsnew file mode 100644index 00000000000..c8ccbed3d5e--- /dev/null+++ b/packages/pieces/community/google-search-console/src/lib/actions/ai/search-analytics-by-site-url.ts@@ -0,0 +1,98 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { googleSearchConsoleAuth } from '../../auth';+import { commonProps } from '../../common';+import { gscInputs } from '../../common/inputs';+import { gscOps } from '../../common/operations';+import { gscOutputSchemas } from '../../output-schemas';++const AI_DEFAULT_ROW_LIMIT = 100;+const AI_MAX_ROW_LIMIT = 1000;++export const searchAnalyticsBySiteUrl = createAction({+ auth: googleSearchConsoleAuth,+ name: 'search_analytics_by_site_url',+ classification: 'SEARCH',+ displayName: 'Search Analytics (by Site URL)',+ description: 'Queries search traffic (clicks, impressions, CTR, position) for a property.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Returns Google Search clicks, impressions, CTR (0-1) and average position for a property, grouped by up to seven dimensions (date, hour, query, page, country, device, searchAppearance). Dates are Pacific Time, data lags 2-3 days and is kept about 16 months; rows without impressions are usually left out (position is null when a row has no impressions). Prefer last_n_days for "last week/month"; page with next_start_row while has_more is true. Read-only and safe to retry.',+ idempotent: true,+ },+ props: {+ site_url: commonProps.aiSiteUrl(),+ last_n_days: Property.Number({+ displayName: 'Last N Days',+ description: 'Number of days ending yesterday (Pacific Time), from 1 to 500. Used when Start Date is empty; defaults to 28. Do not combine with Start Date/End Date.',+ required: false,+ }),+ start_date: Property.ShortText({+ displayName: 'Start Date',+ description: 'First day of the range, YYYY-MM-DD (Pacific Time). Leave empty to use Last N Days.',+ required: false,+ }),+ end_date: Property.ShortText({+ displayName: 'End Date',+ description: 'Last day of the range (inclusive), YYYY-MM-DD (Pacific Time). Defaults to yesterday when Start Date is set.',+ required: false,+ }),+ dimensions: commonProps.dimensionsMulti(),+ search_type: commonProps.searchType(),+ filters: commonProps.filters(),+ aggregation_type: commonProps.aggregationType(),+ data_state: commonProps.dataState(),+ row_limit: Property.Number({+ displayName: 'Row Limit',+ description: `Maximum rows to return, from 1 to ${AI_MAX_ROW_LIMIT}. Defaults to ${AI_DEFAULT_ROW_LIMIT}.`,+ required: false,+ }),+ start_row: Property.Number({+ displayName: 'Start Row',+ description: 'Zero-based index of the first row; pass next_start_row from the previous call to get the next page. Defaults to 0.',+ required: false,+ }),+ },+ outputSchema: gscOutputSchemas.searchAnalyticsAi,+ async run(context) {+ const props = context.propsValue;+ const siteUrl = gscInputs.siteUrl({ value: props.site_url });+ const { startDate, endDate } = gscInputs.dateRange({ startDate: props.start_date, endDate: props.end_date, lastNDays: props.last_n_days });+ const rowLimit = gscInputs.optionalInteger({ value: props.row_limit, label: 'Row Limit', min: 1, max: AI_MAX_ROW_LIMIT }) ?? AI_DEFAULT_ROW_LIMIT;+ const startRow = gscInputs.optionalInteger({ value: props.start_row, label: 'Start Row', min: 0, max: gscInputs.MAX_START_ROW }) ?? 0;+ const query = gscInputs.analyticsQuery({+ startDate,+ endDate,+ dimensions: gscInputs.dimensions({ value: props.dimensions }),+ searchType: props.search_type,+ filters: gscInputs.filters({ value: props.filters }),+ aggregationType: props.aggregation_type,+ dataState: props.data_state,+ rowLimit,+ startRow,+ });+ const result = await gscOps.searchAnalytics({ auth: context.auth, siteUrl, query });+ const metadata = result.data['metadata'];+ const hasMore = result.rows.length === rowLimit;+ return {+ rows: result.rows,+ row_count: result.rows.length,+ has_more: hasMore,+ next_start_row: hasMore ? startRow + result.rows.length : null,+ start_date: startDate,+ end_date: endDate,+ data_state: query.dataState ?? 'final',+ aggregation_type: typeof result.data['responseAggregationType'] === 'string' ? result.data['responseAggregationType'] : null,+ first_incomplete_date: readMetadata({ metadata, key: 'firstIncompleteDate' }),+ first_incomplete_hour: readMetadata({ metadata, key: 'firstIncompleteHour' }),+ };+ },+});++function readMetadata({ metadata, key }: { metadata: unknown; key: string }): string | null {+ if (metadata === null || typeof metadata !== 'object') {+ return null;+ }+ const value: unknown = Reflect.get(metadata, key);+ return typeof value === 'string' ? value : null;+}diff --git a/packages/pieces/community/google-search-console/src/lib/actions/ai/submit-sitemap-by-site-url.ts b/packages/pieces/community/google-search-console/src/lib/actions/ai/submit-sitemap-by-site-url.tsnew file mode 100644index 00000000000..c464df05ed0--- /dev/null+++ b/packages/pieces/community/google-search-console/src/lib/actions/ai/submit-sitemap-by-site-url.ts@@ -0,0 +1,31 @@+import { createAction } from '@activepieces/pieces-framework';+import { googleSearchConsoleAuth } from '../../auth';+import { commonProps } from '../../common';+import { gscInputs } from '../../common/inputs';+import { gscOps } from '../../common/operations';+import { gscOutputSchemas } from '../../output-schemas';++export const submitSitemapBySiteUrl = createAction({+ auth: googleSearchConsoleAuth,+ name: 'submit_sitemap_by_site_url',+ classification: 'WRITE',+ displayName: 'Submit Sitemap (by Site URL)',+ description: 'Submits a sitemap for a property.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Submits a sitemap URL to a property so Google can find its pages, or resubmits it after the sitemap changed. Needs siteOwner or siteFullUser permission. Resubmitting the same URL only refreshes it, so it is safe to retry.',+ idempotent: true,+ },+ props: {+ site_url: commonProps.aiSiteUrl(),+ feedpath: commonProps.feedpathText(),+ },+ outputSchema: gscOutputSchemas.sitemapChangeAi,+ async run(context) {+ const siteUrl = gscInputs.siteUrl({ value: context.propsValue.site_url });+ const feedpath = gscInputs.absoluteUrl({ value: context.propsValue.feedpath, label: 'Sitemap URL' });+ await gscOps.submitSitemap({ auth: context.auth, siteUrl, feedpath });+ return { success: true, site_url: siteUrl, feedpath };+ },+});diff --git a/packages/pieces/community/google-search-console/src/lib/actions/delete-a-site.ts b/packages/pieces/community/google-search-console/src/lib/actions/delete-a-site.tsindex a781e0031b2..d57a0f736e7 100644--- a/packages/pieces/community/google-search-console/src/lib/actions/delete-a-site.ts+++ b/packages/pieces/community/google-search-console/src/lib/actions/delete-a-site.ts@@ -1,34 +1,29 @@import { createAction } from '@activepieces/pieces-framework';import { googleSearchConsoleAuth } from '../auth';-import { createAuthClient } from '../../';import { commonProps } from '../common';+import { gscInputs } from '../common/inputs';+import { gscOps } from '../common/operations';+import { gscOutputSchemas } from '../output-schemas';export const deleteSite = createAction({auth: googleSearchConsoleAuth,name: 'delete_site',classification: 'DESTRUCTIVE',displayName: 'Delete a Site',- description:- "Removes a site from the set of the user's Search Console sites.",- audience: 'both',- aiMetadata: { description: "Remove a site (property) from the authenticated user's Google Search Console account, ending management of it. Choose this to deregister a property. Requires the exact siteUrl of an existing property; a confirmed destructive action. Not idempotent: a repeat call for an already-removed site fails.", idempotent: false },+ description: "Removes a site from the set of the user's Search Console sites.",+ audience: 'human',+ aiMetadata: {+ description:+ "Removes a property picked from a list from the connected account's Search Console. Agents use Delete Site (by Site URL). A second call for the same property fails.",+ idempotent: false,+ },props: {- siteUrl: commonProps.siteUrl,+ siteUrl: commonProps.siteUrlIncludingUnverified,},+ outputSchema: gscOutputSchemas.deleteSite,async run(context) {- const siteUrl = context.propsValue.siteUrl;-- if (!siteUrl) {- throw new Error(- 'You must provide either a Site URL or select one from the list.'- );- }-- const webmasters = createAuthClient(context.auth.access_token);- await webmasters.sites.delete({- siteUrl: siteUrl,- });-- return { success: true };+ const siteUrl = gscInputs.siteUrl({ value: context.propsValue.siteUrl });+ await gscOps.deleteSite({ auth: context.auth, siteUrl });+ return { success: true, siteUrl };},});diff --git a/packages/pieces/community/google-search-console/src/lib/actions/delete-a-sitemap.ts b/packages/pieces/community/google-search-console/src/lib/actions/delete-a-sitemap.tsnew file mode 100644index 00000000000..a5bd3bd7c12--- /dev/null+++ b/packages/pieces/community/google-search-console/src/lib/actions/delete-a-sitemap.ts@@ -0,0 +1,31 @@+import { createAction } from '@activepieces/pieces-framework';+import { googleSearchConsoleAuth } from '../auth';+import { commonProps } from '../common';+import { gscInputs } from '../common/inputs';+import { gscOps } from '../common/operations';+import { gscOutputSchemas } from '../output-schemas';++export const deleteSitemap = createAction({+ auth: googleSearchConsoleAuth,+ name: 'delete_sitemap',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete a Sitemap',+ description: 'Removes a sitemap from the Sitemaps report of a site.',+ audience: 'human',+ aiMetadata: {+ description:+ 'Removes a sitemap picked from a list from the Sitemaps report of a property. Agents use Delete Sitemap (by Site URL). Deleting a sitemap that is already gone also succeeds, so it is safe to retry.',+ idempotent: true,+ },+ props: {+ siteUrl: commonProps.siteUrl,+ feedpath: commonProps.sitemap,+ },+ outputSchema: gscOutputSchemas.sitemapChange,+ async run(context) {+ const siteUrl = gscInputs.siteUrl({ value: context.propsValue.siteUrl });+ const feedpath = gscInputs.absoluteUrl({ value: context.propsValue.feedpath, label: 'Sitemap' });+ await gscOps.deleteSitemap({ auth: context.auth, siteUrl, feedpath });+ return { success: true, siteUrl, feedpath };+ },+});diff --git a/packages/pieces/community/google-search-console/src/lib/actions/list-sitemaps.ts b/packages/pieces/community/google-search-console/src/lib/actions/list-sitemaps.tsindex 73daec5f74f..67191663de7 100644--- a/packages/pieces/community/google-search-console/src/lib/actions/list-sitemaps.ts+++ b/packages/pieces/community/google-search-console/src/lib/actions/list-sitemaps.ts@@ -1,7 +1,9 @@-import { createAction } from '@activepieces/pieces-framework';+import { createAction, Property } from '@activepieces/pieces-framework';import { googleSearchConsoleAuth } from '../auth';-import { createAuthClient } from '../../';import { commonProps } from '../common';+import { gscInputs } from '../common/inputs';+import { gscOps } from '../common/operations';+import { gscOutputSchemas } from '../output-schemas';export const listSitemaps = createAction({auth: googleSearchConsoleAuth,@@ -9,16 +11,25 @@ export const listSitemaps = createAction({classification: 'SEARCH',displayName: 'List Sitemaps',description: 'List all your sitemaps for a given site',- audience: 'both',- aiMetadata: { description: 'List the sitemaps submitted to Google Search Console for a verified site, including their last-download and processing status. Choose this to audit which sitemaps exist before submitting or to check sitemap health. Requires a verified siteUrl; read-only and idempotent.', idempotent: true },+ audience: 'human',+ aiMetadata: {+ description:+ 'Lists the sitemaps submitted for a property picked from a list, with their processing status. Agents use List Sitemaps (by Site URL). Read-only and safe to retry.',+ idempotent: true,+ },props: {siteUrl: commonProps.siteUrl,+ sitemapIndex: Property.ShortText({+ displayName: 'Sitemap Index URL',+ description: 'Optional. The full URL of a sitemap index to list only the sitemaps inside it.',+ required: false,+ }),},+ outputSchema: gscOutputSchemas.listSitemaps,async run(context) {- const webmasters = createAuthClient(context.auth.access_token);- const res = await webmasters.sitemaps.list({- siteUrl: context.propsValue.siteUrl,- });- return res.data;+ const siteUrl = gscInputs.siteUrl({ value: context.propsValue.siteUrl });+ const sitemapIndex = context.propsValue.sitemapIndex ? gscInputs.absoluteUrl({ value: context.propsValue.sitemapIndex, label: 'Sitemap Index URL' }) : undefined;+ const sitemap = await gscOps.listSitemaps({ auth: context.auth, siteUrl, sitemapIndex });+ return { sitemap, count: sitemap.length };},});diff --git a/packages/pieces/community/google-search-console/src/lib/actions/list-sites.ts b/packages/pieces/community/google-search-console/src/lib/actions/list-sites.tsindex c7b987c7977..d8dabe9eaf4 100644--- a/packages/pieces/community/google-search-console/src/lib/actions/list-sites.ts+++ b/packages/pieces/community/google-search-console/src/lib/actions/list-sites.ts@@ -1,6 +1,7 @@import { createAction } from '@activepieces/pieces-framework';import { googleSearchConsoleAuth } from '../auth';-import { createAuthClient } from '../../';+import { gscOps } from '../common/operations';+import { gscOutputSchemas } from '../output-schemas';export const listSites = createAction({auth: googleSearchConsoleAuth,@@ -9,11 +10,14 @@ export const listSites = createAction({displayName: 'List Sites',description: "Lists the user's Search Console sites.",audience: 'both',- aiMetadata: { description: "List all sites the authenticated user has access to in Google Search Console, with each site's permission level. Choose this to discover available siteUrl values before calling other actions, or to verify access. Takes no input; read-only and idempotent.", idempotent: true },+ aiMetadata: {+ description:+ 'Lists every Search Console property the connected Google account can see, with its permission level (siteOwner, siteFullUser, siteRestrictedUser, siteUnverifiedUser). Call it first to get the exact Site URL string the other actions need; unverified properties cannot be queried. Read-only and safe to retry.',+ idempotent: true,+ },props: {},+ outputSchema: gscOutputSchemas.listSites,async run(context) {- const webmasters = createAuthClient(context.auth.access_token);- const res = await webmasters.sites.list();- return res.data;+ return gscOps.listSites({ auth: context.auth });},});diff --git a/packages/pieces/community/google-search-console/src/lib/actions/search-analytics.ts b/packages/pieces/community/google-search-console/src/lib/actions/search-analytics.tsindex 4385df718f1..b6efc8ff03d 100644--- a/packages/pieces/community/google-search-console/src/lib/actions/search-analytics.ts+++ b/packages/pieces/community/google-search-console/src/lib/actions/search-analytics.ts@@ -1,149 +1,72 @@import { createAction, Property } from '@activepieces/pieces-framework';import { googleSearchConsoleAuth } from '../auth';-import { createAuthClient } from '../../';import { commonProps } from '../common';-import dayjs from 'dayjs';-+import { gscInputs } from '../common/inputs';+import { gscOps } from '../common/operations';+import { gscOutputSchemas } from '../output-schemas';export const searchAnalytics = createAction({auth: googleSearchConsoleAuth,name: 'search_analytics',classification: 'SEARCH',displayName: 'Search Analytics',- description:- 'Query traffic data for your site using the Google Search Console API.',- audience: 'both',- aiMetadata: { description: 'Query Google Search Console search-performance metrics (clicks, impressions, CTR, position) for a verified site over a date range, optionally grouped by dimensions (query, page, country, device, searchAppearance, date, hour), filtered by search type, and narrowed with dimension filters. Choose this to analyze or report on a site\'s organic search traffic. Requires a verified siteUrl and a start/end date; read-only and idempotent.', idempotent: true },+ description: 'Query traffic data for your site using the Google Search Console API.',+ audience: 'human',+ aiMetadata: {+ description:+ 'Queries clicks, impressions, CTR and position for a property picked from a list. Agents use Search Analytics (by Site URL). Read-only and safe to retry.',+ idempotent: true,+ },props: {siteUrl: commonProps.siteUrl,startDate: Property.DateTime({displayName: 'Start Date',- description:- 'The start date of the date range to query (in YYYY-MM-DD format).',+ description: 'First day of the range (YYYY-MM-DD), in Pacific Time. Search Console data lags 2-3 days and is kept for about 16 months.',required: true,- defaultValue: new Date().toISOString().split('T')[0],}),endDate: Property.DateTime({displayName: 'End Date',- description:- 'The end date of the date range to query (in YYYY-MM-DD format).',+ description: 'Last day of the range (YYYY-MM-DD, inclusive), in Pacific Time. A range that covers only today or yesterday usually has no data yet.',required: true,- defaultValue: new Date().toISOString().split('T')[0],}),dimensions: Property.Array({displayName: 'Dimensions',description:- 'The dimensions to group results by. Valid values: "query", "page", "country", "device", "searchAppearance", "date", "hour".',- required: false,- }),- searchType: Property.StaticDropdown({- displayName: 'Search Type',- description:- 'Filter results by search type. Defaults to "web".',+ 'The dimensions to group results by, in order. Valid values: "query", "page", "country", "device", "searchAppearance", "date", "hour". Each row of the output gets one column per dimension.',required: false,- options: {- options: [- { label: 'Web', value: 'web' },- { label: 'Discover', value: 'discover' },- { label: 'Google News', value: 'googleNews' },- { label: 'News', value: 'news' },- { label: 'Image', value: 'image' },- { label: 'Video', value: 'video' },- ],- },- }),- filters: Property.Array({- displayName: 'Filters',- description:- 'Optional filters to apply to the data. All filters are AND-ed together.',- properties: {- dimension: Property.StaticDropdown({- displayName: 'Dimension',- description: 'The dimension to filter by.',- required: true,- options: {- options: [- { label: 'Query', value: 'query' },- { label: 'Page', value: 'page' },- { label: 'Country (ISO 3166-1 alpha-3, e.g. "ind")', value: 'country' },- { label: 'Device', value: 'device' },- { label: 'Search Appearance', value: 'searchAppearance' },- ],- },- }),- operator: Property.StaticDropdown({- displayName: 'Operator',- description: 'The filter operator to apply.',- required: true,- options: {- options: [- { label: 'Equals', value: 'equals' },- { label: 'Not Equals', value: 'notEquals' },- { label: 'Contains', value: 'contains' },- { label: 'Not Contains', value: 'notContains' },- { label: 'Including Regex', value: 'includingRegex' },- { label: 'Excluding Regex', value: 'excludingRegex' },- ],- },- }),- expression: Property.ShortText({- displayName: 'Expression',- description:- 'The value to compare against. For "country" use ISO 3166-1 alpha-3 (e.g. "ind"). For "device" use DESKTOP, MOBILE, or TABLET.',- required: true,- }),- },- required: false,- }),- aggregationType: Property.StaticDropdown({- displayName: 'Aggregation Type',- description: 'How data is aggregated. Defaults to "auto".',- required: false,- options: {- options: [- { label: 'Auto', value: 'auto' },- { label: 'By Page', value: 'byPage' },- { label: 'By Property', value: 'byProperty' },- { label: 'By News Showcase Panel', value: 'byNewsShowcasePanel' },- ],- },}),+ searchType: commonProps.searchType(),+ filters: commonProps.filters(),+ aggregationType: commonProps.aggregationType(),+ dataState: commonProps.dataState(),rowLimit: Property.Number({displayName: 'Row Limit',- description: 'The maximum number of rows to return. Min: 1, Max: 5,000. Defaults to 1,000.',+ description: 'The maximum number of rows to return, from 1 to 25,000. Defaults to 1,000.',required: false,}),startRow: Property.Number({displayName: 'Start Row',- description:- 'Zero-based index of the first row to return. Use with Row Limit to paginate results. Defaults to 0.',+ description: 'Zero-based index of the first row to return. Use with Row Limit to page through results. Defaults to 0.',required: false,}),},+ outputSchema: gscOutputSchemas.searchAnalytics,async run(context) {- const webmasters = createAuthClient(context.auth.access_token);- const filters = context.propsValue.filters as any;- const res = await webmasters.searchanalytics.query({- siteUrl: context.propsValue.siteUrl,- requestBody: {- startDate: dayjs(context.propsValue.startDate).format('YYYY-MM-DD'),- endDate: dayjs(context.propsValue.endDate).format('YYYY-MM-DD'),- dimensions: context.propsValue.dimensions as string[],- searchType: context.propsValue.searchType,- dimensionFilterGroups: filters?.length- ? [{- filters: filters.map((filter: any) => ({- dimension: filter.dimension,- operator: filter.operator,- expression: filter.expression,- })),- }]- : undefined,- aggregationType: context.propsValue.aggregationType,- rowLimit: context.propsValue.rowLimit,- startRow: context.propsValue.startRow,- },+ const props = context.propsValue;+ const siteUrl = gscInputs.siteUrl({ value: props.siteUrl });+ const { startDate, endDate } = gscInputs.requiredDateRange({ startDate: props.startDate, endDate: props.endDate });+ const query = gscInputs.analyticsQuery({+ startDate,+ endDate,+ dimensions: gscInputs.dimensions({ value: props.dimensions }),+ searchType: props.searchType,+ filters: gscInputs.filters({ value: props.filters }),+ aggregationType: props.aggregationType,+ dataState: props.dataState,+ rowLimit: gscInputs.optionalInteger({ value: props.rowLimit, label: 'Row Limit', min: 1, max: gscInputs.HUMAN_MAX_ROW_LIMIT }),+ startRow: gscInputs.optionalInteger({ value: props.startRow, label: 'Start Row', min: 0, max: gscInputs.MAX_START_ROW }),});- return res;+ const result = await gscOps.searchAnalytics({ auth: context.auth, siteUrl, query });+ return { data: result.data, status: result.status, rows: result.rows, row_count: result.rows.length };},});diff --git a/packages/pieces/community/google-search-console/src/lib/actions/submit-a-sitemap.ts b/packages/pieces/community/google-search-console/src/lib/actions/submit-a-sitemap.tsindex ea624ca70cf..28af446645d 100644--- a/packages/pieces/community/google-search-console/src/lib/actions/submit-a-sitemap.ts+++ b/packages/pieces/community/google-search-console/src/lib/actions/submit-a-sitemap.ts@@ -1,7 +1,9 @@import { createAction, Property } from '@activepieces/pieces-framework';import { googleSearchConsoleAuth } from '../auth';-import { createAuthClient } from '../../';import { commonProps } from '../common';+import { gscInputs } from '../common/inputs';+import { gscOps } from '../common/operations';+import { gscOutputSchemas } from '../output-schemas';export const submitSitemap = createAction({auth: googleSearchConsoleAuth,@@ -9,21 +11,25 @@ export const submitSitemap = createAction({classification: 'WRITE',displayName: 'Submit a Sitemap',description: 'Submits a sitemap for a site.',- audience: 'both',- aiMetadata: { description: 'Submit a sitemap to Google Search Console for a verified site so Google can discover and crawl its URLs. Choose this when registering a new or updated sitemap. Requires a verified siteUrl and the full sitemap feedpath (URL). Not idempotent: each call re-submits and re-queues the sitemap for processing.', idempotent: false },+ audience: 'human',+ aiMetadata: {+ description:+ 'Submits or resubmits a sitemap URL for a property picked from a list. Agents use Submit Sitemap (by Site URL). Resubmitting the same URL only refreshes it, so it is safe to retry.',+ idempotent: true,+ },props: {siteUrl: commonProps.siteUrl,feedpath: Property.ShortText({displayName: 'Sitemap Path',+ description: 'The full URL of the sitemap, e.g. "https://www.example.com/sitemap.xml".',required: true,}),},+ outputSchema: gscOutputSchemas.sitemapChange,async run(context) {- const webmasters = createAuthClient(context.auth.access_token);- await webmasters.sitemaps.submit({- siteUrl: context.propsValue.siteUrl,- feedpath: context.propsValue.feedpath,- });- return { success: true };+ const siteUrl = gscInputs.siteUrl({ value: context.propsValue.siteUrl });+ const feedpath = gscInputs.absoluteUrl({ value: context.propsValue.feedpath, label: 'Sitemap Path' });+ await gscOps.submitSitemap({ auth: context.auth, siteUrl, feedpath });+ return { success: true, siteUrl, feedpath };},});diff --git a/packages/pieces/community/google-search-console/src/lib/actions/url-inspection.ts b/packages/pieces/community/google-search-console/src/lib/actions/url-inspection.tsindex fe3e23b6039..ed825da1d78 100644--- a/packages/pieces/community/google-search-console/src/lib/actions/url-inspection.ts+++ b/packages/pieces/community/google-search-console/src/lib/actions/url-inspection.ts@@ -1,46 +1,40 @@import { createAction, Property } from '@activepieces/pieces-framework';import { googleSearchConsoleAuth } from '../auth';-import {- AuthenticationType,- httpClient,- HttpMethod,- HttpRequest,-} from '@activepieces/pieces-common';import { commonProps } from '../common';+import { gscInputs } from '../common/inputs';+import { gscOps } from '../common/operations';+import { gscOutputSchemas } from '../output-schemas';export const urlInspection = createAction({auth: googleSearchConsoleAuth,name: 'urlInspection',classification: 'READ',displayName: 'URL Inspection',- description:- "Use the URL Inspection action to check the status and presence of a specific page within Google's index.",- audience: 'both',- aiMetadata: { description: "Inspect a single URL with the Google Search Console URL Inspection API to report its index status, coverage, mobile usability, and rich-result details for a verified site. Choose this to diagnose why a specific page is or isn't indexed. Requires a verified siteUrl and the exact URL to inspect (must belong to that property); read-only and idempotent.", idempotent: true },+ description: "Use the URL Inspection action to check the status and presence of a specific page within Google's index.",+ audience: 'human',+ aiMetadata: {+ description:+ "Reports Google's index status of one URL in a property picked from a list. Agents use Inspect URL (by Site URL). Read-only and safe to retry; limited to 2,000 inspections per property per day.",+ idempotent: true,+ },props: {siteUrl: commonProps.siteUrl,url: Property.ShortText({displayName: 'URL to Inspect',+ description: 'The full URL of the page. It must belong to the selected property.',required: true,}),+ languageCode: Property.ShortText({+ displayName: 'Language Code',+ description: 'Optional language for the issue messages, as a BCP-47 code such as "en-US" or "de". Defaults to English.',+ required: false,+ }),},+ outputSchema: gscOutputSchemas.urlInspection,async run(context) {- const request: HttpRequest = {- method: HttpMethod.POST,- url: 'https://searchconsole.googleapis.com/v1/urlInspection/index:inspect',- authentication: {- type: AuthenticationType.BEARER_TOKEN,- token: context.auth.access_token,- },- headers: { 'Content-Type': 'application/json' },- body: {- inspectionUrl: context.propsValue.url,- siteUrl: context.propsValue.siteUrl,- },- };-- const response = await httpClient.sendRequest(request);-- return response.body;+ const siteUrl = gscInputs.siteUrl({ value: context.propsValue.siteUrl });+ const inspectionUrl = gscInputs.urlInProperty({ value: context.propsValue.url, label: 'URL to Inspect', site: siteUrl });+ const languageCode = gscInputs.languageCode({ value: context.propsValue.languageCode });+ return gscOps.inspectUrl({ auth: context.auth, siteUrl, inspectionUrl, languageCode });},});diff --git a/packages/pieces/community/google-search-console/src/lib/auth.ts b/packages/pieces/community/google-search-console/src/lib/auth.tsindex eb6a29ba747..9e70fa085fe 100644--- a/packages/pieces/community/google-search-console/src/lib/auth.ts+++ b/packages/pieces/community/google-search-console/src/lib/auth.ts@@ -2,21 +2,14 @@ import { PieceAuth } from '@activepieces/pieces-framework';export const googleSearchConsoleAuth = PieceAuth.OAuth2({description: `- 1. Sign in to [Google Cloud Console](https://console.cloud.google.com/).- 2. Create a new project or you can use existing one.- 3. Go to **APIs & Services** and click **Enable APIs & Services**.- 4. Search for **Google Search Console API** in the search bar and enable it.- 5. Go to **OAuth consent screen** and select **External** type and click create.- 6. Fill App Name, User Support Email, and Developer Contact Information. Click on the Save and Continue button.- 7. Click on **Add or Remove Scopes** and add following scopes and click update.- - https://www.googleapis.com/auth/webmasters- 8. Click Save and Continue to finish the Scopes step.- 9. Click on the Add Users button and add a test email You can add your own email)-.Then finally click Save and Continue to finish the Test Users portion.- 10. Go to **Credentials**. Click on the **Create Credentials** button and select the **OAuth client ID** option.- 11. Select the application type as **Web Application** and fill the Name field.- 12. Add https://cloud.activepieces.com/redirect in **Authorized redirect URIs** field, and click on the Create button.- 13. Copy **Client ID** and **Client Secret**.`,+ 1. Sign in to [Google Cloud Console](https://console.cloud.google.com/) and create a project, or pick an existing one.+ 2. Go to **APIs & Services > Library**, search for **Google Search Console API** and click **Enable**. It must be enabled in the same project as the OAuth client you create below.+ 3. Go to **OAuth consent screen**, choose **External**, fill in the app name and the support and developer emails, and save.+ 4. In **Scopes** (Data access), add \`https://www.googleapis.com/auth/webmasters\` and \`email\`, then save.+ 5. While the app is in **Testing**, add the Google account you will connect under **Test users**. Tokens of apps in Testing expire after 7 days; publish the app to avoid reconnecting.+ 6. Go to **Credentials > Create Credentials > OAuth client ID** and choose **Web application**.+ 7. Under **Authorized redirect URIs**, add the Redirect URL shown in this dialog, then click **Create**.+ 8. Copy the **Client ID** and **Client Secret** into the fields below.`,authUrl: 'https://accounts.google.com/o/oauth2/auth',tokenUrl: 'https://oauth2.googleapis.com/token',scope: ['https://www.googleapis.com/auth/webmasters', 'email'],diff --git a/packages/pieces/community/google-search-console/src/lib/common/client.ts b/packages/pieces/community/google-search-console/src/lib/common/client.tsnew file mode 100644index 00000000000..5f75a52da50--- /dev/null+++ b/packages/pieces/community/google-search-console/src/lib/common/client.ts@@ -0,0 +1,189 @@+import { httpClient, HttpMethod, QueryParams } from '@activepieces/pieces-common';++const BASE_URL = 'https://searchconsole.googleapis.com';+const REQUEST_TIMEOUT_MS = 60_000;+const MAX_ERROR_TEXT = 500;++// The shared HTTP client turns off certificate checks for the whole process+// (NODE_TLS_REJECT_UNAUTHORIZED=0). An explicit rejectUnauthorized wins over that,+// so the OAuth token only goes to a server with a valid certificate.+let verifiedTlsAgent: Promise<unknown> | undefined;++function verifiedTls(): Promise<unknown> {+ verifiedTlsAgent ??= import('undici').then(({ Agent }) => new Agent({ connect: { rejectUnauthorized: true } }));+ return verifiedTlsAgent;+}++export class GscApiError extends Error {+ readonly status: number;+ readonly reason: string | undefined;+ readonly responseBody: unknown;++ constructor({ operation, status, responseBody }: { operation: string; status: number; responseBody: unknown }) {+ super(`Google Search Console could not ${operation}: ${describeGscError({ status, responseBody })}`);+ this.name = 'GscApiError';+ this.status = status;+ this.reason = errorReason(responseBody);+ this.responseBody = responseBody;+ }+}++async function request<T>({+ auth,+ method,+ path,+ query,+ body,+ operation,+}: {+ auth: GscAuth;+ method: HttpMethod;+ path: string[];+ query?: Record<string, string | undefined>;+ body?: unknown;+ operation: string;+}): Promise<GscResponse<T>> {+ const url = `${BASE_URL}/${path.join('/')}`;+ try {+ const dispatcher = await verifiedTls();+ const response = await httpClient.sendRequest<T>({+ method,+ url,+ headers: {+ Authorization: `Bearer ${auth.access_token}`,+ Accept: 'application/json',+ ...(body === undefined ? {} : { 'Content-Type': 'application/json' }),+ },+ queryParams: toQueryParams(query),+ body,+ timeout: REQUEST_TIMEOUT_MS,+ followRedirects: false,+ }, { dispatcher });+ if (response.status >= 300) {+ throw new GscApiError({ operation, status: response.status, responseBody: 'Google answered with an unexpected redirect.' });+ }+ return { status: response.status, body: response.body };+ } catch (error) {+ if (error instanceof GscApiError) {+ throw error;+ }+ const status = statusOf(error);+ if (status === undefined) {+ throw error;+ }+ throw new GscApiError({ operation, status, responseBody: responseBodyOf(error) });+ }+}++function sitePath(siteUrl: string): string[] {+ return ['webmasters', 'v3', 'sites', encodeURIComponent(siteUrl)];+}++function toQueryParams(query: Record<string, string | undefined> | undefined): QueryParams | undefined {+ if (!query) {+ return undefined;+ }+ const entries = Object.entries(query).filter((entry): entry is [string, string] => typeof entry[1] === 'string' && entry[1].length > 0);+ return entries.length === 0 ? undefined : Object.fromEntries(entries);+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return value !== null && typeof value === 'object' && !Array.isArray(value);+}++function errorObject(responseBody: unknown): Record<string, unknown> | undefined {+ if (isRecord(responseBody) && isRecord(responseBody['error'])) {+ return responseBody['error'];+ }+ return undefined;+}++function errorReason(responseBody: unknown): string | undefined {+ const error = errorObject(responseBody);+ if (!error) {+ return undefined;+ }+ const details = Array.isArray(error['details']) ? error['details'].filter(isRecord) : [];+ const detailReason = details.map((detail) => detail['reason']).find((reason): reason is string => typeof reason === 'string');+ if (detailReason) {+ return detailReason;+ }+ const errors = Array.isArray(error['errors']) ? error['errors'].filter(isRecord) : [];+ const legacyReason = errors.map((item) => item['reason']).find((reason): reason is string => typeof reason === 'string');+ if (legacyReason) {+ return legacyReason;+ }+ return typeof error['status'] === 'string' ? error['status'] : undefined;+}++function vendorText(responseBody: unknown): string {+ const error = errorObject(responseBody);+ if (error && typeof error['message'] === 'string' && error['message'].trim().length > 0) {+ return error['message'].trim().slice(0, MAX_ERROR_TEXT);+ }+ if (typeof responseBody === 'string' && responseBody.trim().length > 0) {+ return responseBody.trim().slice(0, MAX_ERROR_TEXT);+ }+ if (isRecord(responseBody)) {+ return JSON.stringify(responseBody).slice(0, MAX_ERROR_TEXT);+ }+ return 'no details returned';+}++function describeGscError({ status, responseBody }: { status: number; responseBody: unknown }): string {+ const detail = `Google said: "${vendorText(responseBody)}" (HTTP ${status})`;+ const reason = errorReason(responseBody);+ if (status === 401) {+ return `the connection has expired or was revoked. Reconnect Google Search Console and try again. If your Google OAuth app is in Testing mode, its tokens expire after 7 days. ${detail}`;+ }+ if (status === 403 && (reason === 'SERVICE_DISABLED' || reason === 'accessNotConfigured')) {+ return `the Google Search Console API is not enabled in the Google Cloud project that owns this connection's OAuth client. Enable "Google Search Console API" in that project (APIs & Services > Library), wait a few minutes and try again. ${detail}`;+ }+ if (status === 403) {+ return `the connected Google account has no access to this property, or not enough access. The Site URL must match the property exactly as List Sites shows it (http vs https, www, trailing slash, or the "sc-domain:" prefix for domain properties). Unverified properties cannot be read, and adding or removing sitemaps needs Owner or Full permission. ${detail}`;+ }+ if (status === 404) {+ return `not found. Check the Site URL (exactly as List Sites shows it) and the sitemap URL. ${detail}`;+ }+ if (status === 429) {+ return `the Search Console quota was exceeded. Wait a few minutes; for Search Analytics, use a shorter date range or fewer dimensions; URL Inspection allows 2,000 inspections per property per day. ${detail}`;+ }+ if (status >= 500) {+ return `Google Search Console is temporarily unavailable. Try again later. ${detail}`;+ }+ if (status === 400) {+ return `Google rejected the request. ${detail}`;+ }+ return detail;+}++function statusOf(error: unknown): number | undefined {+ if (!(error instanceof Error)) {+ return undefined;+ }+ const response: unknown = Reflect.get(error, 'response');+ if (isRecord(response) && typeof response['status'] === 'number') {+ return response['status'];+ }+ return undefined;+}++function responseBodyOf(error: unknown): unknown {+ if (!(error instanceof Error)) {+ return undefined;+ }+ const response: unknown = Reflect.get(error, 'response');+ return isRecord(response) ? response['body'] : undefined;+}++export const gscClient = {+ request,+ sitePath,+ isRecord,+ describeGscError,+ BASE_URL,+};++export type GscAuth = { access_token: string };++export type GscResponse<T> = { status: number; body: T };diff --git a/packages/pieces/community/google-search-console/src/lib/common/index.ts b/packages/pieces/community/google-search-console/src/lib/common/index.tsindex 1242f2cdecc..21b1ca1593c 100644--- a/packages/pieces/community/google-search-console/src/lib/common/index.ts+++ b/packages/pieces/community/google-search-console/src/lib/common/index.ts@@ -1,33 +1,205 @@+import { Property } from '@activepieces/pieces-framework';import { googleSearchConsoleAuth } from '../auth';-import { createAuthClient } from '../../';-import { PiecePropValueSchema, Property } from '@activepieces/pieces-framework';+import { DATA_STATES, DIMENSIONS } from './inputs';+import { gscOps } from './operations';+import { gscShape } from './shape';-export const commonProps = {- siteUrl: Property.Dropdown({+function siteDropdown({ includeUnverified }: { includeUnverified: boolean }) {+ return Property.Dropdown({auth: googleSearchConsoleAuth,displayName: 'Site URL',+ description: includeUnverified+ ? 'The Search Console property. Unverified properties are listed too.'+ : 'The Search Console property. Only properties you have verified access to are listed.',required: true,refreshers: [],refreshOnSearch: false,options: async ({ auth }) => {- const authValue = auth- if (!authValue) {+ if (!auth) {+ return { disabled: true, options: [], placeholder: 'Connect your Google account first.' };+ }+ try {+ const { siteEntry } = await gscOps.listSites({ auth });+ const sites = siteEntry+ .filter((site) => site.siteUrl !== '' && (includeUnverified || site.permissionLevel !== 'siteUnverifiedUser'))+ .sort((a, b) => a.siteUrl.localeCompare(b.siteUrl));+ if (sites.length === 0) {+ return {+ disabled: true,+ options: [],+ placeholder: includeUnverified+ ? 'No Search Console properties found for this Google account.'+ : 'No verified Search Console properties found for this Google account. Verify the property in Search Console first.',+ };+ }return {- disabled: true,- options: [],- placeholder: 'Please connect your account first',+ disabled: false,+ options: sites.map((site) => ({ label: `${site.siteUrl} (${gscShape.permissionLabel(site.permissionLevel)})`, value: site.siteUrl })),};+ } catch (error) {+ return failed({ error, what: 'properties' });}- const webmasters = createAuthClient(authValue.access_token);- const res = await webmasters.sites.list();- const sites = res.data.siteEntry || [];-- return {- options: sites.map((site: any) => ({- label: site.siteUrl,- value: site.siteUrl,- })),- };},- }),+ });+}++function sitemapDropdown() {+ return Property.Dropdown({+ auth: googleSearchConsoleAuth,+ displayName: 'Sitemap',+ description: 'A sitemap submitted to the selected property.',+ required: true,+ refreshers: ['siteUrl'],+ refreshOnSearch: false,+ options: async ({ auth, siteUrl }) => {+ if (!auth) {+ return { disabled: true, options: [], placeholder: 'Connect your Google account first.' };+ }+ if (typeof siteUrl !== 'string' || siteUrl.length === 0) {+ return { disabled: true, options: [], placeholder: 'Select a Site URL first.' };+ }+ try {+ const sitemaps = await gscOps.listSitemaps({ auth, siteUrl });+ const paths = sitemaps.map((sitemap) => sitemap['path']).filter((path): path is string => typeof path === 'string' && path.length > 0);+ if (paths.length === 0) {+ return { disabled: true, options: [], placeholder: 'No sitemaps are submitted for this property.' };+ }+ return { disabled: false, options: paths.map((path) => ({ label: path, value: path })) };+ } catch (error) {+ return failed({ error, what: 'sitemaps' });+ }+ },+ });+}++function failed({ error, what }: { error: unknown; what: string }) {+ const message = error instanceof Error ? error.message : 'unknown error';+ return { disabled: true, options: [], placeholder: `Could not load ${what}: ${message}`.slice(0, 400) };+}++function aiSiteUrl() {+ return Property.ShortText({+ displayName: 'Site URL',+ description:+ 'The Search Console property exactly as List Sites returns it: a URL-prefix property ends with "/" (e.g. "https://www.example.com/"), a domain property starts with "sc-domain:" (e.g. "sc-domain:example.com").',+ required: true,+ });+}++function feedpathText() {+ return Property.ShortText({+ displayName: 'Sitemap URL',+ description: 'The full URL of the sitemap, e.g. "https://www.example.com/sitemap.xml".',+ required: true,+ });+}++function dataState() {+ return Property.StaticDropdown({+ displayName: 'Data State',+ description:+ 'Which data to include. "final" (default) has only finalized data; "all" adds fresh, still-changing data from the last days; "hourly_all" is required for the hour dimension and is selected automatically when you group by hour.',+ required: false,+ options: { options: DATA_STATES.map((value) => ({ label: value, value })) },+ });+}++function searchType() {+ return Property.StaticDropdown({+ displayName: 'Search Type',+ description: 'The Google surface to report on. Defaults to "web". Discover and Google News have no search queries.',+ required: false,+ options: {+ options: [+ { label: 'Web', value: 'web' },+ { label: 'Discover', value: 'discover' },+ { label: 'Google News', value: 'googleNews' },+ { label: 'News', value: 'news' },+ { label: 'Image', value: 'image' },+ { label: 'Video', value: 'video' },+ ],+ },+ });+}++function aggregationType() {+ return Property.StaticDropdown({+ displayName: 'Aggregation Type',+ description: 'How results are aggregated. Defaults to "auto". "byProperty" cannot be used with the page dimension or a page filter.',+ required: false,+ options: {+ options: [+ { label: 'Auto', value: 'auto' },+ { label: 'By Page', value: 'byPage' },+ { label: 'By Property', value: 'byProperty' },+ { label: 'By News Showcase Panel', value: 'byNewsShowcasePanel' },+ ],+ },+ });+}++function filtersProp() {+ return Property.Array({+ displayName: 'Filters',+ description: 'Optional filters. All filters are combined with AND.',+ required: false,+ properties: {+ dimension: Property.StaticDropdown({+ displayName: 'Dimension',+ description: 'The dimension to filter by.',+ required: true,+ options: {+ options: [+ { label: 'Query', value: 'query' },+ { label: 'Page', value: 'page' },+ { label: 'Country (ISO 3166-1 alpha-3, e.g. "usa")', value: 'country' },+ { label: 'Device', value: 'device' },+ { label: 'Search Appearance', value: 'searchAppearance' },+ ],+ },+ }),+ operator: Property.StaticDropdown({+ displayName: 'Operator',+ description: 'How the expression is compared. Regex operators use RE2 syntax.',+ required: true,+ options: {+ options: [+ { label: 'Equals', value: 'equals' },+ { label: 'Not Equals', value: 'notEquals' },+ { label: 'Contains', value: 'contains' },+ { label: 'Not Contains', value: 'notContains' },+ { label: 'Including Regex', value: 'includingRegex' },+ { label: 'Excluding Regex', value: 'excludingRegex' },+ ],+ },+ }),+ expression: Property.ShortText({+ displayName: 'Expression',+ description: 'The value to compare with. Country uses ISO 3166-1 alpha-3 codes (e.g. "usa"); device is DESKTOP, MOBILE or TABLET.',+ required: true,+ }),+ },+ });+}++function dimensionsMulti() {+ return Property.StaticMultiSelectDropdown({+ displayName: 'Dimensions',+ description: 'Group results by these dimensions, in this order. Leave empty for one totals row. "hour" covers only the last few days.',+ required: false,+ options: { options: DIMENSIONS.map((value) => ({ label: value, value })) },+ });+}++export const commonProps = {+ siteUrl: siteDropdown({ includeUnverified: false }),+ siteUrlIncludingUnverified: siteDropdown({ includeUnverified: true }),+ sitemap: sitemapDropdown(),+ aiSiteUrl,+ feedpathText,+ dataState,+ searchType,+ aggregationType,+ filters: filtersProp,+ dimensionsMulti,};diff --git a/packages/pieces/community/google-search-console/src/lib/common/inputs.ts b/packages/pieces/community/google-search-console/src/lib/common/inputs.tsnew file mode 100644index 00000000000..66d57db91da--- /dev/null+++ b/packages/pieces/community/google-search-console/src/lib/common/inputs.ts@@ -0,0 +1,326 @@+const DATE_PATTERN = /^(\d{4})-(\d{2})-(\d{2})(?:$|[T ])/;+const URL_PREFIX_PATTERN = /^https?:\/\/[^/\s?#@]+(?:\/[^\s?#]*)?$/i;+const DOMAIN_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?)+$/i;+const LANGUAGE_PATTERN = /^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/;+const PACIFIC_TIME_ZONE = 'America/Los_Angeles';+const DAY_MS = 86_400_000;+const MAX_LAST_N_DAYS = 500;+const HUMAN_MAX_ROW_LIMIT = 25_000;+const MAX_START_ROW = 10_000_000;++function text(value: unknown): string {+ if (typeof value === 'string') {+ return value.trim();+ }+ if (typeof value === 'number' && Number.isFinite(value)) {+ return String(value);+ }+ return '';+}++function siteUrl({ value, label = 'Site URL' }: { value: unknown; label?: string }): string {+ const raw = text(value);+ if (raw.length === 0) {+ throw new Error(`${label} is required. Use the property exactly as List Sites shows it, e.g. "https://www.example.com/" or "sc-domain:example.com".`);+ }+ if (raw.toLowerCase().startsWith('sc-domain:')) {+ const domain = raw.slice('sc-domain:'.length).trim();+ if (!DOMAIN_PATTERN.test(domain)) {+ throw new Error(`${label} "${raw.slice(0, 120)}" is not a valid domain property. Use "sc-domain:" followed by the bare domain, e.g. "sc-domain:example.com".`);+ }+ return `sc-domain:${domain}`;+ }+ if (!URL_PREFIX_PATTERN.test(raw)) {+ throw new Error(`${label} "${raw.slice(0, 120)}" is not a Search Console property. Use a URL-prefix property such as "https://www.example.com/" or a domain property such as "sc-domain:example.com".`);+ }+ return raw.endsWith('/') ? raw : `${raw}/`;+}++function absoluteUrl({ value, label }: { value: unknown; label: string }): string {+ const raw = text(value);+ if (raw.length === 0) {+ throw new Error(`${label} is required.`);+ }+ const parsed = parseUrl(raw);+ if (!parsed || (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') || parsed.username !== '' || parsed.password !== '') {+ throw new Error(`${label} "${raw.slice(0, 200)}" must be a full http(s) URL, e.g. "https://www.example.com/sitemap.xml".`);+ }+ return raw;+}++function urlInProperty({ value, label, site }: { value: unknown; label: string; site: string }): string {+ const url = absoluteUrl({ value, label });+ if (!belongsToProperty({ url, site })) {+ throw new Error(`${label} "${url.slice(0, 200)}" is not part of the property ${site}. ${site.startsWith('sc-domain:') ? `It must be on ${site.slice('sc-domain:'.length)} or one of its subdomains.` : `It must start with ${site}.`}`);+ }+ return url;+}++function belongsToProperty({ url, site }: { url: string; site: string }): boolean {+ if (site.startsWith('sc-domain:')) {+ const domain = site.slice('sc-domain:'.length).toLowerCase();+ const host = parseUrl(url)?.hostname.toLowerCase() ?? '';+ return host === domain || host.endsWith(`.${domain}`);+ }+ const prefix = parseUrl(site);+ const target = parseUrl(url);+ if (!prefix || !target) {+ return false;+ }+ return prefix.protocol === target.protocol && prefix.host.toLowerCase() === target.host.toLowerCase() && target.pathname.startsWith(prefix.pathname);+}++function languageCode({ value }: { value: unknown }): string | undefined {+ const raw = text(value);+ if (raw.length === 0) {+ return undefined;+ }+ if (!LANGUAGE_PATTERN.test(raw)) {+ throw new Error(`Language Code "${raw.slice(0, 40)}" is not a BCP-47 code. Use a code such as "en-US", "de" or "pt-BR".`);+ }+ return raw;+}++function date({ value, label }: { value: unknown; label: string }): string | undefined {+ const raw = text(value);+ if (raw.length === 0) {+ return undefined;+ }+ const match = DATE_PATTERN.exec(raw);+ if (!match) {+ throw new Error(`${label} "${raw.slice(0, 40)}" is not a date. Use YYYY-MM-DD, e.g. "2026-09-01".`);+ }+ const [, year, month, day] = match;+ const parsed = new Date(Date.UTC(Number(year), Number(month) - 1, Number(day)));+ if (parsed.getUTCFullYear() !== Number(year) || parsed.getUTCMonth() !== Number(month) - 1 || parsed.getUTCDate() !== Number(day)) {+ throw new Error(`${label} "${raw.slice(0, 40)}" is not a real calendar date.`);+ }+ return `${year}-${month}-${day}`;+}++function dateRange({ startDate, endDate, lastNDays, today = pacificToday() }: { startDate: unknown; endDate: unknown; lastNDays?: unknown; today?: string }): { startDate: string; endDate: string } {+ const start = date({ value: startDate, label: 'Start Date' });+ const end = date({ value: endDate, label: 'End Date' });+ const days = optionalInteger({ value: lastNDays, label: 'Last N Days', min: 1, max: MAX_LAST_N_DAYS });+ if (days !== undefined && (start !== undefined || end !== undefined)) {+ throw new Error('Use either Last N Days or Start Date/End Date, not both.');+ }+ const yesterday = shiftDate({ value: today, days: -1 });+ if (start === undefined && end !== undefined) {+ throw new Error('Start Date is required when End Date is set.');+ }+ if (start === undefined) {+ const span = days ?? 28;+ return { startDate: shiftDate({ value: yesterday, days: -(span - 1) }), endDate: yesterday };+ }+ const resolvedEnd = end ?? yesterday;+ if (start > resolvedEnd) {+ throw new Error(`Start Date ${start} is after End Date ${resolvedEnd}.`);+ }+ return { startDate: start, endDate: resolvedEnd };+}++function requiredDateRange({ startDate, endDate }: { startDate: unknown; endDate: unknown }): { startDate: string; endDate: string } {+ const start = date({ value: startDate, label: 'Start Date' });+ const end = date({ value: endDate, label: 'End Date' });+ if (start === undefined || end === undefined) {+ throw new Error('Start Date and End Date are required (YYYY-MM-DD, Pacific Time).');+ }+ if (start > end) {+ throw new Error(`Start Date ${start} is after End Date ${end}.`);+ }+ return { startDate: start, endDate: end };+}++function pacificToday(now: Date = new Date()): string {+ return new Intl.DateTimeFormat('en-CA', { timeZone: PACIFIC_TIME_ZONE, year: 'numeric', month: '2-digit', day: '2-digit' }).format(now);+}++function shiftDate({ value, days }: { value: string; days: number }): string {+ const [year, month, day] = value.split('-').map(Number);+ return new Date(Date.UTC(year, month - 1, day) + days * DAY_MS).toISOString().slice(0, 10);+}++function optionalInteger({ value, label, min, max }: { value: unknown; label: string; min: number; max: number }): number | undefined {+ if (value === undefined || value === null || (typeof value === 'string' && value.trim() === '')) {+ return undefined;+ }+ const parsed = typeof value === 'number' ? value : typeof value === 'string' && /^-?\d+$/.test(value.trim()) ? Number(value.trim()) : Number.NaN;+ if (!Number.isInteger(parsed) || parsed < min || parsed > max) {+ throw new Error(`${label} must be a whole number from ${min.toLocaleString('en-US')} to ${max.toLocaleString('en-US')}.`);+ }+ return parsed;+}++function dimensions({ value }: { value: unknown }): Dimension[] {+ if (value === undefined || value === null || value === '') {+ return [];+ }+ const items = Array.isArray(value) ? value : [value];+ const names = items.map((item) => text(item)).filter((item) => item.length > 0);+ const resolved = names.map((name) => {+ const match = DIMENSIONS.find((dimension) => dimension.toLowerCase() === name.toLowerCase());+ if (!match) {+ throw new Error(`Dimension "${name.slice(0, 40)}" is not supported. Use any of: ${DIMENSIONS.join(', ')}.`);+ }+ return match;+ });+ const unique = new Set(resolved);+ if (unique.size !== resolved.length) {+ throw new Error('Each dimension can be used only once.');+ }+ return resolved;+}++function filters({ value }: { value: unknown }): AnalyticsFilter[] {+ if (value === undefined || value === null || value === '') {+ return [];+ }+ if (!Array.isArray(value)) {+ throw new Error('Filters must be a list of { dimension, operator, expression } items.');+ }+ return value.map((item, index) => {+ const position = `Filter ${index + 1}`;+ if (item === null || typeof item !== 'object' || Array.isArray(item)) {+ throw new Error(`${position} must have a dimension, an operator and an expression.`);+ }+ const dimension = FILTER_DIMENSIONS.find((name) => name.toLowerCase() === text(Reflect.get(item, 'dimension')).toLowerCase());+ if (!dimension) {+ throw new Error(`${position}: dimension must be one of ${FILTER_DIMENSIONS.join(', ')}.`);+ }+ const operator = OPERATORS.find((name) => name.toLowerCase() === text(Reflect.get(item, 'operator')).toLowerCase());+ if (!operator) {+ throw new Error(`${position}: operator must be one of ${OPERATORS.join(', ')}.`);+ }+ const raw: unknown = Reflect.get(item, 'expression');+ const expression = typeof raw === 'string' ? raw : text(raw);+ if (expression.trim().length === 0) {+ throw new Error(`${position}: expression is empty.`);+ }+ return { dimension, operator, expression: deviceName({ dimension, operator, expression }) };+ });+}++function deviceName({ dimension, operator, expression }: { dimension: string; operator: string; expression: string }): string {+ if (dimension !== 'device' || (operator !== 'equals' && operator !== 'notEquals')) {+ return expression;+ }+ const device = DEVICES.find((name) => name === expression.trim().toUpperCase());+ return device ?? expression;+}++function choice<T extends string>({ value, options, label }: { value: unknown; options: readonly T[]; label: string }): T | undefined {+ const raw = text(value);+ if (raw.length === 0) {+ return undefined;+ }+ const match = options.find((option) => option.toLowerCase() === raw.toLowerCase());+ if (!match) {+ throw new Error(`${label} "${raw.slice(0, 40)}" is not supported. Use one of: ${options.join(', ')}.`);+ }+ return match;+}++function analyticsQuery({+ startDate,+ endDate,+ dimensions: dimensionList,+ searchType,+ filters: filterList,+ aggregationType,+ dataState,+ rowLimit,+ startRow,+}: {+ startDate: string;+ endDate: string;+ dimensions: Dimension[];+ searchType: unknown;+ filters: AnalyticsFilter[];+ aggregationType: unknown;+ dataState: unknown;+ rowLimit: number | undefined;+ startRow: number | undefined;+}): AnalyticsQuery {+ const type = choice({ value: searchType, options: SEARCH_TYPES, label: 'Search Type' });+ const aggregation = choice({ value: aggregationType, options: AGGREGATION_TYPES, label: 'Aggregation Type' });+ const requestedState = choice({ value: dataState, options: DATA_STATES, label: 'Data State' });+ const usesHour = dimensionList.includes('hour');+ if (usesHour && requestedState !== undefined && requestedState !== 'hourly_all') {+ throw new Error('The "hour" dimension needs Data State "hourly_all" (or leave Data State empty). Hourly data covers only the last few days.');+ }+ const state = usesHour ? 'hourly_all' : requestedState;+ const usesPage = dimensionList.includes('page') || filterList.some((filter) => filter.dimension === 'page');+ if (aggregation === 'byProperty' && usesPage) {+ throw new Error('Aggregation Type "byProperty" cannot be combined with the "page" dimension or a page filter. Use "auto" or "byPage".');+ }+ const usesQuery = dimensionList.includes('query') || filterList.some((filter) => filter.dimension === 'query');+ if ((type === 'discover' || type === 'googleNews') && usesQuery) {+ throw new Error(`Search Type "${type}" has no search queries. Remove the "query" dimension and query filters.`);+ }+ if (aggregation === 'byNewsShowcasePanel' && type !== 'discover' && type !== 'googleNews') {+ throw new Error('Aggregation Type "byNewsShowcasePanel" works only with Search Type "discover" or "googleNews".');+ }+ return {+ startDate,+ endDate,+ ...(dimensionList.length > 0 ? { dimensions: dimensionList } : {}),+ ...(type ? { type } : {}),+ ...(filterList.length > 0 ? { dimensionFilterGroups: [{ groupType: 'and', filters: filterList }] } : {}),+ ...(aggregation ? { aggregationType: aggregation } : {}),+ ...(state ? { dataState: state } : {}),+ ...(rowLimit !== undefined ? { rowLimit } : {}),+ ...(startRow !== undefined ? { startRow } : {}),+ };+}++function parseUrl(value: string): URL | undefined {+ try {+ return new URL(value);+ } catch {+ return undefined;+ }+}++export const DIMENSIONS = ['date', 'hour', 'query', 'page', 'country', 'device', 'searchAppearance'] as const;+export const FILTER_DIMENSIONS = ['query', 'page', 'country', 'device', 'searchAppearance'] as const;+export const OPERATORS = ['equals', 'notEquals', 'contains', 'notContains', 'includingRegex', 'excludingRegex'] as const;+export const SEARCH_TYPES = ['web', 'image', 'video', 'news', 'discover', 'googleNews'] as const;+export const AGGREGATION_TYPES = ['auto', 'byPage', 'byProperty', 'byNewsShowcasePanel'] as const;+const DEVICES = ['DESKTOP', 'MOBILE', 'TABLET'];++export const DATA_STATES = ['final', 'all', 'hourly_all'] as const;++export const gscInputs = {+ siteUrl,+ absoluteUrl,+ urlInProperty,+ belongsToProperty,+ languageCode,+ date,+ dateRange,+ requiredDateRange,+ pacificToday,+ optionalInteger,+ dimensions,+ filters,+ choice,+ analyticsQuery,+ HUMAN_MAX_ROW_LIMIT,+ MAX_START_ROW,+ MAX_LAST_N_DAYS,+};++export type Dimension = (typeof DIMENSIONS)[number];+export type AnalyticsFilter = { dimension: (typeof FILTER_DIMENSIONS)[number]; operator: (typeof OPERATORS)[number]; expression: string };+export type AnalyticsQuery = {+ startDate: string;+ endDate: string;+ dimensions?: Dimension[];+ type?: (typeof SEARCH_TYPES)[number];+ dimensionFilterGroups?: { groupType: 'and'; filters: AnalyticsFilter[] }[];+ aggregationType?: (typeof AGGREGATION_TYPES)[number];+ dataState?: (typeof DATA_STATES)[number];+ rowLimit?: number;+ startRow?: number;+};diff --git a/packages/pieces/community/google-search-console/src/lib/common/operations.ts b/packages/pieces/community/google-search-console/src/lib/common/operations.tsnew file mode 100644index 00000000000..2b6a6ca3228--- /dev/null+++ b/packages/pieces/community/google-search-console/src/lib/common/operations.ts@@ -0,0 +1,117 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { gscClient, GscAuth } from './client';+import { AnalyticsQuery, Dimension } from './inputs';+import { gscShape } from './shape';++async function listSites({ auth }: { auth: GscAuth }): Promise<{ siteEntry: SiteEntryList; count: number }> {+ const response = await gscClient.request<unknown>({ auth, method: HttpMethod.GET, path: ['webmasters', 'v3', 'sites'], operation: 'list sites' });+ const siteEntry = gscShape.list({ value: response.body, key: 'siteEntry' }).map(gscShape.site);+ return { siteEntry, count: siteEntry.length };+}++async function getSite({ auth, siteUrl }: { auth: GscAuth; siteUrl: string }) {+ const response = await gscClient.request<unknown>({ auth, method: HttpMethod.GET, path: gscClient.sitePath(siteUrl), operation: `read the property ${siteUrl}` });+ return gscShape.site(response.body);+}++async function addSite({ auth, siteUrl }: { auth: GscAuth; siteUrl: string }): Promise<{ success: true; siteUrl: string; permissionLevel: string | null }> {+ await gscClient.request<unknown>({ auth, method: HttpMethod.PUT, path: gscClient.sitePath(siteUrl), operation: `add the property ${siteUrl}` });+ try {+ const site = await getSite({ auth, siteUrl });+ return { success: true, siteUrl, permissionLevel: site.permissionLevel || null };+ } catch {+ return { success: true, siteUrl, permissionLevel: null };+ }+}++async function deleteSite({ auth, siteUrl }: { auth: GscAuth; siteUrl: string }): Promise<void> {+ await gscClient.request<unknown>({ auth, method: HttpMethod.DELETE, path: gscClient.sitePath(siteUrl), operation: `remove the property ${siteUrl}` });+}++async function listSitemaps({ auth, siteUrl, sitemapIndex }: { auth: GscAuth; siteUrl: string; sitemapIndex?: string }): Promise<Record<string, unknown>[]> {+ const response = await gscClient.request<unknown>({+ auth,+ method: HttpMethod.GET,+ path: [...gscClient.sitePath(siteUrl), 'sitemaps'],+ query: { sitemapIndex },+ operation: `list the sitemaps of ${siteUrl}`,+ });+ return gscShape.list({ value: response.body, key: 'sitemap' });+}++async function getSitemap({ auth, siteUrl, feedpath }: { auth: GscAuth; siteUrl: string; feedpath: string }): Promise<unknown> {+ const response = await gscClient.request<unknown>({+ auth,+ method: HttpMethod.GET,+ path: [...gscClient.sitePath(siteUrl), 'sitemaps', encodeURIComponent(feedpath)],+ operation: `read the sitemap ${feedpath}`,+ });+ return response.body;+}++async function submitSitemap({ auth, siteUrl, feedpath }: { auth: GscAuth; siteUrl: string; feedpath: string }): Promise<void> {+ await gscClient.request<unknown>({+ auth,+ method: HttpMethod.PUT,+ path: [...gscClient.sitePath(siteUrl), 'sitemaps', encodeURIComponent(feedpath)],+ operation: `submit the sitemap ${feedpath}`,+ });+}++async function deleteSitemap({ auth, siteUrl, feedpath }: { auth: GscAuth; siteUrl: string; feedpath: string }): Promise<void> {+ await gscClient.request<unknown>({+ auth,+ method: HttpMethod.DELETE,+ path: [...gscClient.sitePath(siteUrl), 'sitemaps', encodeURIComponent(feedpath)],+ operation: `delete the sitemap ${feedpath}`,+ });+}++async function searchAnalytics({ auth, siteUrl, query }: { auth: GscAuth; siteUrl: string; query: AnalyticsQuery }): Promise<AnalyticsResult> {+ const response = await gscClient.request<unknown>({+ auth,+ method: HttpMethod.POST,+ path: [...gscClient.sitePath(siteUrl), 'searchAnalytics', 'query'],+ body: query,+ operation: `query search analytics for ${siteUrl}`,+ });+ const body = gscShape.isRecord(response.body) ? response.body : {};+ const rawRows = gscShape.list({ value: body, key: 'rows' });+ const dimensions: Dimension[] = query.dimensions ?? [];+ return {+ status: response.status,+ data: { ...body, rows: rawRows },+ rows: rawRows.map((row) => gscShape.analyticsRow({ row, dimensions })),+ };+}++async function inspectUrl({ auth, siteUrl, inspectionUrl, languageCode }: { auth: GscAuth; siteUrl: string; inspectionUrl: string; languageCode?: string }): Promise<unknown> {+ const response = await gscClient.request<unknown>({+ auth,+ method: HttpMethod.POST,+ path: ['v1', 'urlInspection', 'index:inspect'],+ body: { inspectionUrl, siteUrl, ...(languageCode ? { languageCode } : {}) },+ operation: `inspect ${inspectionUrl}`,+ });+ return response.body;+}++export const gscOps = {+ listSites,+ getSite,+ addSite,+ deleteSite,+ listSitemaps,+ getSitemap,+ submitSitemap,+ deleteSitemap,+ searchAnalytics,+ inspectUrl,+};++type SiteEntryList = { siteUrl: string; permissionLevel: string }[];+type AnalyticsResult = {+ status: number;+ data: Record<string, unknown> & { rows: Record<string, unknown>[] };+ rows: Record<string, string | number | null>[];+};diff --git a/packages/pieces/community/google-search-console/src/lib/common/shape.ts b/packages/pieces/community/google-search-console/src/lib/common/shape.tsnew file mode 100644index 00000000000..e1cc53084d8--- /dev/null+++ b/packages/pieces/community/google-search-console/src/lib/common/shape.ts@@ -0,0 +1,193 @@+import { Dimension } from './inputs';++const MAX_REFERRING_URLS = 20;++function isRecord(value: unknown): value is Record<string, unknown> {+ return value !== null && typeof value === 'object' && !Array.isArray(value);+}++function str(value: unknown): string | null {+ return typeof value === 'string' && value.length > 0 ? value : null;+}++function num(value: unknown): number | null {+ if (typeof value === 'number' && Number.isFinite(value)) {+ return value;+ }+ if (typeof value === 'string' && value.trim() !== '' && Number.isFinite(Number(value))) {+ return Number(value);+ }+ return null;+}++function bool(value: unknown): boolean {+ return value === true;+}++function records(value: unknown): Record<string, unknown>[] {+ return Array.isArray(value) ? value.filter(isRecord) : [];+}++function strings(value: unknown): string[] {+ return Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : [];+}++function list({ value, key }: { value: unknown; key: string }): Record<string, unknown>[] {+ return isRecord(value) ? records(value[key]) : [];+}++function site(value: unknown): SiteEntry {+ const record = isRecord(value) ? value : {};+ return { siteUrl: str(record['siteUrl']) ?? '', permissionLevel: str(record['permissionLevel']) ?? '' };+}++function siteFlat(value: unknown): FlatSite {+ const entry = site(value);+ return {+ site_url: entry.siteUrl,+ permission_level: entry.permissionLevel,+ is_verified: entry.permissionLevel !== '' && entry.permissionLevel !== 'siteUnverifiedUser',+ };+}++function permissionLabel(level: string): string {+ return PERMISSION_LABELS[level] ?? level;+}++function analyticsRow({ row, dimensions }: { row: unknown; dimensions: Dimension[] }): FlatRow {+ const record = isRecord(row) ? row : {};+ const keys = strings(record['keys']);+ const columns = Object.fromEntries(dimensions.map((dimension, index) => [DIMENSION_COLUMNS[dimension], keys[index] ?? null]));+ const impressions = num(record['impressions']) ?? 0;+ return {+ ...columns,+ clicks: num(record['clicks']) ?? 0,+ impressions,+ ctr: num(record['ctr']) ?? 0,+ position: impressions > 0 ? num(record['position']) : null,+ };+}++function sitemapFlat(value: unknown): FlatSitemap {+ const record = isRecord(value) ? value : {};+ const contents = records(record['contents']).map((content) => ({ type: str(content['type']), submitted: num(content['submitted']) ?? 0 }));+ return {+ path: str(record['path']),+ type: str(record['type']),+ is_sitemaps_index: bool(record['isSitemapsIndex']),+ is_pending: bool(record['isPending']),+ last_submitted: str(record['lastSubmitted']),+ last_downloaded: str(record['lastDownloaded']),+ errors: num(record['errors']) ?? 0,+ warnings: num(record['warnings']) ?? 0,+ submitted_urls: contents.reduce((total, content) => total + content.submitted, 0),+ contents,+ };+}++function inspection({ body, inspectedUrl }: { body: unknown; inspectedUrl: string }): FlatInspection {+ const result = isRecord(body) && isRecord(body['inspectionResult']) ? body['inspectionResult'] : {};+ const index = isRecord(result['indexStatusResult']) ? result['indexStatusResult'] : {};+ const rich = isRecord(result['richResultsResult']) ? result['richResultsResult'] : {};+ const amp = isRecord(result['ampResult']) ? result['ampResult'] : {};+ const mobile = isRecord(result['mobileUsabilityResult']) ? result['mobileUsabilityResult'] : {};+ const referring = strings(index['referringUrls']);+ const detected = records(rich['detectedItems']);+ const issues = detected.flatMap((group) =>+ records(group['items']).flatMap((item) =>+ records(item['issues']).map((issue) => ({+ type: str(group['richResultType']),+ item: str(item['name']),+ severity: str(issue['severity']),+ message: str(issue['issueMessage']),+ })),+ ),+ );+ return {+ inspected_url: inspectedUrl,+ verdict: str(index['verdict']),+ coverage_state: str(index['coverageState']),+ indexing_state: str(index['indexingState']),+ robots_txt_state: str(index['robotsTxtState']),+ page_fetch_state: str(index['pageFetchState']),+ last_crawl_time: str(index['lastCrawlTime']),+ crawled_as: str(index['crawledAs']),+ google_canonical: str(index['googleCanonical']),+ user_canonical: str(index['userCanonical']),+ sitemaps: strings(index['sitemap']),+ referring_urls: referring.slice(0, MAX_REFERRING_URLS),+ referring_urls_truncated: referring.length > MAX_REFERRING_URLS,+ rich_results_verdict: str(rich['verdict']),+ rich_result_types: detected.map((group) => str(group['richResultType'])).filter((type): type is string => type !== null),+ rich_result_issues: issues,+ amp_verdict: str(amp['verdict']),+ mobile_usability_verdict: str(mobile['verdict']),+ inspection_result_link: str(result['inspectionResultLink']),+ };+}++const PERMISSION_LABELS: Record<string, string> = {+ siteOwner: 'Owner',+ siteFullUser: 'Full',+ siteRestrictedUser: 'Restricted',+ siteUnverifiedUser: 'Unverified',+};++const DIMENSION_COLUMNS: Record<Dimension, string> = {+ date: 'date',+ hour: 'hour',+ query: 'query',+ page: 'page',+ country: 'country',+ device: 'device',+ searchAppearance: 'search_appearance',+};++export const gscShape = {+ isRecord,+ list,+ site,+ siteFlat,+ permissionLabel,+ analyticsRow,+ sitemapFlat,+ inspection,+ MAX_REFERRING_URLS,+};++export type SiteEntry = { siteUrl: string; permissionLevel: string };+export type FlatSite = { site_url: string; permission_level: string; is_verified: boolean };+export type FlatRow = Record<string, string | number | null>;+export type FlatSitemap = {+ path: string | null;+ type: string | null;+ is_sitemaps_index: boolean;+ is_pending: boolean;+ last_submitted: string | null;+ last_downloaded: string | null;+ errors: number;+ warnings: number;+ submitted_urls: number;+ contents: { type: string | null; submitted: number }[];+};+export type FlatInspection = {+ inspected_url: string;+ verdict: string | null;+ coverage_state: string | null;+ indexing_state: string | null;+ robots_txt_state: string | null;+ page_fetch_state: string | null;+ last_crawl_time: string | null;+ crawled_as: string | null;+ google_canonical: string | null;+ user_canonical: string | null;+ sitemaps: string[];+ referring_urls: string[];+ referring_urls_truncated: boolean;+ rich_results_verdict: string | null;+ rich_result_types: string[];+ rich_result_issues: { type: string | null; item: string | null; severity: string | null; message: string | null }[];+ amp_verdict: string | null;+ mobile_usability_verdict: string | null;+ inspection_result_link: string | null;+};diff --git a/packages/pieces/community/google-search-console/src/lib/output-schemas.ts b/packages/pieces/community/google-search-console/src/lib/output-schemas.tsnew file mode 100644index 00000000000..65d76451e1d--- /dev/null+++ b/packages/pieces/community/google-search-console/src/lib/output-schemas.ts@@ -0,0 +1,250 @@+import { OutputSchema } from '@activepieces/pieces-framework';++const siteEntryFields: OutputSchema['fields'] = [+ { key: 'siteUrl', label: 'Site URL' },+ { key: 'permissionLevel', label: 'Permission Level' },+];++const flatSiteFields: OutputSchema['fields'] = [+ { key: 'site_url', label: 'Site URL' },+ { key: 'permission_level', label: 'Permission Level' },+ { key: 'is_verified', label: 'Is Verified', format: 'boolean' },+];++const rawSitemapFields: OutputSchema['fields'] = [+ { key: 'path', label: 'Sitemap URL', format: 'url' },+ { key: 'type', label: 'Type' },+ { key: 'lastSubmitted', label: 'Last Submitted', format: 'datetime' },+ { key: 'lastDownloaded', label: 'Last Downloaded', format: 'datetime' },+ { key: 'isPending', label: 'Is Pending', format: 'boolean' },+ { key: 'isSitemapsIndex', label: 'Is Sitemap Index', format: 'boolean' },+ { key: 'errors', label: 'Errors', format: 'number' },+ { key: 'warnings', label: 'Warnings', format: 'number' },+ {+ key: 'contents',+ label: 'Contents',+ labelKey: 'type',+ listItems: [+ { key: 'type', label: 'Type' },+ { key: 'submitted', label: 'Submitted URLs', format: 'number' },+ ],+ },+];++const flatSitemapFields: OutputSchema['fields'] = [+ { key: 'path', label: 'Sitemap URL', format: 'url' },+ { key: 'type', label: 'Type' },+ { key: 'is_sitemaps_index', label: 'Is Sitemap Index', format: 'boolean' },+ { key: 'is_pending', label: 'Is Pending', format: 'boolean' },+ { key: 'last_submitted', label: 'Last Submitted', format: 'datetime' },+ { key: 'last_downloaded', label: 'Last Downloaded', format: 'datetime' },+ { key: 'errors', label: 'Errors', format: 'number' },+ { key: 'warnings', label: 'Warnings', format: 'number' },+ { key: 'submitted_urls', label: 'Submitted URLs', format: 'number' },+ {+ key: 'contents',+ label: 'Contents',+ labelKey: 'type',+ listItems: [+ { key: 'type', label: 'Type' },+ { key: 'submitted', label: 'Submitted URLs', format: 'number' },+ ],+ },+];++const analyticsRowFields: OutputSchema['fields'] = [+ { key: 'date', label: 'Date', format: 'date' },+ { key: 'hour', label: 'Hour', format: 'datetime' },+ { key: 'query', label: 'Query' },+ { key: 'page', label: 'Page', format: 'url' },+ { key: 'country', label: 'Country' },+ { key: 'device', label: 'Device' },+ { key: 'search_appearance', label: 'Search Appearance' },+ { key: 'clicks', label: 'Clicks', format: 'number' },+ { key: 'impressions', label: 'Impressions', format: 'number' },+ { key: 'ctr', label: 'CTR', format: 'number', description: 'Click-through rate as a fraction from 0 to 1.' },+ { key: 'position', label: 'Average Position', format: 'number', description: 'Impression-weighted average position (1 is the top); empty when the row has no impressions.' },+];++const inspectionFields: OutputSchema['fields'] = [+ { key: 'inspected_url', label: 'Inspected URL', format: 'url' },+ { key: 'verdict', label: 'Verdict' },+ { key: 'coverage_state', label: 'Coverage State' },+ { key: 'indexing_state', label: 'Indexing State' },+ { key: 'robots_txt_state', label: 'robots.txt State' },+ { key: 'page_fetch_state', label: 'Page Fetch State' },+ { key: 'last_crawl_time', label: 'Last Crawl Time', format: 'datetime' },+ { key: 'crawled_as', label: 'Crawled As' },+ { key: 'google_canonical', label: 'Google Canonical', format: 'url' },+ { key: 'user_canonical', label: 'User Canonical', format: 'url' },+ { key: 'sitemaps', label: 'Sitemaps' },+ { key: 'referring_urls', label: 'Referring URLs' },+ { key: 'referring_urls_truncated', label: 'Referring URLs Truncated', format: 'boolean' },+ { key: 'rich_results_verdict', label: 'Rich Results Verdict' },+ { key: 'rich_result_types', label: 'Rich Result Types' },+ {+ key: 'rich_result_issues',+ label: 'Rich Result Issues',+ labelKey: 'message',+ listItems: [+ { key: 'type', label: 'Rich Result Type' },+ { key: 'item', label: 'Item' },+ { key: 'severity', label: 'Severity' },+ { key: 'message', label: 'Message' },+ ],+ },+ { key: 'amp_verdict', label: 'AMP Verdict' },+ { key: 'mobile_usability_verdict', label: 'Mobile Usability Verdict' },+ { key: 'inspection_result_link', label: 'Search Console Link', format: 'url' },+];++const listSites: OutputSchema = {+ fields: [+ { key: 'siteEntry', label: 'Sites', labelKey: 'siteUrl', listItems: siteEntryFields },+ { key: 'count', label: 'Count', format: 'number' },+ ],+};++const getSite: OutputSchema = { fields: flatSiteFields };++const addSite: OutputSchema = {+ fields: [+ { key: 'success', label: 'Success', format: 'boolean' },+ { key: 'siteUrl', label: 'Site URL' },+ { key: 'permissionLevel', label: 'Permission Level' },+ ],+};++const deleteSite: OutputSchema = {+ fields: [+ { key: 'success', label: 'Success', format: 'boolean' },+ { key: 'siteUrl', label: 'Site URL' },+ ],+};++const deleteSiteAi: OutputSchema = {+ fields: [+ { key: 'success', label: 'Success', format: 'boolean' },+ { key: 'site_url', label: 'Site URL' },+ ],+};++const listSitemaps: OutputSchema = {+ fields: [+ { key: 'sitemap', label: 'Sitemaps', labelKey: 'path', listItems: rawSitemapFields },+ { key: 'count', label: 'Count', format: 'number' },+ ],+};++const listSitemapsAi: OutputSchema = {+ fields: [+ { key: 'sitemaps', label: 'Sitemaps', labelKey: 'path', listItems: flatSitemapFields },+ { key: 'count', label: 'Count', format: 'number' },+ ],+};++const getSitemap: OutputSchema = { fields: flatSitemapFields };++const sitemapChange: OutputSchema = {+ fields: [+ { key: 'success', label: 'Success', format: 'boolean' },+ { key: 'siteUrl', label: 'Site URL' },+ { key: 'feedpath', label: 'Sitemap URL', format: 'url' },+ ],+};++const sitemapChangeAi: OutputSchema = {+ fields: [+ { key: 'success', label: 'Success', format: 'boolean' },+ { key: 'site_url', label: 'Site URL' },+ { key: 'feedpath', label: 'Sitemap URL', format: 'url' },+ ],+};++const searchAnalytics: OutputSchema = {+ fields: [+ { key: 'rows', label: 'Rows', listItems: analyticsRowFields },+ { key: 'row_count', label: 'Row Count', format: 'number' },+ {+ key: 'data',+ label: 'Google Response',+ children: [+ { key: 'responseAggregationType', label: 'Aggregation Type' },+ {+ key: 'metadata',+ label: 'Metadata',+ children: [+ { key: 'firstIncompleteDate', label: 'First Incomplete Date', format: 'date' },+ { key: 'firstIncompleteHour', label: 'First Incomplete Hour', format: 'datetime' },+ ],+ },+ ],+ },+ { key: 'status', label: 'HTTP Status', format: 'number' },+ ],+};++const searchAnalyticsAi: OutputSchema = {+ fields: [+ { key: 'rows', label: 'Rows', listItems: analyticsRowFields },+ { key: 'row_count', label: 'Row Count', format: 'number' },+ { key: 'has_more', label: 'Has More', format: 'boolean' },+ { key: 'next_start_row', label: 'Next Start Row', format: 'number' },+ { key: 'start_date', label: 'Start Date', format: 'date' },+ { key: 'end_date', label: 'End Date', format: 'date' },+ { key: 'data_state', label: 'Data State' },+ { key: 'aggregation_type', label: 'Aggregation Type' },+ { key: 'first_incomplete_date', label: 'First Incomplete Date', format: 'date' },+ { key: 'first_incomplete_hour', label: 'First Incomplete Hour', format: 'datetime' },+ ],+};++const urlInspection: OutputSchema = {+ fields: [+ {+ key: 'inspectionResult',+ label: 'Inspection Result',+ children: [+ { key: 'inspectionResultLink', label: 'Search Console Link', format: 'url' },+ {+ key: 'indexStatusResult',+ label: 'Index Status',+ children: [+ { key: 'verdict', label: 'Verdict' },+ { key: 'coverageState', label: 'Coverage State' },+ { key: 'indexingState', label: 'Indexing State' },+ { key: 'robotsTxtState', label: 'robots.txt State' },+ { key: 'pageFetchState', label: 'Page Fetch State' },+ { key: 'lastCrawlTime', label: 'Last Crawl Time', format: 'datetime' },+ { key: 'crawledAs', label: 'Crawled As' },+ { key: 'googleCanonical', label: 'Google Canonical', format: 'url' },+ { key: 'userCanonical', label: 'User Canonical', format: 'url' },+ { key: 'sitemap', label: 'Sitemaps' },+ { key: 'referringUrls', label: 'Referring URLs' },+ ],+ },+ { key: 'richResultsResult', label: 'Rich Results', children: [{ key: 'verdict', label: 'Verdict' }] },+ { key: 'mobileUsabilityResult', label: 'Mobile Usability', children: [{ key: 'verdict', label: 'Verdict' }] },+ ],+ },+ ],+};++const inspectUrlAi: OutputSchema = { fields: inspectionFields };++export const gscOutputSchemas = {+ listSites,+ getSite,+ addSite,+ deleteSite,+ deleteSiteAi,+ listSitemaps,+ listSitemapsAi,+ getSitemap,+ sitemapChange,+ sitemapChangeAi,+ searchAnalytics,+ searchAnalyticsAi,+ urlInspection,+ inspectUrlAi,+};diff --git a/packages/pieces/community/google-search-console/test/actions.test.ts b/packages/pieces/community/google-search-console/test/actions.test.tsnew file mode 100644index 00000000000..03d3e3937a0--- /dev/null+++ b/packages/pieces/community/google-search-console/test/actions.test.ts@@ -0,0 +1,262 @@+import { afterEach, describe, expect, test, vi } from 'vitest';+import { addSite } from '../src/lib/actions/add-a-site';+import { deleteSiteBySiteUrl } from '../src/lib/actions/ai/delete-site-by-site-url';+import { deleteSitemapBySiteUrl } from '../src/lib/actions/ai/delete-sitemap-by-site-url';+import { getSite } from '../src/lib/actions/ai/get-site';+import { getSitemap } from '../src/lib/actions/ai/get-sitemap';+import { inspectUrlBySiteUrl } from '../src/lib/actions/ai/inspect-url-by-site-url';+import { listSitemapsBySiteUrl } from '../src/lib/actions/ai/list-sitemaps-by-site-url';+import { searchAnalyticsBySiteUrl } from '../src/lib/actions/ai/search-analytics-by-site-url';+import { submitSitemapBySiteUrl } from '../src/lib/actions/ai/submit-sitemap-by-site-url';+import { deleteSite } from '../src/lib/actions/delete-a-site';+import { deleteSitemap } from '../src/lib/actions/delete-a-sitemap';+import { listSitemaps } from '../src/lib/actions/list-sitemaps';+import { listSites } from '../src/lib/actions/list-sites';+import { searchAnalytics } from '../src/lib/actions/search-analytics';+import { submitSitemap } from '../src/lib/actions/submit-a-sitemap';+import { urlInspection } from '../src/lib/actions/url-inspection';+import { context, googleError, SITE, SITE_ENCODED, stubFetch } from './helpers';++afterEach(() => {+ vi.unstubAllGlobals();+});++const SITES = '/webmasters/v3/sites';+const FEED = 'https://ap-gsc-delete-test.example.com/sitemap-ap-test.xml';+const FEED_ENCODED = 'https%3A%2F%2Fap-gsc-delete-test.example.com%2Fsitemap-ap-test.xml';++describe('sites', () => {+ test('list sites returns an empty list and count when Google omits siteEntry', async () => {+ const seen = stubFetch(() => ({ body: {} }));+ expect(await listSites.run(context({}))).toEqual({ siteEntry: [], count: 0 });+ expect(seen[0].method).toBe('GET');+ expect(seen[0].rawPath).toBe(SITES);+ });++ test('get site reports permission and verification', async () => {+ const seen = stubFetch(() => ({ body: { siteUrl: SITE, permissionLevel: 'siteUnverifiedUser' } }));+ expect(await getSite.run(context({ site_url: 'https://ap-gsc-delete-test.example.com' }))).toEqual({+ site_url: SITE,+ permission_level: 'siteUnverifiedUser',+ is_verified: false,+ });+ expect(seen[0].rawPath).toBe(`${SITES}/${SITE_ENCODED}`);+ });++ test('add site PUTs then reads the permission level', async () => {+ const seen = stubFetch((request) => (request.method === 'PUT' ? { status: 204 } : { body: { siteUrl: SITE, permissionLevel: 'siteUnverifiedUser' } }));+ expect(await addSite.run(context({ siteUrl: 'https://ap-gsc-delete-test.example.com' }))).toEqual({ success: true, siteUrl: SITE, permissionLevel: 'siteUnverifiedUser' });+ expect(seen.map((request) => `${request.method} ${request.rawPath}`)).toEqual([`PUT ${SITES}/${SITE_ENCODED}`, `GET ${SITES}/${SITE_ENCODED}`]);+ });++ test('add site still succeeds when the follow-up read fails', async () => {+ stubFetch((request) => (request.method === 'PUT' ? { status: 204 } : { status: 503, body: googleError({ code: 503, message: 'backend' }) }));+ expect(await addSite.run(context({ siteUrl: SITE }))).toEqual({ success: true, siteUrl: SITE, permissionLevel: null });+ });++ test('add site still succeeds when the follow-up read hits a network error', async () => {+ let calls = 0;+ vi.stubGlobal(+ 'fetch',+ vi.fn(async () => {+ calls += 1;+ if (calls === 1) {+ return new Response(null, { status: 204 });+ }+ throw new TypeError('fetch failed');+ }),+ );+ expect(await addSite.run(context({ siteUrl: SITE }))).toEqual({ success: true, siteUrl: SITE, permissionLevel: null });+ expect(calls).toBe(2);+ });++ test('add site fails when the PUT fails', async () => {+ stubFetch(() => ({ status: 400, body: googleError({ code: 400, message: 'Invalid site URL', reason: 'invalid' }) }));+ await expect(addSite.run(context({ siteUrl: SITE }))).rejects.toThrow('Invalid site URL');+ });++ test('delete site, human and ai', async () => {+ const seen = stubFetch(() => ({ status: 204 }));+ expect(await deleteSite.run(context({ siteUrl: SITE }))).toEqual({ success: true, siteUrl: SITE });+ expect(await deleteSiteBySiteUrl.run(context({ site_url: 'sc-domain:example.com' }))).toEqual({ success: true, site_url: 'sc-domain:example.com' });+ expect(seen.map((request) => `${request.method} ${request.rawPath}`)).toEqual([`DELETE ${SITES}/${SITE_ENCODED}`, `DELETE ${SITES}/sc-domain%3Aexample.com`]);+ });++ test('a second delete surfaces the 404 instead of reporting success', async () => {+ stubFetch(() => ({ status: 404, body: googleError({ code: 404, message: `'${SITE}' is not a verified Search Console site in this account.`, reason: 'notFound' }) }));+ await expect(deleteSiteBySiteUrl.run(context({ site_url: SITE }))).rejects.toThrow('not found');+ });++ test('refuses a malformed site URL before any request', async () => {+ const seen = stubFetch(() => ({ body: {} }));+ await expect(deleteSiteBySiteUrl.run(context({ site_url: 'example.com' }))).rejects.toThrow('not a Search Console property');+ expect(seen).toHaveLength(0);+ });+});++describe('sitemaps', () => {+ const rawSitemap = {+ path: FEED,+ lastSubmitted: '2026-10-01T10:00:00.000Z',+ isPending: true,+ isSitemapsIndex: false,+ type: 'sitemap',+ warnings: '0',+ errors: '2',+ contents: [{ type: 'web', submitted: '5', indexed: '0' }],+ };++ test('list sitemaps (human) keeps the raw items, adds a count and passes sitemapIndex', async () => {+ const seen = stubFetch(() => ({ body: { sitemap: [rawSitemap] } }));+ expect(await listSitemaps.run(context({ siteUrl: SITE, sitemapIndex: 'https://ap-gsc-delete-test.example.com/index.xml' }))).toEqual({ sitemap: [rawSitemap], count: 1 });+ expect(seen[0].rawPath).toBe(`${SITES}/${SITE_ENCODED}/sitemaps`);+ expect(seen[0].query.get('sitemapIndex')).toBe('https://ap-gsc-delete-test.example.com/index.xml');+ });++ test('list sitemaps returns [] when Google omits the key', async () => {+ stubFetch(() => ({ body: {} }));+ expect(await listSitemaps.run(context({ siteUrl: SITE }))).toEqual({ sitemap: [], count: 0 });+ expect(await listSitemapsBySiteUrl.run(context({ site_url: SITE }))).toEqual({ sitemaps: [], count: 0 });+ });++ test('list and get sitemap (ai) flatten counts to numbers', async () => {+ const seen = stubFetch((request) => (request.rawPath.endsWith('/sitemaps') ? { body: { sitemap: [rawSitemap] } } : { body: rawSitemap }));+ const listed = await listSitemapsBySiteUrl.run(context({ site_url: SITE }));+ expect(listed).toMatchObject({ count: 1, sitemaps: [{ path: FEED, errors: 2, warnings: 0, submitted_urls: 5, is_pending: true }] });+ const single = await getSitemap.run(context({ site_url: SITE, feedpath: FEED }));+ expect(single).toMatchObject({ path: FEED, errors: 2, submitted_urls: 5, last_downloaded: null });+ expect(seen[1].rawPath).toBe(`${SITES}/${SITE_ENCODED}/sitemaps/${FEED_ENCODED}`);+ });++ test('submit and delete sitemap send PUT/DELETE to the encoded feedpath', async () => {+ const seen = stubFetch(() => ({ status: 204 }));+ expect(await submitSitemap.run(context({ siteUrl: SITE, feedpath: FEED }))).toEqual({ success: true, siteUrl: SITE, feedpath: FEED });+ expect(await submitSitemapBySiteUrl.run(context({ site_url: SITE, feedpath: FEED }))).toEqual({ success: true, site_url: SITE, feedpath: FEED });+ expect(await deleteSitemap.run(context({ siteUrl: SITE, feedpath: FEED }))).toEqual({ success: true, siteUrl: SITE, feedpath: FEED });+ expect(await deleteSitemapBySiteUrl.run(context({ site_url: SITE, feedpath: FEED }))).toEqual({ success: true, site_url: SITE, feedpath: FEED });+ const target = `${SITES}/${SITE_ENCODED}/sitemaps/${FEED_ENCODED}`;+ expect(seen.map((request) => `${request.method} ${request.rawPath}`)).toEqual([`PUT ${target}`, `PUT ${target}`, `DELETE ${target}`, `DELETE ${target}`]);+ });++ test('submit refuses a relative sitemap path', async () => {+ const seen = stubFetch(() => ({ status: 204 }));+ await expect(submitSitemapBySiteUrl.run(context({ site_url: SITE, feedpath: 'sitemap.xml' }))).rejects.toThrow('full http(s) URL');+ expect(seen).toHaveLength(0);+ });++ test('a restricted user gets the permission hint', async () => {+ stubFetch(() => ({ status: 403, body: googleError({ code: 403, message: `User does not have sufficient permission for site '${SITE}'.` }) }));+ await expect(submitSitemapBySiteUrl.run(context({ site_url: SITE, feedpath: FEED }))).rejects.toThrow('Owner or Full permission');+ });+});++describe('search analytics', () => {+ const response = {+ rows: [+ { keys: ['shoes', 'https://ex.com/p'], clicks: 3, impressions: 40, ctr: 0.075, position: 4.2 },+ { keys: ['boots', 'https://ex.com/q'], clicks: 1, impressions: 10, ctr: 0.1, position: 8 },+ ],+ responseAggregationType: 'byPage',+ };++ test('human action sends the typed body and returns data, status and flattened rows', async () => {+ const seen = stubFetch(() => ({ body: response }));+ const result = await searchAnalytics.run(+ context({+ siteUrl: SITE,+ startDate: '2026-09-01T00:00:00.000Z',+ endDate: '2026-09-30T00:00:00.000Z',+ dimensions: ['Query', 'page'],+ searchType: 'web',+ filters: [{ dimension: 'device', operator: 'equals', expression: 'mobile' }],+ rowLimit: 2,+ }),+ );+ expect(seen[0].method).toBe('POST');+ expect(seen[0].rawPath).toBe(`${SITES}/${SITE_ENCODED}/searchAnalytics/query`);+ expect(seen[0].json).toEqual({+ startDate: '2026-09-01',+ endDate: '2026-09-30',+ dimensions: ['query', 'page'],+ type: 'web',+ dimensionFilterGroups: [{ groupType: 'and', filters: [{ dimension: 'device', operator: 'equals', expression: 'MOBILE' }] }],+ rowLimit: 2,+ });+ expect(result).toEqual({+ data: response,+ status: 200,+ rows: [+ { query: 'shoes', page: 'https://ex.com/p', clicks: 3, impressions: 40, ctr: 0.075, position: 4.2 },+ { query: 'boots', page: 'https://ex.com/q', clicks: 1, impressions: 10, ctr: 0.1, position: 8 },+ ],+ row_count: 2,+ });+ expect(Object.keys(result)).not.toContain('config');+ expect(Object.keys(result)).not.toContain('headers');+ });++ test('human action normalises absent rows and sends hourly_all for hour', async () => {+ const seen = stubFetch(() => ({ body: { responseAggregationType: 'byProperty' } }));+ const result = await searchAnalytics.run(context({ siteUrl: SITE, startDate: '2026-10-01', endDate: '2026-10-05', dimensions: ['hour'] }));+ expect(Reflect.get(Object(seen[0].json), 'dataState')).toBe('hourly_all');+ expect(result).toMatchObject({ data: { rows: [], responseAggregationType: 'byProperty' }, rows: [], row_count: 0 });+ });++ test('human action validates row limit and dates before any request', async () => {+ const seen = stubFetch(() => ({ body: {} }));+ await expect(searchAnalytics.run(context({ siteUrl: SITE, startDate: '2026-09-01', endDate: '2026-09-30', rowLimit: 30000 }))).rejects.toThrow('25,000');+ await expect(searchAnalytics.run(context({ siteUrl: SITE, startDate: '2026-09-30', endDate: '2026-09-01' }))).rejects.toThrow('after End Date');+ await expect(searchAnalytics.run(context({ siteUrl: SITE, startDate: undefined, endDate: '2026-09-01' }))).rejects.toThrow('required');+ expect(seen).toHaveLength(0);+ });++ test('ai action defaults to 28 days and 100 rows and reports paging', async () => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date('2026-10-07T18:00:00Z'));+ const seen = stubFetch(() => ({ body: { ...response, metadata: { firstIncompleteDate: '2026-10-05' } } }));+ const result = await searchAnalyticsBySiteUrl.run(context({ site_url: SITE, dimensions: ['query', 'page'], data_state: 'all', row_limit: 2 }));+ vi.useRealTimers();+ expect(seen[0].json).toEqual({ startDate: '2026-09-09', endDate: '2026-10-06', dimensions: ['query', 'page'], dataState: 'all', rowLimit: 2, startRow: 0 });+ expect(result).toMatchObject({+ row_count: 2,+ has_more: true,+ next_start_row: 2,+ start_date: '2026-09-09',+ end_date: '2026-10-06',+ data_state: 'all',+ aggregation_type: 'byPage',+ first_incomplete_date: '2026-10-05',+ first_incomplete_hour: null,+ });+ });++ test('ai action caps rows at 1,000 and reports no more on a short page', async () => {+ const seen = stubFetch(() => ({ body: response }));+ await expect(searchAnalyticsBySiteUrl.run(context({ site_url: SITE, row_limit: 5000 }))).rejects.toThrow('from 1 to 1,000');+ const result = await searchAnalyticsBySiteUrl.run(context({ site_url: SITE, start_date: '2026-09-01', end_date: '2026-09-30', start_row: 100 }));+ expect(Reflect.get(Object(seen[0].json), 'rowLimit')).toBe(100);+ expect(Reflect.get(Object(seen[0].json), 'startRow')).toBe(100);+ expect(result).toMatchObject({ has_more: false, next_start_row: null, data_state: 'final' });+ });+});++describe('url inspection', () => {+ const body = { inspectionResult: { inspectionResultLink: 'https://search.google.com/x', indexStatusResult: { verdict: 'NEUTRAL', coverageState: 'URL is unknown to Google' } } };++ test('human action posts to v1 with languageCode and returns the raw result', async () => {+ const seen = stubFetch(() => ({ body }));+ const result = await urlInspection.run(context({ siteUrl: SITE, url: 'https://ap-gsc-delete-test.example.com/a', languageCode: 'de' }));+ expect(seen[0].url).toBe('https://searchconsole.googleapis.com/v1/urlInspection/index:inspect');+ expect(seen[0].json).toEqual({ inspectionUrl: 'https://ap-gsc-delete-test.example.com/a', siteUrl: SITE, languageCode: 'de' });+ expect(result).toEqual(body);+ });++ test('ai action flattens and refuses a URL outside the property', async () => {+ const seen = stubFetch(() => ({ body }));+ await expect(inspectUrlBySiteUrl.run(context({ site_url: SITE, inspection_url: 'https://other.example.com/a' }))).rejects.toThrow('not part of the property');+ expect(seen).toHaveLength(0);+ const result = await inspectUrlBySiteUrl.run(context({ site_url: SITE, inspection_url: 'https://ap-gsc-delete-test.example.com/a' }));+ expect(seen[0].json).toEqual({ inspectionUrl: 'https://ap-gsc-delete-test.example.com/a', siteUrl: SITE });+ expect(result).toMatchObject({ verdict: 'NEUTRAL', coverage_state: 'URL is unknown to Google', referring_urls: [], rich_result_issues: [], inspection_result_link: 'https://search.google.com/x' });+ });+});diff --git a/packages/pieces/community/google-search-console/test/client.test.ts b/packages/pieces/community/google-search-console/test/client.test.tsnew file mode 100644index 00000000000..5481f12bbe1--- /dev/null+++ b/packages/pieces/community/google-search-console/test/client.test.ts@@ -0,0 +1,76 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { afterEach, describe, expect, test, vi } from 'vitest';+import { gscClient, GscApiError } from '../src/lib/common/client';+import { googleError, stubFetch, TOKEN } from './helpers';++afterEach(() => {+ vi.unstubAllGlobals();+});++const auth = { access_token: TOKEN };++describe('gscClient.request', () => {+ test('sends the bearer token to searchconsole.googleapis.com and encodes the property', async () => {+ const seen = stubFetch(() => ({ body: { siteUrl: 'sc-domain:example.com', permissionLevel: 'siteOwner' } }));+ await gscClient.request({ auth, method: HttpMethod.GET, path: gscClient.sitePath('sc-domain:example.com'), operation: 'x' });+ expect(seen[0].url).toBe('https://searchconsole.googleapis.com/webmasters/v3/sites/sc-domain%3Aexample.com');+ expect(seen[0].headers.get('authorization')).toBe(`Bearer ${TOKEN}`);+ expect(seen[0].headers.get('accept')).toBe('application/json');+ });++ test('sends every request through an agent that checks HTTPS certificates', async () => {+ stubFetch(() => ({ body: {} }));+ await gscClient.request({ auth, method: HttpMethod.GET, path: ['webmasters', 'v3', 'sites'], operation: 'x' });+ const init = vi.mocked(fetch).mock.calls[0][1];+ const dispatcher = Reflect.get(Object(init), 'dispatcher');+ expect(dispatcher?.constructor?.name).toBe('Agent');+ });++ test('maps a 403 permission error to a site URL hint and keeps Google text', async () => {+ const message = "User does not have sufficient permission for site 'https://example.com/'. See also: https://support.google.com/webmasters/answer/2451999.";+ stubFetch(() => ({ status: 403, body: googleError({ code: 403, message }) }));+ const error = await gscClient.request({ auth, method: HttpMethod.GET, path: ['webmasters', 'v3', 'sites'], operation: 'list sites' }).catch((e: unknown) => e);+ expect(error).toBeInstanceOf(GscApiError);+ const text = String(Reflect.get(Object(error), 'message'));+ expect(text).toContain('must match the property exactly');+ expect(text).toContain(message);+ expect(text).toContain('HTTP 403');+ expect(Reflect.get(Object(error), 'body')).toBeUndefined();+ expect(Reflect.get(Object(error), 'responseBody')).toBeDefined();+ });++ test('maps SERVICE_DISABLED to an enable-the-API hint', async () => {+ stubFetch(() => ({+ status: 403,+ body: {+ error: {+ code: 403,+ message: 'Google Search Console API has not been used in project 123 before or it is disabled.',+ status: 'PERMISSION_DENIED',+ details: [{ '@type': 'type.googleapis.com/google.rpc.ErrorInfo', reason: 'SERVICE_DISABLED' }],+ },+ },+ }));+ await expect(gscClient.request({ auth, method: HttpMethod.GET, path: ['webmasters', 'v3', 'sites'], operation: 'x' })).rejects.toThrow(+ 'Enable "Google Search Console API"',+ );+ });++ test('maps 401, 404, 429 and 5xx', async () => {+ const replies: Record<string, FakeStatus> = { a: 401, b: 404, c: 429, d: 503 };+ stubFetch((request) => {+ const status = replies[request.url.slice(-1)];+ return { status, body: googleError({ code: status, message: `status ${status}` }) };+ });+ await expect(gscClient.request({ auth, method: HttpMethod.GET, path: ['a'], operation: 'x' })).rejects.toThrow('expired or was revoked');+ await expect(gscClient.request({ auth, method: HttpMethod.GET, path: ['b'], operation: 'x' })).rejects.toThrow('not found');+ await expect(gscClient.request({ auth, method: HttpMethod.GET, path: ['c'], operation: 'x' })).rejects.toThrow('quota was exceeded');+ await expect(gscClient.request({ auth, method: HttpMethod.GET, path: ['d'], operation: 'x' })).rejects.toThrow('temporarily unavailable');+ });++ test('describes a non-JSON error body', () => {+ expect(gscClient.describeGscError({ status: 400, responseBody: 'Bad Request' })).toContain('Google said: "Bad Request" (HTTP 400)');+ });+});++type FakeStatus = number;diff --git a/packages/pieces/community/google-search-console/test/helpers.ts b/packages/pieces/community/google-search-console/test/helpers.tsnew file mode 100644index 00000000000..778095788a4--- /dev/null+++ b/packages/pieces/community/google-search-console/test/helpers.ts@@ -0,0 +1,69 @@+import { vi } from 'vitest';++export const TOKEN = 'ya29.test-token';++export function stubFetch(respond: (request: SeenRequest, index: number) => FakeReply): SeenRequest[] {+ const seen: SeenRequest[] = [];+ vi.stubGlobal(+ 'fetch',+ vi.fn(async (input: string | URL | Request, init?: RequestInit) => {+ const url = input instanceof Request ? input.url : String(input);+ const headers = new Headers(init?.headers);+ const parsed = new URL(url);+ const raw = init?.body;+ const text = typeof raw === 'string' ? raw : '';+ const request: SeenRequest = {+ url,+ method: (init?.method ?? 'GET').toUpperCase(),+ rawPath: url.slice(parsed.origin.length).split('?')[0],+ query: parsed.searchParams,+ headers,+ json: text ? JSON.parse(text) : null,+ };+ seen.push(request);+ const reply = respond(request, seen.length - 1);+ return new Response(reply.body === undefined ? null : JSON.stringify(reply.body), {+ status: reply.status ?? 200,+ headers: { 'content-type': 'application/json' },+ });+ }),+ );+ return seen;+}++export function context(propsValue: Record<string, unknown>) {+ return {+ auth: { access_token: TOKEN },+ propsValue,+ store: {},+ files: {},+ server: { apiUrl: '', publicUrl: '', token: '' },+ run: { id: 'run-1' },+ step: { name: 'step_1' },+ };+}++export function googleError({ code, message, reason, status }: { code: number; message: string; reason?: string; status?: string }) {+ return {+ error: {+ code,+ message,+ errors: [{ message, domain: 'global', reason: reason ?? 'forbidden' }],+ ...(status ? { status } : {}),+ },+ };+}++export const SITE = 'https://ap-gsc-delete-test.example.com/';+export const SITE_ENCODED = 'https%3A%2F%2Fap-gsc-delete-test.example.com%2F';++export type SeenRequest = {+ url: string;+ method: string;+ rawPath: string;+ query: URLSearchParams;+ headers: Headers;+ json: unknown;+};++export type FakeReply = { status?: number; body?: unknown };diff --git a/packages/pieces/community/google-search-console/test/inputs.test.ts b/packages/pieces/community/google-search-console/test/inputs.test.tsnew file mode 100644index 00000000000..2360c6f59d4--- /dev/null+++ b/packages/pieces/community/google-search-console/test/inputs.test.ts@@ -0,0 +1,225 @@+import { describe, expect, test } from 'vitest';+import { gscInputs } from '../src/lib/common/inputs';+import { gscShape } from '../src/lib/common/shape';++describe('siteUrl', () => {+ test('normalises URL-prefix and domain properties', () => {+ expect(gscInputs.siteUrl({ value: ' https://www.example.com ' })).toBe('https://www.example.com/');+ expect(gscInputs.siteUrl({ value: 'https://example.com/blog' })).toBe('https://example.com/blog/');+ expect(gscInputs.siteUrl({ value: 'http://example.com/' })).toBe('http://example.com/');+ expect(gscInputs.siteUrl({ value: 'sc-domain:example.com' })).toBe('sc-domain:example.com');+ expect(gscInputs.siteUrl({ value: 'SC-DOMAIN: example.com' })).toBe('sc-domain:example.com');+ });++ test('refuses anything else', () => {+ expect(() => gscInputs.siteUrl({ value: '' })).toThrow('required');+ expect(() => gscInputs.siteUrl({ value: 'example.com' })).toThrow('not a Search Console property');+ expect(() => gscInputs.siteUrl({ value: 'https://example.com/?a=1' })).toThrow('not a Search Console property');+ expect(() => gscInputs.siteUrl({ value: 'sc-domain:https://example.com' })).toThrow('not a valid domain property');+ expect(() => gscInputs.siteUrl({ value: 'ftp://example.com/' })).toThrow('not a Search Console property');+ });+});++describe('urls', () => {+ test('urlInProperty checks prefix and domain properties', () => {+ expect(gscInputs.urlInProperty({ value: 'https://example.com/blog/a', label: 'URL', site: 'https://example.com/blog/' })).toBe('https://example.com/blog/a');+ expect(() => gscInputs.urlInProperty({ value: 'https://example.com/shop', label: 'URL', site: 'https://example.com/blog/' })).toThrow('not part of the property');+ expect(() => gscInputs.urlInProperty({ value: 'http://example.com/blog/a', label: 'URL', site: 'https://example.com/blog/' })).toThrow('not part of the property');+ expect(gscInputs.urlInProperty({ value: 'https://shop.example.com/x', label: 'URL', site: 'sc-domain:example.com' })).toBe('https://shop.example.com/x');+ expect(() => gscInputs.urlInProperty({ value: 'https://example.com.evil.io/x', label: 'URL', site: 'sc-domain:example.com' })).toThrow('not part of the property');+ });++ test('absoluteUrl refuses relative paths and credentials', () => {+ expect(() => gscInputs.absoluteUrl({ value: '/sitemap.xml', label: 'Sitemap URL' })).toThrow('full http(s) URL');+ expect(() => gscInputs.absoluteUrl({ value: 'https://user:[email protected]/s.xml', label: 'Sitemap URL' })).toThrow('full http(s) URL');+ });++ test('languageCode', () => {+ expect(gscInputs.languageCode({ value: '' })).toBeUndefined();+ expect(gscInputs.languageCode({ value: 'pt-BR' })).toBe('pt-BR');+ expect(() => gscInputs.languageCode({ value: 'english please' })).toThrow('BCP-47');+ });+});++describe('dates', () => {+ test('takes the literal date part without a time zone shift', () => {+ expect(gscInputs.date({ value: '2026-09-01T23:30:00.000Z', label: 'Start Date' })).toBe('2026-09-01');+ expect(gscInputs.date({ value: '2026-09-01', label: 'Start Date' })).toBe('2026-09-01');+ expect(() => gscInputs.date({ value: '2026-02-30', label: 'Start Date' })).toThrow('real calendar date');+ expect(() => gscInputs.date({ value: '09/01/2026', label: 'Start Date' })).toThrow('YYYY-MM-DD');+ });++ test('requiredDateRange checks order', () => {+ expect(gscInputs.requiredDateRange({ startDate: '2026-09-01', endDate: '2026-09-30' })).toEqual({ startDate: '2026-09-01', endDate: '2026-09-30' });+ expect(() => gscInputs.requiredDateRange({ startDate: '2026-09-30', endDate: '2026-09-01' })).toThrow('after End Date');+ expect(() => gscInputs.requiredDateRange({ startDate: undefined, endDate: '2026-09-01' })).toThrow('required');+ });++ test('dateRange defaults to the last 28 days ending yesterday', () => {+ expect(gscInputs.dateRange({ startDate: undefined, endDate: undefined, today: '2026-10-07' })).toEqual({ startDate: '2026-09-09', endDate: '2026-10-06' });+ expect(gscInputs.dateRange({ startDate: '', endDate: '', lastNDays: 7, today: '2026-03-02' })).toEqual({ startDate: '2026-02-23', endDate: '2026-03-01' });+ expect(gscInputs.dateRange({ startDate: '2026-09-01', endDate: undefined, today: '2026-10-07' })).toEqual({ startDate: '2026-09-01', endDate: '2026-10-06' });+ expect(() => gscInputs.dateRange({ startDate: '2026-09-01', endDate: undefined, lastNDays: 7 })).toThrow('not both');+ expect(() => gscInputs.dateRange({ startDate: undefined, endDate: '2026-09-01' })).toThrow('Start Date is required');+ expect(() => gscInputs.dateRange({ startDate: undefined, endDate: undefined, lastNDays: 0 })).toThrow('from 1 to 500');+ });++ test('pacificToday uses Pacific Time', () => {+ expect(gscInputs.pacificToday(new Date('2026-10-07T05:00:00Z'))).toBe('2026-10-06');+ expect(gscInputs.pacificToday(new Date('2026-10-07T09:00:00Z'))).toBe('2026-10-07');+ });+});++describe('numbers', () => {+ test('optionalInteger accepts integers and numeric strings in range', () => {+ expect(gscInputs.optionalInteger({ value: undefined, label: 'Row Limit', min: 1, max: 25000 })).toBeUndefined();+ expect(gscInputs.optionalInteger({ value: '250', label: 'Row Limit', min: 1, max: 25000 })).toBe(250);+ expect(gscInputs.optionalInteger({ value: 25000, label: 'Row Limit', min: 1, max: 25000 })).toBe(25000);+ expect(() => gscInputs.optionalInteger({ value: 25001, label: 'Row Limit', min: 1, max: 25000 })).toThrow('from 1 to 25,000');+ expect(() => gscInputs.optionalInteger({ value: 1.5, label: 'Row Limit', min: 1, max: 25000 })).toThrow('whole number');+ expect(() => gscInputs.optionalInteger({ value: -1, label: 'Start Row', min: 0, max: 10 })).toThrow('whole number');+ expect(() => gscInputs.optionalInteger({ value: 'ten', label: 'Start Row', min: 0, max: 10 })).toThrow('whole number');+ });+});++describe('analytics query', () => {+ test('normalises dimension case and refuses unknown or duplicate ones', () => {+ expect(gscInputs.dimensions({ value: ['Query', 'SEARCHAPPEARANCE', 'date'] })).toEqual(['query', 'searchAppearance', 'date']);+ expect(gscInputs.dimensions({ value: undefined })).toEqual([]);+ expect(() => gscInputs.dimensions({ value: ['queries'] })).toThrow('not supported');+ expect(() => gscInputs.dimensions({ value: ['page', 'Page'] })).toThrow('only once');+ });++ test('filters are validated and device is upper-cased', () => {+ expect(gscInputs.filters({ value: [{ dimension: 'device', operator: 'equals', expression: 'mobile' }] })).toEqual([{ dimension: 'device', operator: 'equals', expression: 'MOBILE' }]);+ expect(() => gscInputs.filters({ value: [{ dimension: 'date', operator: 'equals', expression: 'x' }] })).toThrow('Filter 1: dimension');+ expect(() => gscInputs.filters({ value: [{ dimension: 'query', operator: 'like', expression: 'x' }] })).toThrow('Filter 1: operator');+ expect(() => gscInputs.filters({ value: [{ dimension: 'query', operator: 'contains', expression: ' ' }] })).toThrow('expression is empty');+ });++ test('filter expressions are sent exactly as given except device names for equals/notEquals', () => {+ expect(gscInputs.filters({ value: [{ dimension: 'device', operator: 'includingRegex', expression: '^\\w+$' }] })).toEqual([+ { dimension: 'device', operator: 'includingRegex', expression: '^\\w+$' },+ ]);+ expect(gscInputs.filters({ value: [{ dimension: 'query', operator: 'contains', expression: ' shoes ' }] })).toEqual([{ dimension: 'query', operator: 'contains', expression: ' shoes ' }]);+ expect(gscInputs.filters({ value: [{ dimension: 'device', operator: 'notEquals', expression: ' tablet ' }] })).toEqual([{ dimension: 'device', operator: 'notEquals', expression: 'TABLET' }]);+ expect(gscInputs.filters({ value: [{ dimension: 'device', operator: 'contains', expression: 'mob' }] })).toEqual([{ dimension: 'device', operator: 'contains', expression: 'mob' }]);+ });++ const base = { startDate: '2026-09-01', endDate: '2026-09-30', searchType: undefined, filters: [], aggregationType: undefined, dataState: undefined, rowLimit: undefined, startRow: undefined };++ test('hour forces hourly_all and rejects another data state', () => {+ expect(gscInputs.analyticsQuery({ ...base, dimensions: ['hour'] }).dataState).toBe('hourly_all');+ expect(() => gscInputs.analyticsQuery({ ...base, dimensions: ['hour'], dataState: 'final' })).toThrow('hourly_all');+ expect(gscInputs.analyticsQuery({ ...base, dimensions: ['date'], dataState: 'all' }).dataState).toBe('all');+ });++ test('refuses incompatible combinations before any request', () => {+ expect(() => gscInputs.analyticsQuery({ ...base, dimensions: ['page'], aggregationType: 'byProperty' })).toThrow('byProperty');+ expect(() =>+ gscInputs.analyticsQuery({ ...base, dimensions: [], aggregationType: 'byProperty', filters: [{ dimension: 'page', operator: 'contains', expression: '/blog' }] }),+ ).toThrow('byProperty');+ expect(() => gscInputs.analyticsQuery({ ...base, dimensions: ['query'], searchType: 'discover' })).toThrow('no search queries');+ expect(() => gscInputs.analyticsQuery({ ...base, dimensions: [], aggregationType: 'byNewsShowcasePanel', searchType: 'web' })).toThrow('byNewsShowcasePanel');+ expect(() => gscInputs.analyticsQuery({ ...base, dimensions: [], searchType: 'shopping' })).toThrow('Search Type');+ });++ test('builds the request body with only the fields that are set', () => {+ expect(gscInputs.analyticsQuery({ ...base, dimensions: [] })).toEqual({ startDate: '2026-09-01', endDate: '2026-09-30' });+ expect(+ gscInputs.analyticsQuery({+ ...base,+ dimensions: ['query', 'page'],+ searchType: 'web',+ filters: [{ dimension: 'country', operator: 'equals', expression: 'usa' }],+ aggregationType: 'byPage',+ rowLimit: 10,+ startRow: 20,+ }),+ ).toEqual({+ startDate: '2026-09-01',+ endDate: '2026-09-30',+ dimensions: ['query', 'page'],+ type: 'web',+ dimensionFilterGroups: [{ groupType: 'and', filters: [{ dimension: 'country', operator: 'equals', expression: 'usa' }] }],+ aggregationType: 'byPage',+ rowLimit: 10,+ startRow: 20,+ });+ });+});++describe('shape', () => {+ test('analytics rows get one named column per dimension and numeric metrics', () => {+ expect(+ gscShape.analyticsRow({ row: { keys: ['buy shoes', 'https://ex.com/p'], clicks: 12, impressions: 340, ctr: 0.0353, position: 7.4 }, dimensions: ['query', 'page'] }),+ ).toEqual({ query: 'buy shoes', page: 'https://ex.com/p', clicks: 12, impressions: 340, ctr: 0.0353, position: 7.4 });+ expect(gscShape.analyticsRow({ row: { clicks: 1, impressions: 2, ctr: 0.5, position: 3 }, dimensions: [] })).toEqual({ clicks: 1, impressions: 2, ctr: 0.5, position: 3 });+ expect(gscShape.analyticsRow({ row: { keys: ['DESKTOP'] }, dimensions: ['searchAppearance'] })).toMatchObject({ search_appearance: 'DESKTOP' });+ expect(gscShape.analyticsRow({ row: { keys: ['2026-09-26'], clicks: 0, impressions: 0, ctr: 0, position: 0 }, dimensions: ['date'] })).toEqual({ date: '2026-09-26', clicks: 0, impressions: 0, ctr: 0, position: null });+ });++ test('sitemap counts become numbers', () => {+ expect(+ gscShape.sitemapFlat({+ path: 'https://ex.com/sitemap.xml',+ lastSubmitted: '2026-10-01T10:00:00.000Z',+ isPending: false,+ isSitemapsIndex: false,+ type: 'sitemap',+ lastDownloaded: '2026-10-02T10:00:00.000Z',+ warnings: '1',+ errors: '0',+ contents: [+ { type: 'web', submitted: '12', indexed: '0' },+ { type: 'image', submitted: '3' },+ ],+ }),+ ).toEqual({+ path: 'https://ex.com/sitemap.xml',+ type: 'sitemap',+ is_sitemaps_index: false,+ is_pending: false,+ last_submitted: '2026-10-01T10:00:00.000Z',+ last_downloaded: '2026-10-02T10:00:00.000Z',+ errors: 0,+ warnings: 1,+ submitted_urls: 15,+ contents: [+ { type: 'web', submitted: 12 },+ { type: 'image', submitted: 3 },+ ],+ });+ });++ test('inspection is flattened and referring URLs are capped', () => {+ const referringUrls = Array.from({ length: 25 }, (_, index) => `https://ex.com/r${index}`);+ const flat = gscShape.inspection({+ inspectedUrl: 'https://ex.com/a',+ body: {+ inspectionResult: {+ inspectionResultLink: 'https://search.google.com/search-console/inspect?resource_id=x',+ indexStatusResult: { verdict: 'PASS', coverageState: 'Submitted and indexed', sitemap: ['https://ex.com/sitemap.xml'], referringUrls, lastCrawlTime: '2026-10-01T00:00:00Z' },+ richResultsResult: {+ verdict: 'PARTIAL',+ detectedItems: [{ richResultType: 'Breadcrumbs', items: [{ name: 'Unnamed item', issues: [{ issueMessage: 'Missing field "item"', severity: 'WARNING' }] }] }],+ },+ mobileUsabilityResult: { verdict: 'VERDICT_UNSPECIFIED' },+ },+ },+ });+ expect(flat).toMatchObject({+ inspected_url: 'https://ex.com/a',+ verdict: 'PASS',+ coverage_state: 'Submitted and indexed',+ sitemaps: ['https://ex.com/sitemap.xml'],+ referring_urls_truncated: true,+ rich_results_verdict: 'PARTIAL',+ rich_result_types: ['Breadcrumbs'],+ rich_result_issues: [{ type: 'Breadcrumbs', item: 'Unnamed item', severity: 'WARNING', message: 'Missing field "item"' }],+ amp_verdict: null,+ mobile_usability_verdict: 'VERDICT_UNSPECIFIED',+ });+ expect(flat.referring_urls).toHaveLength(20);+ });+});diff --git a/packages/pieces/community/google-search-console/test/metadata.test.ts b/packages/pieces/community/google-search-console/test/metadata.test.tsnew file mode 100644index 00000000000..23ddae37e16--- /dev/null+++ b/packages/pieces/community/google-search-console/test/metadata.test.ts@@ -0,0 +1,64 @@+import { describe, expect, test } from 'vitest';+import { googleSearchConsolePiece } from '../src';++const actions = Object.values(googleSearchConsolePiece.actions());+const handWritten = actions.filter((action) => action.name !== 'custom_api_call');++describe('piece metadata', () => {+ test('16 actions plus custom API call, existing names unchanged', () => {+ expect(handWritten).toHaveLength(16);+ const names = actions.map((action) => action.name);+ for (const name of ['search_analytics', 'list_sitemaps', 'submit_sitemap', 'list_sites', 'add_site', 'delete_site', 'urlInspection', 'custom_api_call']) {+ expect(names).toContain(name);+ }+ });++ test.each(handWritten.map((action) => [action.name, action]))('%s declares audience, classification, aiMetadata and outputSchema', (_name, action) => {+ expect(['both', 'ai', 'human']).toContain(action.audience);+ expect(['READ', 'SEARCH', 'WRITE', 'DESTRUCTIVE']).toContain(action.classification);+ expect(action.aiMetadata?.description?.length ?? 0).toBeGreaterThan(60);+ expect(typeof action.aiMetadata?.idempotent).toBe('boolean');+ expect(action.outputSchema?.fields.length).toBeGreaterThan(0);+ });++ test('agent-visible actions have no dynamic dropdowns', () => {+ for (const action of handWritten.filter((item) => item.audience !== 'human')) {+ const types = Object.values(action.props).map((prop: unknown) => (prop !== null && typeof prop === 'object' ? Reflect.get(prop, 'type') : undefined));+ expect(types, action.name).not.toContain('DROPDOWN');+ expect(types, action.name).not.toContain('DYNAMIC');+ }+ });++ test('every human action has an ai twin', () => {+ const twins: Record<string, string> = {+ search_analytics: 'search_analytics_by_site_url',+ list_sitemaps: 'list_sitemaps_by_site_url',+ submit_sitemap: 'submit_sitemap_by_site_url',+ delete_sitemap: 'delete_sitemap_by_site_url',+ delete_site: 'delete_site_by_site_url',+ urlInspection: 'inspect_url_by_site_url',+ };+ const byName = new Map(handWritten.map((action) => [action.name, action]));+ for (const action of handWritten.filter((item) => item.audience === 'human')) {+ const twin = byName.get(twins[action.name]);+ expect(twin?.audience, action.name).toBe('ai');+ expect(twin?.classification, action.name).toBe(action.classification);+ }+ });++ test('deletes are destructive; site deletes fail on retry, sitemap deletes do not; submit and add are idempotent writes', () => {+ for (const action of handWritten.filter((item) => item.name.startsWith('delete_'))) {+ expect(action.classification).toBe('DESTRUCTIVE');+ expect(action.aiMetadata?.idempotent).toBe(action.name.startsWith('delete_sitemap'));+ }+ for (const action of handWritten.filter((item) => item.name.startsWith('submit_') || item.name === 'add_site')) {+ expect(action.classification).toBe('WRITE');+ expect(action.aiMetadata?.idempotent).toBe(true);+ }+ });++ test('piece-level settings', () => {+ expect(googleSearchConsolePiece.minimumSupportedRelease).toBe('0.88.2');+ expect(googleSearchConsolePiece.categories).toEqual(['MARKETING']);+ });+});diff --git a/packages/pieces/community/google-search-console/vitest.config.ts b/packages/pieces/community/google-search-console/vitest.config.tsnew file mode 100644index 00000000000..79c97261904--- /dev/null+++ b/packages/pieces/community/google-search-console/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'),+ },+ },+})