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(short-io): agent-ready link, folder, QR and statistics actions; fix TTL and trigger password leak (#16420)
Odai Ahmadb5e7818f56be
diff --git a/bun.lock b/bun.lockindex 4234401cd95..b4fb2b8349b 100644--- a/bun.lock+++ b/bun.lock@@ -8374,15 +8374,17 @@},"packages/pieces/community/short-io": {"name": "@activepieces/piece-short-io",- "version": "0.2.0",+ "version": "0.3.0","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*","@activepieces/pieces-common": "workspace:*","@activepieces/pieces-framework": "workspace:*",+ "undici": "7.29.1",},"devDependencies": {"tslib": "^2.3.0",+ "vitest": "3.2.6",},},"packages/pieces/community/sign-now": {diff --git a/packages/pieces/community/short-io/package.json b/packages/pieces/community/short-io/package.jsonindex 9339c986d02..80d7df68f01 100644--- a/packages/pieces/community/short-io/package.json+++ b/packages/pieces/community/short-io/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/piece-short-io",- "version": "0.2.0",+ "version": "0.3.0","type": "commonjs","main": "./dist/src/index.js","types": "./dist/src/index.d.ts",@@ -8,14 +8,17 @@"@activepieces/pieces-common": "workspace:*","@activepieces/pieces-framework": "workspace:*","@activepieces/core-piece-types": "workspace:*",- "@activepieces/core-utils": "workspace:*"+ "@activepieces/core-utils": "workspace:*",+ "undici": "7.29.1"},"devDependencies": {- "tslib": "^2.3.0"+ "tslib": "^2.3.0",+ "vitest": "3.2.6"},"scripts": {"build": "tsc -p tsconfig.lib.json && cp package.json dist/","bundle": "node ../../../../dist/packages/cli/src/index.js pieces bundle",- "lint": "eslint 'src/**/*.ts'"+ "lint": "eslint 'src/**/*.ts'",+ "test": "vitest run"}}diff --git a/packages/pieces/community/short-io/src/i18n/translation.json b/packages/pieces/community/short-io/src/i18n/translation.jsonindex 74337fafaa3..ec9f1537e2a 100644--- a/packages/pieces/community/short-io/src/i18n/translation.json+++ b/packages/pieces/community/short-io/src/i18n/translation.json@@ -10,6 +10,31 @@"Get Link Clicks": "Get Link Clicks","List Links": "List Links","Update Short Link": "Update Short Link",+ "List Domains": "List Domains",+ "Get Domain": "Get Domain",+ "Get Link by ID": "Get Link by ID",+ "Find Links by Original URL": "Find Links by Original URL",+ "Create Short Links (Bulk)": "Create Short Links (Bulk)",+ "Archive Short Link": "Archive Short Link",+ "Unarchive Short Link": "Unarchive Short Link",+ "Add Tag to Links": "Add Tag to Links",+ "Generate QR Code": "Generate QR Code",+ "List Folders": "List Folders",+ "Create Folder": "Create Folder",+ "List Country Targeting Rules": "List Country Targeting Rules",+ "Delete Country Targeting Rule": "Delete Country Targeting Rule",+ "List Recent Clicks": "List Recent Clicks",+ "Get Top Links": "Get Top Links",+ "Duplicate Short Link": "Duplicate Short Link",+ "Get Folder": "Get Folder",+ "Get Link Social Preview (OpenGraph)": "Get Link Social Preview (OpenGraph)",+ "Create Short Link (AI)": "Create Short Link (AI)",+ "Update Short Link (AI)": "Update Short Link (AI)",+ "Find Link by Short URL (AI)": "Find Link by Short URL (AI)",+ "List Links (AI)": "List Links (AI)",+ "Delete Short Link (AI)": "Delete Short Link (AI)",+ "Add Country Targeting Rule (AI)": "Add Country Targeting Rule (AI)",+ "Get Domain Statistics (AI)": "Get Domain Statistics (AI)","Custom API Call": "Custom API Call","Set geographic targeting rules for a link with specific destination per country.": "Set geographic targeting rules for a link with specific destination per country.","Create a new short link with optional parameters (title, UTM tags, expiration, cloaking, etc.)": "Create a new short link with optional parameters (title, UTM tags, expiration, cloaking, etc.)",@@ -18,8 +43,33 @@"Retrieve usage stats (clicks, conversions) for a domain within a time period.": "Retrieve usage stats (clicks, conversions) for a domain within a time period.","Retrieve detailed information about a short link using its domain and path.": "Retrieve detailed information about a short link using its domain and path.","Retrieve click statistics for specific short links by their IDs.": "Retrieve click statistics for specific short links by their IDs.",- "Retrieve all links on a domain, with pagination and date-range filters.": "Retrieve all links on a domain, with pagination and date-range filters.",+ "Retrieve one page of links on a domain, with pagination and date-range filters.": "Retrieve one page of links on a domain, with pagination and date-range filters.","Update an existing short link's original URL, path, title, or other properties using its link ID.": "Update an existing short link's original URL, path, title, or other properties using its link ID.",+ "List every domain on the Short.io account.": "List every domain on the Short.io account.",+ "Get the settings of one Short.io domain.": "Get the settings of one Short.io domain.",+ "Get a short link and its settings by link ID.": "Get a short link and its settings by link ID.",+ "Find every short link on a domain that points to a given long URL.": "Find every short link on a domain that points to a given long URL.",+ "Create up to 1,000 short links on one domain in a single request.": "Create up to 1,000 short links on one domain in a single request.",+ "Archive a short link (hide it from the dashboard; the short URL keeps redirecting).": "Archive a short link (hide it from the dashboard; the short URL keeps redirecting).",+ "Restore an archived short link to the active list.": "Restore an archived short link to the active list.",+ "Append one tag to one or more short links.": "Append one tag to one or more short links.",+ "Generate a QR code image (PNG or SVG) for a short link.": "Generate a QR code image (PNG or SVG) for a short link.",+ "List the link folders on a domain.": "List the link folders on a domain.",+ "Create a link folder on a domain.": "Create a link folder on a domain.",+ "List the country redirect rules of a short link.": "List the country redirect rules of a short link.",+ "Remove the country redirect rule for one country from a short link.": "Remove the country redirect rule for one country from a short link.",+ "List the latest raw clicks on a domain (time, path, country, referrer, browser). Includes visitor IP and user agent.": "List the latest raw clicks on a domain (time, path, country, referrer, browser). Includes visitor IP and user agent.",+ "Get the most-clicked link paths on a domain for a period.": "Get the most-clicked link paths on a domain for a period.",+ "Create a copy of a short link with the same destination and settings.": "Create a copy of a short link with the same destination and settings.",+ "Get a link folder by its ID.": "Get a link folder by its ID.",+ "Get the custom social-preview (OpenGraph) title, description and image set on a short link.": "Get the custom social-preview (OpenGraph) title, description and image set on a short link.",+ "Create a short link on a domain given by hostname or ID.": "Create a short link on a domain given by hostname or ID.",+ "Change the settings of a short link by link ID; only the fields you give are changed.": "Change the settings of a short link by link ID; only the fields you give are changed.",+ "Find a short link from its full short URL, or from a domain plus slug.": "Find a short link from its full short URL, or from a domain plus slug.",+ "List one page of links on a domain, newest first by default.": "List one page of links on a domain, newest first by default.",+ "Permanently delete a short link by ID; a repeat call reports it as already deleted.": "Permanently delete a short link by ID; a repeat call reports it as already deleted.",+ "Send visitors from one country to a different URL.": "Send visitors from one country to a different URL.",+ "Get click and link totals for a whole domain over a period.": "Get click and link totals for a whole domain over a period.","Make a custom API call to a specific endpoint": "Make a custom API call to a specific endpoint","Domain": "Domain","Short Link": "Short Link",@@ -71,6 +121,26 @@"Date Sort Order": "Date Sort Order","Page Token": "Page Token","Custom Path (Slug)": "Custom Path (Slug)",+ "Links": "Links",+ "Folder ID": "Folder ID",+ "Tag": "Tag",+ "Format": "Format",+ "Size": "Size",+ "Color": "Color",+ "Background Color": "Background Color",+ "Folder Name": "Folder Name",+ "Link Paths": "Link Paths",+ "Human Clicks Only": "Human Clicks Only",+ "Period": "Period",+ "New Path (Slug)": "New Path (Slug)",+ "Path (Slug)": "Path (Slug)",+ "Expires At": "Expires At",+ "Delete At": "Delete At",+ "Short URL or Slug": "Short URL or Slug",+ "Created After": "Created After",+ "Created Before": "Created Before",+ "Sort Order": "Sort Order",+ "Country Redirect URL": "Country Redirect URL","Method": "Method","Headers": "Headers","Query Parameters": "Query Parameters",@@ -81,14 +151,14 @@"Timeout": "Timeout","Follow redirects": "Follow redirects","Select the domain to use for the link": "Select the domain to use for the link",- "Select the short link from the domain": "Select the short link from the domain",+ "Select the short link from the domain (the newest 1,500 links are listed).": "Select the short link from the domain (the newest 1,500 links are listed).","ISO 3166-1 alpha-2 country code (e.g., US, GB, CA, IN). Must be exactly 2 characters.": "ISO 3166-1 alpha-2 country code (e.g., US, GB, CA, IN). Must be exactly 2 characters.","The destination URL when users from this country access the link. Must be a valid URL.": "The destination URL when users from this country access the link. Must be a valid URL.","Select the folder to add the link to.": "Select the folder to add the link to.","The HTTP status code for the redirect. The default is 302 (Found).": "The HTTP status code for the redirect. The default is 302 (Found).","The date and time when the link will become inactive.": "The date and time when the link will become inactive.","Array of tags for the link": "Array of tags for the link",- "⚠️ CAUTION: Link will be PERMANENTLY DELETED after this many seconds. This action cannot be undone. Use with extreme caution.": "⚠️ CAUTION: Link will be PERMANENTLY DELETED after this many seconds. This action cannot be undone. Use with extreme caution.",+ "Permanently deletes the link this many seconds from now (minimum 604800 = 7 days). Short.io may delete it up to 2 hours later. This cannot be undone.": "Permanently deletes the link this many seconds from now (minimum 604800 = 7 days). Short.io may delete it up to 2 hours later. This cannot be undone.","Overrides the creation time of the link.": "Overrides the creation time of the link.","Disable link after specified number of clicks (minimum: 1)": "Disable link after specified number of clicks (minimum: 1)","Split URL percentage (1-100)": "Split URL percentage (1-100)",@@ -97,15 +167,15 @@"Optional URL to redirect users when the link has expired.": "Optional URL to redirect users when the link has expired.","Select the domain to get statistics for": "Select the domain to get statistics for","Select a predefined time interval or choose \"Custom\" to set specific dates.": "Select a predefined time interval or choose \"Custom\" to set specific dates.",- "Start date for statistics (required when period is \"Custom\").": "Start date for statistics (required when period is \"Custom\").",- "End date for statistics (required when period is \"Custom\").": "End date for statistics (required when period is \"Custom\").",+ "Start date for statistics (required when period is \"Custom\"). The calendar day you pick is sent as is.": "Start date for statistics (required when period is \"Custom\"). The calendar day you pick is sent as is.",+ "End date for statistics (required when period is \"Custom\"). The calendar day you pick is sent as is.": "End date for statistics (required when period is \"Custom\"). The calendar day you pick is sent as is.","Timezone for statistics (e.g., UTC, America/New_York, Europe/London). Defaults to UTC.": "Timezone for statistics (e.g., UTC, America/New_York, Europe/London). Defaults to UTC.","Granularity for click statistics chart data.": "Granularity for click statistics chart data.","The path/slug of the short link (e.g., \"abc123\", \"my-link\"). Do not include domain or slashes.": "The path/slug of the short link (e.g., \"abc123\", \"my-link\"). Do not include domain or slashes.","Select the domain containing the links": "Select the domain containing the links","List of link IDs to fetch click statistics for (e.g., lnk_61Mb_0dnRUg3vvtmAPZh3dhQh6).": "List of link IDs to fetch click statistics for (e.g., lnk_61Mb_0dnRUg3vvtmAPZh3dhQh6).",- "Start date for click statistics (optional).": "Start date for click statistics (optional).",- "End date for click statistics (optional).": "End date for click statistics (optional).",+ "Start date for click statistics (optional). The calendar day you pick is sent as is.": "Start date for click statistics (optional). The calendar day you pick is sent as is.",+ "End date for click statistics (optional). The calendar day you pick is sent as is.": "End date for click statistics (optional). The calendar day you pick is sent as is.","Select the domain to retrieve links from": "Select the domain to retrieve links from","Number of results to return (1-150). Default is 50.": "Number of results to return (1-150). Default is 50.","Filter by specific link ID (optional).": "Filter by specific link ID (optional).",@@ -114,6 +184,46 @@"Return links created after this date and time.": "Return links created after this date and time.","Order links by creation date.": "Order links by creation date.","Token for paginated results (get this from previous response).": "Token for paginated results (get this from previous response).",+ "Short.io domain hostname (e.g. link.example.com) or its numeric domain ID. Use List Domains to see them.": "Short.io domain hostname (e.g. link.example.com) or its numeric domain ID. Use List Domains to see them.",+ "Short.io link ID: the idString field of a link, e.g. link_8yXK_034ebx7JWAtAAK3vFcl6ye.": "Short.io link ID: the idString field of a link, e.g. link_8yXK_034ebx7JWAtAAK3vFcl6ye.",+ "The full destination URL to look up, exactly as it was shortened.": "The full destination URL to look up, exactly as it was shortened.",+ "JSON array of links, e.g. [{\"originalURL\": \"https://example.com/a\", \"path\": \"a\"}, {\"originalURL\": \"https://example.com/b\"}]. Allowed keys: originalURL (required), path, title, tags, utmSource, utmMedium, utmCampaign, utmTerm, utmContent, expiresAt, expiredURL, redirectType, androidURL, iphoneURL, cloaking.": "JSON array of links, e.g. [{\"originalURL\": \"https://example.com/a\", \"path\": \"a\"}, {\"originalURL\": \"https://example.com/b\"}]. Allowed keys: originalURL (required), path, title, tags, utmSource, utmMedium, utmCampaign, utmTerm, utmContent, expiresAt, expiredURL, redirectType, androidURL, iphoneURL, cloaking.",+ "Optional folder ID (use List Folders to find it).": "Optional folder ID (use List Folders to find it).",+ "Create a new link even when one already points to the same URL.": "Create a new link even when one already points to the same URL.",+ "The tag to add.": "The tag to add.",+ "Link IDs to tag (the idString of each link, e.g. link_8yXK_034ebx7JWAtAAK3vFcl6ye).": "Link IDs to tag (the idString of each link, e.g. link_8yXK_034ebx7JWAtAAK3vFcl6ye).",+ "Scale factor from 1 to 99 (Short.io default when empty).": "Scale factor from 1 to 99 (Short.io default when empty).",+ "Hex color of the code, e.g. 000000.": "Hex color of the code, e.g. 000000.",+ "Hex background color, e.g. FFFFFF.": "Hex background color, e.g. FFFFFF.",+ "ISO 3166-1 alpha-2 code of the rule to remove, e.g. US.": "ISO 3166-1 alpha-2 code of the rule to remove, e.g. US.",+ "How many clicks to return (1-1000). Default 30.": "How many clicks to return (1-1000). Default 30.",+ "Only clicks on these paths, e.g. promo. Needs a Short.io Team plan.": "Only clicks on these paths, e.g. promo. Needs a Short.io Team plan.",+ "Skip clicks Short.io identifies as bots.": "Skip clicks Short.io identifies as bots.",+ "Time period to rank links over. Default: last 30 days.": "Time period to rank links over. Default: last 30 days.",+ "First day (YYYY-MM-DD) when Period is \"custom\".": "First day (YYYY-MM-DD) when Period is \"custom\".",+ "Last day (YYYY-MM-DD) when Period is \"custom\".": "Last day (YYYY-MM-DD) when Period is \"custom\".",+ "IANA timezone for day boundaries, e.g. UTC or America/New_York. Defaults to UTC.": "IANA timezone for day boundaries, e.g. UTC or America/New_York. Defaults to UTC.",+ "How many links to return (1-100). Default 10.": "How many links to return (1-100). Default 10.",+ "Slug for the copy, e.g. spring-sale-email. Empty = Short.io generates one.": "Slug for the copy, e.g. spring-sale-email. Empty = Short.io generates one.",+ "The folder ID, e.g. the FolderId field of a link.": "The folder ID, e.g. the FolderId field of a link.",+ "The long URL the short link redirects to.": "The long URL the short link redirects to.",+ "Custom slug after the domain, e.g. spring-sale. Empty = Short.io generates one.": "Custom slug after the domain, e.g. spring-sale. Empty = Short.io generates one.",+ "Tags for the link. On update this replaces the existing tags.": "Tags for the link. On update this replaces the existing tags.",+ "Folder ID from List Folders.": "Folder ID from List Folders.",+ "ISO 8601 date-time after which the link shows the expired page (it is not deleted).": "ISO 8601 date-time after which the link shows the expired page (it is not deleted).",+ "Where visitors go after the link expires.": "Where visitors go after the link expires.",+ "Expire the link after this many clicks (minimum 1).": "Expire the link after this many clicks (minimum 1).",+ "ISO 8601 date-time at which Short.io permanently deletes the link; must be at least 7 days ahead. Deletion may lag by up to 2 hours.": "ISO 8601 date-time at which Short.io permanently deletes the link; must be at least 7 days ahead. Deletion may lag by up to 2 hours.",+ "New destination URL.": "New destination URL.",+ "Full short URL like https://link.example.com/promo, or just the slug \"promo\" when Domain is given.": "Full short URL like https://link.example.com/promo, or just the slug \"promo\" when Domain is given.",+ "Domain hostname or ID; needed only when Short URL is a bare slug.": "Domain hostname or ID; needed only when Short URL is a bare slug.",+ "ISO 8601 date-time; only links created after it.": "ISO 8601 date-time; only links created after it.",+ "ISO 8601 date-time; only links created before it.": "ISO 8601 date-time; only links created before it.",+ "Links per page (1-150). Default 50.": "Links per page (1-150). Default 50.",+ "nextPageToken from a previous call.": "nextPageToken from a previous call.",+ "ISO 3166-1 alpha-2 code, e.g. US, DE.": "ISO 3166-1 alpha-2 code, e.g. US, DE.",+ "Where visitors from that country go.": "Where visitors from that country go.",+ "Time period for the statistics. Default: last 30 days.": "Time period for the statistics. Default: last 30 days.","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.",@@ -131,6 +241,7 @@"Last 30 Days": "Last 30 Days","This Month": "This Month","Last Month": "Last Month",+ "All Time": "All Time","Custom Date Range": "Custom Date Range","Hour": "Hour","Day": "Day",@@ -138,6 +249,11 @@"Month": "Month","Ascending (Oldest First)": "Ascending (Oldest First)","Descending (Newest First)": "Descending (Newest First)",+ "PNG": "PNG",+ "SVG": "SVG",+ "This Week": "This Week",+ "Newest first": "Newest first",+ "Oldest first": "Oldest first","GET": "GET","POST": "POST","PATCH": "PATCH",@@ -148,7 +264,7 @@"Fires when a new short link is created on a domain. Useful to sync newly created links to other systems.": "Fires when a new short link is created on a domain. Useful to sync newly created links to other systems.","Polling Interval": "Polling Interval","Select the domain to monitor for new links": "Select the domain to monitor for new links",- "How often to check for new links. More frequent polling may hit rate limits.": "How often to check for new links. More frequent polling may hit rate limits.",+ "Not used: Activepieces sets the polling schedule. Kept so existing flows keep working.": "Not used: Activepieces sets the polling schedule. Kept so existing flows keep working.","Every 1 minute": "Every 1 minute","Every 5 minutes": "Every 5 minutes","Every 15 minutes": "Every 15 minutes",diff --git a/packages/pieces/community/short-io/src/index.ts b/packages/pieces/community/short-io/src/index.tsindex 501cce47eb9..38391a11cdd 100644--- a/packages/pieces/community/short-io/src/index.ts+++ b/packages/pieces/community/short-io/src/index.ts@@ -1,23 +1,46 @@-import {- createCustomApiCallAction-} from '@activepieces/pieces-common';+import { createCustomApiCallAction } from '@activepieces/pieces-common';import { createPiece } from '@activepieces/pieces-framework';-import { shortIoAuth } from './lib/common/auth';+import { addTagToLinksAction } from './lib/actions/add-tag-to-links';+import { createLinkAiAction } from './lib/actions/ai/create-link';+import { deleteLinkAiAction } from './lib/actions/ai/delete-link';+import { findLinkByPathAiAction } from './lib/actions/ai/find-link-by-path';+import { getDomainStatisticsAiAction } from './lib/actions/ai/get-domain-statistics';+import { listLinksAiAction } from './lib/actions/ai/list-links';+import { setCountryRuleAiAction } from './lib/actions/ai/set-country-rule';+import { updateLinkAiAction } from './lib/actions/ai/update-link';+import { archiveLinkAction } from './lib/actions/archive-link';import { createCountryTargetingRuleAction } from './lib/actions/create-country-targeting-for-a-link';+import { createFolderAction } from './lib/actions/create-folder';+import { createLinksBulkAction } from './lib/actions/create-links-bulk';import { createShortLinkAction } from './lib/actions/create-short-link';+import { deleteCountryRuleAction } from './lib/actions/delete-country-rule';+import { duplicateLinkAction } from './lib/actions/duplicate-link';+import { getFolderAction } from './lib/actions/get-folder';+import { getLinkOpenGraphAction } from './lib/actions/get-link-open-graph';import { deleteShortLinkAction } from './lib/actions/delete-short-link';-import { expireShortLinkAction } from './lib/actions/expire-short-link';import { domainStatisticsAction } from './lib/actions/domain-statistics';+import { expireShortLinkAction } from './lib/actions/expire-short-link';+import { findLinksByOriginalUrlAction } from './lib/actions/find-links-by-original-url';+import { generateQrCodeAction } from './lib/actions/generate-qr-code';+import { getDomainAction } from './lib/actions/get-domain';+import { getLinkAction } from './lib/actions/get-link';import { getLinkByPathAction } from './lib/actions/get-link-by-path';import { getLinkClicksAction } from './lib/actions/get-link-clicks';+import { getTopLinksAction } from './lib/actions/get-top-links';+import { listCountryRulesAction } from './lib/actions/list-country-rules';+import { listDomainsAction } from './lib/actions/list-domains';+import { listFoldersAction } from './lib/actions/list-folders';import { listLinksAction } from './lib/actions/list-links';+import { listRecentClicksAction } from './lib/actions/list-recent-clicks';+import { unarchiveLinkAction } from './lib/actions/unarchive-link';import { updateShortLinkAction } from './lib/actions/update-short-link';+import { shortIoAuth } from './lib/common/auth';import { newLinkCreatedTrigger } from './lib/triggers/new-link-created';export const shortIo = createPiece({displayName: 'Short.io',auth: shortIoAuth,- minimumSupportedRelease: '0.36.1',+ minimumSupportedRelease: '0.88.2',logoUrl: 'https://cdn.activepieces.com/pieces/short-io.png',authors: ['aryel780'],actions: [@@ -30,15 +53,37 @@ export const shortIo = createPiece({getLinkClicksAction,listLinksAction,updateShortLinkAction,+ listDomainsAction,+ getDomainAction,+ getLinkAction,+ findLinksByOriginalUrlAction,+ createLinksBulkAction,+ archiveLinkAction,+ unarchiveLinkAction,+ addTagToLinksAction,+ generateQrCodeAction,+ listFoldersAction,+ createFolderAction,+ listCountryRulesAction,+ deleteCountryRuleAction,+ listRecentClicksAction,+ getTopLinksAction,+ duplicateLinkAction,+ getFolderAction,+ getLinkOpenGraphAction,+ createLinkAiAction,+ updateLinkAiAction,+ findLinkByPathAiAction,+ listLinksAiAction,+ deleteLinkAiAction,+ setCountryRuleAiAction,+ getDomainStatisticsAiAction,createCustomApiCallAction({auth: shortIoAuth,baseUrl: () => 'https://api.short.io',- authMapping: async (auth) => {- const { apiKey } = auth.props;- return {- Authorization: apiKey,- };- },+ authMapping: async (auth) => ({+ Authorization: auth.props.apiKey,+ }),}),],triggers: [newLinkCreatedTrigger],diff --git a/packages/pieces/community/short-io/src/lib/actions/add-tag-to-links.ts b/packages/pieces/community/short-io/src/lib/actions/add-tag-to-links.tsnew file mode 100644index 00000000000..32be780fb8a--- /dev/null+++ b/packages/pieces/community/short-io/src/lib/actions/add-tag-to-links.ts@@ -0,0 +1,55 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { shortIoAuth } from '../common/auth';+import { shortIoClient } from '../common/client';+import { shortIoSchemas } from '../common/output-schemas';+import { shortIoValues } from '../common/values';++const LINK_ID_PATTERN = /^(lnk|link)_[^/\s]+$/;++export const addTagToLinksAction = createAction({+ auth: shortIoAuth,+ name: 'add_tag_to_links',+ displayName: 'Add Tag to Links',+ description: 'Append one tag to one or more short links.',+ audience: 'both',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Appends a single tag to one or more short links given their link IDs; existing tags are kept. Idempotent: tagging a link that already has the tag changes nothing.',+ idempotent: true,+ },+ outputSchema: shortIoSchemas.tagLinks,+ props: {+ tag: Property.ShortText({+ displayName: 'Tag',+ description: 'The tag to add.',+ required: true,+ }),+ linkIds: Property.Array({+ displayName: 'Link IDs',+ description: 'Link IDs to tag (the idString of each link, e.g. link_8yXK_034ebx7JWAtAAK3vFcl6ye).',+ required: true,+ }),+ },+ async run({ auth, propsValue }) {+ const tag = propsValue.tag.trim();+ if (!tag) {+ throw new Error('Tag is required.');+ }+ const linkIds = [...new Set(shortIoValues.stringList(propsValue.linkIds))];+ if (linkIds.length === 0) {+ throw new Error('At least one Link ID is required.');+ }+ const invalid = linkIds.filter((id) => !LINK_ID_PATTERN.test(id));+ if (invalid.length > 0) {+ throw new Error(`These are not Short.io link IDs (expected link_… or lnk_…): ${invalid.slice(0, 5).join(', ')}`);+ }+ try {+ await shortIoClient.request({ auth, method: HttpMethod.POST, path: '/tags/bulk', body: { tag, link_ids: linkIds } });+ return { tag, linkIds, count: linkIds.length };+ } catch (error) {+ return shortIoClient.rethrowWithHint({ error, hints: { 400: 'Short.io rejected the tag request.' } });+ }+ },+});diff --git a/packages/pieces/community/short-io/src/lib/actions/ai/create-link.ts b/packages/pieces/community/short-io/src/lib/actions/ai/create-link.tsnew file mode 100644index 00000000000..3842e5fdf39--- /dev/null+++ b/packages/pieces/community/short-io/src/lib/actions/ai/create-link.ts@@ -0,0 +1,51 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { shortIoAiLinkFields } from '../../common/ai-link-fields';+import { shortIoAiProps } from '../../common/ai-props';+import { shortIoAuth } from '../../common/auth';+import { shortIoClient } from '../../common/client';+import { shortIoLinks } from '../../common/links';+import { shortIoSchemas } from '../../common/output-schemas';+import { shortIoTargeting } from '../../common/targeting';++export const createLinkAiAction = createAction({+ auth: shortIoAuth,+ name: 'create_link',+ displayName: 'Create Short Link (AI)',+ description: 'Create a short link on a domain given by hostname or ID.',+ audience: 'ai',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Creates a short link on a Short.io domain for a long URL, optionally with a custom slug, title, tags, UTM parameters, expiry date or scheduled deletion. Not idempotent: a repeat call with no slug creates another link; with the same slug it fails unless the URL matches.',+ idempotent: false,+ },+ outputSchema: shortIoSchemas.link,+ props: {+ domain: shortIoAiProps.domain(),+ originalURL: Property.ShortText({ displayName: 'Original URL', description: 'The long URL the short link redirects to.', required: true }),+ ...shortIoAiLinkFields.linkSettingProps,+ },+ async run({ auth, propsValue }) {+ const originalURL = shortIoTargeting.httpUrl({ value: propsValue.originalURL, label: 'Original URL' });+ const body = shortIoAiLinkFields.aiLinkBody({ values: { ...propsValue }, now: Date.now() });+ const domain = await shortIoLinks.resolveDomain({ auth, input: propsValue.domain });+ try {+ const response = await shortIoClient.request({+ auth,+ method: HttpMethod.POST,+ path: '/links',+ body: { ...body, originalURL, domain: domain.hostname },+ });+ return shortIoLinks.scrubLink(response);+ } catch (error) {+ return shortIoClient.rethrowWithHint({+ error,+ hints: {+ 409: 'A link with this path already exists on the domain and points to a different URL.',+ 400: 'Short.io rejected the link settings.',+ },+ });+ }+ },+});diff --git a/packages/pieces/community/short-io/src/lib/actions/ai/delete-link.ts b/packages/pieces/community/short-io/src/lib/actions/ai/delete-link.tsnew file mode 100644index 00000000000..12e1b4a393e--- /dev/null+++ b/packages/pieces/community/short-io/src/lib/actions/ai/delete-link.ts@@ -0,0 +1,35 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { shortIoAiProps } from '../../common/ai-props';+import { shortIoAuth } from '../../common/auth';+import { shortIoClient } from '../../common/client';+import { shortIoSchemas } from '../../common/output-schemas';++export const deleteLinkAiAction = createAction({+ auth: shortIoAuth,+ name: 'delete_link',+ displayName: 'Delete Short Link (AI)',+ description: 'Permanently delete a short link by ID; a repeat call reports it as already deleted.',+ audience: 'ai',+ classification: 'DESTRUCTIVE',+ aiMetadata: {+ description: 'Permanently deletes a short link by ID; the short URL stops working. A repeat call reports already deleted.',+ idempotent: true,+ },+ outputSchema: shortIoSchemas.deleteLink,+ props: {+ linkId: shortIoAiProps.linkId(),+ },+ async run({ auth, propsValue }) {+ const linkId = propsValue.linkId.trim();+ try {+ await shortIoClient.request({ auth, method: HttpMethod.DELETE, path: `/links/${shortIoClient.seg({ value: linkId, label: 'Link ID' })}` });+ return { linkId, deleted: true, alreadyDeleted: false };+ } catch (error) {+ if (shortIoClient.errorStatus(error) === 404) {+ return { linkId, deleted: false, alreadyDeleted: true };+ }+ return shortIoClient.rethrowWithHint({ error, hints: {} });+ }+ },+});diff --git a/packages/pieces/community/short-io/src/lib/actions/ai/find-link-by-path.ts b/packages/pieces/community/short-io/src/lib/actions/ai/find-link-by-path.tsnew file mode 100644index 00000000000..4a79a743d84--- /dev/null+++ b/packages/pieces/community/short-io/src/lib/actions/ai/find-link-by-path.ts@@ -0,0 +1,45 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { shortIoAuth } from '../../common/auth';+import { shortIoLinkQueries } from '../../common/link-queries';+import { shortIoLinks } from '../../common/links';+import { shortIoSchemas } from '../../common/output-schemas';++export const findLinkByPathAiAction = createAction({+ auth: shortIoAuth,+ name: 'find_link_by_path',+ displayName: 'Find Link by Short URL (AI)',+ description: 'Find a short link from its full short URL, or from a domain plus slug.',+ audience: 'ai',+ classification: 'SEARCH',+ aiMetadata: {+ description:+ 'Looks up a short link from its public short URL (e.g. https://link.example.com/promo) or from a domain plus slug, returning the link ID and settings. Returns found=false when the slug does not exist. Read-only.',+ idempotent: true,+ },+ outputSchema: shortIoSchemas.linkLookup,+ props: {+ shortUrl: Property.ShortText({+ displayName: 'Short URL or Slug',+ description: 'Full short URL like https://link.example.com/promo, or just the slug "promo" when Domain is given.',+ required: true,+ }),+ domain: Property.ShortText({+ displayName: 'Domain',+ description: 'Domain hostname or ID; needed only when Short URL is a bare slug.',+ required: false,+ }),+ },+ async run({ auth, propsValue }) {+ const parsed = shortIoLinks.parseShortUrl(propsValue.shortUrl ?? '');+ if (!parsed.path) {+ throw new Error('Give a short URL with a slug, e.g. https://link.example.com/promo.');+ }+ const domainInput = parsed.hostname ?? propsValue.domain?.trim();+ if (!domainInput) {+ throw new Error('Domain is required when Short URL is only a slug.');+ }+ const domain = await shortIoLinks.resolveDomain({ auth, input: domainInput });+ const link = await shortIoLinkQueries.expand({ auth, hostname: domain.hostname, path: parsed.path });+ return { found: link !== null, link };+ },+});diff --git a/packages/pieces/community/short-io/src/lib/actions/ai/get-domain-statistics.ts b/packages/pieces/community/short-io/src/lib/actions/ai/get-domain-statistics.tsnew file mode 100644index 00000000000..f79340f570a--- /dev/null+++ b/packages/pieces/community/short-io/src/lib/actions/ai/get-domain-statistics.ts@@ -0,0 +1,39 @@+import { createAction } from '@activepieces/pieces-framework';+import { shortIoAiProps } from '../../common/ai-props';+import { shortIoAuth } from '../../common/auth';+import { shortIoLinks } from '../../common/links';+import { shortIoSchemas } from '../../common/output-schemas';+import { shortIoStats } from '../../common/stats';++export const getDomainStatisticsAiAction = createAction({+ auth: shortIoAuth,+ name: 'get_domain_statistics',+ displayName: 'Get Domain Statistics (AI)',+ description: 'Get click and link totals for a whole domain over a period.',+ audience: 'ai',+ classification: 'READ',+ aiMetadata: {+ description:+ 'Returns total and human clicks, links created, and top countries, referrers and browsers for a whole Short.io domain over a period. Custom period needs start and end dates (YYYY-MM-DD). Read-only.',+ idempotent: true,+ },+ outputSchema: shortIoSchemas.domainStats,+ props: {+ domain: shortIoAiProps.domain(),+ period: shortIoAiProps.period('Time period for the statistics. Default: last 30 days.'),+ startDate: shortIoAiProps.startDate(),+ endDate: shortIoAiProps.endDate(),+ tz: shortIoAiProps.timezone(),+ },+ async run({ auth, propsValue }) {+ const domain = await shortIoLinks.resolveDomain({ auth, input: propsValue.domain });+ return shortIoStats.domainStatistics({+ auth,+ domainId: domain.id,+ period: propsValue.period,+ startDate: propsValue.startDate,+ endDate: propsValue.endDate,+ tz: propsValue.tz,+ });+ },+});diff --git a/packages/pieces/community/short-io/src/lib/actions/ai/list-links.ts b/packages/pieces/community/short-io/src/lib/actions/ai/list-links.tsnew file mode 100644index 00000000000..39d2463324b--- /dev/null+++ b/packages/pieces/community/short-io/src/lib/actions/ai/list-links.ts@@ -0,0 +1,55 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { shortIoAiProps } from '../../common/ai-props';+import { shortIoAuth } from '../../common/auth';+import { shortIoLinkQueries } from '../../common/link-queries';+import { shortIoLinks } from '../../common/links';+import { shortIoSchemas } from '../../common/output-schemas';+import { shortIoValues } from '../../common/values';++export const listLinksAiAction = createAction({+ auth: shortIoAuth,+ name: 'list_links',+ displayName: 'List Links (AI)',+ description: 'List one page of links on a domain, newest first by default.',+ audience: 'ai',+ classification: 'SEARCH',+ aiMetadata: {+ description:+ 'Lists one page (up to 150) of short links on a domain, optionally in one folder or created before/after a date. Returns items, nextPageToken and hasMore; pass nextPageToken back as Page Token for the next page. Read-only.',+ idempotent: true,+ },+ outputSchema: shortIoSchemas.linkList,+ props: {+ domain: shortIoAiProps.domain(),+ folderId: shortIoAiProps.folderId(),+ createdAfter: Property.ShortText({ displayName: 'Created After', description: 'ISO 8601 date-time; only links created after it.', required: false }),+ createdBefore: Property.ShortText({ displayName: 'Created Before', description: 'ISO 8601 date-time; only links created before it.', required: false }),+ sortOrder: Property.StaticDropdown({+ displayName: 'Sort Order',+ required: false,+ defaultValue: 'desc',+ options: { disabled: false, options: [{ label: 'Newest first', value: 'desc' }, { label: 'Oldest first', value: 'asc' }] },+ }),+ limit: Property.Number({ displayName: 'Limit', description: 'Links per page (1-150). Default 50.', required: false }),+ pageToken: Property.ShortText({ displayName: 'Page Token', description: 'nextPageToken from a previous call.', required: false }),+ },+ async run({ auth, propsValue }) {+ const limit = shortIoValues.optionalNumber({ value: propsValue.limit, label: 'Limit', min: 1, max: 150 }) ?? 50;+ const afterDate = propsValue.createdAfter?.trim() ? shortIoValues.toIsoDateTime({ value: propsValue.createdAfter, label: 'Created After' }) : undefined;+ const beforeDate = propsValue.createdBefore?.trim() ? shortIoValues.toIsoDateTime({ value: propsValue.createdBefore, label: 'Created Before' }) : undefined;+ const domain = await shortIoLinks.resolveDomain({ auth, input: propsValue.domain });+ const page = await shortIoLinkQueries.listPage({+ auth,+ domainId: domain.id,+ query: {+ limit,+ folderId: propsValue.folderId?.trim(),+ afterDate,+ beforeDate,+ dateSortOrder: propsValue.sortOrder === 'asc' ? 'asc' : 'desc',+ pageToken: propsValue.pageToken?.trim(),+ },+ });+ return { items: page.links, count: page.links.length, nextPageToken: page.nextPageToken, hasMore: page.nextPageToken !== null };+ },+});diff --git a/packages/pieces/community/short-io/src/lib/actions/ai/set-country-rule.ts b/packages/pieces/community/short-io/src/lib/actions/ai/set-country-rule.tsnew file mode 100644index 00000000000..2aea88823a5--- /dev/null+++ b/packages/pieces/community/short-io/src/lib/actions/ai/set-country-rule.ts@@ -0,0 +1,34 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { shortIoAiProps } from '../../common/ai-props';+import { shortIoAuth } from '../../common/auth';+import { shortIoSchemas } from '../../common/output-schemas';+import { shortIoTargeting } from '../../common/targeting';++export const setCountryRuleAiAction = createAction({+ auth: shortIoAuth,+ name: 'set_country_rule',+ displayName: 'Add Country Targeting Rule (AI)',+ description: 'Send visitors from one country to a different URL.',+ audience: 'ai',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Adds a country-targeting rule to a short link (by link ID): visitors from the given country (2-letter ISO code) are sent to the given URL instead of the default destination. Not idempotent: a second rule for the same country may be rejected.',+ idempotent: false,+ },+ outputSchema: shortIoSchemas.countryRule,+ props: {+ linkId: shortIoAiProps.linkId(),+ country: Property.ShortText({ displayName: 'Country Code', description: 'ISO 3166-1 alpha-2 code, e.g. US, DE.', required: true }),+ originalURL: Property.ShortText({ displayName: 'Country Redirect URL', description: 'Where visitors from that country go.', required: true }),+ },+ async run({ auth, propsValue }) {+ const rule = await shortIoTargeting.addCountryRule({+ auth,+ linkId: propsValue.linkId,+ country: propsValue.country,+ originalURL: propsValue.originalURL,+ });+ return { linkId: rule.linkId, country: rule.country, originalURL: rule.originalURL, rule: rule.raw };+ },+});diff --git a/packages/pieces/community/short-io/src/lib/actions/ai/update-link.ts b/packages/pieces/community/short-io/src/lib/actions/ai/update-link.tsnew file mode 100644index 00000000000..fc6ab1c3e0a--- /dev/null+++ b/packages/pieces/community/short-io/src/lib/actions/ai/update-link.ts@@ -0,0 +1,52 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { shortIoAiLinkFields } from '../../common/ai-link-fields';+import { shortIoAiProps } from '../../common/ai-props';+import { shortIoAuth } from '../../common/auth';+import { shortIoClient } from '../../common/client';+import { shortIoLinks } from '../../common/links';+import { shortIoSchemas } from '../../common/output-schemas';+import { shortIoTargeting } from '../../common/targeting';++export const updateLinkAiAction = createAction({+ auth: shortIoAuth,+ name: 'update_link',+ displayName: 'Update Short Link (AI)',+ description: 'Change the settings of a short link by link ID; only the fields you give are changed.',+ audience: 'ai',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Updates an existing short link by link ID: destination URL, slug, title, tags (replaces the list), folder, UTM fields, expiry or scheduled deletion. Only fields you provide change. Idempotent: sending the same values again leaves the link the same.',+ idempotent: true,+ },+ outputSchema: shortIoSchemas.link,+ props: {+ linkId: shortIoAiProps.linkId(),+ originalURL: Property.ShortText({ displayName: 'Original URL', description: 'New destination URL.', required: false }),+ ...shortIoAiLinkFields.linkSettingProps,+ },+ async run({ auth, propsValue }) {+ if (propsValue.originalURL?.trim()) {+ shortIoTargeting.httpUrl({ value: propsValue.originalURL, label: 'Original URL' });+ }+ const body = shortIoAiLinkFields.aiLinkBody({ values: { ...propsValue }, now: Date.now() });+ if (Object.keys(body).length === 0) {+ throw new Error('Nothing to update: give at least one field to change.');+ }+ const linkId = shortIoClient.seg({ value: propsValue.linkId, label: 'Link ID' });+ try {+ const response = await shortIoClient.request({ auth, method: HttpMethod.POST, path: `/links/${linkId}`, body });+ return shortIoLinks.scrubLink(response);+ } catch (error) {+ return shortIoClient.rethrowWithHint({+ error,+ hints: {+ 404: 'Short link not found. Check the link ID.',+ 409: 'Another link on this domain already uses this path.',+ 400: 'Short.io rejected the link settings.',+ },+ });+ }+ },+});diff --git a/packages/pieces/community/short-io/src/lib/actions/archive-link.ts b/packages/pieces/community/short-io/src/lib/actions/archive-link.tsnew file mode 100644index 00000000000..f46544ab00d--- /dev/null+++ b/packages/pieces/community/short-io/src/lib/actions/archive-link.ts@@ -0,0 +1,25 @@+import { createAction } from '@activepieces/pieces-framework';+import { shortIoAiProps } from '../common/ai-props';+import { shortIoArchive } from '../common/archive';+import { shortIoAuth } from '../common/auth';+import { shortIoSchemas } from '../common/output-schemas';++export const archiveLinkAction = createAction({+ auth: shortIoAuth,+ name: 'archive_link',+ displayName: 'Archive Short Link',+ description: 'Archive a short link (hide it from the dashboard; the short URL keeps redirecting).',+ audience: 'both',+ classification: 'WRITE',+ aiMetadata: {+ description: 'Archives a short link by link ID, hiding it from the default dashboard list; the short URL keeps working. Reversible with Unarchive Short Link. Idempotent: archiving an archived link changes nothing.',+ idempotent: true,+ },+ outputSchema: shortIoSchemas.archive,+ props: {+ linkId: shortIoAiProps.linkId(),+ },+ async run({ auth, propsValue }) {+ return shortIoArchive.setArchived({ auth, linkId: propsValue.linkId, archived: true });+ },+});diff --git a/packages/pieces/community/short-io/src/lib/actions/create-country-targeting-for-a-link.ts b/packages/pieces/community/short-io/src/lib/actions/create-country-targeting-for-a-link.tsindex 940fc32c83d..d70c64c810e 100644--- a/packages/pieces/community/short-io/src/lib/actions/create-country-targeting-for-a-link.ts+++ b/packages/pieces/community/short-io/src/lib/actions/create-country-targeting-for-a-link.ts@@ -1,8 +1,9 @@-import { HttpMethod } from '@activepieces/pieces-common';import { createAction, Property } from '@activepieces/pieces-framework';-import { shortIoApiCall } from '../common/client';import { shortIoAuth } from '../common/auth';+import { shortIoLinks } from '../common/links';+import { shortIoSchemas } from '../common/output-schemas';import { domainIdDropdown, linkIdDropdown } from '../common/props';+import { shortIoTargeting } from '../common/targeting';export const createCountryTargetingRuleAction = createAction({auth: shortIoAuth,@@ -10,8 +11,13 @@ export const createCountryTargetingRuleAction = createAction({classification: 'WRITE',displayName: 'Create Country Targeting Rule',description: 'Set geographic targeting rules for a link with specific destination per country.',- audience: 'both',- aiMetadata: { description: 'Adds a country-targeting rule to an existing short link so visitors from a given country are redirected to a country-specific URL instead of the default destination. Use to set up geo-redirects on a link you already have the ID for. Requires the link ID, a 2-letter ISO country code, and a valid redirect URL; not idempotent — a rule for a country that already exists is rejected (409).', idempotent: false },+ audience: 'human',+ aiMetadata: {+ description:+ 'Adds a country-targeting rule to an existing short link so visitors from a given country are redirected to a country-specific URL instead of the default destination. Requires the link, a 2-letter ISO country code and a valid redirect URL. Not idempotent: Short.io may reject a second rule for the same country.',+ idempotent: false,+ },+ outputSchema: shortIoSchemas.legacyCountryRule,props: {domain: domainIdDropdown,linkId: linkIdDropdown,@@ -27,77 +33,18 @@ export const createCountryTargetingRuleAction = createAction({}),},async run({ propsValue, auth }) {- const { linkId, domain: domainString, country, originalURL } = propsValue;-- if (!country || country.trim().length !== 2) {- throw new Error('Country code must be exactly 2 characters (e.g., US, GB, CA)');- }-- const countryCode = country.trim().toUpperCase();-- try {- new URL(originalURL);- } catch (error) {- throw new Error('Invalid URL format. Please provide a valid URL starting with http:// or https://');- }-- const query: Record<string, string> = {};- if (domainString) {- const domainObject = JSON.parse(domainString as string);- query['domainId'] = String(domainObject.id);- }-- const body = {- country: countryCode,- originalURL,+ const domain = shortIoLinks.parseDomainProp(propsValue.domain);+ const rule = await shortIoTargeting.addCountryRule({+ auth,+ linkId: propsValue.linkId,+ domainId: domain.id,+ country: propsValue.country,+ originalURL: propsValue.originalURL,+ });+ return {+ success: true,+ message: `Country targeting rule for ${rule.country} created successfully`,+ data: rule.raw ?? { country: rule.country, originalURL: rule.originalURL },};-- try {- const response = await shortIoApiCall({- method: HttpMethod.POST,- auth,- resourceUri: `/link_country/${linkId}`,- query,- body,- });-- return {- success: true,- message: `Country targeting rule for ${countryCode} created successfully`,- data: response,- };- } catch (error: any) {- if (error.message.includes('400')) {- throw new Error(- 'Invalid request parameters. Please check the country code format and URL validity.'- );- }-- if (error.message.includes('401') || error.message.includes('403')) {- throw new Error(- 'Authentication failed. Please check your API key and permissions.'- );- }-- if (error.message.includes('404')) {- throw new Error(- 'Short link not found. Please check the link ID and try again.'- );- }-- if (error.message.includes('409')) {- throw new Error(- `A country targeting rule for ${countryCode} already exists for this link.`- );- }-- if (error.message.includes('429')) {- throw new Error(- 'Rate limit exceeded. Please wait a moment before trying again.'- );- }-- throw new Error(`Failed to create country targeting rule: ${error.message}`);- }},});diff --git a/packages/pieces/community/short-io/src/lib/actions/create-folder.ts b/packages/pieces/community/short-io/src/lib/actions/create-folder.tsnew file mode 100644index 00000000000..ee5689e8586--- /dev/null+++ b/packages/pieces/community/short-io/src/lib/actions/create-folder.ts@@ -0,0 +1,48 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { shortIoAiProps } from '../common/ai-props';+import { shortIoAuth } from '../common/auth';+import { shortIoClient } from '../common/client';+import { shortIoLinks } from '../common/links';+import { shortIoSchemas } from '../common/output-schemas';++export const createFolderAction = createAction({+ auth: shortIoAuth,+ name: 'create_folder',+ displayName: 'Create Folder',+ description: 'Create a link folder on a domain.',+ audience: 'both',+ classification: 'WRITE',+ aiMetadata: {+ description: 'Creates a new link folder on a Short.io domain and returns its ID. Not idempotent: a repeat call may create a second folder with the same name.',+ idempotent: false,+ },+ outputSchema: shortIoSchemas.folder,+ props: {+ domain: shortIoAiProps.domain(),+ name: Property.ShortText({+ displayName: 'Folder Name',+ required: true,+ }),+ },+ async run({ auth, propsValue }) {+ const name = propsValue.name.trim();+ if (!name) {+ throw new Error('Folder name is required.');+ }+ const domain = await shortIoLinks.resolveDomain({ auth, input: propsValue.domain });+ try {+ const response = await shortIoClient.request({+ auth,+ method: HttpMethod.POST,+ path: '/links/folders',+ body: { domainId: domain.id, name },+ });+ const record = shortIoLinks.isRecord(response) ? response : {};+ const folder = shortIoLinks.isRecord(record['linkFolder']) ? record['linkFolder'] : record;+ return { ...folder, id: folder['id'] ?? null, name: folder['name'] ?? name, domainId: domain.id };+ } catch (error) {+ return shortIoClient.rethrowWithHint({ error, hints: { 409: 'A folder with this name already exists.' } });+ }+ },+});diff --git a/packages/pieces/community/short-io/src/lib/actions/create-links-bulk.ts b/packages/pieces/community/short-io/src/lib/actions/create-links-bulk.tsnew file mode 100644index 00000000000..417d4a248f2--- /dev/null+++ b/packages/pieces/community/short-io/src/lib/actions/create-links-bulk.ts@@ -0,0 +1,95 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { shortIoAiProps } from '../common/ai-props';+import { shortIoAuth } from '../common/auth';+import { shortIoClient } from '../common/client';+import { shortIoLinks } from '../common/links';+import { shortIoSchemas } from '../common/output-schemas';+import { shortIoTargeting } from '../common/targeting';++const MAX_BULK_LINKS = 1000;+const ALLOWED_KEYS = ['originalURL', 'path', 'title', 'tags', 'utmSource', 'utmMedium', 'utmCampaign', 'utmTerm', 'utmContent', 'expiresAt', 'expiredURL', 'redirectType', 'androidURL', 'iphoneURL', 'cloaking'];++function normalizeLinks(value: unknown): Record<string, unknown>[] {+ const list: unknown = typeof value === 'string' ? parseJson(value) : value;+ if (!Array.isArray(list) || list.length === 0) {+ throw new Error('Links must be a non-empty JSON array of objects like {"originalURL": "https://…", "path": "optional-slug"}.');+ }+ if (list.length > MAX_BULK_LINKS) {+ throw new Error(`Short.io accepts at most ${MAX_BULK_LINKS} links per bulk request (got ${list.length}).`);+ }+ return list.map((item, index) => {+ const record = typeof item === 'string' ? { originalURL: item } : item;+ if (!shortIoLinks.isRecord(record)) {+ throw new Error(`Link #${index + 1} must be an object or a URL string.`);+ }+ const picked = Object.fromEntries(ALLOWED_KEYS.filter((key) => record[key] !== undefined && record[key] !== null && record[key] !== '').map((key) => [key, record[key]]));+ return { ...picked, originalURL: shortIoTargeting.httpUrl({ value: record['originalURL'], label: `Link #${index + 1} originalURL` }) };+ });+}++function parseJson(text: string): unknown {+ try {+ return JSON.parse(text);+ } catch {+ throw new Error('Links must be valid JSON.');+ }+}++export const createLinksBulkAction = createAction({+ auth: shortIoAuth,+ name: 'create_links_bulk',+ displayName: 'Create Short Links (Bulk)',+ description: 'Create up to 1,000 short links on one domain in a single request.',+ audience: 'both',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Creates up to 1000 short links on one domain in a single call. Each item needs originalURL and may set path, title, tags, UTM fields, expiresAt and redirectType. Returns the created links plus per-item errors. Not idempotent: a repeat call without fixed paths creates duplicates.',+ idempotent: false,+ },+ outputSchema: shortIoSchemas.bulkCreate,+ props: {+ domain: shortIoAiProps.domain(),+ links: Property.Json({+ displayName: 'Links',+ description:+ 'JSON array of links, e.g. [{"originalURL": "https://example.com/a", "path": "a"}, {"originalURL": "https://example.com/b"}]. Allowed keys: originalURL (required), path, title, tags, utmSource, utmMedium, utmCampaign, utmTerm, utmContent, expiresAt, expiredURL, redirectType, androidURL, iphoneURL, cloaking.',+ required: true,+ }),+ folderId: shortIoAiProps.folderId(),+ allowDuplicates: Property.Checkbox({+ displayName: 'Allow Duplicates',+ description: 'Create a new link even when one already points to the same URL.',+ required: false,+ defaultValue: false,+ }),+ },+ async run({ auth, propsValue }) {+ const links = normalizeLinks(propsValue.links);+ const domain = await shortIoLinks.resolveDomain({ auth, input: propsValue.domain });+ try {+ const response = await shortIoClient.request({+ auth,+ method: HttpMethod.POST,+ path: '/links/bulk',+ body: {+ domain: domain.hostname,+ links,+ allowDuplicates: propsValue.allowDuplicates === true,+ ...(propsValue.folderId?.trim() ? { folderId: propsValue.folderId.trim() } : {}),+ },+ });+ const results = Array.isArray(response) ? response : [];+ const items = results.filter((item) => shortIoLinks.isRecord(item) && typeof item['idString'] === 'string').map(shortIoLinks.scrubLink);+ const errors = results.flatMap((item, index) =>+ shortIoLinks.isRecord(item) && typeof item['idString'] === 'string'+ ? []+ : [{ index, originalURL: links[index]?.['originalURL'], error: shortIoClient.vendorMessage({ responseBody: item, fallback: 'not created' }) }],+ );+ return { items, createdCount: items.length, errors, errorCount: errors.length };+ } catch (error) {+ return shortIoClient.rethrowWithHint({ error, hints: { 400: 'Short.io rejected the bulk request.' } });+ }+ },+});diff --git a/packages/pieces/community/short-io/src/lib/actions/create-short-link.ts b/packages/pieces/community/short-io/src/lib/actions/create-short-link.tsindex 04fd5a4c397..c384ed5687c 100644--- a/packages/pieces/community/short-io/src/lib/actions/create-short-link.ts+++ b/packages/pieces/community/short-io/src/lib/actions/create-short-link.ts@@ -1,7 +1,10 @@import { HttpMethod } from '@activepieces/pieces-common';import { createAction, Property } from '@activepieces/pieces-framework';-import { shortIoApiCall } from '../common/client';import { shortIoAuth } from '../common/auth';+import { shortIoClient } from '../common/client';+import { shortIoLinkBody } from '../common/link-body';+import { shortIoLinks } from '../common/links';+import { shortIoSchemas } from '../common/output-schemas';import { domainIdDropdown, folderIdDropdown } from '../common/props';export const createShortLinkAction = createAction({@@ -11,8 +14,9 @@ export const createShortLinkAction = createAction({displayName: 'Create Short Link',description:'Create a new short link with optional parameters (title, UTM tags, expiration, cloaking, etc.)',- audience: 'both',+ audience: 'human',aiMetadata: { description: 'Creates a new short link on a Short.io domain pointing to a target URL, with optional path/slug, title, UTM tags, expiration, click limit, cloaking, A/B split, and analytics integrations. Use to generate a shortened URL. Requires an original URL and a domain; not idempotent — each call creates a new link (set Allow Duplicates to avoid 409 conflicts on a repeated path).', idempotent: false },+ outputSchema: shortIoSchemas.legacyLink,props: {originalURL: Property.ShortText({displayName: 'Original URL',@@ -85,7 +89,7 @@ export const createShortLinkAction = createAction({ttl: Property.Number({displayName: 'Time to Live (in seconds)',description:- '⚠️ CAUTION: Link will be PERMANENTLY DELETED after this many seconds. This action cannot be undone. Use with extreme caution.',+ 'Permanently deletes the link this many seconds from now (minimum 604800 = 7 days). Short.io may delete it up to 2 hours later. This cannot be undone.',required: false,}),androidURL: Property.ShortText({@@ -154,137 +158,27 @@ export const createShortLinkAction = createAction({}),},async run({ propsValue, auth }) {- const {- originalURL,- domain: domainString,- path,- title,- cloaking,- password,- redirectType,- expiresAt,- expiredURL,- tags,- utmSource,- utmMedium,- utmCampaign,- utmTerm,- utmContent,- ttl,- androidURL,- iphoneURL,- createdAt,- clicksLimit,- passwordContact,- skipQS,- archived,- splitURL,- splitPercent,- integrationAdroll,- integrationFB,- integrationGA,- integrationGTM,- allowDuplicates,- folderId,- } = propsValue;-- // Input validation- if (clicksLimit && clicksLimit < 1) {- throw new Error('Clicks limit must be at least 1');- }-- if (splitPercent && (splitPercent < 1 || splitPercent > 100)) {- throw new Error('Split percent must be between 1 and 100');- }-- if (redirectType && !['301', '302', '303', '307', '308'].includes(redirectType)) {- throw new Error('Invalid redirect type. Must be one of: 301, 302, 303, 307, 308');- }-- const domainObject = JSON.parse(domainString as string);-- const body: Record<string, unknown> = {- originalURL,- domain: domainObject.hostname,- };-- const optionalParams = {- path,- title,- cloaking,- password,- redirectType,- expiresAt,- expiredURL,- tags,- utmSource,- utmMedium,- utmCampaign,- utmTerm,- utmContent,- ttl: ttl ? ttl * 1000 : undefined,- androidURL,- iphoneURL,- createdAt,- clicksLimit,- passwordContact,- skipQS,- archived,- splitURL,- splitPercent,- integrationAdroll,- integrationFB,- integrationGA,- integrationGTM,- allowDuplicates,- folderId,+ const domain = shortIoLinks.parseDomainProp(propsValue.domain);+ const body = {+ ...shortIoLinkBody.legacyLinkBody({ values: { ...propsValue }, now: Date.now() }),+ originalURL: propsValue.originalURL,+ domain: domain.hostname,};-- for (const [key, value] of Object.entries(optionalParams)) {- if (value !== null && value !== undefined && value !== '') {- body[key] = value;- }- }-try {- const response = await shortIoApiCall({- method: HttpMethod.POST,- auth,- resourceUri: '/links',- body,- });-+ const response = await shortIoClient.request({ method: HttpMethod.POST, auth, path: '/links', body });return {success: true,message: 'Short link created successfully',- data: response,+ data: shortIoLinks.scrubLink(response),};- } catch (error: any) {- if (error.message.includes('409')) {- throw new Error(- 'A short link with this path already exists but points to a different original URL.'- );- }-- if (error.message.includes('400')) {- throw new Error(- 'Invalid request parameters. Please check your input values and try again.'- );- }-- if (error.message.includes('401') || error.message.includes('403')) {- throw new Error(- 'Authentication failed. Please check your API key and permissions.'- );- }-- if (error.message.includes('429')) {- throw new Error(- 'Rate limit exceeded. Please wait a moment before trying again.'- );- }-- throw new Error(`Failed to create short link: ${error.message}`);+ } catch (error) {+ return shortIoClient.rethrowWithHint({+ error,+ hints: {+ 409: 'A short link with this path already exists but points to a different original URL.',+ 400: 'Short.io rejected the link settings.',+ },+ });}},});diff --git a/packages/pieces/community/short-io/src/lib/actions/delete-country-rule.ts b/packages/pieces/community/short-io/src/lib/actions/delete-country-rule.tsnew file mode 100644index 00000000000..9bd26ac883c--- /dev/null+++ b/packages/pieces/community/short-io/src/lib/actions/delete-country-rule.ts@@ -0,0 +1,47 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { shortIoAiProps } from '../common/ai-props';+import { shortIoAuth } from '../common/auth';+import { shortIoClient } from '../common/client';+import { shortIoSchemas } from '../common/output-schemas';+import { shortIoTargeting } from '../common/targeting';++export const deleteCountryRuleAction = createAction({+ auth: shortIoAuth,+ name: 'delete_country_rule',+ displayName: 'Delete Country Targeting Rule',+ description: 'Remove the country redirect rule for one country from a short link.',+ audience: 'both',+ classification: 'DESTRUCTIVE',+ aiMetadata: {+ description:+ 'Removes the country-targeting rule for one country (2-letter code) from a short link; visitors from that country then go to the default destination. A repeat call reports alreadyDeleted.',+ idempotent: true,+ },+ outputSchema: shortIoSchemas.countryRuleDelete,+ props: {+ linkId: shortIoAiProps.linkId(),+ country: Property.ShortText({+ displayName: 'Country Code',+ description: 'ISO 3166-1 alpha-2 code of the rule to remove, e.g. US.',+ required: true,+ }),+ },+ async run({ auth, propsValue }) {+ const linkId = propsValue.linkId.trim();+ const country = shortIoTargeting.countryCode(propsValue.country);+ try {+ await shortIoClient.request({+ auth,+ method: HttpMethod.DELETE,+ path: `/link_country/${shortIoClient.seg({ value: linkId, label: 'Link ID' })}/${country}`,+ });+ return { linkId, country, deleted: true, alreadyDeleted: false };+ } catch (error) {+ if (shortIoClient.errorStatus(error) === 404) {+ return { linkId, country, deleted: false, alreadyDeleted: true };+ }+ return shortIoClient.rethrowWithHint({ error, hints: {} });+ }+ },+});diff --git a/packages/pieces/community/short-io/src/lib/actions/delete-short-link.ts b/packages/pieces/community/short-io/src/lib/actions/delete-short-link.tsindex 515eb91f226..801a7c7887c 100644--- a/packages/pieces/community/short-io/src/lib/actions/delete-short-link.ts+++ b/packages/pieces/community/short-io/src/lib/actions/delete-short-link.ts@@ -1,7 +1,8 @@import { HttpMethod } from '@activepieces/pieces-common';import { createAction, Property } from '@activepieces/pieces-framework';-import { shortIoApiCall } from '../common/client';import { shortIoAuth } from '../common/auth';+import { shortIoClient } from '../common/client';+import { shortIoSchemas } from '../common/output-schemas';export const deleteShortLinkAction = createAction({auth: shortIoAuth,@@ -10,7 +11,12 @@ export const deleteShortLinkAction = createAction({displayName: 'Delete Short Link',description: 'Permanently delete a short link by its unique link ID.',audience: 'both',- aiMetadata: { description: 'Permanently deletes a short link identified by its link ID. Use to remove a link that is no longer needed. Not idempotent — repeating the call returns a not-found error once the link is already gone; this is destructive and cannot be undone.', idempotent: false },+ aiMetadata: {+ description:+ 'Permanently deletes a short link identified by its link ID (lnk_…); the short URL stops working and this cannot be undone. Not idempotent: a repeat call fails with a not-found error once the link is gone (Delete Short Link (AI) reports alreadyDeleted instead).',+ idempotent: false,+ },+ outputSchema: shortIoSchemas.legacyDelete,props: {linkId: Property.ShortText({displayName: 'Link ID',@@ -19,50 +25,19 @@ export const deleteShortLinkAction = createAction({}),},async run({ propsValue, auth }) {- const { linkId } = propsValue;-- if (!linkId || linkId.trim() === '') {- throw new Error('Link ID is required and cannot be empty');- }-+ const linkId = shortIoClient.seg({ value: propsValue.linkId, label: 'Link ID' });try {- const response = await shortIoApiCall({- method: HttpMethod.DELETE,- auth,- resourceUri: `/links/${linkId}`,- });-+ const response = await shortIoClient.request({ method: HttpMethod.DELETE, auth, path: `/links/${linkId}` });return {success: true,- message: `Short link with ID ${linkId} deleted successfully`,+ message: `Short link with ID ${propsValue.linkId.trim()} deleted successfully`,data: response,};- } catch (error: any) {- if (error.message.includes('400')) {- throw new Error(- 'Invalid request. Please check the link ID format and try again.'- );- }-- if (error.message.includes('401') || error.message.includes('403')) {- throw new Error(- 'Authentication failed. Please check your API key and permissions.'- );- }-- if (error.message.includes('404')) {- throw new Error(- `Short link with ID ${linkId} not found. It may have already been deleted.`- );- }-- if (error.message.includes('429')) {- throw new Error(- 'Rate limit exceeded. Please wait a moment before trying again.'- );- }-- throw new Error(`Failed to delete short link: ${error.message}`);+ } catch (error) {+ return shortIoClient.rethrowWithHint({+ error,+ hints: { 404: `Short link with ID ${propsValue.linkId.trim()} not found. It may have already been deleted.` },+ });}},});diff --git a/packages/pieces/community/short-io/src/lib/actions/domain-statistics.ts b/packages/pieces/community/short-io/src/lib/actions/domain-statistics.tsindex a97fdbbc765..914e680d0da 100644--- a/packages/pieces/community/short-io/src/lib/actions/domain-statistics.ts+++ b/packages/pieces/community/short-io/src/lib/actions/domain-statistics.ts@@ -1,8 +1,9 @@-import { HttpMethod } from '@activepieces/pieces-common';import { createAction, Property } from '@activepieces/pieces-framework';-import { shortIoApiCall } from '../common/client';import { shortIoAuth } from '../common/auth';+import { shortIoLinks } from '../common/links';+import { shortIoSchemas } from '../common/output-schemas';import { domainIdDropdown } from '../common/props';+import { shortIoStats } from '../common/stats';export const domainStatisticsAction = createAction({auth: shortIoAuth,@@ -10,8 +11,13 @@ export const domainStatisticsAction = createAction({classification: 'READ',displayName: 'Domain Statistics',description: 'Retrieve usage stats (clicks, conversions) for a domain within a time period.',- audience: 'both',- aiMetadata: { description: 'Retrieves aggregate click and link statistics for a whole Short.io domain over a chosen time window — either a preset range (today, last 7/30 days, this/last month) or a custom start/end date. Use to report on overall domain performance rather than a single link. Custom range requires both start and end dates; read-only and idempotent.', idempotent: true },+ audience: 'human',+ aiMetadata: {+ description:+ 'Retrieves aggregate click and link statistics for a whole Short.io domain over a preset period (today, last 7/30 days, this/last month) or a custom start/end date. Custom range requires both dates. Read-only and idempotent.',+ idempotent: true,+ },+ outputSchema: shortIoSchemas.legacyDomainStats,props: {domainId: {...domainIdDropdown,@@ -30,20 +36,21 @@ export const domainStatisticsAction = createAction({{ label: 'Yesterday', value: 'yesterday' },{ label: 'Last 7 Days', value: 'last7' },{ label: 'Last 30 Days', value: 'last30' },- { label: 'This Month', value: 'thisMonth' },- { label: 'Last Month', value: 'lastMonth' },+ { label: 'This Month', value: 'month' },+ { label: 'Last Month', value: 'lastmonth' },+ { label: 'All Time', value: 'total' },{ label: 'Custom Date Range', value: 'custom' },],},}),startDate: Property.DateTime({displayName: 'Start Date',- description: 'Start date for statistics (required when period is "Custom").',+ description: 'Start date for statistics (required when period is "Custom"). The calendar day you pick is sent as is.',required: false,}),endDate: Property.DateTime({displayName: 'End Date',- description: 'End date for statistics (required when period is "Custom").',+ description: 'End date for statistics (required when period is "Custom"). The calendar day you pick is sent as is.',required: false,}),tz: Property.ShortText({@@ -67,90 +74,23 @@ export const domainStatisticsAction = createAction({}),},async run({ propsValue, auth }) {- const { domainId: domainString, period, startDate, endDate, tz, clicksChartInterval } = propsValue;-- if (!domainString) {- throw new Error('Domain is required. Please select a domain.');- }-- const domainObject = JSON.parse(domainString as string);-- if (period === 'custom') {- if (!startDate || !endDate) {- throw new Error('Start Date and End Date are both required when using custom period.');- }-- const start = new Date(startDate);- const end = new Date(endDate);-- if (start >= end) {- throw new Error('Start date must be before end date.');- }- }-- if (tz && tz.trim() !== '') {- const tzValue = tz.trim();- if (tzValue.length < 3 || tzValue.includes(' ')) {- throw new Error('Invalid timezone format. Use standard timezone names like UTC, America/New_York, Europe/London.');- }- }-- const query: Record<string, string> = {- period,+ const domain = shortIoLinks.parseDomainProp(propsValue.domainId);+ const stats = await shortIoStats.domainStatistics({+ auth,+ domainId: domain.id,+ period: propsValue.period,+ startDate: propsValue.startDate,+ endDate: propsValue.endDate,+ tz: propsValue.tz,+ clicksChartInterval: propsValue.clicksChartInterval,+ ignoreDatesForPresets: true,+ });+ const clicks = Number(stats['clicks'] ?? 0);+ const links = Number(stats['links'] ?? 0);+ return {+ success: true,+ message: `Retrieved statistics for ${propsValue.period}: ${clicks} clicks across ${links} links`,+ data: stats,};-- if (period === 'custom' && startDate && endDate) {- query['startDate'] = new Date(startDate).toISOString().split('T')[0];- query['endDate'] = new Date(endDate).toISOString().split('T')[0];- }-- if (tz && tz.trim() !== '') query['tz'] = tz.trim();- if (clicksChartInterval) query['clicksChartInterval'] = clicksChartInterval;-- try {- const response = await shortIoApiCall({- method: HttpMethod.GET,- auth,- url: `https://statistics.short.io/statistics/domain/${domainObject.id}`,- query,- });-- const stats = response as any;- const clicks = stats['clicks'] || 0;- const links = stats['links'] || 0;- const periodLabel = period === 'custom' ? 'custom period' : period.replace(/([a-z])([A-Z])/g, '$1 $2').toLowerCase();-- return {- success: true,- message: `Retrieved statistics for ${periodLabel}: ${clicks} clicks across ${links} links`,- data: response,- };- } catch (error: any) {- if (error.message.includes('400')) {- throw new Error(- 'Invalid request parameters. Please check your date range, timezone, and other settings.'- );- }-- if (error.message.includes('401') || error.message.includes('403')) {- throw new Error(- 'Authentication failed or insufficient permissions. Please check your API key and domain access.'- );- }-- if (error.message.includes('404')) {- throw new Error(- 'Domain not found. Please verify the domain exists and you have access to its statistics.'- );- }-- if (error.message.includes('429')) {- throw new Error(- 'Rate limit exceeded. Please wait a moment before trying again.'- );- }-- throw new Error(`Failed to retrieve domain statistics: ${error.message}`);- }},});diff --git a/packages/pieces/community/short-io/src/lib/actions/duplicate-link.ts b/packages/pieces/community/short-io/src/lib/actions/duplicate-link.tsnew file mode 100644index 00000000000..b6bb6fee4d7--- /dev/null+++ b/packages/pieces/community/short-io/src/lib/actions/duplicate-link.ts@@ -0,0 +1,50 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { shortIoAiProps } from '../common/ai-props';+import { shortIoAuth } from '../common/auth';+import { shortIoClient } from '../common/client';+import { shortIoLinks } from '../common/links';+import { shortIoSchemas } from '../common/output-schemas';++export const duplicateLinkAction = createAction({+ auth: shortIoAuth,+ name: 'duplicate_link',+ displayName: 'Duplicate Short Link',+ description: 'Create a copy of a short link with the same destination and settings.',+ audience: 'both',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Creates a new short link on the same domain that copies an existing link (destination URL, title, tags, UTM and redirect settings), optionally with a custom slug. Use to make a variant of a link, e.g. one per campaign channel, without re-entering its settings. Returns the new link and duplicatedFrom. Without a slug every call creates another copy; a repeat call with the same slug returns the existing copy.',+ idempotent: false,+ },+ outputSchema: shortIoSchemas.duplicatedLink,+ props: {+ linkId: shortIoAiProps.linkId(),+ path: Property.ShortText({+ displayName: 'New Path (Slug)',+ description: 'Slug for the copy, e.g. spring-sale-email. Empty = Short.io generates one.',+ required: false,+ }),+ },+ async run({ auth, propsValue }) {+ const path = propsValue.path?.trim().replace(/^\/+/, '');+ try {+ const response = await shortIoClient.request({+ auth,+ method: HttpMethod.POST,+ path: `/links/duplicate/${shortIoClient.seg({ value: propsValue.linkId, label: 'Link ID' })}`,+ body: path ? { path } : {},+ });+ return shortIoLinks.scrubLink(response);+ } catch (error) {+ return shortIoClient.rethrowWithHint({+ error,+ hints: {+ 404: 'Short link not found. Check the link ID.',+ 409: 'Another link on this domain already uses this path.',+ },+ });+ }+ },+});diff --git a/packages/pieces/community/short-io/src/lib/actions/expire-short-link.ts b/packages/pieces/community/short-io/src/lib/actions/expire-short-link.tsindex 2f47418b020..f0c301de049 100644--- a/packages/pieces/community/short-io/src/lib/actions/expire-short-link.ts+++ b/packages/pieces/community/short-io/src/lib/actions/expire-short-link.ts@@ -1,8 +1,12 @@import { HttpMethod } from '@activepieces/pieces-common';import { createAction, Property } from '@activepieces/pieces-framework';-import { shortIoApiCall } from '../common/client';import { shortIoAuth } from '../common/auth';+import { shortIoClient } from '../common/client';+import { shortIoLinkBody } from '../common/link-body';+import { shortIoLinks } from '../common/links';+import { shortIoSchemas } from '../common/output-schemas';import { domainIdDropdown, linkIdDropdown } from '../common/props';+import { shortIoValues } from '../common/values';export const expireShortLinkAction = createAction({auth: shortIoAuth,@@ -10,8 +14,13 @@ export const expireShortLinkAction = createAction({classification: 'DESTRUCTIVE',displayName: 'Expire Short Link',description: 'Set an expiration date or click limit to deactivate a short link.',- audience: 'both',- aiMetadata: { description: 'Sets an expiration on an existing short link (identified by its link ID) so it deactivates at a given date/time or after a number of clicks, optionally redirecting expired visitors to a fallback URL. Use to schedule a link to stop working. Requires either an expiration date or a click limit; idempotent — re-applying the same expiry settings to the same link leaves it in the same state.', idempotent: true },+ audience: 'human',+ aiMetadata: {+ description:+ 'Sets an expiration on an existing short link so it deactivates at a given date/time or after a number of clicks, optionally sending expired visitors to a fallback URL. Requires an expiration date or a click limit. Idempotent: re-applying the same settings leaves the link unchanged.',+ idempotent: true,+ },+ outputSchema: shortIoSchemas.legacyLink,props: {domain: domainIdDropdown,linkId: linkIdDropdown,@@ -32,82 +41,32 @@ export const expireShortLinkAction = createAction({}),},async run({ propsValue, auth }) {- const {- linkId,- domain: domainString,- expiresAt,- clicksLimit,- expiredURL,- } = propsValue;-- if (!expiresAt && !clicksLimit) {+ const { clicksLimit } = shortIoLinkBody.validateLinkOptions({+ clicksLimit: propsValue.clicksLimit,+ splitPercent: undefined,+ redirectType: undefined,+ });+ const expiresAt = propsValue.expiresAt ? shortIoValues.toIsoDateTime({ value: propsValue.expiresAt, label: 'Expiration date' }) : undefined;+ if (expiresAt === undefined && clicksLimit === undefined) {throw new Error('You must provide either an expiration date or a clicks limit to expire the link.');}-- if (clicksLimit && clicksLimit < 1) {- throw new Error('Clicks limit must be at least 1');- }-- const query: Record<string, string> = {};- if (domainString) {- const domainObject = JSON.parse(domainString as string);- query['domain_id'] = String(domainObject.id);- }-- const body: Record<string, unknown> = {};-- if (expiresAt) {- body['expiresAt'] = expiresAt;- }-- if (clicksLimit) {- body['clicksLimit'] = clicksLimit;- }-- if (expiredURL && expiredURL.trim() !== '') {- body['expiredURL'] = expiredURL;- }-+ const domain = shortIoLinks.parseDomainProp(propsValue.domain);+ const linkId = shortIoClient.seg({ value: propsValue.linkId, label: 'Short Link' });try {- const response = await shortIoApiCall({+ const response = await shortIoClient.request({method: HttpMethod.POST,auth,- resourceUri: `/links/${linkId}`,- query,- body,+ path: `/links/${linkId}`,+ query: { domain_id: domain.id },+ body: shortIoValues.compact({ expiresAt, clicksLimit, expiredURL: propsValue.expiredURL?.trim() }),});-return {success: true,message: 'Short link expiration settings updated successfully',- data: response,+ data: shortIoLinks.scrubLink(response),};- } catch (error: any) {- if (error.message.includes('400')) {- throw new Error(- 'Invalid request parameters. Please check your expiration settings and try again.'- );- }-- if (error.message.includes('401') || error.message.includes('403')) {- throw new Error(- 'Authentication failed. Please check your API key and permissions.'- );- }-- if (error.message.includes('404')) {- throw new Error(- 'Short link not found. Please check the link ID and try again.'- );- }-- if (error.message.includes('429')) {- throw new Error(- 'Rate limit exceeded. Please wait a moment before trying again.'- );- }-- throw new Error(`Failed to set link expiration: ${error.message}`);+ } catch (error) {+ return shortIoClient.rethrowWithHint({ error, hints: { 404: 'Short link not found. Check the link and domain.' } });}},-});\ No newline at end of file+});diff --git a/packages/pieces/community/short-io/src/lib/actions/find-links-by-original-url.ts b/packages/pieces/community/short-io/src/lib/actions/find-links-by-original-url.tsnew file mode 100644index 00000000000..2c65a89a287--- /dev/null+++ b/packages/pieces/community/short-io/src/lib/actions/find-links-by-original-url.ts@@ -0,0 +1,53 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { shortIoAiProps } from '../common/ai-props';+import { shortIoAuth } from '../common/auth';+import { shortIoClient } from '../common/client';+import { shortIoLinks } from '../common/links';+import { shortIoSchemas } from '../common/output-schemas';++export const findLinksByOriginalUrlAction = createAction({+ auth: shortIoAuth,+ name: 'find_links_by_original_url',+ displayName: 'Find Links by Original URL',+ description: 'Find every short link on a domain that points to a given long URL.',+ audience: 'both',+ classification: 'SEARCH',+ aiMetadata: {+ description:+ 'Finds all short links on a domain whose destination (original URL) exactly equals the given URL. Use to check whether a URL was already shortened before creating a new link. Returns an empty list when none match. Read-only.',+ idempotent: true,+ },+ outputSchema: shortIoSchemas.linksByUrl,+ props: {+ domain: shortIoAiProps.domain(),+ originalURL: Property.ShortText({+ displayName: 'Original URL',+ description: 'The full destination URL to look up, exactly as it was shortened.',+ required: true,+ }),+ },+ async run({ auth, propsValue }) {+ const originalURL = propsValue.originalURL.trim();+ if (!originalURL) {+ throw new Error('Original URL is required.');+ }+ const domain = await shortIoLinks.resolveDomain({ auth, input: propsValue.domain });+ try {+ const response = await shortIoClient.request({+ auth,+ method: HttpMethod.GET,+ path: '/links/multiple-by-url',+ query: { domain: domain.hostname, originalURL },+ });+ const raw = shortIoLinks.isRecord(response) && Array.isArray(response['links']) ? response['links'] : response;+ const items = shortIoLinks.scrubLinks(raw);+ return { items, count: items.length };+ } catch (error) {+ if (shortIoClient.errorStatus(error) === 404) {+ return { items: [], count: 0 };+ }+ return shortIoClient.rethrowWithHint({ error, hints: {} });+ }+ },+});diff --git a/packages/pieces/community/short-io/src/lib/actions/generate-qr-code.ts b/packages/pieces/community/short-io/src/lib/actions/generate-qr-code.tsnew file mode 100644index 00000000000..acc892453cc--- /dev/null+++ b/packages/pieces/community/short-io/src/lib/actions/generate-qr-code.ts@@ -0,0 +1,84 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { shortIoAiProps } from '../common/ai-props';+import { shortIoAuth } from '../common/auth';+import { shortIoClient } from '../common/client';+import { shortIoSchemas } from '../common/output-schemas';+import { shortIoQr } from '../common/qr';+import { shortIoValues } from '../common/values';++const HEX_COLOR = /^[0-9A-Fa-f]{6,8}$/;++function color({ value, label }: { value: string | undefined; label: string }): string | undefined {+ const text = value?.trim().replace(/^#/, '');+ if (!text) {+ return undefined;+ }+ if (!HEX_COLOR.test(text)) {+ throw new Error(`${label} must be a hex color like 000000 or FF8800.`);+ }+ return text;+}++export const generateQrCodeAction = createAction({+ auth: shortIoAuth,+ name: 'generate_qr_code',+ displayName: 'Generate QR Code',+ description: 'Generate a QR code image (PNG or SVG) for a short link.',+ audience: 'both',+ classification: 'READ',+ aiMetadata: {+ description:+ 'Generates a QR code image for a short link (by link ID) and returns it as a file. Optional colors, size (1-99) and PNG or SVG format. Does not change the link.',+ idempotent: true,+ },+ outputSchema: shortIoSchemas.qrCode,+ props: {+ linkId: shortIoAiProps.linkId(),+ type: Property.StaticDropdown({+ displayName: 'Format',+ required: false,+ defaultValue: 'png',+ options: {+ disabled: false,+ options: [+ { label: 'PNG', value: 'png' },+ { label: 'SVG', value: 'svg' },+ ],+ },+ }),+ size: Property.Number({+ displayName: 'Size',+ description: 'Scale factor from 1 to 99 (Short.io default when empty).',+ required: false,+ }),+ color: Property.ShortText({+ displayName: 'Color',+ description: 'Hex color of the code, e.g. 000000.',+ required: false,+ }),+ backgroundColor: Property.ShortText({+ displayName: 'Background Color',+ description: 'Hex background color, e.g. FFFFFF.',+ required: false,+ }),+ },+ async run({ auth, propsValue, files }) {+ const format = propsValue.type === 'svg' ? 'svg' : 'png';+ const size = shortIoValues.optionalNumber({ value: propsValue.size, label: 'Size', min: 1, max: 99 });+ const fg = color({ value: propsValue.color, label: 'Color' });+ const bg = color({ value: propsValue.backgroundColor, label: 'Background color' });+ const linkId = propsValue.linkId.trim();+ try {+ const { data } = await shortIoQr.renderQrImage({+ auth,+ linkId,+ options: shortIoValues.compact({ type: format, size, color: fg, backgroundColor: bg, useDomainSettings: fg === undefined && bg === undefined }),+ });+ const fileName = `qr-${linkId.replace(/[^A-Za-z0-9_-]/g, '_')}.${format}`;+ const file = await files.write({ fileName, data });+ return { linkId, format, fileName, file, size: data.length };+ } catch (error) {+ return shortIoClient.rethrowWithHint({ error, hints: { 404: 'Short link not found. Check the link ID.' } });+ }+ },+});diff --git a/packages/pieces/community/short-io/src/lib/actions/get-domain.ts b/packages/pieces/community/short-io/src/lib/actions/get-domain.tsnew file mode 100644index 00000000000..ee3f4687b07--- /dev/null+++ b/packages/pieces/community/short-io/src/lib/actions/get-domain.ts@@ -0,0 +1,37 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { shortIoAiProps } from '../common/ai-props';+import { shortIoAuth } from '../common/auth';+import { shortIoClient } from '../common/client';+import { shortIoLinks } from '../common/links';+import { shortIoSchemas } from '../common/output-schemas';++export const getDomainAction = createAction({+ auth: shortIoAuth,+ name: 'get_domain',+ displayName: 'Get Domain',+ description: 'Get the settings of one Short.io domain.',+ audience: 'both',+ classification: 'READ',+ aiMetadata: {+ description: 'Returns the details of one Short.io domain (ID, hostname, state, link type, redirects) given its hostname or numeric ID. Read-only.',+ idempotent: true,+ },+ outputSchema: shortIoSchemas.domain,+ props: {+ domain: shortIoAiProps.domain(),+ },+ async run({ auth, propsValue }) {+ const domain = await shortIoLinks.resolveDomain({ auth, input: propsValue.domain });+ try {+ const response = await shortIoClient.request({+ auth,+ method: HttpMethod.GET,+ path: `/domains/${shortIoClient.domainIdSeg(domain.id)}`,+ });+ return shortIoLinks.pickDomain(shortIoLinks.isRecord(response) ? response : {});+ } catch (error) {+ return shortIoClient.rethrowWithHint({ error, hints: { 404: 'Domain not found.' } });+ }+ },+});diff --git a/packages/pieces/community/short-io/src/lib/actions/get-folder.ts b/packages/pieces/community/short-io/src/lib/actions/get-folder.tsnew file mode 100644index 00000000000..b83a39264ac--- /dev/null+++ b/packages/pieces/community/short-io/src/lib/actions/get-folder.ts@@ -0,0 +1,50 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { shortIoAiProps } from '../common/ai-props';+import { shortIoAuth } from '../common/auth';+import { shortIoClient } from '../common/client';+import { shortIoLinks } from '../common/links';+import { shortIoSchemas } from '../common/output-schemas';++export const getFolderAction = createAction({+ auth: shortIoAuth,+ name: 'get_folder',+ displayName: 'Get Folder',+ description: 'Get a link folder by its ID.',+ audience: 'both',+ classification: 'READ',+ aiMetadata: {+ description:+ 'Returns one link folder (ID and name) on a Short.io domain, given the domain and the folder ID from List Folders or a link’s FolderId. Use to turn a link’s folder ID into its name. Returns found=false when no folder has that ID. Read-only.',+ idempotent: true,+ },+ outputSchema: shortIoSchemas.folderLookup,+ props: {+ domain: shortIoAiProps.domain(),+ folderId: Property.ShortText({+ displayName: 'Folder ID',+ description: 'The folder ID, e.g. the FolderId field of a link.',+ required: true,+ }),+ },+ async run({ auth, propsValue }) {+ const folderSeg = shortIoClient.seg({ value: propsValue.folderId, label: 'Folder ID' });+ const domain = await shortIoLinks.resolveDomain({ auth, input: propsValue.domain });+ try {+ const response = await shortIoClient.request({+ auth,+ method: HttpMethod.GET,+ path: `/links/folders/${shortIoClient.domainIdSeg(domain.id)}/${folderSeg}`,+ });+ if (!shortIoLinks.isRecord(response)) {+ return { found: false, folder: null };+ }+ return { found: true, folder: { id: response['id'], name: response['name'], domainId: domain.id } };+ } catch (error) {+ if (shortIoClient.errorStatus(error) === 404) {+ return { found: false, folder: null };+ }+ return shortIoClient.rethrowWithHint({ error, hints: {} });+ }+ },+});diff --git a/packages/pieces/community/short-io/src/lib/actions/get-link-by-path.ts b/packages/pieces/community/short-io/src/lib/actions/get-link-by-path.tsindex 94561247ec9..c58059ddd60 100644--- a/packages/pieces/community/short-io/src/lib/actions/get-link-by-path.ts+++ b/packages/pieces/community/short-io/src/lib/actions/get-link-by-path.ts@@ -1,7 +1,8 @@-import { HttpMethod } from '@activepieces/pieces-common';import { createAction, Property } from '@activepieces/pieces-framework';-import { shortIoApiCall } from '../common/client';import { shortIoAuth } from '../common/auth';+import { shortIoLinkQueries } from '../common/link-queries';+import { shortIoLinks } from '../common/links';+import { shortIoSchemas } from '../common/output-schemas';import { domainIdDropdown } from '../common/props';export const getLinkByPathAction = createAction({@@ -10,8 +11,13 @@ export const getLinkByPathAction = createAction({classification: 'READ',displayName: 'Get Link by Path',description: 'Retrieve detailed information about a short link using its domain and path.',- audience: 'both',- aiMetadata: { description: 'Looks up a single short link and its full details by its domain plus path/slug (rather than by link ID). Use when you know the public short URL path but not the internal link ID. Requires a domain and the bare slug (no domain or slashes in the path); read-only and idempotent.', idempotent: true },+ audience: 'human',+ aiMetadata: {+ description:+ 'Looks up one short link and its details by domain plus path/slug (rather than by link ID). Requires a domain and the bare slug. Read-only and idempotent.',+ idempotent: true,+ },+ outputSchema: shortIoSchemas.legacyLink,props: {domain: domainIdDropdown,path: Property.ShortText({@@ -21,68 +27,22 @@ export const getLinkByPathAction = createAction({}),},async run({ propsValue, auth }) {- const { domain: domainString, path } = propsValue;-- if (!domainString) {- throw new Error('Domain is required. Please select a domain first.');- }-- if (!path || path.trim() === '') {+ const domain = shortIoLinks.parseDomainProp(propsValue.domain);+ const cleanPath = (propsValue.path ?? '').trim();+ if (!cleanPath) {throw new Error('Path is required and cannot be empty.');}-- const cleanPath = path.trim();-- if (cleanPath.includes('/') || cleanPath.includes('http')) {+ if (cleanPath.includes('/') || /^https?:/i.test(cleanPath)) {throw new Error('Path should only contain the slug (e.g., "abc123"), not the full URL or domain.');}-- const domainObject = JSON.parse(domainString as string);-- const query = {- domain: domainObject.hostname,- path: cleanPath,- };-- try {- const response = await shortIoApiCall({- method: HttpMethod.GET,- auth,- resourceUri: `/links/expand`,- query,- });-- return {- success: true,- message: `Link information for "${cleanPath}" retrieved successfully`,- data: response,- };- } catch (error: any) {- if (error.message.includes('400')) {- throw new Error(- 'Invalid request parameters. Please check the domain and path values.'- );- }-- if (error.message.includes('401') || error.message.includes('403')) {- throw new Error(- 'Authentication failed. Please check your API key and permissions.'- );- }-- if (error.message.includes('404')) {- throw new Error(- `Short link with path "${cleanPath}" not found on domain "${domainObject.hostname}". Please verify the path exists.`- );- }-- if (error.message.includes('429')) {- throw new Error(- 'Rate limit exceeded. Please wait a moment before trying again.'- );- }-- throw new Error(`Failed to retrieve link information: ${error.message}`);+ const link = await shortIoLinkQueries.expand({ auth, hostname: domain.hostname, path: cleanPath });+ if (!link) {+ throw new Error(`Short link with path "${cleanPath}" not found on domain "${domain.hostname}".`);}+ return {+ success: true,+ message: `Link information for "${cleanPath}" retrieved successfully`,+ data: link,+ };},});diff --git a/packages/pieces/community/short-io/src/lib/actions/get-link-clicks.ts b/packages/pieces/community/short-io/src/lib/actions/get-link-clicks.tsindex f90dde348cf..2c48b18f031 100644--- a/packages/pieces/community/short-io/src/lib/actions/get-link-clicks.ts+++ b/packages/pieces/community/short-io/src/lib/actions/get-link-clicks.ts@@ -1,8 +1,11 @@import { HttpMethod } from '@activepieces/pieces-common';import { createAction, Property } from '@activepieces/pieces-framework';-import { shortIoApiCall } from '../common/client';import { shortIoAuth } from '../common/auth';+import { shortIoClient } from '../common/client';+import { shortIoLinks } from '../common/links';+import { shortIoSchemas } from '../common/output-schemas';import { domainIdDropdown } from '../common/props';+import { shortIoValues } from '../common/values';export const getLinkClicksAction = createAction({auth: shortIoAuth,@@ -10,8 +13,13 @@ export const getLinkClicksAction = createAction({classification: 'READ',displayName: 'Get Link Clicks',description: 'Retrieve click statistics for specific short links by their IDs.',- audience: 'both',- aiMetadata: { description: 'Retrieves click statistics for one or more specific short links (by their link IDs) on a domain, optionally scoped to a start/end date range. Use to measure performance of particular links rather than a whole domain. Requires the domain and at least one link ID, and if filtering by date both start and end must be supplied; read-only and idempotent.', idempotent: true },+ audience: 'human',+ aiMetadata: {+ description:+ 'Retrieves click counts for one or more short links (by link ID) on a domain, optionally for a start/end date range (both dates needed). Returns a map of link ID to clicks. Read-only and idempotent.',+ idempotent: true,+ },+ outputSchema: shortIoSchemas.legacyLinkClicks,props: {domain: {...domainIdDropdown,@@ -25,92 +33,46 @@ export const getLinkClicksAction = createAction({}),startDate: Property.DateTime({displayName: 'Start Date',- description: 'Start date for click statistics (optional).',+ description: 'Start date for click statistics (optional). The calendar day you pick is sent as is.',required: false,}),endDate: Property.DateTime({displayName: 'End Date',- description: 'End date for click statistics (optional).',+ description: 'End date for click statistics (optional). The calendar day you pick is sent as is.',required: false,}),},async run({ propsValue, auth }) {- const { domain: domainString, ids, startDate, endDate } = propsValue;-- if (!domainString) {- throw new Error('Domain is required. Please select a domain.');- }-- if (!ids || ids.length === 0) {+ const domain = shortIoLinks.parseDomainProp(propsValue.domain);+ const ids = shortIoValues.stringList(propsValue.ids);+ if (ids.length === 0) {throw new Error('At least one Link ID is required.');}-- if ((startDate && !endDate) || (!startDate && endDate)) {+ const { startDate, endDate } = propsValue;+ if (Boolean(startDate) !== Boolean(endDate)) {throw new Error('Both Start Date and End Date must be provided if using a date range filter.');}-- if (startDate && endDate) {- const start = new Date(startDate);- const end = new Date(endDate);-- if (start >= end) {- throw new Error('Start date must be before end date.');- }- }-- const domainObject = JSON.parse(domainString as string);-- const query: Record<string, string> = {- ids: (ids as string[]).join(','),- };-- if (startDate && endDate) {- query['startDate'] = new Date(startDate).toISOString().split('T')[0]; // YYYY-MM-DD format- query['endDate'] = new Date(endDate).toISOString().split('T')[0];+ const start = startDate ? shortIoValues.toApiDate({ value: startDate, label: 'Start date' }) : undefined;+ const end = endDate ? shortIoValues.toApiDate({ value: endDate, label: 'End date' }) : undefined;+ if (start && end && start > end) {+ throw new Error('Start date must not be after end date.');}-try {- const response = await shortIoApiCall({+ const response = await shortIoClient.request({method: HttpMethod.GET,auth,- url: `https://statistics.short.io/statistics/domain/${domainObject.id}/link_clicks`,- query,+ base: 'stats',+ path: `/domain/${shortIoClient.domainIdSeg(domain.id)}/link_clicks`,+ query: { ids: ids.join(','), startDate: start, endDate: end },});-- const linkCount = ids.length;- const dateRange = startDate && endDate ? ` for ${query['startDate']} to ${query['endDate']}` : '';-+ const range = start && end ? ` for ${start} to ${end}` : '';return {success: true,- message: `Retrieved click statistics for ${linkCount} link${linkCount > 1 ? 's' : ''}${dateRange}`,- data: response,+ message: `Retrieved click statistics for ${ids.length} link${ids.length > 1 ? 's' : ''}${range}`,+ data: shortIoLinks.isRecord(response) ? response : {},};- } catch (error: any) {- if (error.message.includes('400')) {- throw new Error(- 'Invalid request parameters. Please check your link IDs and date range.'- );- }-- if (error.message.includes('401') || error.message.includes('403')) {- throw new Error(- 'Authentication failed or insufficient permissions. Please check your API key and domain access.'- );- }-- if (error.message.includes('404')) {- throw new Error(- 'Domain or links not found. Please verify the domain and link IDs exist.'- );- }-- if (error.message.includes('429')) {- throw new Error(- 'Rate limit exceeded. Please wait a moment before trying again.'- );- }-- throw new Error(`Failed to retrieve link click statistics: ${error.message}`);+ } catch (error) {+ return shortIoClient.rethrowWithHint({ error, hints: { 404: 'Domain or links not found.' } });}},});diff --git a/packages/pieces/community/short-io/src/lib/actions/get-link-open-graph.ts b/packages/pieces/community/short-io/src/lib/actions/get-link-open-graph.tsnew file mode 100644index 00000000000..f3b2716c933--- /dev/null+++ b/packages/pieces/community/short-io/src/lib/actions/get-link-open-graph.ts@@ -0,0 +1,55 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { shortIoAiProps } from '../common/ai-props';+import { shortIoAuth } from '../common/auth';+import { shortIoClient } from '../common/client';+import { shortIoLinks } from '../common/links';+import { shortIoSchemas } from '../common/output-schemas';++function toPairs(response: unknown): { property: string; value: string }[] {+ if (!Array.isArray(response)) {+ return [];+ }+ return response.flatMap((pair) =>+ Array.isArray(pair) && typeof pair[0] === 'string' && pair[1] !== undefined && pair[1] !== null ? [{ property: pair[0], value: String(pair[1]) }] : [],+ );+}++export const getLinkOpenGraphAction = createAction({+ auth: shortIoAuth,+ name: 'get_link_open_graph',+ displayName: 'Get Link Social Preview (OpenGraph)',+ description: 'Get the custom social-preview (OpenGraph) title, description and image set on a short link.',+ audience: 'both',+ classification: 'READ',+ aiMetadata: {+ description:+ 'Returns the custom OpenGraph properties (og title, description, image, twitter card…) set on a short link, i.e. what social networks show when the link is shared. Use to check or report a link’s social preview. Empty when none are set (custom OpenGraph needs a Short.io Pro plan). Read-only.',+ idempotent: true,+ },+ outputSchema: shortIoSchemas.openGraph,+ props: {+ domain: shortIoAiProps.domain(),+ linkId: shortIoAiProps.linkId(),+ },+ async run({ auth, propsValue }) {+ const linkSeg = shortIoClient.seg({ value: propsValue.linkId, label: 'Link ID' });+ const domain = await shortIoLinks.resolveDomain({ auth, input: propsValue.domain });+ try {+ const response = await shortIoClient.request({+ auth,+ method: HttpMethod.GET,+ path: `/links/opengraph/${shortIoClient.domainIdSeg(domain.id)}/${linkSeg}`,+ });+ const items = toPairs(response);+ return {+ linkId: propsValue.linkId.trim(),+ properties: Object.fromEntries(items.map((item) => [item.property, item.value])),+ items,+ count: items.length,+ };+ } catch (error) {+ return shortIoClient.rethrowWithHint({ error, hints: { 404: 'Short link not found on this domain. Check the link ID and domain.' } });+ }+ },+});diff --git a/packages/pieces/community/short-io/src/lib/actions/get-link.ts b/packages/pieces/community/short-io/src/lib/actions/get-link.tsnew file mode 100644index 00000000000..4a10eb88e3a--- /dev/null+++ b/packages/pieces/community/short-io/src/lib/actions/get-link.ts@@ -0,0 +1,27 @@+import { createAction } from '@activepieces/pieces-framework';+import { shortIoAiProps } from '../common/ai-props';+import { shortIoAuth } from '../common/auth';+import { shortIoLinkQueries } from '../common/link-queries';+import { shortIoSchemas } from '../common/output-schemas';++export const getLinkAction = createAction({+ auth: shortIoAuth,+ name: 'get_link',+ displayName: 'Get Link by ID',+ description: 'Get a short link and its settings by link ID.',+ audience: 'both',+ classification: 'READ',+ aiMetadata: {+ description:+ 'Returns one short link (short URL, original URL, path, title, tags, expiry, folder) by its link ID. Returns found=false when no link has that ID. The link password is never returned. Read-only.',+ idempotent: true,+ },+ outputSchema: shortIoSchemas.linkLookup,+ props: {+ linkId: shortIoAiProps.linkId(),+ },+ async run({ auth, propsValue }) {+ const link = await shortIoLinkQueries.getById({ auth, linkId: propsValue.linkId });+ return { found: link !== null, link };+ },+});diff --git a/packages/pieces/community/short-io/src/lib/actions/get-top-links.ts b/packages/pieces/community/short-io/src/lib/actions/get-top-links.tsnew file mode 100644index 00000000000..c56a853b873--- /dev/null+++ b/packages/pieces/community/short-io/src/lib/actions/get-top-links.ts@@ -0,0 +1,56 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { shortIoAiProps } from '../common/ai-props';+import { shortIoAuth } from '../common/auth';+import { shortIoClient } from '../common/client';+import { shortIoLinks } from '../common/links';+import { shortIoSchemas } from '../common/output-schemas';+import { shortIoStats } from '../common/stats';+import { shortIoValues } from '../common/values';++export const getTopLinksAction = createAction({+ auth: shortIoAuth,+ name: 'get_top_links',+ displayName: 'Get Top Links',+ description: 'Get the most-clicked link paths on a domain for a period.',+ audience: 'both',+ classification: 'SEARCH',+ aiMetadata: {+ description:+ 'Returns the most-clicked link paths on a Short.io domain for a period, ordered by clicks (descending), with the click count of each. Custom period needs start and end dates (YYYY-MM-DD). Read-only.',+ idempotent: true,+ },+ outputSchema: shortIoSchemas.topLinks,+ props: {+ domain: shortIoAiProps.domain(),+ period: shortIoAiProps.period('Time period to rank links over. Default: last 30 days.'),+ startDate: shortIoAiProps.startDate(),+ endDate: shortIoAiProps.endDate(),+ tz: shortIoAiProps.timezone(),+ limit: Property.Number({+ displayName: 'Limit',+ description: 'How many links to return (1-100). Default 10.',+ required: false,+ }),+ },+ async run({ auth, propsValue }) {+ const limit = shortIoValues.optionalNumber({ value: propsValue.limit, label: 'Limit', min: 1, max: 100 }) ?? 10;+ const range = shortIoValues.statsRange({ period: propsValue.period, startDate: propsValue.startDate, endDate: propsValue.endDate });+ const tz = shortIoValues.validateTimezone(propsValue.tz);+ const domain = await shortIoLinks.resolveDomain({ auth, input: propsValue.domain });+ try {+ const response = await shortIoStats.statsQuery({+ auth,+ domainId: domain.id,+ report: 'top',+ body: shortIoValues.compact({ column: 'path', limit, tz, ...range }),+ });+ const items = (Array.isArray(response) ? response : []).filter(shortIoLinks.isRecord).map((row) => ({+ path: row['column'] ?? row['path'],+ clicks: Number(row['score'] ?? 0),+ }));+ return { items, count: items.length };+ } catch (error) {+ return shortIoClient.rethrowWithHint({ error, hints: { 400: 'Short.io rejected the statistics period.' } });+ }+ },+});diff --git a/packages/pieces/community/short-io/src/lib/actions/list-country-rules.ts b/packages/pieces/community/short-io/src/lib/actions/list-country-rules.tsnew file mode 100644index 00000000000..61a47fd026d--- /dev/null+++ b/packages/pieces/community/short-io/src/lib/actions/list-country-rules.ts@@ -0,0 +1,38 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { shortIoAiProps } from '../common/ai-props';+import { shortIoAuth } from '../common/auth';+import { shortIoClient } from '../common/client';+import { shortIoLinks } from '../common/links';+import { shortIoSchemas } from '../common/output-schemas';++export const listCountryRulesAction = createAction({+ auth: shortIoAuth,+ name: 'list_country_rules',+ displayName: 'List Country Targeting Rules',+ description: 'List the country redirect rules of a short link.',+ audience: 'both',+ classification: 'SEARCH',+ aiMetadata: {+ description: 'Lists the country-targeting rules of a short link (by link ID): which countries get redirected to which URL. Read-only.',+ idempotent: true,+ },+ outputSchema: shortIoSchemas.countryRuleList,+ props: {+ linkId: shortIoAiProps.linkId(),+ },+ async run({ auth, propsValue }) {+ const linkId = propsValue.linkId.trim();+ try {+ const response = await shortIoClient.request({+ auth,+ method: HttpMethod.GET,+ path: `/link_country/${shortIoClient.seg({ value: linkId, label: 'Link ID' })}`,+ });+ const items = (Array.isArray(response) ? response : []).filter(shortIoLinks.isRecord);+ return { linkId, items, count: items.length };+ } catch (error) {+ return shortIoClient.rethrowWithHint({ error, hints: { 404: 'Short link not found. Check the link ID.' } });+ }+ },+});diff --git a/packages/pieces/community/short-io/src/lib/actions/list-domains.ts b/packages/pieces/community/short-io/src/lib/actions/list-domains.tsnew file mode 100644index 00000000000..8df9f8fb4ed--- /dev/null+++ b/packages/pieces/community/short-io/src/lib/actions/list-domains.ts@@ -0,0 +1,25 @@+import { createAction } from '@activepieces/pieces-framework';+import { shortIoAuth } from '../common/auth';+import { shortIoLinks } from '../common/links';+import { shortIoSchemas } from '../common/output-schemas';++export const listDomainsAction = createAction({+ auth: shortIoAuth,+ name: 'list_domains',+ displayName: 'List Domains',+ description: 'List every domain on the Short.io account.',+ audience: 'both',+ classification: 'SEARCH',+ aiMetadata: {+ description:+ 'Lists all branded domains on the connected Short.io account with their numeric ID and hostname. Use first to learn which domain to pass to other Short.io steps. Read-only.',+ idempotent: true,+ },+ outputSchema: shortIoSchemas.domainList,+ props: {},+ async run({ auth }) {+ const domains = await shortIoLinks.listAllDomains(auth);+ const items = domains.map(shortIoLinks.pickDomain);+ return { items, count: items.length };+ },+});diff --git a/packages/pieces/community/short-io/src/lib/actions/list-folders.ts b/packages/pieces/community/short-io/src/lib/actions/list-folders.tsnew file mode 100644index 00000000000..2459e4709d7--- /dev/null+++ b/packages/pieces/community/short-io/src/lib/actions/list-folders.ts@@ -0,0 +1,39 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { shortIoAiProps } from '../common/ai-props';+import { shortIoAuth } from '../common/auth';+import { shortIoClient } from '../common/client';+import { shortIoLinks } from '../common/links';+import { shortIoSchemas } from '../common/output-schemas';++export const listFoldersAction = createAction({+ auth: shortIoAuth,+ name: 'list_folders',+ displayName: 'List Folders',+ description: 'List the link folders on a domain.',+ audience: 'both',+ classification: 'SEARCH',+ aiMetadata: {+ description: 'Lists the link folders of a Short.io domain with their IDs and names, to use as Folder ID in other steps. Read-only.',+ idempotent: true,+ },+ outputSchema: shortIoSchemas.folderList,+ props: {+ domain: shortIoAiProps.domain(),+ },+ async run({ auth, propsValue }) {+ const domain = await shortIoLinks.resolveDomain({ auth, input: propsValue.domain });+ try {+ const response = await shortIoClient.request({+ auth,+ method: HttpMethod.GET,+ path: `/links/folders/${shortIoClient.domainIdSeg(domain.id)}`,+ });+ const folders = shortIoLinks.isRecord(response) && Array.isArray(response['linkFolders']) ? response['linkFolders'].filter(shortIoLinks.isRecord) : [];+ const items = folders.map((folder) => ({ ...folder, id: folder['id'], name: folder['name'] }));+ return { items, count: items.length };+ } catch (error) {+ return shortIoClient.rethrowWithHint({ error, hints: {} });+ }+ },+});diff --git a/packages/pieces/community/short-io/src/lib/actions/list-links.ts b/packages/pieces/community/short-io/src/lib/actions/list-links.tsindex 42b97bb38b6..0dd17755100 100644--- a/packages/pieces/community/short-io/src/lib/actions/list-links.ts+++ b/packages/pieces/community/short-io/src/lib/actions/list-links.ts@@ -1,18 +1,24 @@-import { HttpMethod } from '@activepieces/pieces-common';import { createAction, Property } from '@activepieces/pieces-framework';-import { shortIoApiCall } from '../common/client';import { shortIoAuth } from '../common/auth';+import { shortIoLinkQueries } from '../common/link-queries';+import { shortIoLinks } from '../common/links';+import { shortIoSchemas } from '../common/output-schemas';import { domainIdDropdown, folderIdDropdown } from '../common/props';+import { shortIoValues } from '../common/values';export const listLinksAction = createAction({auth: shortIoAuth,name: 'list-short-links',classification: 'SEARCH',displayName: 'List Links',- description:- 'Retrieve all links on a domain, with pagination and date-range filters.',- audience: 'both',- aiMetadata: { description: 'Lists short links on a Short.io domain, with optional filters by folder, link ID, exact or before/after creation date, sort order, and a page token for paginating large result sets. Use to enumerate or search a domain\'s links, or to fetch the next page of a prior result. Requires a domain; read-only and idempotent.', idempotent: true },+ description: 'Retrieve one page of links on a domain, with pagination and date-range filters.',+ audience: 'human',+ aiMetadata: {+ description:+ 'Lists one page of short links on a domain, with optional folder, link ID, creation-date and sort filters. Pass the returned nextPageToken as Page Token to get the next page. Read-only and idempotent.',+ idempotent: true,+ },+ outputSchema: shortIoSchemas.legacyLinkList,props: {domain: {...domainIdDropdown,@@ -64,82 +70,26 @@ export const listLinksAction = createAction({}),},async run({ propsValue, auth }) {- const {- domain: domainString,- limit,- idString,- createdAt,- beforeDate,- afterDate,- dateSortOrder,- pageToken,- folderId,- } = propsValue;-- if (!domainString) {- throw new Error('Domain is required. Please select a domain.');- }-- if (limit && (limit < 1 || limit > 150)) {- throw new Error('Limit must be between 1 and 150.');- }-- const query: Record<string, string> = {};-- const domainObject = JSON.parse(domainString as string);- query['domain_id'] = String(domainObject.id);-- if (limit) query['limit'] = String(limit);- if (idString && idString.trim() !== '') query['idString'] = String(idString);- if (createdAt && createdAt.trim() !== '') query['createdAt'] = String(createdAt);- if (beforeDate) query['beforeDate'] = beforeDate;- if (afterDate) query['afterDate'] = afterDate;- if (dateSortOrder) query['dateSortOrder'] = String(dateSortOrder);- if (pageToken && pageToken.trim() !== '') query['pageToken'] = String(pageToken);- if (folderId) query['folderId'] = String(folderId);-- try {- const response = await shortIoApiCall({- method: HttpMethod.GET,- auth,- resourceUri: '/api/links',- query,- });-- const linkCount = (response as any)['count'] || ((response as any)['links'] ? (response as any)['links'].length : 0);- const hasNextPage = (response as any)['nextPageToken'] ? ' (more pages available)' : '';-- return {- success: true,- message: `Retrieved ${linkCount} links successfully${hasNextPage}`,- data: response,- };- } catch (error: any) {- if (error.message.includes('400')) {- throw new Error(- 'Invalid request parameters. Please check your filter values and try again.'- );- }-- if (error.message.includes('401') || error.message.includes('403')) {- throw new Error(- 'Authentication failed or insufficient permissions. Please check your API key and domain access.'- );- }-- if (error.message.includes('404')) {- throw new Error(- 'Domain not found. Please verify the domain exists and you have access to it.'- );- }-- if (error.message.includes('429')) {- throw new Error(- 'Rate limit exceeded. Please wait a moment before trying again.'- );- }-- throw new Error(`Failed to retrieve links: ${error.message}`);- }+ const domain = shortIoLinks.parseDomainProp(propsValue.domain);+ const limit = shortIoValues.optionalNumber({ value: propsValue.limit, label: 'Limit', min: 1, max: 150 });+ const page = await shortIoLinkQueries.listPage({+ auth,+ domainId: domain.id,+ query: {+ limit,+ idString: propsValue.idString?.trim(),+ createdAt: propsValue.createdAt?.trim(),+ beforeDate: propsValue.beforeDate,+ afterDate: propsValue.afterDate,+ dateSortOrder: propsValue.dateSortOrder,+ pageToken: propsValue.pageToken?.trim(),+ folderId: propsValue.folderId,+ },+ });+ return {+ success: true,+ message: `Retrieved ${page.links.length} links on this page${page.nextPageToken ? ' (more pages available)' : ''}`,+ data: { count: page.count, links: page.links, nextPageToken: page.nextPageToken },+ };},});diff --git a/packages/pieces/community/short-io/src/lib/actions/list-recent-clicks.ts b/packages/pieces/community/short-io/src/lib/actions/list-recent-clicks.tsnew file mode 100644index 00000000000..c8527b5436f--- /dev/null+++ b/packages/pieces/community/short-io/src/lib/actions/list-recent-clicks.ts@@ -0,0 +1,64 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { shortIoAiProps } from '../common/ai-props';+import { shortIoAuth } from '../common/auth';+import { shortIoClient } from '../common/client';+import { shortIoLinks } from '../common/links';+import { shortIoSchemas } from '../common/output-schemas';+import { shortIoStats } from '../common/stats';+import { shortIoValues } from '../common/values';++export const listRecentClicksAction = createAction({+ auth: shortIoAuth,+ name: 'list_recent_clicks',+ displayName: 'List Recent Clicks',+ description: 'List the latest raw clicks on a domain (time, path, country, referrer, browser). Includes visitor IP and user agent.',+ audience: 'both',+ classification: 'SEARCH',+ aiMetadata: {+ description:+ 'Lists the most recent individual clicks on a Short.io domain, newest first, with time, path, country, city, referrer, browser and OS. Output includes visitor IP addresses and user agents (personal data). Optional filter by link path and human clicks only. Read-only.',+ idempotent: true,+ },+ outputSchema: shortIoSchemas.clicks,+ props: {+ domain: shortIoAiProps.domain(),+ limit: Property.Number({+ displayName: 'Limit',+ description: 'How many clicks to return (1-1000). Default 30.',+ required: false,+ }),+ paths: Property.Array({+ displayName: 'Link Paths',+ description: 'Only clicks on these paths, e.g. promo. Needs a Short.io Team plan.',+ required: false,+ }),+ humanOnly: Property.Checkbox({+ displayName: 'Human Clicks Only',+ description: 'Skip clicks Short.io identifies as bots.',+ required: false,+ defaultValue: false,+ }),+ },+ async run({ auth, propsValue }) {+ const limit = shortIoValues.optionalNumber({ value: propsValue.limit, label: 'Limit', min: 1, max: 1000 }) ?? 30;+ const paths = shortIoValues.stringList(propsValue.paths).map((path) => `/${path.replace(/^\/+/, '')}`);+ const include = shortIoValues.compact({+ paths: paths.length > 0 ? paths : undefined,+ human: propsValue.humanOnly === true ? true : undefined,+ });+ const domain = await shortIoLinks.resolveDomain({ auth, input: propsValue.domain });+ try {+ const response = await shortIoStats.statsQuery({+ auth,+ domainId: domain.id,+ report: 'last_clicks',+ body: { limit, ...(Object.keys(include).length > 0 ? { include } : {}) },+ });+ const raw = Array.isArray(response) ? response : shortIoLinks.isRecord(response) && Array.isArray(response['clicks']) ? response['clicks'] : [];+ const items = raw.filter(shortIoLinks.isRecord);+ return { items, count: items.length };+ } catch (error) {+ return shortIoClient.rethrowWithHint({ error, hints: { 403: 'Raw click data is not available for this domain or plan.' } });+ }+ },+});diff --git a/packages/pieces/community/short-io/src/lib/actions/unarchive-link.ts b/packages/pieces/community/short-io/src/lib/actions/unarchive-link.tsnew file mode 100644index 00000000000..6a9bf2d0d94--- /dev/null+++ b/packages/pieces/community/short-io/src/lib/actions/unarchive-link.ts@@ -0,0 +1,25 @@+import { createAction } from '@activepieces/pieces-framework';+import { shortIoAiProps } from '../common/ai-props';+import { shortIoArchive } from '../common/archive';+import { shortIoAuth } from '../common/auth';+import { shortIoSchemas } from '../common/output-schemas';++export const unarchiveLinkAction = createAction({+ auth: shortIoAuth,+ name: 'unarchive_link',+ displayName: 'Unarchive Short Link',+ description: 'Restore an archived short link to the active list.',+ audience: 'both',+ classification: 'WRITE',+ aiMetadata: {+ description: 'Restores an archived short link (by link ID) to the active link list. Idempotent: unarchiving an active link changes nothing.',+ idempotent: true,+ },+ outputSchema: shortIoSchemas.archive,+ props: {+ linkId: shortIoAiProps.linkId(),+ },+ async run({ auth, propsValue }) {+ return shortIoArchive.setArchived({ auth, linkId: propsValue.linkId, archived: false });+ },+});diff --git a/packages/pieces/community/short-io/src/lib/actions/update-short-link.ts b/packages/pieces/community/short-io/src/lib/actions/update-short-link.tsindex 9a2aa7800a6..b2ff801ce8f 100644--- a/packages/pieces/community/short-io/src/lib/actions/update-short-link.ts+++ b/packages/pieces/community/short-io/src/lib/actions/update-short-link.ts@@ -1,7 +1,10 @@import { HttpMethod } from '@activepieces/pieces-common';import { createAction, Property } from '@activepieces/pieces-framework';-import { shortIoApiCall } from '../common/client';import { shortIoAuth } from '../common/auth';+import { shortIoClient } from '../common/client';+import { shortIoLinkBody } from '../common/link-body';+import { shortIoLinks } from '../common/links';+import { shortIoSchemas } from '../common/output-schemas';import { domainIdDropdown, linkIdDropdown, folderIdDropdown } from '../common/props';export const updateShortLinkAction = createAction({@@ -11,8 +14,9 @@ export const updateShortLinkAction = createAction({displayName: 'Update Short Link',description:"Update an existing short link's original URL, path, title, or other properties using its link ID.",- audience: 'both',+ audience: 'human',aiMetadata: { description: "Updates properties of an existing short link identified by its link ID — destination URL, path/slug, title, folder, UTM tags, expiration, cloaking, A/B split, and analytics integrations. Use to modify a link you already created rather than making a new one. Only the fields you set are changed; idempotent — re-sending the same values keyed on the link ID yields the same result.", idempotent: true },+ outputSchema: shortIoSchemas.legacyLink,props: {domain: domainIdDropdown,linkId: linkIdDropdown,@@ -90,7 +94,7 @@ export const updateShortLinkAction = createAction({ttl: Property.Number({displayName: 'Time to Live (in seconds)',description:- '⚠️ CAUTION: Link will be PERMANENTLY DELETED after this many seconds. This action cannot be undone. Use with extreme caution.',+ 'Permanently deletes the link this many seconds from now (minimum 604800 = 7 days). Short.io may delete it up to 2 hours later. This cannot be undone.',required: false,}),androidURL: Property.ShortText({@@ -150,137 +154,31 @@ export const updateShortLinkAction = createAction({}),},async run({ propsValue, auth }) {- const {- linkId,- domain: domainString,- originalURL,- path,- title,- folderId,- cloaking,- password,- redirectType,- expiresAt,- expiredURL,- tags,- utmSource,- utmMedium,- utmCampaign,- utmTerm,- utmContent,- ttl,- androidURL,- iphoneURL,- createdAt,- clicksLimit,- passwordContact,- skipQS,- archived,- splitURL,- splitPercent,- integrationAdroll,- integrationFB,- integrationGA,- integrationGTM,- } = propsValue;-- if (clicksLimit && clicksLimit < 1) {- throw new Error('Clicks limit must be at least 1');- }-- if (splitPercent && (splitPercent < 1 || splitPercent > 100)) {- throw new Error('Split percent must be between 1 and 100');- }-- if (redirectType && !['301', '302', '303', '307', '308'].includes(redirectType)) {- throw new Error('Invalid redirect type. Must be one of: 301, 302, 303, 307, 308');- }-- const query: Record<string, string> = {};- if (domainString) {- const domainObject = JSON.parse(domainString as string);- query['domain_id'] = String(domainObject.id);- }-- const optionalParams = {- originalURL,- path,- title,- folderId,- cloaking,- password,- redirectType,- expiresAt,- expiredURL,- tags,- utmSource,- utmMedium,- utmCampaign,- utmTerm,- utmContent,- ttl: ttl ? ttl * 1000 : undefined,- androidURL,- iphoneURL,- createdAt,- clicksLimit,- passwordContact,- skipQS,- archived,- splitURL,- splitPercent,- integrationAdroll,- integrationFB,- integrationGA,- integrationGTM,- };-- const body: Record<string, unknown> = {};- for (const [key, value] of Object.entries(optionalParams)) {- if (value !== null && value !== undefined && value !== '') {- body[key] = value;- }- }-+ const domain = shortIoLinks.parseDomainProp(propsValue.domain);+ const linkId = shortIoClient.seg({ value: propsValue.linkId, label: 'Short Link' });+ const body = shortIoLinkBody.legacyLinkBody({ values: { ...propsValue }, now: Date.now() });try {- const response = await shortIoApiCall({+ const response = await shortIoClient.request({method: HttpMethod.POST,auth,- resourceUri: `/links/${linkId}`,- query,+ path: `/links/${linkId}`,+ query: { domain_id: domain.id },body,});-return {success: true,message: 'Short link updated successfully',- data: response,+ data: shortIoLinks.scrubLink(response),};- } catch (error: any) {- if (error.message.includes('400')) {- throw new Error(- 'Invalid request parameters. Please check your input values and try again.'- );- }-- if (error.message.includes('401') || error.message.includes('403')) {- throw new Error(- 'Authentication failed. Please check your API key and permissions.'- );- }-- if (error.message.includes('404')) {- throw new Error(- 'Short link not found. Please check the link ID and try again.'- );- }-- if (error.message.includes('429')) {- throw new Error(- 'Rate limit exceeded. Please wait a moment before trying again.'- );- }-- throw new Error(`Failed to update short link: ${error.message}`);+ } catch (error) {+ return shortIoClient.rethrowWithHint({+ error,+ hints: {+ 404: 'Short link not found. Check the link and domain.',+ 400: 'Short.io rejected the link settings.',+ 409: 'Another link on this domain already uses this path.',+ },+ });}},});diff --git a/packages/pieces/community/short-io/src/lib/common/ai-link-fields.ts b/packages/pieces/community/short-io/src/lib/common/ai-link-fields.tsnew file mode 100644index 00000000000..b262bd0c5b0--- /dev/null+++ b/packages/pieces/community/short-io/src/lib/common/ai-link-fields.ts@@ -0,0 +1,72 @@+import { Property } from '@activepieces/pieces-framework';+import { shortIoLinkBody } from './link-body';+import { shortIoValues } from './values';++const linkSettingProps = {+ path: Property.ShortText({ displayName: 'Path (Slug)', description: 'Custom slug after the domain, e.g. spring-sale. Empty = Short.io generates one.', required: false }),+ title: Property.ShortText({ displayName: 'Title', required: false }),+ tags: Property.Array({ displayName: 'Tags', description: 'Tags for the link. On update this replaces the existing tags.', required: false }),+ folderId: Property.ShortText({ displayName: 'Folder ID', description: 'Folder ID from List Folders.', required: false }),+ utmSource: Property.ShortText({ displayName: 'UTM Source', required: false }),+ utmMedium: Property.ShortText({ displayName: 'UTM Medium', required: false }),+ utmCampaign: Property.ShortText({ displayName: 'UTM Campaign', required: false }),+ utmTerm: Property.ShortText({ displayName: 'UTM Term', required: false }),+ utmContent: Property.ShortText({ displayName: 'UTM Content', required: false }),+ redirectType: Property.StaticDropdown({+ displayName: 'Redirect Type',+ required: false,+ options: {+ disabled: false,+ options: [+ { label: '301 (Moved Permanently)', value: '301' },+ { label: '302 (Found)', value: '302' },+ { label: '303 (See Other)', value: '303' },+ { label: '307 (Temporary Redirect)', value: '307' },+ { label: '308 (Permanent Redirect)', value: '308' },+ ],+ },+ }),+ expiresAt: Property.ShortText({ displayName: 'Expires At', description: 'ISO 8601 date-time after which the link shows the expired page (it is not deleted).', required: false }),+ expiredURL: Property.ShortText({ displayName: 'Expired Redirect URL', description: 'Where visitors go after the link expires.', required: false }),+ clicksLimit: Property.Number({ displayName: 'Clicks Limit', description: 'Expire the link after this many clicks (minimum 1).', required: false }),+ deleteAt: Property.ShortText({+ displayName: 'Delete At',+ description: 'ISO 8601 date-time at which Short.io permanently deletes the link; must be at least 7 days ahead. Deletion may lag by up to 2 hours.',+ required: false,+ }),+};++function aiLinkBody({ values, now }: { values: Record<string, unknown>; now: number }): Record<string, unknown> {+ const { clicksLimit, redirectType } = shortIoLinkBody.validateLinkOptions({+ clicksLimit: values['clicksLimit'],+ splitPercent: undefined,+ redirectType: values['redirectType'],+ });+ const text = (key: string): string | undefined => {+ const value = values[key];+ return typeof value === 'string' && value.trim() ? value.trim() : undefined;+ };+ const tags = values['tags'] === undefined || values['tags'] === null ? undefined : shortIoValues.stringList(values['tags']);+ const expiresAt = text('expiresAt');+ const deleteAt = text('deleteAt');+ const originalURL = text('originalURL');+ return shortIoValues.compact({+ originalURL,+ path: text('path')?.replace(/^\/+/, ''),+ title: text('title'),+ tags,+ folderId: text('folderId'),+ utmSource: text('utmSource'),+ utmMedium: text('utmMedium'),+ utmCampaign: text('utmCampaign'),+ utmTerm: text('utmTerm'),+ utmContent: text('utmContent'),+ redirectType,+ expiresAt: expiresAt ? shortIoValues.toIsoDateTime({ value: expiresAt, label: 'Expires At' }) : undefined,+ expiredURL: text('expiredURL'),+ clicksLimit,+ ttl: deleteAt ? shortIoValues.deleteAtToIso({ value: deleteAt, now }) : undefined,+ });+}++export const shortIoAiLinkFields = { linkSettingProps, aiLinkBody };diff --git a/packages/pieces/community/short-io/src/lib/common/ai-props.ts b/packages/pieces/community/short-io/src/lib/common/ai-props.tsnew file mode 100644index 00000000000..f48406eddf0--- /dev/null+++ b/packages/pieces/community/short-io/src/lib/common/ai-props.ts@@ -0,0 +1,61 @@+import { Property } from '@activepieces/pieces-framework';++export const shortIoAiProps = {+ domain: () =>+ Property.ShortText({+ displayName: 'Domain',+ description: 'Short.io domain hostname (e.g. link.example.com) or its numeric domain ID. Use List Domains to see them.',+ required: true,+ }),+ linkId: () =>+ Property.ShortText({+ displayName: 'Link ID',+ description: 'Short.io link ID: the idString field of a link, e.g. link_8yXK_034ebx7JWAtAAK3vFcl6ye.',+ required: true,+ }),+ folderId: () =>+ Property.ShortText({+ displayName: 'Folder ID',+ description: 'Optional folder ID (use List Folders to find it).',+ required: false,+ }),+ period: (description: string) =>+ Property.StaticDropdown({+ displayName: 'Period',+ description,+ required: false,+ defaultValue: 'last30',+ options: {+ disabled: false,+ options: [+ { label: 'Today', value: 'today' },+ { label: 'Yesterday', value: 'yesterday' },+ { label: 'Last 7 Days', value: 'last7' },+ { label: 'Last 30 Days', value: 'last30' },+ { label: 'This Week', value: 'week' },+ { label: 'This Month', value: 'month' },+ { label: 'Last Month', value: 'lastmonth' },+ { label: 'All Time', value: 'total' },+ { label: 'Custom Date Range', value: 'custom' },+ ],+ },+ }),+ startDate: () =>+ Property.ShortText({+ displayName: 'Start Date',+ description: 'First day (YYYY-MM-DD) when Period is "custom".',+ required: false,+ }),+ endDate: () =>+ Property.ShortText({+ displayName: 'End Date',+ description: 'Last day (YYYY-MM-DD) when Period is "custom".',+ required: false,+ }),+ timezone: () =>+ Property.ShortText({+ displayName: 'Timezone',+ description: 'IANA timezone for day boundaries, e.g. UTC or America/New_York. Defaults to UTC.',+ required: false,+ }),+};diff --git a/packages/pieces/community/short-io/src/lib/common/archive.ts b/packages/pieces/community/short-io/src/lib/common/archive.tsnew file mode 100644index 00000000000..e45cddeec8d--- /dev/null+++ b/packages/pieces/community/short-io/src/lib/common/archive.ts@@ -0,0 +1,24 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { shortIoClient, ShortIoAuthValue } from './client';+import { shortIoLinks } from './links';++async function setArchived({ auth, linkId, archived }: { auth: ShortIoAuthValue; linkId: string; archived: boolean }): Promise<{ linkId: string; archived: boolean }> {+ const id = linkId.trim();+ shortIoClient.seg({ value: id, label: 'Link ID' });+ try {+ const response = await shortIoClient.request({+ auth,+ method: HttpMethod.POST,+ path: archived ? '/links/archive' : '/links/unarchive',+ body: { link_id: id },+ });+ if (shortIoLinks.isRecord(response) && response['success'] === false) {+ throw new Error(`Short.io did not ${archived ? 'archive' : 'unarchive'} the link: ${shortIoClient.vendorMessage({ responseBody: response, fallback: 'unknown error' })}`);+ }+ return { linkId: id, archived };+ } catch (error) {+ return shortIoClient.rethrowWithHint({ error, hints: { 404: 'Short link not found. Check the link ID.' } });+ }+}++export const shortIoArchive = { setArchived };diff --git a/packages/pieces/community/short-io/src/lib/common/auth.ts b/packages/pieces/community/short-io/src/lib/common/auth.tsindex 26b641c286c..5588f7501db 100644--- a/packages/pieces/community/short-io/src/lib/common/auth.ts+++ b/packages/pieces/community/short-io/src/lib/common/auth.ts@@ -1,7 +1,6 @@-import { PieceAuth } from '@activepieces/pieces-framework';-import { shortIoApiCall } from './client';import { HttpMethod } from '@activepieces/pieces-common';-import { AppConnectionType } from '@activepieces/pieces-framework';+import { PieceAuth } from '@activepieces/pieces-framework';+import { shortIoClient } from './client';export const shortIoAuth = PieceAuth.CustomAuth({description: 'Enter your Short.io API Key',@@ -13,19 +12,21 @@ export const shortIoAuth = PieceAuth.CustomAuth({},validate: async ({ auth }) => {try {- await shortIoApiCall({+ await shortIoClient.request({method: HttpMethod.GET,- auth: {- type: AppConnectionType.CUSTOM_AUTH,- props: auth,- },- resourceUri: '/api/domains',+ auth: { props: { apiKey: auth.apiKey } },+ path: '/api/domains',+ query: { limit: 1 },});return { valid: true };- } catch (e) {+ } catch (error) {+ const status = shortIoClient.errorStatus(error);+ if (status === 401 || status === 403) {+ return { valid: false, error: 'Invalid API Key. Use a secret API key from Short.io > Integrations & API; public keys can only create links from a browser.' };+ }return {valid: false,- error: 'Invalid API Key',+ error: `Could not reach Short.io to check the API key: ${error instanceof Error ? error.message : String(error)}`,};}},diff --git a/packages/pieces/community/short-io/src/lib/common/client.ts b/packages/pieces/community/short-io/src/lib/common/client.tsindex 4f3fe963350..2f316ce5ab3 100644--- a/packages/pieces/community/short-io/src/lib/common/client.ts+++ b/packages/pieces/community/short-io/src/lib/common/client.ts@@ -1,66 +1,225 @@-import {- httpClient,- HttpMethod,- HttpRequest,- HttpMessageBody,- QueryParams,-} from '@activepieces/pieces-common';-import { AppConnectionValueForAuthProperty } from '@activepieces/pieces-framework';-import { shortIoAuth } from './auth';--export type ShortioAuthProps = AppConnectionValueForAuthProperty<typeof shortIoAuth>;--export type ShortioApiCallParams = {- method: HttpMethod;- resourceUri?: string;- url?: string;- query?: Record<string, string | number | string[] | undefined>;- body?: unknown;- auth: ShortioAuthProps;-};+import { httpClient, HttpMethod, QueryParams } from '@activepieces/pieces-common';++const SHORT_IO_API_BASE = 'https://api.short.io';+const SHORT_IO_STATS_BASE = 'https://statistics.short.io/statistics';+const REQUEST_TIMEOUT_MS = 30_000;+const MAX_RETRIES_ON_429 = 2;+const MAX_RETRY_WAIT_MS = 10_000;+let verifiedTlsAgent: Promise<unknown> | undefined;++export class ShortIoApiError extends Error {+ constructor(+ message: string,+ public readonly status: number,+ public readonly responseBody: unknown,+ ) {+ super(message);+ this.name = 'ShortIoApiError';+ }+}++function getApiKey(auth: ShortIoAuthValue): string {+ const key = auth?.props?.apiKey?.trim();+ if (!key) {+ throw new Error('The Short.io connection has no API key.');+ }+ return key;+}++function toText(value: unknown): string {+ if (typeof value === 'number' && Number.isFinite(value)) {+ return String(value);+ }+ return typeof value === 'string' ? value.trim() : '';+}++function seg({ value, label }: { value: unknown; label: string }): string {+ const text = toText(value);+ if (text === '' || text === '.' || text === '..') {+ throw new Error(`${label} is required.`);+ }+ return encodeURIComponent(text);+}-export async function shortIoApiCall<T extends HttpMessageBody>({- method,- resourceUri,- url,- query,- body,- auth,-}: ShortioApiCallParams): Promise<T> {- const finalUrl = url ?? `https://api.short.io${resourceUri ?? ''}`;-- const queryParams: QueryParams = {};- if (query) {- for (const [key, value] of Object.entries(query)) {- if (value !== null && value !== undefined) {- queryParams[key] = String(value);- }+function domainIdSeg(value: unknown): string {+ const text = toText(value);+ if (!/^\d+$/.test(text)) {+ throw new Error(`Domain ID must be a number (got "${text}").`);+ }+ return text;+}++function vendorMessage({ responseBody, fallback }: { responseBody: unknown; fallback: string }): string {+ if (responseBody !== null && typeof responseBody === 'object') {+ const message = Reflect.get(responseBody, 'message');+ const error = Reflect.get(responseBody, 'error');+ const field = Reflect.get(responseBody, 'field');+ const text = typeof message === 'string' && message ? message : typeof error === 'string' && error ? error : '';+ if (text) {+ return typeof field === 'string' && field ? `${text} (field: ${field})` : text;}}+ if (typeof responseBody === 'string' && responseBody.trim()) {+ return responseBody.trim().slice(0, 500);+ }+ return fallback;+}++function buildQuery(query?: Record<string, QueryValue>): QueryParams {+ return Object.fromEntries(+ Object.entries(query ?? {})+ .filter(([, value]) => value !== undefined && value !== null && value !== '')+ .map(([key, value]) => [key, String(value)]),+ );+}++function retryDelayMs({ header, attempt }: { header: string | null; attempt: number }): number {+ const seconds = header ? Number(header) : NaN;+ const wait = Number.isFinite(seconds) && seconds >= 0 ? seconds * 1000 : 1000 * 2 ** attempt;+ return Math.min(wait, MAX_RETRY_WAIT_MS);+}++function verifiedTls(): Promise<unknown> {+ verifiedTlsAgent ??= import('undici').then(({ Agent }) => new Agent({ connect: { rejectUnauthorized: true } }));+ return verifiedTlsAgent;+}++function carriesSecret(body: unknown): boolean {+ return body !== null && typeof body === 'object' && !Array.isArray(body) && Reflect.get(body, 'password') !== undefined;+}- const request: HttpRequest = {- method,- url: finalUrl,- headers: {- authorization: auth.props.apiKey,- 'Content-Type': 'application/json',- accept: 'application/json',- },- queryParams,- body,- };+function headerValue({ headers, name }: { headers: unknown; name: string }): string | null {+ if (headers === null || typeof headers !== 'object') {+ return null;+ }+ const value = Reflect.get(headers, name);+ if (Array.isArray(value)) {+ return typeof value[0] === 'string' ? value[0] : null;+ }+ return typeof value === 'string' ? value : null;+}+function toApiError({ status, responseBody }: { status: number; responseBody: unknown }): ShortIoApiError {+ const fallback = status >= 300 && status < 400 ? 'unexpected redirect' : 'request failed';+ return new ShortIoApiError(`Short.io API error (${status}): ${vendorMessage({ responseBody, fallback })}`, status, responseBody);+}++function failureOf(error: unknown): RawResponse | null {+ if (error === null || typeof error !== 'object') {+ return null;+ }+ const response = Reflect.get(error, 'response');+ if (response === null || typeof response !== 'object') {+ return null;+ }+ const status = Reflect.get(response, 'status');+ return typeof status === 'number' ? { status, body: Reflect.get(response, 'body'), headers: {} } : null;+}++async function viaHttpClient({ request, url, binary }: { request: ShortIoRequest; url: string; binary: boolean }): Promise<RawResponse> {+ const dispatcher = await verifiedTls();+ const hasBody = request.body !== undefined && request.method !== HttpMethod.GET;try {- const response = await httpClient.sendRequest<T>(request);- return response.body;- } catch (error: any) {- const status = error.response?.status;- const message =- error.response?.body?.message ||- error.message ||- 'Unknown Short.io API error';- throw new Error(- `Short.io API Error (${status || 'No Status'}): ${message}`+ const response = await httpClient.sendRequest(+ {+ method: request.method,+ url,+ headers: {+ authorization: getApiKey(request.auth),+ accept: binary ? '*/*' : 'application/json',+ ...(hasBody ? { 'content-type': 'application/json' } : {}),+ },+ queryParams: buildQuery(request.query),+ body: hasBody ? request.body : undefined,+ timeout: REQUEST_TIMEOUT_MS,+ followRedirects: false,+ responseType: binary ? 'arraybuffer' : 'json',+ redactBodyInErrors: hasBody && carriesSecret(request.body),+ },+ { dispatcher },);+ return { status: response.status, body: response.body, headers: response.headers };+ } catch (error) {+ const failure = failureOf(error);+ if (failure) {+ return failure;+ }+ throw error;+ }+}++async function send({ request, binary }: { request: ShortIoRequest; binary: boolean }): Promise<RawResponse> {+ const url = (request.base === 'stats' ? SHORT_IO_STATS_BASE : SHORT_IO_API_BASE) + request.path;+ for (let attempt = 0; ; attempt++) {+ const response = await viaHttpClient({ request, url, binary });+ if (response.status === 429 && attempt < MAX_RETRIES_ON_429) {+ await new Promise((resolve) => setTimeout(resolve, retryDelayMs({ header: headerValue({ headers: response.headers, name: 'retry-after' }), attempt })));+ continue;+ }+ if (response.status < 200 || response.status >= 300) {+ throw toApiError({ status: response.status, responseBody: response.body });+ }+ return response;}}++async function request(req: ShortIoRequest): Promise<unknown> {+ const response = await send({ request: req, binary: false });+ return response.body;+}++async function binaryRequest(req: ShortIoRequest): Promise<{ data: Buffer; contentType: string }> {+ const response = await send({ request: req, binary: true });+ const data = Buffer.isBuffer(response.body) ? response.body : Buffer.from(typeof response.body === 'string' ? response.body : '');+ return { data, contentType: headerValue({ headers: response.headers, name: 'content-type' }) ?? '' };+}++function errorStatus(error: unknown): number | undefined {+ return error instanceof ShortIoApiError ? error.status : undefined;+}++function rethrowWithHint({ error, hints }: { error: unknown; hints: Partial<Record<number, string>> }): never {+ if (error instanceof ShortIoApiError) {+ const defaults: Record<number, string> = {+ 401: 'Authentication failed. Check the API key on the Short.io connection.',+ 402: 'This feature needs a paid Short.io plan.',+ 403: 'Access denied. The API key cannot access this domain or link.',+ 429: 'Short.io rate limit reached. Try again in a moment.',+ };+ const hint = hints[error.status] ?? defaults[error.status];+ if (hint) {+ throw new ShortIoApiError(+ `${hint} Short.io said: ${vendorMessage({ responseBody: error.responseBody, fallback: error.message })}`,+ error.status,+ error.responseBody,+ );+ }+ }+ throw error;+}++export const shortIoClient = {+ request,+ binaryRequest,+ seg,+ domainIdSeg,+ vendorMessage,+ errorStatus,+ rethrowWithHint,+ getApiKey,+};++type RawResponse = { status: number; body: unknown; headers: unknown };++export type ShortIoAuthValue = { props: { apiKey: string } };++export type QueryValue = string | number | boolean | undefined | null;++export type ShortIoRequest = {+ auth: ShortIoAuthValue;+ method: HttpMethod;+ path: string;+ base?: 'api' | 'stats';+ query?: Record<string, QueryValue>;+ body?: unknown;+};diff --git a/packages/pieces/community/short-io/src/lib/common/link-body.ts b/packages/pieces/community/short-io/src/lib/common/link-body.tsnew file mode 100644index 00000000000..bfe757fb6df--- /dev/null+++ b/packages/pieces/community/short-io/src/lib/common/link-body.ts@@ -0,0 +1,45 @@+import { shortIoValues } from './values';++const REDIRECT_TYPES = ['301', '302', '303', '307', '308'];++function validateLinkOptions({ clicksLimit, splitPercent, redirectType }: { clicksLimit: unknown; splitPercent: unknown; redirectType: unknown }): {+ clicksLimit?: number;+ splitPercent?: number;+ redirectType?: number;+} {+ const clicks = shortIoValues.optionalNumber({ value: clicksLimit, label: 'Clicks limit', min: 1 });+ if (clicks !== undefined && !Number.isInteger(clicks)) {+ throw new Error('Clicks limit must be a whole number.');+ }+ const split = shortIoValues.optionalNumber({ value: splitPercent, label: 'Split percent', min: 1, max: 100 });+ let redirect: number | undefined;+ if (redirectType !== undefined && redirectType !== null && redirectType !== '') {+ if (!REDIRECT_TYPES.includes(String(redirectType))) {+ throw new Error(`Invalid redirect type. Must be one of: ${REDIRECT_TYPES.join(', ')}`);+ }+ redirect = Number(redirectType);+ }+ return { clicksLimit: clicks, splitPercent: split, redirectType: redirect };+}++function legacyLinkBody({ values, now }: { values: Record<string, unknown>; now: number }): Record<string, unknown> {+ const { clicksLimit, splitPercent, redirectType } = validateLinkOptions({+ clicksLimit: values['clicksLimit'],+ splitPercent: values['splitPercent'],+ redirectType: values['redirectType'],+ });+ const ttlSeconds = shortIoValues.optionalNumber({ value: values['ttl'], label: 'Time to Live' });+ const tags = values['tags'] === undefined || values['tags'] === null ? undefined : shortIoValues.stringList(values['tags']);+ return shortIoValues.compact({+ ...values,+ domain: undefined,+ linkId: undefined,+ tags,+ clicksLimit,+ splitPercent,+ redirectType,+ ttl: ttlSeconds === undefined ? undefined : shortIoValues.ttlSecondsToDeleteAt({ seconds: ttlSeconds, now }),+ });+}++export const shortIoLinkBody = { validateLinkOptions, legacyLinkBody, REDIRECT_TYPES };diff --git a/packages/pieces/community/short-io/src/lib/common/link-queries.ts b/packages/pieces/community/short-io/src/lib/common/link-queries.tsnew file mode 100644index 00000000000..03cf287e9bf--- /dev/null+++ b/packages/pieces/community/short-io/src/lib/common/link-queries.ts@@ -0,0 +1,54 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { shortIoClient, ShortIoAuthValue } from './client';+import { shortIoLinks } from './links';++async function expand({ auth, hostname, path }: { auth: ShortIoAuthValue; hostname: string; path: string }): Promise<Record<string, unknown> | null> {+ try {+ const response = await shortIoClient.request({ auth, method: HttpMethod.GET, path: '/links/expand', query: { domain: hostname, path } });+ return shortIoLinks.scrubLink(response);+ } catch (error) {+ if (shortIoClient.errorStatus(error) === 404) {+ return null;+ }+ return shortIoClient.rethrowWithHint({ error, hints: {} });+ }+}++async function getById({ auth, linkId, domainId }: { auth: ShortIoAuthValue; linkId: unknown; domainId?: number }): Promise<Record<string, unknown> | null> {+ const id = shortIoClient.seg({ value: linkId, label: 'Link ID' });+ try {+ const response = await shortIoClient.request({ auth, method: HttpMethod.GET, path: `/links/${id}`, query: { domainId } });+ return shortIoLinks.scrubLink(response);+ } catch (error) {+ if (shortIoClient.errorStatus(error) === 404) {+ return null;+ }+ return shortIoClient.rethrowWithHint({ error, hints: {} });+ }+}++async function listPage({ auth, domainId, query }: {+ auth: ShortIoAuthValue;+ domainId: number;+ query: Record<string, string | number | undefined>;+}): Promise<{ links: Record<string, unknown>[]; nextPageToken: string | null; count: number | null }> {+ try {+ const response = await shortIoClient.request({+ auth,+ method: HttpMethod.GET,+ path: '/api/links',+ query: { ...query, domain_id: domainId },+ });+ const record = shortIoLinks.isRecord(response) ? response : {};+ const token = record['nextPageToken'];+ return {+ links: shortIoLinks.scrubLinks(record['links']),+ nextPageToken: typeof token === 'string' && token ? token : null,+ count: typeof record['count'] === 'number' ? record['count'] : null,+ };+ } catch (error) {+ return shortIoClient.rethrowWithHint({ error, hints: { 400: 'Short.io rejected the link filters.' } });+ }+}++export const shortIoLinkQueries = { expand, getById, listPage };diff --git a/packages/pieces/community/short-io/src/lib/common/links.ts b/packages/pieces/community/short-io/src/lib/common/links.tsnew file mode 100644index 00000000000..ad9931708b6--- /dev/null+++ b/packages/pieces/community/short-io/src/lib/common/links.ts@@ -0,0 +1,123 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { shortIoClient, ShortIoAuthValue } from './client';++const MAX_DOMAIN_PAGES = 20;+const DOMAIN_PAGE_SIZE = 100;++function isRecord(value: unknown): value is Record<string, unknown> {+ return value !== null && typeof value === 'object' && !Array.isArray(value);+}++function scrubLink(raw: unknown): Record<string, unknown> {+ if (!isRecord(raw)) {+ return {};+ }+ const { password: _password, User: user, ...rest } = raw;+ const owner = isRecord(user) ? { User: Object.fromEntries(Object.entries(user).filter(([key]) => key !== 'photoURL')) } : {};+ const idString = typeof rest['idString'] === 'string' ? rest['idString'] : undefined;+ return { ...rest, ...owner, ...(idString ? { linkId: idString } : {}) };+}++function scrubLinks(raw: unknown): Record<string, unknown>[] {+ return Array.isArray(raw) ? raw.map(scrubLink) : [];+}++function parseDomainProp(value: unknown): ShortIoDomainRef {+ const parsed: unknown = typeof value === 'string' ? safeJson(value) : value;+ if (isRecord(parsed)) {+ const id = Number(parsed['id']);+ const hostname = typeof parsed['hostname'] === 'string' ? parsed['hostname'] : '';+ if (Number.isInteger(id) && id > 0 && hostname) {+ return { id, hostname };+ }+ }+ throw new Error('Select a domain from the Domain dropdown.');+}++function safeJson(text: string): unknown {+ try {+ return JSON.parse(text);+ } catch {+ return undefined;+ }+}++function normalizeHostname(input: string): string {+ return input+ .trim()+ .toLowerCase()+ .replace(/^https?:\/\//, '')+ .replace(/\/.*$/, '');+}++async function listAllDomains(auth: ShortIoAuthValue): Promise<Record<string, unknown>[]> {+ const pages: Record<string, unknown>[][] = [];+ for (let page = 0; page < MAX_DOMAIN_PAGES; page++) {+ const batch = await shortIoClient.request({+ auth,+ method: HttpMethod.GET,+ path: '/api/domains',+ query: { limit: DOMAIN_PAGE_SIZE, offset: page * DOMAIN_PAGE_SIZE },+ });+ const items = Array.isArray(batch) ? batch.filter(isRecord) : [];+ pages.push(items);+ if (items.length < DOMAIN_PAGE_SIZE) {+ break;+ }+ }+ return pages.flat();+}++async function resolveDomain({ auth, input }: { auth: ShortIoAuthValue; input: string | undefined }): Promise<ShortIoDomainRef> {+ const text = (input ?? '').trim();+ if (!text) {+ throw new Error('Domain is required: give the domain hostname (e.g. link.example.com) or its numeric ID.');+ }+ const domains = await listAllDomains(auth);+ const wanted = normalizeHostname(text);+ const match = domains.find((domain) =>+ /^\d+$/.test(text)+ ? String(domain['id']) === text+ : [domain['hostname'], domain['unicodeHostname']].some((name) => typeof name === 'string' && name.toLowerCase() === wanted),+ );+ if (!match) {+ const known = domains+ .map((domain) => domain['hostname'])+ .filter((name): name is string => typeof name === 'string')+ .slice(0, 20);+ throw new Error(+ known.length === 0+ ? 'This Short.io account has no domains. Add a domain in Short.io first.'+ : `Domain "${text}" was not found on this Short.io account. Known domains: ${known.join(', ')}.`,+ );+ }+ return { id: Number(match['id']), hostname: String(match['hostname']) };+}++function parseShortUrl(input: string): { hostname?: string; path: string } {+ const text = input.trim();+ if (/^https?:\/\//i.test(text) || /^[^/\s]+\.[^/\s]+\/.+/.test(text)) {+ const url = new URL(/^https?:\/\//i.test(text) ? text : `https://${text}`);+ return { hostname: url.hostname.toLowerCase(), path: decodeURIComponent(url.pathname.replace(/^\/+/, '')) };+ }+ return { path: text.replace(/^\/+/, '') };+}++const DOMAIN_KEYS = ['id', 'hostname', 'unicodeHostname', 'state', 'linkType', 'cloaking', 'caseSensitive', 'redirect404', 'httpsLinks', 'TeamId', 'createdAt', 'updatedAt'];++function pickDomain(raw: Record<string, unknown>): Record<string, unknown> {+ return Object.fromEntries(DOMAIN_KEYS.filter((key) => key in raw).map((key) => [key, raw[key]]));+}++export const shortIoLinks = {+ pickDomain,+ scrubLink,+ scrubLinks,+ parseDomainProp,+ resolveDomain,+ listAllDomains,+ parseShortUrl,+ isRecord,+};++export type ShortIoDomainRef = { id: number; hostname: string };diff --git a/packages/pieces/community/short-io/src/lib/common/output-schemas.ts b/packages/pieces/community/short-io/src/lib/common/output-schemas.tsnew file mode 100644index 00000000000..e3ea6ce31ad--- /dev/null+++ b/packages/pieces/community/short-io/src/lib/common/output-schemas.ts@@ -0,0 +1,324 @@+import { OutputSchema } from '@activepieces/pieces-framework';++type Fields = OutputSchema['fields'];++const linkFields: Fields = [+ { key: 'idString', label: 'Link ID', description: 'Pass this as Link ID to other Short.io steps.' },+ { key: 'linkId', label: 'Link ID (copy)' },+ { key: 'id', label: 'Legacy Numeric ID' },+ { key: 'shortURL', label: 'Short URL', format: 'url' },+ { key: 'secureShortURL', label: 'Secure Short URL', format: 'url' },+ { key: 'originalURL', label: 'Original URL', format: 'url' },+ { key: 'path', label: 'Path' },+ { key: 'title', label: 'Title' },+ { key: 'tags', label: 'Tags' },+ { key: 'DomainId', label: 'Domain ID', format: 'number' },+ { key: 'FolderId', label: 'Folder ID' },+ { key: 'OwnerId', label: 'Owner ID', format: 'number' },+ { key: 'hasPassword', label: 'Password Protected', format: 'boolean', description: 'The password itself is never returned.' },+ { key: 'cloaking', label: 'Cloaking', format: 'boolean' },+ { key: 'redirectType', label: 'Redirect Type' },+ { key: 'archived', label: 'Archived', format: 'boolean' },+ { key: 'expiresAt', label: 'Expires At' },+ { key: 'expiredURL', label: 'Expired Redirect URL', format: 'url' },+ { key: 'clicksLimit', label: 'Clicks Limit', format: 'number' },+ { key: 'ttl', label: 'Scheduled Deletion Time' },+ { key: 'createdAt', label: 'Created At', format: 'datetime' },+ { key: 'utmSource', label: 'UTM Source' },+ { key: 'utmMedium', label: 'UTM Medium' },+ { key: 'utmCampaign', label: 'UTM Campaign' },+ { key: 'utmTerm', label: 'UTM Term' },+ { key: 'utmContent', label: 'UTM Content' },+ { key: 'androidURL', label: 'Android URL', format: 'url' },+ { key: 'iphoneURL', label: 'iPhone URL', format: 'url' },+ { key: 'splitURL', label: 'Split URL', format: 'url' },+ { key: 'splitPercent', label: 'Split Percent', format: 'number' },+ { key: 'User', label: 'Owner', children: [+ { key: 'id', label: 'User ID', format: 'number' },+ { key: 'name', label: 'Name' },+ { key: 'email', label: 'Email', format: 'email' },+ ] },+];++const domainFields: Fields = [+ { key: 'id', label: 'Domain ID', format: 'number', description: 'Pass this (or the hostname) as Domain to other steps.' },+ { key: 'hostname', label: 'Hostname' },+ { key: 'unicodeHostname', label: 'Unicode Hostname' },+ { key: 'state', label: 'State' },+ { key: 'linkType', label: 'Link Type' },+ { key: 'cloaking', label: 'Cloaking', format: 'boolean' },+ { key: 'caseSensitive', label: 'Case Sensitive', format: 'boolean' },+ { key: 'redirect404', label: '404 Redirect', format: 'url' },+ { key: 'httpsLinks', label: 'HTTPS Links', format: 'boolean' },+ { key: 'TeamId', label: 'Team ID', format: 'number' },+ { key: 'createdAt', label: 'Created At', format: 'datetime' },+ { key: 'updatedAt', label: 'Updated At', format: 'datetime' },+];++const scoreList = ({ key, label, valueKey }: { key: string; label: string; valueKey: string }): Fields[number] => ({+ key,+ label,+ listItems: [+ { key: valueKey, label: 'Value' },+ { key: 'score', label: 'Clicks', format: 'number' },+ ],+});++const statsBreakdownFields: Fields = [+ { key: 'interval', label: 'Interval', children: [+ { key: 'startDate', label: 'Start', format: 'datetime' },+ { key: 'endDate', label: 'End', format: 'datetime' },+ { key: 'tz', label: 'Timezone' },+ ] },+ { key: 'clickStatistics', label: 'Clicks Over Time', description: 'datasets[0].data holds {x: date, y: clicks} points.' },+ scoreList({ key: 'country', label: 'Top Countries', valueKey: 'country' }),+ scoreList({ key: 'referer', label: 'Top Referrers', valueKey: 'referer' }),+ scoreList({ key: 'browser', label: 'Top Browsers', valueKey: 'browser' }),+ scoreList({ key: 'os', label: 'Top Operating Systems', valueKey: 'os' }),+ scoreList({ key: 'social', label: 'Top Social Networks', valueKey: 'social' }),+ scoreList({ key: 'city', label: 'Top Cities', valueKey: 'name' }),+];++const domainStatsFields: Fields = [+ { key: 'clicks', label: 'Total Clicks', format: 'number' },+ { key: 'humanClicks', label: 'Human Clicks', format: 'number' },+ { key: 'links', label: 'Links Created', format: 'number' },+ { key: 'clicksPerLink', label: 'Clicks per Link' },+ { key: 'prevClicks', label: 'Clicks in Previous Period', format: 'number' },+ { key: 'prevHumanClicks', label: 'Human Clicks in Previous Period', format: 'number' },+ ...statsBreakdownFields,+];++const wrapped = ({ data, description }: { data: Fields; description: string }): OutputSchema => ({+ fields: [+ { key: 'success', label: 'Success', format: 'boolean' },+ { key: 'message', label: 'Message' },+ { key: 'data', label: 'Data', description, children: data },+ ],+});++const clickFields: Fields = [+ { key: 'dt', label: 'Clicked At', format: 'datetime' },+ { key: 'path', label: 'Path' },+ { key: 'url', label: 'Short URL', format: 'url' },+ { key: 'host', label: 'Host' },+ { key: 'country', label: 'Country' },+ { key: 'city', label: 'City' },+ { key: 'ref', label: 'Referrer URL' },+ { key: 'refhost', label: 'Referrer Host' },+ { key: 'browser', label: 'Browser' },+ { key: 'os', label: 'Operating System' },+ { key: 'social', label: 'Social Network' },+ { key: 'human', label: 'Human', format: 'boolean' },+ { key: 'st', label: 'HTTP Status', format: 'number' },+ { key: 'utm_source', label: 'UTM Source' },+ { key: 'utm_medium', label: 'UTM Medium' },+ { key: 'utm_campaign', label: 'UTM Campaign' },+ { key: 'ip', label: 'Visitor IP', description: 'Personal data; empty when the domain hides visitor IPs.' },+ { key: 'ua', label: 'User Agent' },+];++export const shortIoSchemas = {+ linkFields,+ domainFields,+ clickFields,+ wrapped,+ legacyLink: wrapped({ data: linkFields, description: 'The Short.io link (password removed).' }),+ legacyLinkList: wrapped({+ data: [+ { key: 'count', label: 'Total Links', format: 'number', description: 'Total links matching on the domain, not just this page.' },+ { key: 'nextPageToken', label: 'Next Page Token', description: 'Pass as Page Token to get the next page; empty on the last page.' },+ { key: 'links', label: 'Links', listItems: linkFields },+ ],+ description: 'The page of links returned by Short.io (passwords removed).',+ }),+ legacyDelete: wrapped({+ data: [+ { key: 'success', label: 'Deleted', format: 'boolean' },+ { key: 'idString', label: 'Link ID' },+ ],+ description: 'Short.io delete response.',+ }),+ legacyCountryRule: wrapped({+ data: [+ { key: 'country', label: 'Country Code' },+ { key: 'originalURL', label: 'Country Redirect URL', format: 'url' },+ ],+ description: 'DRAFT: rule echoed by Short.io (not verified live; needs a Hobby plan).',+ }),+ legacyDomainStats: wrapped({ data: domainStatsFields, description: 'Domain statistics for the period.' }),+ legacyLinkClicks: wrapped({ data: [], description: 'A map of link ID to click count, e.g. {"link_abc": 45}.' }),+ link: { fields: linkFields },+ linkLookup: {+ fields: [+ { key: 'found', label: 'Found', format: 'boolean' },+ { key: 'link', label: 'Link', children: linkFields },+ ],+ } satisfies OutputSchema,+ linkList: {+ fields: [+ { key: 'items', label: 'Links', listItems: linkFields },+ { key: 'count', label: 'Count on This Page', format: 'number' },+ { key: 'nextPageToken', label: 'Next Page Token' },+ { key: 'hasMore', label: 'Has More', format: 'boolean', description: 'True when another page exists; pass Next Page Token to get it.' },+ ],+ } satisfies OutputSchema,+ domain: { fields: domainFields } satisfies OutputSchema,+ domainList: {+ fields: [+ { key: 'items', label: 'Domains', listItems: domainFields },+ { key: 'count', label: 'Count', format: 'number' },+ ],+ } satisfies OutputSchema,+ bulkCreate: {+ fields: [+ { key: 'items', label: 'Created Links', listItems: linkFields },+ { key: 'createdCount', label: 'Created', format: 'number' },+ { key: 'errors', label: 'Failed Items', listItems: [+ { key: 'index', label: 'Input Index', format: 'number' },+ { key: 'originalURL', label: 'Original URL', format: 'url' },+ { key: 'error', label: 'Error' },+ ] },+ { key: 'errorCount', label: 'Failed', format: 'number' },+ ],+ } satisfies OutputSchema,+ archive: {+ fields: [+ { key: 'linkId', label: 'Link ID' },+ { key: 'archived', label: 'Archived', format: 'boolean' },+ ],+ } satisfies OutputSchema,+ deleteLink: {+ fields: [+ { key: 'linkId', label: 'Link ID' },+ { key: 'deleted', label: 'Deleted', format: 'boolean' },+ { key: 'alreadyDeleted', label: 'Already Deleted', format: 'boolean', description: 'True when the link did not exist (a repeat call).' },+ ],+ } satisfies OutputSchema,+ tagLinks: {+ fields: [+ { key: 'tag', label: 'Tag' },+ { key: 'linkIds', label: 'Link IDs' },+ { key: 'count', label: 'Links Tagged', format: 'number' },+ ],+ } satisfies OutputSchema,+ qrCode: {+ fields: [+ { key: 'linkId', label: 'Link ID' },+ { key: 'format', label: 'Format' },+ { key: 'fileName', label: 'File Name' },+ { key: 'file', label: 'File', description: 'Stored file reference; pass to steps that take a file.' },+ { key: 'size', label: 'Size (bytes)', format: 'filesize' },+ ],+ } satisfies OutputSchema,+ folderList: {+ fields: [+ { key: 'items', label: 'Folders', listItems: [+ { key: 'id', label: 'Folder ID' },+ { key: 'name', label: 'Name' },+ ] },+ { key: 'count', label: 'Count', format: 'number' },+ ],+ } satisfies OutputSchema,+ folder: {+ fields: [+ { key: 'id', label: 'Folder ID' },+ { key: 'name', label: 'Name' },+ { key: 'domainId', label: 'Domain ID', format: 'number' },+ ],+ } satisfies OutputSchema,+ countryRuleList: {+ fields: [+ { key: 'linkId', label: 'Link ID' },+ { key: 'items', label: 'Rules', description: 'DRAFT: rule fields not verified live (country targeting needs a Hobby plan).', listItems: [+ { key: 'country', label: 'Country Code' },+ { key: 'originalURL', label: 'Redirect URL', format: 'url' },+ ] },+ { key: 'count', label: 'Count', format: 'number' },+ ],+ } satisfies OutputSchema,+ countryRule: {+ fields: [+ { key: 'linkId', label: 'Link ID' },+ { key: 'country', label: 'Country Code' },+ { key: 'originalURL', label: 'Redirect URL', format: 'url' },+ { key: 'rule', label: 'Raw Rule', description: 'DRAFT: Short.io response, not verified live (needs a Hobby plan).' },+ ],+ } satisfies OutputSchema,+ countryRuleDelete: {+ fields: [+ { key: 'linkId', label: 'Link ID' },+ { key: 'country', label: 'Country Code' },+ { key: 'deleted', label: 'Deleted', format: 'boolean' },+ { key: 'alreadyDeleted', label: 'Already Deleted', format: 'boolean' },+ ],+ } satisfies OutputSchema,+ domainStats: { fields: domainStatsFields } satisfies OutputSchema,+ clicks: {+ fields: [+ { key: 'items', label: 'Clicks', listItems: clickFields },+ { key: 'count', label: 'Count', format: 'number' },+ ],+ } satisfies OutputSchema,+ topLinks: {+ fields: [+ { key: 'items', label: 'Top Links', listItems: [+ { key: 'path', label: 'Path' },+ { key: 'clicks', label: 'Clicks', format: 'number' },+ ] },+ { key: 'count', label: 'Count', format: 'number' },+ ],+ } satisfies OutputSchema,+ duplicatedLink: {+ fields: [{ key: 'duplicatedFrom', label: 'Copied From Link ID' }, ...linkFields],+ } satisfies OutputSchema,+ folderLookup: {+ fields: [+ { key: 'found', label: 'Found', format: 'boolean' },+ { key: 'folder', label: 'Folder', children: [+ { key: 'id', label: 'Folder ID' },+ { key: 'name', label: 'Name' },+ { key: 'domainId', label: 'Domain ID', format: 'number' },+ ] },+ ],+ } satisfies OutputSchema,+ openGraph: {+ fields: [+ { key: 'linkId', label: 'Link ID' },+ { key: 'properties', label: 'Properties', dynamicKey: true, description: 'Map of OpenGraph property (title, description, image, twitter:card…) to value.' },+ { key: 'items', label: 'Property List', listItems: [+ { key: 'property', label: 'Property' },+ { key: 'value', label: 'Value' },+ ] },+ { key: 'count', label: 'Count', format: 'number' },+ ],+ } satisfies OutputSchema,+ linksByUrl: {+ fields: [+ { key: 'items', label: 'Links', listItems: linkFields },+ { key: 'count', label: 'Count', format: 'number' },+ ],+ } satisfies OutputSchema,+ trigger: {+ fields: [+ { key: 'id', label: 'Link ID' },+ { key: 'shortURL', label: 'Short URL', format: 'url' },+ { key: 'secureShortURL', label: 'Secure Short URL', format: 'url' },+ { key: 'originalURL', label: 'Original URL', format: 'url' },+ { key: 'path', label: 'Path' },+ { key: 'title', label: 'Title' },+ { key: 'tags', label: 'Tags' },+ { key: 'createdAt', label: 'Created At', format: 'datetime' },+ { key: 'domainId', label: 'Domain ID', format: 'number' },+ { key: 'folderId', label: 'Folder ID' },+ { key: 'hasPassword', label: 'Password Protected', format: 'boolean' },+ { key: 'archived', label: 'Archived', format: 'boolean' },+ { key: 'expiresAt', label: 'Expires At' },+ { key: 'triggerInfo', label: 'Trigger Info', children: [+ { key: 'domain', label: 'Domain' },+ { key: 'detectedAt', label: 'Detected At', format: 'datetime' },+ ] },+ { key: 'raw', label: 'Raw Link', description: 'Full Short.io link object without the password.' },+ ],+ } satisfies OutputSchema,+};diff --git a/packages/pieces/community/short-io/src/lib/common/props.ts b/packages/pieces/community/short-io/src/lib/common/props.tsindex 84ff00a0eb6..ba563aec976 100644--- a/packages/pieces/community/short-io/src/lib/common/props.ts+++ b/packages/pieces/community/short-io/src/lib/common/props.ts@@ -1,180 +1,115 @@-import { Property } from '@activepieces/pieces-framework';import { HttpMethod } from '@activepieces/pieces-common';-import { shortIoApiCall, ShortioAuthProps } from './client';+import { Property } from '@activepieces/pieces-framework';import { shortIoAuth } from './auth';+import { shortIoClient } from './client';+import { shortIoLinks } from './links';-interface ShortIoDomain {- id: number;- hostname: string;-}--interface ShortIoLink {- idString: string;- path: string;- originalURL: string;-}+const MAX_LINK_PAGES = 10;+const LINK_PAGE_SIZE = 150;-interface ShortIoLinksResponse {- links: ShortIoLink[];+function errorText(error: unknown): string {+ return error instanceof Error ? error.message : String(error);}-interface ShortIoFolder {- id: string;- name: string;-}--interface ShortIoFoldersResponse {- linkFolders: ShortIoFolder[];-}--export const domainIdDropdown =Property.Dropdown({+export const domainIdDropdown = Property.Dropdown({auth: shortIoAuth,-displayName: 'Domain',description: 'Select the domain to use for the link',required: true,refreshers: ['auth'],options: async ({ auth }) => {if (!auth) {- return {- disabled: true,- options: [],- placeholder: 'Connect your Short.io account first',- };+ return { disabled: true, options: [], placeholder: 'Connect your Short.io account first' };}-try {- const domains = await shortIoApiCall<ShortIoDomain[]>({- auth: auth as ShortioAuthProps,- method: HttpMethod.GET,- resourceUri: '/api/domains',- });-+ const domains = await shortIoLinks.listAllDomains(auth);return {disabled: false,options: domains.map((domain) => ({- label: domain.hostname,- value: JSON.stringify({- id: domain.id,- hostname: domain.hostname,- }),+ label: String(domain['hostname']),+ value: JSON.stringify({ id: domain['id'], hostname: domain['hostname'] }),})),- placeholder:- domains.length === 0 ? 'No domains available' : 'Select a domain',- };- } catch (error: any) {- return {- disabled: true,- options: [],- placeholder: `Error loading domains: ${error.message}`,+ placeholder: domains.length === 0 ? 'No domains available' : 'Select a domain',};+ } catch (error) {+ return { disabled: true, options: [], placeholder: `Error loading domains: ${errorText(error)}` };}},});-export const linkIdDropdown =Property.Dropdown({+export const linkIdDropdown = Property.Dropdown({auth: shortIoAuth,-displayName: 'Short Link',- description: 'Select the short link from the domain',+ description: 'Select the short link from the domain (the newest 1,500 links are listed).',required: true,refreshers: ['auth', 'domain'],options: async ({ auth, domain }) => {if (!auth) {- return {- disabled: true,- options: [],- placeholder: 'Connect your Short.io account first',- };+ return { disabled: true, options: [], placeholder: 'Connect your Short.io account first' };}-if (!domain) {- return {- disabled: true,- options: [],- placeholder: 'Select a domain first',- };+ return { disabled: true, options: [], placeholder: 'Select a domain first' };}-try {- const domainObject = JSON.parse(domain as string);- const response = await shortIoApiCall<ShortIoLinksResponse>({- auth: auth as ShortioAuthProps,- method: HttpMethod.GET,- resourceUri: '/api/links',- query: {- domain_id: domainObject.id,- limit: 100,- },- });-+ const domainRef = shortIoLinks.parseDomainProp(domain);+ const links: Record<string, unknown>[] = [];+ let pageToken: string | undefined;+ for (let page = 0; page < MAX_LINK_PAGES; page++) {+ const response = await shortIoClient.request({+ auth,+ method: HttpMethod.GET,+ path: '/api/links',+ query: { domain_id: domainRef.id, limit: LINK_PAGE_SIZE, dateSortOrder: 'desc', pageToken },+ });+ const record = shortIoLinks.isRecord(response) ? response : {};+ links.push(...shortIoLinks.scrubLinks(record['links']));+ pageToken = typeof record['nextPageToken'] === 'string' && record['nextPageToken'] ? record['nextPageToken'] : undefined;+ if (!pageToken) {+ break;+ }+ }return {disabled: false,- options: response.links.map((link) => ({- label: `${link.path || '(auto)'} → ${link.originalURL}`,- value: link.idString,+ options: links.map((link) => ({+ label: `${link['path'] || '(auto)'} → ${link['originalURL']}`,+ value: String(link['idString']),})),- placeholder:- response.links.length === 0 ? 'No links available' : 'Select a link',- };- } catch (error: any) {- return {- disabled: true,- options: [],- placeholder: `Error loading links: ${error.message}`,+ placeholder: links.length === 0 ? 'No links available' : pageToken ? 'Select a link (older links: use Link ID in an AI step or List Links)' : 'Select a link',};+ } catch (error) {+ return { disabled: true, options: [], placeholder: `Error loading links: ${errorText(error)}` };}},});-export const folderIdDropdown =Property.Dropdown({+export const folderIdDropdown = Property.Dropdown({auth: shortIoAuth,-displayName: 'Folder',description: 'Select the folder to add the link to.',required: false,refreshers: ['auth', 'domain'],options: async ({ auth, domain }) => {if (!auth || !domain) {- return {- disabled: true,- options: [],- placeholder: 'Select a domain first',- };+ return { disabled: true, options: [], placeholder: 'Select a domain first' };}-try {- const domainObject = JSON.parse(domain as string);- const response = await shortIoApiCall<ShortIoFoldersResponse>({- auth: auth as ShortioAuthProps,+ const domainRef = shortIoLinks.parseDomainProp(domain);+ const response = await shortIoClient.request({+ auth,method: HttpMethod.GET,- resourceUri: `/links/folders/${domainObject.id}`,+ path: `/links/folders/${shortIoClient.domainIdSeg(domainRef.id)}`,});-- const foldersArray = response.linkFolders;-- if (!foldersArray || foldersArray.length === 0) {- return {- disabled: true,- options: [],- placeholder: 'No folders found in this domain',- };+ const folders = shortIoLinks.isRecord(response) && Array.isArray(response['linkFolders']) ? response['linkFolders'].filter(shortIoLinks.isRecord) : [];+ if (folders.length === 0) {+ return { disabled: true, options: [], placeholder: 'No folders found in this domain' };}-return {disabled: false,- options: foldersArray.map((folder: ShortIoFolder) => ({- label: folder.name,- value: folder.id,- })),+ options: folders.map((folder) => ({ label: String(folder['name']), value: String(folder['id']) })),placeholder: 'Select a folder',};- } catch (error: any) {- return {- disabled: true,- options: [],- placeholder: `Error: Could not load folders. ${error.message}`,- };+ } catch (error) {+ return { disabled: true, options: [], placeholder: `Error: Could not load folders. ${errorText(error)}` };}},});diff --git a/packages/pieces/community/short-io/src/lib/common/qr.ts b/packages/pieces/community/short-io/src/lib/common/qr.tsnew file mode 100644index 00000000000..319bd156c7d--- /dev/null+++ b/packages/pieces/community/short-io/src/lib/common/qr.ts@@ -0,0 +1,13 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { shortIoClient, ShortIoAuthValue } from './client';++async function renderQrImage({ auth, linkId, options }: { auth: ShortIoAuthValue; linkId: string; options: Record<string, unknown> }): Promise<{ data: Buffer; contentType: string }> {+ return shortIoClient.binaryRequest({+ auth,+ method: HttpMethod.POST,+ path: `/links/qr/${shortIoClient.seg({ value: linkId, label: 'Link ID' })}`,+ body: options,+ });+}++export const shortIoQr = { renderQrImage };diff --git a/packages/pieces/community/short-io/src/lib/common/stats.ts b/packages/pieces/community/short-io/src/lib/common/stats.tsnew file mode 100644index 00000000000..5078db53f1d--- /dev/null+++ b/packages/pieces/community/short-io/src/lib/common/stats.ts@@ -0,0 +1,60 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { shortIoClient, ShortIoAuthValue } from './client';+import { shortIoLinks } from './links';+import { shortIoValues } from './values';++const CHART_INTERVALS = ['hour', 'day', 'week', 'month'];++function chartInterval(value: unknown): string | undefined {+ if (value === undefined || value === null || value === '') {+ return undefined;+ }+ if (!CHART_INTERVALS.includes(String(value))) {+ throw new Error(`Chart interval must be one of: ${CHART_INTERVALS.join(', ')}.`);+ }+ return String(value);+}++async function domainStatistics({ auth, domainId, period, startDate, endDate, tz, clicksChartInterval, ignoreDatesForPresets }: StatsInput & {+ ignoreDatesForPresets?: boolean;+ domainId: number;+ clicksChartInterval?: unknown;+}): Promise<Record<string, unknown>> {+ const query = {+ ...shortIoValues.statsRange({ period, startDate, endDate, ignoreDatesForPresets }),+ tz: shortIoValues.validateTimezone(tz),+ clicksChartInterval: chartInterval(clicksChartInterval),+ };+ try {+ const response = await shortIoClient.request({+ auth,+ method: HttpMethod.GET,+ base: 'stats',+ path: `/domain/${shortIoClient.domainIdSeg(domainId)}`,+ query,+ });+ return shortIoLinks.isRecord(response) ? response : {};+ } catch (error) {+ return shortIoClient.rethrowWithHint({ error, hints: { 404: 'Domain not found or it has no statistics access.', 400: 'Short.io rejected the statistics period.' } });+ }+}++async function statsQuery({ auth, domainId, report, body }: { auth: ShortIoAuthValue; domainId: number; report: 'top' | 'last_clicks'; body: Record<string, unknown> }): Promise<unknown> {+ return shortIoClient.request({+ auth,+ method: HttpMethod.POST,+ base: 'stats',+ path: `/domain/${shortIoClient.domainIdSeg(domainId)}/${report}`,+ body,+ });+}++export const shortIoStats = { domainStatistics, chartInterval, statsQuery };++type StatsInput = {+ auth: ShortIoAuthValue;+ period: unknown;+ startDate?: string;+ endDate?: string;+ tz?: string;+};diff --git a/packages/pieces/community/short-io/src/lib/common/targeting.ts b/packages/pieces/community/short-io/src/lib/common/targeting.tsnew file mode 100644index 00000000000..31bb757a22c--- /dev/null+++ b/packages/pieces/community/short-io/src/lib/common/targeting.ts@@ -0,0 +1,52 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { shortIoClient, ShortIoAuthValue } from './client';++function countryCode(value: unknown): string {+ const code = typeof value === 'string' ? value.trim().toUpperCase() : '';+ if (!/^[A-Z]{2}$/.test(code)) {+ throw new Error('Country code must be exactly 2 letters (e.g., US, GB, CA).');+ }+ return code;+}++function httpUrl({ value, label }: { value: unknown; label: string }): string {+ const text = typeof value === 'string' ? value.trim() : '';+ const protocol = URL.canParse(text) ? new URL(text).protocol : '';+ if (protocol === 'http:' || protocol === 'https:') {+ return text;+ }+ throw new Error(`${label} must be a valid URL starting with http:// or https://`);+}++async function addCountryRule({ auth, linkId, domainId, country, originalURL }: {+ auth: ShortIoAuthValue;+ linkId: unknown;+ domainId?: number;+ country: unknown;+ originalURL: unknown;+}): Promise<{ linkId: string; country: string; originalURL: string; raw: unknown }> {+ const code = countryCode(country);+ const url = httpUrl({ value: originalURL, label: 'Country redirect URL' });+ const id = shortIoClient.seg({ value: linkId, label: 'Link ID' });+ try {+ const raw = await shortIoClient.request({+ auth,+ method: HttpMethod.POST,+ path: `/link_country/${id}`,+ query: { domainId },+ body: { country: code, originalURL: url },+ });+ return { linkId: decodeURIComponent(id), country: code, originalURL: url, raw };+ } catch (error) {+ return shortIoClient.rethrowWithHint({+ error,+ hints: {+ 404: 'Short link not found. Check the link ID.',+ 409: `A country targeting rule for ${code} already exists on this link.`,+ 400: 'Short.io rejected the country rule.',+ },+ });+ }+}++export const shortIoTargeting = { countryCode, httpUrl, addCountryRule };diff --git a/packages/pieces/community/short-io/src/lib/common/values.ts b/packages/pieces/community/short-io/src/lib/common/values.tsnew file mode 100644index 00000000000..fdc0a105d55--- /dev/null+++ b/packages/pieces/community/short-io/src/lib/common/values.ts@@ -0,0 +1,128 @@+const SEVEN_DAYS_MS = 7 * 24 * 60 * 60 * 1000;+const PERIODS = ['today', 'yesterday', 'last7', 'last30', 'week', 'month', 'lastmonth', 'total', 'custom'];+const LEGACY_PERIODS: Record<string, string> = { thisMonth: 'month', lastMonth: 'lastmonth' };++function ttlSecondsToDeleteAt({ seconds, now }: { seconds: number; now: number }): string {+ if (!Number.isFinite(seconds) || seconds <= 0) {+ throw new Error('Time to Live must be a positive number of seconds.');+ }+ const deleteAt = now + seconds * 1000;+ if (deleteAt - now < SEVEN_DAYS_MS) {+ throw new Error('Time to Live must be at least 604800 seconds (7 days): Short.io only accepts a deletion time at least one week ahead.');+ }+ return new Date(deleteAt).toISOString();+}++function deleteAtToIso({ value, now }: { value: string; now: number }): string {+ const time = Date.parse(value);+ if (Number.isNaN(time)) {+ throw new Error(`Delete At must be an ISO 8601 date-time (got "${value}").`);+ }+ if (time - now < SEVEN_DAYS_MS) {+ throw new Error('Delete At must be at least 7 days in the future: Short.io only accepts a deletion time at least one week ahead.');+ }+ return new Date(time).toISOString();+}++function toIsoDateTime({ value, label }: { value: string; label: string }): string {+ const time = Date.parse(value);+ if (Number.isNaN(time)) {+ throw new Error(`${label} must be an ISO 8601 date-time (got "${value}").`);+ }+ return new Date(time).toISOString();+}++function toApiDate({ value, label }: { value: string; label: string }): string {+ const trimmed = value.trim();+ const match = /^(\d{4}-\d{2}-\d{2})/.exec(trimmed);+ if (!match || Number.isNaN(Date.parse(match[1]))) {+ throw new Error(`${label} must be a date like 2026-01-31 (got "${value}").`);+ }+ return match[1];+}++function normalizePeriod(value: unknown): string {+ const text = typeof value === 'string' && value ? value : 'last30';+ const period = LEGACY_PERIODS[text] ?? text;+ if (!PERIODS.includes(period)) {+ throw new Error(`Period must be one of: ${PERIODS.join(', ')}.`);+ }+ return period;+}++function validateTimezone(value: string | undefined): string | undefined {+ const tz = value?.trim();+ if (!tz) {+ return undefined;+ }+ try {+ new Intl.DateTimeFormat('en-US', { timeZone: tz });+ } catch {+ throw new Error(`Unknown timezone "${tz}". Use an IANA name like UTC, America/New_York or Europe/London.`);+ }+ return tz;+}++function statsRange({ period, startDate, endDate, ignoreDatesForPresets = false }: {+ period: unknown;+ startDate?: string;+ endDate?: string;+ ignoreDatesForPresets?: boolean;+}): Record<string, string> {+ const normalized = normalizePeriod(period);+ if (normalized !== 'custom') {+ if (!ignoreDatesForPresets && (startDate || endDate)) {+ throw new Error('Start and end dates are only used when the period is "custom".');+ }+ return { period: normalized };+ }+ if (!startDate || !endDate) {+ throw new Error('Start date and end date are both required when the period is "custom".');+ }+ const start = toApiDate({ value: startDate, label: 'Start date' });+ const end = toApiDate({ value: endDate, label: 'End date' });+ if (start > end) {+ throw new Error('Start date must not be after end date.');+ }+ return { period: normalized, startDate: start, endDate: end };+}++function optionalNumber({ value, label, min, max }: { value: unknown; label: string; min?: number; max?: number }): number | undefined {+ if (value === undefined || value === null || value === '') {+ return undefined;+ }+ const num = typeof value === 'number' ? value : Number(value);+ if (!Number.isFinite(num)) {+ throw new Error(`${label} must be a number.`);+ }+ if ((min !== undefined && num < min) || (max !== undefined && num > max)) {+ throw new Error(`${label} must be between ${min ?? '-∞'} and ${max ?? '∞'}.`);+ }+ return num;+}++function stringList(value: unknown): string[] {+ if (value === undefined || value === null || value === '') {+ return [];+ }+ const items = Array.isArray(value) ? value : String(value).split(',');+ return items.map((item) => (typeof item === 'string' ? item.trim() : typeof item === 'number' ? String(item) : '')).filter((item) => item !== '');+}++function compact(record: Record<string, unknown>): Record<string, unknown> {+ return Object.fromEntries(Object.entries(record).filter(([, value]) => value !== undefined && value !== null && value !== ''));+}++export const shortIoValues = {+ ttlSecondsToDeleteAt,+ deleteAtToIso,+ toIsoDateTime,+ toApiDate,+ normalizePeriod,+ validateTimezone,+ statsRange,+ optionalNumber,+ stringList,+ compact,+ PERIODS,+};diff --git a/packages/pieces/community/short-io/src/lib/triggers/new-link-created.ts b/packages/pieces/community/short-io/src/lib/triggers/new-link-created.tsindex c08639000f1..190825017f7 100644--- a/packages/pieces/community/short-io/src/lib/triggers/new-link-created.ts+++ b/packages/pieces/community/short-io/src/lib/triggers/new-link-created.ts@@ -1,10 +1,187 @@-import { createTrigger, TriggerStrategy, Property } from '@activepieces/pieces-framework';-import { HttpMethod } from '@activepieces/pieces-common';+import { createTrigger, Property, Store, TriggerStrategy } from '@activepieces/pieces-framework';import { shortIoAuth } from '../common/auth';-import { shortIoApiCall } from '../common/client';+import { ShortIoAuthValue } from '../common/client';+import { shortIoLinkQueries } from '../common/link-queries';+import { shortIoLinks, ShortIoDomainRef } from '../common/links';+import { shortIoSchemas } from '../common/output-schemas';import { domainIdDropdown } from '../common/props';-const LAST_LINK_IDS_KEY = 'shortio-last-link-ids';+const LEGACY_IDS_KEY = 'shortio-last-link-ids';+const STATE_KEY = 'shortio-new-links-v3';+const PAGE_SIZE = 150;+const MAX_PAGES = 10;+const DEEP_SCAN_PAGES = 20;+const SEEN_LIMIT = 5000;+const UPDATED_AT_MARGIN_MS = 5 * 60 * 1000;+const TEST_SAMPLE_SIZE = 5;++function timeMs({ link, key }: { link: Record<string, unknown>; key: string }): number {+ const value = link[key];+ if (typeof value === 'number') {+ return value;+ }+ return typeof value === 'string' ? Date.parse(value) : NaN;+}++function linkId(link: Record<string, unknown>): string {+ return String(link['idString'] ?? link['id'] ?? '');+}++function idOrderKey(id: string): string {+ const parts = id.split('_');+ return parts.length >= 3 ? parts.slice(2).join('_') : id;+}++function maxOrderKey(ids: string[]): string | null {+ return ids.map(idOrderKey).reduce<string | null>((max, key) => (max === null || key > max ? key : max), null);+}++function createdAfterBaseline({ link, state }: { link: Record<string, unknown>; state: PollState }): boolean {+ const idIsNewer = state.baselineMaxKey === null || idOrderKey(linkId(link)) > state.baselineMaxKey;+ return idIsNewer || timeMs({ link, key: 'createdAt' }) >= state.baselineAt;+}++function backdatedSinceLastPoll({ link, state }: { link: Record<string, unknown>; state: PollState }): boolean {+ const idIsNewer = state.baselineMaxKey !== null && idOrderKey(linkId(link)) > state.baselineMaxKey;+ const updatedAt = timeMs({ link, key: 'updatedAt' });+ return idIsNewer && updatedAt >= state.baselineAt && updatedAt >= state.lastPollAt - UPDATED_AT_MARGIN_MS;+}++function toEvent({ link, domain }: { link: Record<string, unknown>; domain: ShortIoDomainRef }): Record<string, unknown> {+ return {+ id: linkId(link),+ originalURL: link['originalURL'],+ shortURL: link['shortURL'],+ secureShortURL: link['secureShortURL'],+ title: link['title'],+ path: link['path'],+ createdAt: link['createdAt'],+ updatedAt: link['updatedAt'],+ tags: link['tags'],+ redirectType: link['redirectType'],+ domainId: link['DomainId'] ?? link['domainId'],+ folderId: link['FolderId'],+ ownerId: link['OwnerId'],+ hasPassword: link['hasPassword'],+ cloaking: link['cloaking'],+ expiresAt: link['expiresAt'],+ expiredURL: link['expiredURL'],+ clicksLimit: link['clicksLimit'],+ archived: link['archived'],+ utmSource: link['utmSource'],+ utmMedium: link['utmMedium'],+ utmCampaign: link['utmCampaign'],+ utmTerm: link['utmTerm'],+ utmContent: link['utmContent'],+ androidURL: link['androidURL'],+ iphoneURL: link['iphoneURL'],+ triggerInfo: {+ source: 'short.io',+ type: 'new_link_created',+ detectedAt: new Date().toISOString(),+ domain: domain.hostname,+ },+ raw: link,+ };+}++async function newestLinks({ auth, domain, limit }: { auth: ShortIoAuthValue; domain: ShortIoDomainRef; limit: number }): Promise<Record<string, unknown>[]> {+ const page = await shortIoLinkQueries.listPage({ auth, domainId: domain.id, query: { limit, dateSortOrder: 'desc' } });+ return page.links;+}++async function scan({ auth, domain, seen, startToken, maxPages, stopWhenSeen, accept, order = 'desc' }: {+ auth: ShortIoAuthValue;+ order?: 'asc' | 'desc';+ domain: ShortIoDomainRef;+ seen: Set<string>;+ startToken: string | undefined;+ maxPages: number;+ stopWhenSeen: boolean;+ accept: (link: Record<string, unknown>) => boolean;+}): Promise<ScanResult> {+ const found: Record<string, unknown>[] = [];+ const pageIds: string[] = [];+ let pageToken = startToken;+ let count: number | null = null;+ for (let page = 0; page < maxPages; page++) {+ const result = await shortIoLinkQueries.listPage({+ auth,+ domainId: domain.id,+ query: { limit: PAGE_SIZE, dateSortOrder: order, pageToken },+ });+ count = count ?? result.count;+ pageIds.push(...result.links.map(linkId));+ const fresh = result.links.filter((link) => !seen.has(linkId(link)) && accept(link));+ found.push(...fresh);+ pageToken = result.nextPageToken ?? undefined;+ if (!pageToken || (stopWhenSeen && fresh.length === 0)) {+ return { found, pageIds, nextToken: pageToken ?? null, exhausted: pageToken === undefined, stoppedOnSeenPage: fresh.length === 0, count };+ }+ }+ return { found, pageIds, nextToken: pageToken ?? null, exhausted: false, stoppedOnSeenPage: false, count };+}++async function baseline({ auth, domain, store }: { auth: ShortIoAuthValue; domain: ShortIoDomainRef; store: Store }): Promise<PollState> {+ const result = await scan({ auth, domain, seen: new Set(), startToken: undefined, maxPages: MAX_PAGES, stopWhenSeen: false, accept: () => true });+ const oldest = result.exhausted+ ? null+ : await scan({ auth, domain, seen: new Set(result.pageIds), startToken: undefined, maxPages: MAX_PAGES, stopWhenSeen: false, accept: () => true, order: 'asc' });+ const now = Date.now();+ const ids = [...result.found, ...(oldest?.found ?? [])].map(linkId);+ const state: PollState = { seen: ids.slice(0, SEEN_LIMIT), lastCount: result.count, lastPollAt: now, resumeToken: null, baselineAt: now, baselineMaxKey: maxOrderKey(ids) };+ await store.put<PollState>(STATE_KEY, state);+ return state;+}++async function pollNewLinks({ auth, domain, store }: { auth: ShortIoAuthValue; domain: ShortIoDomainRef; store: Store }): Promise<Record<string, unknown>[]> {+ const state = await store.get<PollState>(STATE_KEY);+ if (!state || typeof state.baselineAt !== 'number') {+ return migrateFromLegacy({ auth, domain, store });+ }+ const now = Date.now();+ const seen = new Set(state.seen);+ const top = await scan({ auth, domain, seen, startToken: undefined, maxPages: MAX_PAGES, stopWhenSeen: true, accept: (link) => createdAfterBaseline({ link, state }) });+ top.found.forEach((link) => seen.add(linkId(link)));+ const resumed = state.resumeToken+ ? await scan({ auth, domain, seen, startToken: state.resumeToken, maxPages: MAX_PAGES, stopWhenSeen: false, accept: (link) => createdAfterBaseline({ link, state }) })+ : null;+ resumed?.found.forEach((link) => seen.add(linkId(link)));+ const resumeToken = !top.stoppedOnSeenPage && !top.exhausted ? top.nextToken : resumed && !resumed.exhausted ? resumed.nextToken : null;+ const foundSoFar = top.found.length + (resumed?.found.length ?? 0);+ const growth = top.count !== null && state.lastCount !== null ? top.count - state.lastCount : 0;+ const deep =+ growth > foundSoFar && resumeToken === null && top.nextToken+ ? await scan({+ auth,+ domain,+ seen,+ startToken: top.nextToken,+ maxPages: DEEP_SCAN_PAGES,+ stopWhenSeen: false,+ accept: (link) => backdatedSinceLastPoll({ link, state }),+ })+ : null;+ const emitted = [...top.found, ...(resumed?.found ?? []), ...(deep?.found ?? [])];+ const unique = [...new Map(emitted.map((link) => [linkId(link), link])).values()].sort(+ (a, b) => timeMs({ link: a, key: 'updatedAt' }) - timeMs({ link: b, key: 'updatedAt' }),+ );+ const nextSeen = [...new Set([...top.pageIds, ...unique.map(linkId).reverse(), ...state.seen])].slice(0, SEEN_LIMIT);+ await store.put<PollState>(STATE_KEY, { ...state, seen: nextSeen, lastCount: top.count ?? state.lastCount, lastPollAt: now, resumeToken });+ return unique;+}++async function migrateFromLegacy({ auth, domain, store }: { auth: ShortIoAuthValue; domain: ShortIoDomainRef; store: Store }): Promise<Record<string, unknown>[]> {+ const legacyIds = await store.get<string[]>(LEGACY_IDS_KEY);+ const links = await newestLinks({ auth, domain, limit: PAGE_SIZE });+ await baseline({ auth, domain, store });+ if (!legacyIds) {+ return [];+ }+ await store.delete(LEGACY_IDS_KEY);+ const known = new Set(legacyIds);+ return links.filter((link) => !known.has(linkId(link))).reverse();+}export const newLinkCreatedTrigger = createTrigger({auth: shortIoAuth,@@ -13,10 +190,11 @@ export const newLinkCreatedTrigger = createTrigger({displayName: 'New Link Created',description: 'Fires when a new short link is created on a domain. Useful to sync newly created links to other systems.',aiMetadata: {- description: 'Fires when a new short link appears on the selected Short.io domain, detected by polling the domain\'s link list on a configurable interval. Each event represents one newly created link with its details. Use to kick off a workflow whenever someone creates a link on the domain.',+ description:+ "Fires once for each new short link created on the selected Short.io domain, detected by polling the domain's link list. Each event is one link (short URL, original URL, path, title, tags); the link password is never included.",},type: TriggerStrategy.POLLING,-+ outputSchema: shortIoSchemas.trigger,props: {domain: {...domainIdDropdown,@@ -25,8 +203,8 @@ export const newLinkCreatedTrigger = createTrigger({},pollingInterval: Property.StaticDropdown({displayName: 'Polling Interval',- description: 'How often to check for new links. More frequent polling may hit rate limits.',- required: true,+ description: 'Not used: Activepieces sets the polling schedule. Kept so existing flows keep working.',+ required: false,defaultValue: '5',options: {disabled: false,@@ -40,200 +218,25 @@ export const newLinkCreatedTrigger = createTrigger({},}),},-async onEnable(context) {- const { domain: domainString } = context.propsValue;-- if (!domainString) {- throw new Error('Domain is required. Please select a domain.');- }-- const domainObject = JSON.parse(domainString as string);- const domainId = domainObject.id;-- try {- const response = await shortIoApiCall<{ links: ShortIoLink[] }>({- auth: context.auth,- method: HttpMethod.GET,- resourceUri: `/api/links`,- query: {- domain_id: domainId,- limit: 100,- dateSortOrder: 'desc',- },- });-- const currentIds = (response.links || []).map((link) => link.idString);- await context.store.put<string[]>(LAST_LINK_IDS_KEY, currentIds);- } catch (error: any) {- throw new Error(`Failed to initialize trigger: ${error.message}`);- }+ const domain = shortIoLinks.parseDomainProp(context.propsValue.domain);+ await context.store.delete(LEGACY_IDS_KEY);+ await baseline({ auth: context.auth, domain, store: context.store });},-- async onDisable() {- // No-op+ async onDisable(context) {+ await context.store.delete(STATE_KEY);+ await context.store.delete(LEGACY_IDS_KEY);},-async run(context) {- const { domain: domainString } = context.propsValue;-- if (!domainString) {- throw new Error('Domain is required. Please select a domain.');- }-- const domainObject = JSON.parse(domainString as string);- const domainId = domainObject.id;-- const previousIds = await context.store.get<string[]>(LAST_LINK_IDS_KEY) || [];-- try {- const response = await shortIoApiCall<{ links: ShortIoLink[] }>({- auth: context.auth,- method: HttpMethod.GET,- resourceUri: `/api/links`,- query: {- domain_id: domainId,- limit: 100,- dateSortOrder: 'desc',- },- });-- const allLinks = response.links || [];- const currentIds = allLinks.map((link) => link.idString);-- await context.store.put<string[]>(LAST_LINK_IDS_KEY, currentIds);-- const newLinks = allLinks.filter((link) => !previousIds.includes(link.idString));-- return newLinks.map((link) => ({- id: link.idString,- originalURL: link.originalURL,- shortURL: link.shortURL,- secureShortURL: link.secureShortURL,- title: link.title,- path: link.path,- createdAt: link.createdAt,- updatedAt: link.updatedAt,- tags: link.tags,- redirectType: link.redirectType,- domainId: link.DomainId || link.domainId,- folderId: link.FolderId,- ownerId: link.OwnerId,- hasPassword: link.hasPassword,- cloaking: link.cloaking,- password: link.password,- expiresAt: link.expiresAt,- expiredURL: link.expiredURL,- clicksLimit: link.clicksLimit,- archived: link.archived,- utmSource: link.utmSource,- utmMedium: link.utmMedium,- utmCampaign: link.utmCampaign,- utmTerm: link.utmTerm,- utmContent: link.utmContent,- androidURL: link.androidURL,- iphoneURL: link.iphoneURL,- triggerInfo: {- source: 'short.io',- type: 'new_link_created',- detectedAt: new Date().toISOString(),- domain: domainObject.hostname,- },- raw: link,- }));- } catch (error: any) {- if (error.message.includes('403')) {- throw new Error(`Access denied to domain. Please check your API key permissions for domain: ${domainObject.hostname}`);- }-- if (error.message.includes('404')) {- throw new Error(`Domain not found: ${domainObject.hostname}. Please verify the domain exists.`);- }-- if (error.message.includes('429')) {- throw new Error('Rate limit exceeded. Consider increasing the polling interval.');- }-- throw new Error(`Failed to check for new links: ${error.message}`);- }+ const domain = shortIoLinks.parseDomainProp(context.propsValue.domain);+ const links = await pollNewLinks({ auth: context.auth, domain, store: context.store });+ return links.map((link) => toEvent({ link, domain }));},-async test(context) {- const { domain: domainString } = context.propsValue;-- if (!domainString) {- throw new Error('Domain is required. Please select a domain.');- }-- const domainObject = JSON.parse(domainString as string);- const domainId = domainObject.id;-- try {- const response = await shortIoApiCall<{ links: ShortIoLink[] }>({- auth: context.auth,- method: HttpMethod.GET,- resourceUri: `/api/links`,- query: {- domain_id: domainId,- limit: 1,- dateSortOrder: 'desc',- },- });-- const link = response.links?.[0];- if (link) {- return [{- id: link.idString,- originalURL: link.originalURL,- shortURL: link.shortURL,- secureShortURL: link.secureShortURL,- title: link.title,- path: link.path,- createdAt: link.createdAt,- updatedAt: link.updatedAt,- tags: link.tags,- redirectType: link.redirectType,- domainId: link.DomainId || link.domainId,- folderId: link.FolderId,- ownerId: link.OwnerId,- hasPassword: link.hasPassword,- cloaking: link.cloaking,- password: link.password,- expiresAt: link.expiresAt,- expiredURL: link.expiredURL,- clicksLimit: link.clicksLimit,- archived: link.archived,- utmSource: link.utmSource,- utmMedium: link.utmMedium,- utmCampaign: link.utmCampaign,- utmTerm: link.utmTerm,- utmContent: link.utmContent,- androidURL: link.androidURL,- iphoneURL: link.iphoneURL,- triggerInfo: {- source: 'short.io',- type: 'new_link_created',- detectedAt: new Date().toISOString(),- domain: domainObject.hostname,- },- raw: link,- }];- }-- return [];- } catch (error: any) {- if (error.message.includes('403')) {- throw new Error(`Access denied to domain. Please check your API key permissions for domain: ${domainObject.hostname}`);- }-- if (error.message.includes('404')) {- throw new Error(`Domain not found: ${domainObject.hostname}. Please verify the domain exists.`);- }-- throw new Error(`Failed to test trigger: ${error.message}`);- }+ const domain = shortIoLinks.parseDomainProp(context.propsValue.domain);+ const links = await newestLinks({ auth: context.auth, domain, limit: TEST_SAMPLE_SIZE });+ return links.map((link) => toEvent({ link, domain }));},-sampleData: {id: 'lnk_61Mb_0dnRUg3vvtmAPZh3dhQh6',originalURL: 'https://example.com/page',@@ -250,7 +253,6 @@ export const newLinkCreatedTrigger = createTrigger({ownerId: 789,hasPassword: false,cloaking: false,- password: null,expiresAt: null,expiredURL: null,clicksLimit: null,@@ -272,50 +274,13 @@ export const newLinkCreatedTrigger = createTrigger({},});-interface ShortIoLink {- idString: string;- id: string;- originalURL: string;- shortURL: string;- secureShortURL: string;- title?: string;- path: string;- createdAt: string;- updatedAt?: string;- tags: string[];- redirectType?: number;- DomainId?: number;- domainId?: number;- FolderId?: string | null;- OwnerId?: number;- hasPassword?: boolean;- cloaking?: boolean;- password?: string | null;- expiresAt?: string | number | null;- expiredURL?: string | null;- clicksLimit?: number | null;- passwordContact?: boolean | null;- skipQS?: boolean;- archived?: boolean;- splitURL?: string | null;- splitPercent?: number | null;- utmSource?: string;- utmMedium?: string;- utmCampaign?: string;- utmTerm?: string;- utmContent?: string;- ttl?: string | number | null;- androidURL?: string | null;- iphoneURL?: string | null;- integrationAdroll?: string | null;- integrationFB?: string | null;- integrationGA?: string | null;- integrationGTM?: string | null;- User?: {- id: number;- name: string | null;- email: string;- photoURL: string | null;- };- [key: string]: any;-}+type PollState = {+ seen: string[];+ lastCount: number | null;+ lastPollAt: number;+ resumeToken: string | null;+ baselineAt: number;+ baselineMaxKey: string | null;+};++type ScanResult = { found: Record<string, unknown>[]; pageIds: string[]; nextToken: string | null; exhausted: boolean; stoppedOnSeenPage: boolean; count: number | null };diff --git a/packages/pieces/community/short-io/test/client.test.ts b/packages/pieces/community/short-io/test/client.test.tsnew file mode 100644index 00000000000..078c6de74a9--- /dev/null+++ b/packages/pieces/community/short-io/test/client.test.ts@@ -0,0 +1,77 @@+import { afterEach, describe, expect, test, vi } from 'vitest';+import { shortIoAuth } from '../src/lib/common/auth';+import { shortIoClient, ShortIoApiError } from '../src/lib/common/client';+import { API_KEY, replies, stubFetch } from './helpers';+import { HttpMethod } from '@activepieces/pieces-common';++const auth = { props: { apiKey: ` ${API_KEY} ` } };++afterEach(() => {+ vi.unstubAllGlobals();+ vi.useRealTimers();+});++describe('client', () => {+ test('seg encodes and rejects dot segments', () => {+ expect(shortIoClient.seg({ value: '../domains/settings/1', label: 'Link ID' })).toBe('..%2Fdomains%2Fsettings%2F1');+ expect(() => shortIoClient.seg({ value: '..', label: 'Link ID' })).toThrow('Link ID is required');+ expect(() => shortIoClient.seg({ value: ' ', label: 'Link ID' })).toThrow();+ expect(() => shortIoClient.domainIdSeg('12/../3')).toThrow('Domain ID must be a number');+ expect(shortIoClient.domainIdSeg(42)).toBe('42');+ });+ test('sends the raw trimmed key and parses the vendor error field into responseBody', async () => {+ const seen = stubFetch(replies([{ status: 404, body: { error: 'Domain not found' } }]));+ const error = await shortIoClient.request({ auth, method: HttpMethod.GET, path: '/links/x' }).catch((e: unknown) => e);+ expect(seen[0].headers.get('authorization')).toBe(API_KEY);+ expect(seen[0].url.origin).toBe('https://api.short.io');+ expect(error).toBeInstanceOf(ShortIoApiError);+ expect(error).toMatchObject({ status: 404, responseBody: { error: 'Domain not found' } });+ expect(error).not.toHaveProperty('body');+ expect(String(error)).toContain('Domain not found');+ });+ test('status mapping uses the status, not text in the message', async () => {+ stubFetch(replies([{ status: 500, body: { message: 'path 404-page broke' } }]));+ const error = await shortIoClient.request({ auth, method: HttpMethod.GET, path: '/x' }).catch((e: unknown) => e);+ expect(() => shortIoClient.rethrowWithHint({ error, hints: { 404: 'not found hint' } })).toThrow('path 404-page broke');+ expect(() => shortIoClient.rethrowWithHint({ error, hints: { 404: 'not found hint' } })).not.toThrow('not found hint');+ });+ test('retries 429 at most twice', async () => {+ vi.useFakeTimers();+ const seen = stubFetch(replies([{ status: 429, headers: { 'retry-after': '1' } }, { status: 429 }, { status: 429, body: { error: 'slow down' } }]));+ const promise = shortIoClient.request({ auth, method: HttpMethod.GET, path: '/x' }).catch((e: unknown) => e);+ await vi.runAllTimersAsync();+ expect(await promise).toMatchObject({ status: 429 });+ expect(seen).toHaveLength(3);+ });+ test('stats requests go to statistics.short.io', async () => {+ const seen = stubFetch(replies([{ body: {} }]));+ await shortIoClient.request({ auth, method: HttpMethod.GET, base: 'stats', path: '/domain/1', query: { period: 'last7', tz: undefined } });+ expect(seen[0].url.toString()).toBe('https://statistics.short.io/statistics/domain/1?period=last7');+ });+});++describe('auth.validate', () => {+ test('401 is invalid key, 500 is a reachability error', async () => {+ stubFetch(replies([{ status: 401, body: { error: 'Unauthorized' } }]));+ expect(await shortIoAuth.validate?.({ auth: { apiKey: 'bad' }, server: { apiUrl: '', publicUrl: '', mintOidcToken: async () => '' } })).toMatchObject({ valid: false, error: expect.stringContaining('Invalid API Key') });+ stubFetch(replies([{ status: 500, body: { error: 'Upstream service error' } }]));+ const result = await shortIoAuth.validate?.({ auth: { apiKey: 'k' }, server: { apiUrl: '', publicUrl: '', mintOidcToken: async () => '' } });+ expect(result).toMatchObject({ valid: false });+ expect(JSON.stringify(result)).toContain('Upstream service error');+ });+});++describe('secret bodies', () => {+ test('a request carrying a link password is never logged on failure', async () => {+ const logged = vi.spyOn(console, 'error').mockImplementation(() => undefined);+ stubFetch(replies([{ status: 400, body: { message: 'bad' } }]));+ await expect(shortIoClient.request({ auth, method: HttpMethod.POST, path: '/links', body: { originalURL: 'https://a.b', password: 'hunter2' } })).rejects.toThrow('bad');+ expect(JSON.stringify(logged.mock.calls)).not.toContain('hunter2');+ logged.mockRestore();+ });+ test('a request without a password goes through httpClient and keeps the redirect off', async () => {+ const seen = stubFetch(replies([{ status: 302, body: {} }]));+ await expect(shortIoClient.request({ auth, method: HttpMethod.GET, path: '/api/domains' })).rejects.toThrow('302');+ expect(seen).toHaveLength(1);+ });+});diff --git a/packages/pieces/community/short-io/test/follow-up-actions.test.ts b/packages/pieces/community/short-io/test/follow-up-actions.test.tsnew file mode 100644index 00000000000..5e1ee71e848--- /dev/null+++ b/packages/pieces/community/short-io/test/follow-up-actions.test.ts@@ -0,0 +1,56 @@+import { afterEach, describe, expect, test, vi } from 'vitest';+import { duplicateLinkAction } from '../src/lib/actions/duplicate-link';+import { getFolderAction } from '../src/lib/actions/get-folder';+import { getLinkOpenGraphAction } from '../src/lib/actions/get-link-open-graph';+import { DOMAINS, link, run, stubFetch } from './helpers';++afterEach(() => vi.unstubAllGlobals());++describe('duplicate_link', () => {+ test('posts to /links/duplicate/{id} with the optional slug and scrubs the copy', async () => {+ const seen = stubFetch(() => ({ body: link({ idString: 'link_new_1', duplicatedFrom: 'link_a_b', path: 'promo-email' }) }));+ const result = await run({ action: duplicateLinkAction, props: { linkId: 'link_a_b', path: '/promo-email' } });+ expect(seen[0].method).toBe('POST');+ expect(seen[0].url.pathname).toBe('/links/duplicate/link_a_b');+ expect(seen[0].body).toEqual({ path: 'promo-email' });+ expect(result).toMatchObject({ idString: 'link_new_1', duplicatedFrom: 'link_a_b', linkId: 'link_new_1' });+ expect(JSON.stringify(result)).not.toContain('hunter2');+ });+ test('sends an empty body without a slug and encodes the ID', async () => {+ const seen = stubFetch(() => ({ body: link() }));+ await run({ action: duplicateLinkAction, props: { linkId: '../x' } });+ expect(seen[0].url.pathname).toBe('/links/duplicate/..%2Fx');+ expect(seen[0].body).toEqual({});+ });+});++describe('get_folder', () => {+ test('returns the folder, or found=false when Short.io answers null', async () => {+ const seen = stubFetch((request) =>+ request.url.pathname === '/api/domains' ? { body: DOMAINS } : request.url.pathname.endsWith('/f1') ? { body: { id: 'f1', DomainId: 101, name: 'Promo' } } : { raw: new TextEncoder().encode('null') },+ );+ expect(await run({ action: getFolderAction, props: { domain: 'go.example.com', folderId: 'f1' } })).toEqual({ found: true, folder: { id: 'f1', name: 'Promo', domainId: 101 } });+ expect(seen[1].url.pathname).toBe('/links/folders/101/f1');+ expect(await run({ action: getFolderAction, props: { domain: '101', folderId: 'nope' } })).toEqual({ found: false, folder: null });+ });+});++describe('get_link_open_graph', () => {+ test('turns [property, value] pairs into a map and a list', async () => {+ const seen = stubFetch((request) =>+ request.url.pathname === '/api/domains' ? { body: DOMAINS } : { body: [['title', 'Spring sale'], ['image', 'https://x.io/a.png'], ['bad']] },+ );+ const result = await run({ action: getLinkOpenGraphAction, props: { domain: 'go.example.com', linkId: 'link_a_b' } });+ expect(seen[1].url.pathname).toBe('/links/opengraph/101/link_a_b');+ expect(result).toEqual({+ linkId: 'link_a_b',+ properties: { title: 'Spring sale', image: 'https://x.io/a.png' },+ items: [{ property: 'title', value: 'Spring sale' }, { property: 'image', value: 'https://x.io/a.png' }],+ count: 2,+ });+ });+ test('empty array when nothing is set', async () => {+ stubFetch((request) => (request.url.pathname === '/api/domains' ? { body: DOMAINS } : { body: [] }));+ expect(await run({ action: getLinkOpenGraphAction, props: { domain: 'go.example.com', linkId: 'link_a_b' } })).toEqual({ linkId: 'link_a_b', properties: {}, items: [], count: 0 });+ });+});diff --git a/packages/pieces/community/short-io/test/helpers.ts b/packages/pieces/community/short-io/test/helpers.tsnew file mode 100644index 00000000000..86e44f29c58--- /dev/null+++ b/packages/pieces/community/short-io/test/helpers.ts@@ -0,0 +1,98 @@+import { AppConnectionType, Store } from '@activepieces/pieces-framework';+import { vi } from 'vitest';++export type SeenRequest = { url: URL; method: string; headers: Headers; body: unknown };+export type FakeReply = { status?: number; body?: unknown; raw?: Uint8Array; headers?: Record<string, string> };++export function stubFetch(respond: (request: SeenRequest, index: number) => FakeReply): SeenRequest[] {+ const seen: SeenRequest[] = [];+ vi.stubGlobal(+ 'fetch',+ vi.fn(async (input: string | URL, init?: RequestInit) => {+ const request: SeenRequest = {+ url: new URL(String(input)),+ method: (init?.method ?? 'GET').toUpperCase(),+ headers: new Headers(init?.headers),+ body: typeof init?.body === 'string' ? JSON.parse(init.body) : null,+ };+ seen.push(request);+ const reply = respond(request, seen.length - 1);+ const status = reply.status ?? 200;+ const payload = reply.raw ?? (status === 204 ? null : JSON.stringify(reply.body ?? {}));+ return new Response(payload, { status, headers: { 'content-type': 'application/json', ...(reply.headers ?? {}) } });+ }),+ );+ return seen;+}++export function replies(list: FakeReply[]): (request: SeenRequest, index: number) => FakeReply {+ return (_request, index) => list[Math.min(index, list.length - 1)];+}++export const API_KEY = 'sk_test_key';+export const DOMAINS = [+ { id: 101, hostname: 'go.example.com', unicodeHostname: 'go.example.com', segmentKey: 'secret' },+ { id: 202, hostname: 'links.acme.io', unicodeHostname: 'links.acme.io' },+];+export const DOMAIN_PROP = JSON.stringify({ id: 101, hostname: 'go.example.com' });++export function memoryStore(initial: Record<string, unknown> = {}): Store & { read: (key: string) => unknown } {+ const data = new Map<string, string>(Object.entries(initial).map(([key, value]) => [key, JSON.stringify(value)]));+ return {+ read: (key: string): unknown => {+ const raw = data.get(key);+ return raw === undefined ? undefined : JSON.parse(raw);+ },+ put: async <T>(key: string, value: T): Promise<T> => {+ data.set(key, JSON.stringify(value));+ return value;+ },+ get: async <T>(key: string): Promise<T | null> => {+ const raw = data.get(key);+ return raw === undefined ? null : JSON.parse(raw);+ },+ delete: async (key: string): Promise<void> => {+ data.delete(key);+ },+ };+}++export function testContext(propsValue: Record<string, unknown>): TestContext {+ return {+ auth: { type: AppConnectionType.CUSTOM_AUTH, props: { apiKey: API_KEY } },+ propsValue,+ store: memoryStore(),+ files: { write: async ({ fileName }: { fileName: string }): Promise<string> => `file://${fileName}` },+ server: { apiUrl: 'http://localhost:3000/api/', publicUrl: 'http://localhost:4200/', token: 'x' },+ };+}++export function run({ action, props }: { action: Runnable; props: Record<string, unknown> }): Promise<unknown> {+ return action.run(testContext(props));+}++export function link(overrides: Record<string, unknown> = {}): Record<string, unknown> {+ return {+ idString: 'lnk_abc_123',+ id: '123',+ originalURL: 'https://example.com/a',+ shortURL: 'https://go.example.com/a',+ secureShortURL: 'https://go.example.com/a',+ path: 'a',+ password: 'hunter2',+ hasPassword: true,+ createdAt: '2026-10-01T10:00:00.000Z',+ DomainId: 101,+ ...overrides,+ };+}++export type TestContext = {+ auth: { type: AppConnectionType.CUSTOM_AUTH; props: { apiKey: string } };+ propsValue: Record<string, unknown>;+ store: Store;+ files: { write: (input: { fileName: string; data: Buffer }) => Promise<string> };+ server: { apiUrl: string; publicUrl: string; token: string };+};++type Runnable = { run(context: TestContext): Promise<unknown> };diff --git a/packages/pieces/community/short-io/test/links.test.ts b/packages/pieces/community/short-io/test/links.test.tsnew file mode 100644index 00000000000..0285ff2d85c--- /dev/null+++ b/packages/pieces/community/short-io/test/links.test.ts@@ -0,0 +1,110 @@+import { afterEach, describe, expect, test, vi } from 'vitest';+import { createShortLinkAction } from '../src/lib/actions/create-short-link';+import { updateShortLinkAction } from '../src/lib/actions/update-short-link';+import { domainStatisticsAction } from '../src/lib/actions/domain-statistics';+import { createLinkAiAction } from '../src/lib/actions/ai/create-link';+import { findLinkByPathAiAction } from '../src/lib/actions/ai/find-link-by-path';+import { shortIoValues } from '../src/lib/common/values';+import { DOMAIN_PROP, DOMAINS, link, replies, run, stubFetch } from './helpers';++const NOW = Date.parse('2026-10-12T00:00:00.000Z');++afterEach(() => {+ vi.unstubAllGlobals();+ vi.useRealTimers();+});++describe('TTL (P1-1)', () => {+ test('converts seconds to an absolute deletion time', () => {+ expect(shortIoValues.ttlSecondsToDeleteAt({ seconds: 8 * 86400, now: NOW })).toBe('2026-10-20T00:00:00.000Z');+ });+ test('rejects less than 7 days instead of sending a 1970 timestamp', () => {+ expect(() => shortIoValues.ttlSecondsToDeleteAt({ seconds: 86400, now: NOW })).toThrow('at least 604800 seconds');+ });+ test('create-short-link sends ttl as ISO time from now, never ttl*1000', async () => {+ vi.useFakeTimers({ now: NOW, toFake: ['Date'] });+ const seen = stubFetch(replies([{ body: link() }]));+ await run({ action: createShortLinkAction, props: { domain: DOMAIN_PROP, originalURL: 'https://example.com/a', ttl: 8 * 86400, clicksLimit: 0 } }).catch(() => undefined);+ expect(seen).toHaveLength(0);+ await run({ action: createShortLinkAction, props: { domain: DOMAIN_PROP, originalURL: 'https://example.com/a', ttl: 8 * 86400 } });+ expect(seen[0].body).toMatchObject({ domain: 'go.example.com', originalURL: 'https://example.com/a', ttl: '2026-10-20T00:00:00.000Z' });+ });+ test('AI create_link deleteAt must be 7+ days ahead', async () => {+ vi.useFakeTimers({ now: NOW, toFake: ['Date'] });+ stubFetch(replies([{ body: DOMAINS }, { body: link() }]));+ await expect(run({ action: createLinkAiAction, props: { domain: 'go.example.com', originalURL: 'https://example.com', deleteAt: '2026-10-13T00:00:00Z' } })).rejects.toThrow('at least 7 days');+ });+});++describe('password scrub (P1-2) and path encoding (P1-3)', () => {+ test('create returns the link without password', async () => {+ stubFetch(replies([{ body: link() }]));+ const result = await run({ action: createShortLinkAction, props: { domain: DOMAIN_PROP, originalURL: 'https://example.com/a', password: 'hunter2' } });+ expect(JSON.stringify(result)).not.toContain('hunter2');+ expect(result).toMatchObject({ success: true, data: { idString: 'lnk_abc_123', linkId: 'lnk_abc_123', hasPassword: true } });+ });+ test('update encodes link ID and passes domain_id', async () => {+ const seen = stubFetch(replies([{ body: link() }]));+ await run({ action: updateShortLinkAction, props: { domain: DOMAIN_PROP, linkId: '../domains/settings/1', title: 'x' } });+ expect(seen[0].url.pathname).toBe('/links/..%2Fdomains%2Fsettings%2F1');+ expect(seen[0].url.searchParams.get('domain_id')).toBe('101');+ expect(seen[0].body).toEqual({ title: 'x' });+ });+ test('clicksLimit 0 is rejected, not silently dropped', async () => {+ stubFetch(replies([{ body: link() }]));+ await expect(run({ action: updateShortLinkAction, props: { domain: DOMAIN_PROP, linkId: 'lnk_a_b', clicksLimit: 0 } })).rejects.toThrow('Clicks limit');+ });+});++describe('statistics', () => {+ test('legacy thisMonth maps to month and dates keep the picked day', async () => {+ const seen = stubFetch(replies([{ body: { clicks: 3, links: 1 } }]));+ await run({ action: domainStatisticsAction, props: { domainId: DOMAIN_PROP, period: 'thisMonth' } });+ expect(seen[0].url.searchParams.get('period')).toBe('month');+ await run({ action: domainStatisticsAction, props: { domainId: DOMAIN_PROP, period: 'custom', startDate: '2026-10-01T23:30:00-05:00', endDate: '2026-10-05', tz: 'America/Chicago' } });+ expect(seen[1].url.searchParams.get('startDate')).toBe('2026-10-01');+ expect(seen[1].url.searchParams.get('tz')).toBe('America/Chicago');+ });+ test('unknown timezone fails before any request', async () => {+ const seen = stubFetch(replies([{ body: {} }]));+ await expect(run({ action: domainStatisticsAction, props: { domainId: DOMAIN_PROP, period: 'last7', tz: 'Mars/Base' } })).rejects.toThrow('Unknown timezone');+ expect(seen).toHaveLength(0);+ });+});++describe('domain resolver and short URL lookup', () => {+ test('resolves hostname from a full short URL and returns found=false on 404', async () => {+ const seen = stubFetch((request) => (request.url.pathname === '/api/domains' ? { body: DOMAINS } : { status: 404, body: { error: 'Link not found' } }));+ const result = await run({ action: findLinkByPathAiAction, props: { shortUrl: 'https://links.acme.io/promo' } });+ expect(result).toEqual({ found: false, link: null });+ expect(seen[1].url.searchParams.get('domain')).toBe('links.acme.io');+ expect(seen[1].url.searchParams.get('path')).toBe('promo');+ });+ test('unknown domain lists known ones', async () => {+ stubFetch(replies([{ body: DOMAINS }]));+ await expect(run({ action: findLinkByPathAiAction, props: { shortUrl: 'promo', domain: 'nope.com' } })).rejects.toThrow('Known domains: go.example.com, links.acme.io');+ });+});++describe('owner photo URL', () => {+ test('presigned User.photoURL is removed from link output', async () => {+ stubFetch(replies([{ body: link({ User: { id: 1, name: 'A', email: '[email protected]', photoURL: 'https://s3/x?X-Amz-Security-Token=t' } }) }]));+ const result = await run({ action: createShortLinkAction, props: { domain: DOMAIN_PROP, originalURL: 'https://example.com/a' } });+ expect(JSON.stringify(result)).not.toContain('X-Amz');+ expect(result).toMatchObject({ data: { User: { id: 1, email: '[email protected]' } } });+ });+});++describe('Greptile follow-ups', () => {+ test('old Domain Statistics ignores leftover dates when a preset period is set', async () => {+ const seen = stubFetch(replies([{ body: { clicks: 1, links: 1 } }]));+ await run({ action: domainStatisticsAction, props: { domainId: DOMAIN_PROP, period: 'last7', startDate: '2026-01-01', endDate: '2026-01-02' } });+ expect(seen[0].url.searchParams.get('period')).toBe('last7');+ expect(seen[0].url.searchParams.get('startDate')).toBeNull();+ });+ test('update-short-link sends tags: [] to clear tags', async () => {+ const seen = stubFetch(replies([{ body: link() }]));+ await run({ action: updateShortLinkAction, props: { domain: DOMAIN_PROP, linkId: 'link_a_b', tags: [] } });+ expect(seen[0].body).toEqual({ tags: [] });+ });+});diff --git a/packages/pieces/community/short-io/test/metadata.test.ts b/packages/pieces/community/short-io/test/metadata.test.tsnew file mode 100644index 00000000000..5569fa2b70d--- /dev/null+++ b/packages/pieces/community/short-io/test/metadata.test.ts@@ -0,0 +1,54 @@+import { describe, expect, test } from 'vitest';+import { shortIo } from '../src';++const actions = Object.values(shortIo.actions());+const nonCustom = actions.filter((action) => action.name !== 'custom_api_call');+const byName = Object.fromEntries(actions.map((action) => [action.name, action]));+const LEGACY_HUMAN = [+ 'create-short-link',+ 'update-short-link',+ 'expire-short-link',+ 'create-country-targeting-rule',+ 'get-short-link-info-by-path',+ 'list-short-links',+ 'get-domain-statistics',+ 'get-link-clicks',+];+const AI_TWINS = ['create_link', 'update_link', 'find_link_by_path', 'list_links', 'delete_link', 'set_country_rule', 'get_domain_statistics'];++describe('piece metadata', () => {+ test('34 actions plus Custom API Call, 1 trigger, 0.88.2', () => {+ expect(nonCustom).toHaveLength(34);+ expect(byName['custom_api_call']).toBeDefined();+ expect(Object.keys(shortIo.triggers())).toEqual(['new_link_created']);+ expect(shortIo.minimumSupportedRelease).toBe('0.88.2');+ });+ test.each(nonCustom.map((action) => [action.name, action]))('%s has 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('8 dropdown actions are human, 7 AI twins are ai, 19 are both', () => {+ expect(nonCustom.filter((action) => action.audience === 'human').map((action) => action.name).sort()).toEqual([...LEGACY_HUMAN].sort());+ expect(nonCustom.filter((action) => action.audience === 'ai').map((action) => action.name).sort()).toEqual([...AI_TWINS].sort());+ expect(nonCustom.filter((action) => action.audience === 'both')).toHaveLength(19);+ });+ test('AI-visible actions have no dynamic dropdowns', () => {+ for (const action of nonCustom.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');+ }+ });+ test('non-idempotent actions are the creating ones', () => {+ expect(nonCustom.filter((action) => action.aiMetadata?.idempotent === false).map((action) => action.name).sort()).toEqual(+ ['create-country-targeting-rule', 'create-short-link', 'create_folder', 'create_link', 'create_links_bulk', 'delete-short-link', 'duplicate_link', 'set_country_rule'].sort(),+ );+ });+ test('trigger has aiMetadata, outputSchema and no password in sample data', () => {+ const trigger = shortIo.triggers()['new_link_created'];+ expect(trigger.outputSchema?.fields.length).toBeGreaterThan(0);+ expect(trigger.sampleData).not.toHaveProperty('password');+ });+});diff --git a/packages/pieces/community/short-io/test/new-actions.test.ts b/packages/pieces/community/short-io/test/new-actions.test.tsnew file mode 100644index 00000000000..4fd70f3c852--- /dev/null+++ b/packages/pieces/community/short-io/test/new-actions.test.ts@@ -0,0 +1,65 @@+import { afterEach, describe, expect, test, vi } from 'vitest';+import { addTagToLinksAction } from '../src/lib/actions/add-tag-to-links';+import { deleteLinkAiAction } from '../src/lib/actions/ai/delete-link';+import { createLinksBulkAction } from '../src/lib/actions/create-links-bulk';+import { generateQrCodeAction } from '../src/lib/actions/generate-qr-code';+import { getLinkAction } from '../src/lib/actions/get-link';+import { getTopLinksAction } from '../src/lib/actions/get-top-links';+import { listDomainsAction } from '../src/lib/actions/list-domains';+import { archiveLinkAction } from '../src/lib/actions/archive-link';+import { deleteShortLinkAction } from '../src/lib/actions/delete-short-link';+import { DOMAINS, link, replies, run, stubFetch } from './helpers';++afterEach(() => vi.unstubAllGlobals());++describe('new actions', () => {+ test('list_domains drops non-schema fields like segmentKey', async () => {+ stubFetch(replies([{ body: DOMAINS }]));+ const result = await run({ action: listDomainsAction, props: {} });+ expect(result).toMatchObject({ count: 2, items: [{ id: 101, hostname: 'go.example.com' }, { id: 202 }] });+ expect(JSON.stringify(result)).not.toContain('secret');+ });+ test('delete_link reports alreadyDeleted on 404; legacy delete still throws', async () => {+ stubFetch(replies([{ status: 404, body: { error: 'Link not found' } }]));+ expect(await run({ action: deleteLinkAiAction, props: { linkId: 'lnk_a_b' } })).toEqual({ linkId: 'lnk_a_b', deleted: false, alreadyDeleted: true });+ await expect(run({ action: deleteShortLinkAction, props: { linkId: 'lnk_a_b' } })).rejects.toThrow('may have already been deleted');+ });+ test('add_tag_to_links sends tag + link_ids and validates IDs first', async () => {+ const seen = stubFetch(replies([{ body: {} }]));+ await expect(run({ action: addTagToLinksAction, props: { tag: 'x', linkIds: ['nope'] } })).rejects.toThrow('not Short.io link IDs');+ expect(seen).toHaveLength(0);+ await run({ action: addTagToLinksAction, props: { tag: ' promo ', linkIds: ['link_a_b', 'link_a_b', 'lnk_c_d'] } });+ expect(seen[0].url.pathname).toBe('/tags/bulk');+ expect(seen[0].body).toEqual({ tag: 'promo', link_ids: ['link_a_b', 'lnk_c_d'] });+ });+ test('generate_qr_code writes the image to a file', async () => {+ const seen = stubFetch(replies([{ raw: new Uint8Array([137, 80, 78, 71]), headers: { 'content-type': 'image/png' } }]));+ const result = await run({ action: generateQrCodeAction, props: { linkId: 'lnk_a_b', size: 10, color: '#ff0000' } });+ expect(seen[0].body).toEqual({ type: 'png', size: 10, color: 'ff0000', useDomainSettings: false });+ expect(result).toMatchObject({ linkId: 'lnk_a_b', format: 'png', fileName: 'qr-lnk_a_b.png', file: 'file://qr-lnk_a_b.png', size: 4 });+ });+ test('create_links_bulk validates, then splits created and failed items', async () => {+ const seen = stubFetch((request) => (request.url.pathname === '/api/domains' ? { body: DOMAINS } : { body: [link({ password: 'p' }), { error: 'bad url' }] }));+ await expect(run({ action: createLinksBulkAction, props: { domain: 'go.example.com', links: [{ originalURL: 'javascript:alert(1)' }] } })).rejects.toThrow('http');+ const result = await run({ action: createLinksBulkAction, props: { domain: '101', links: '[{"originalURL":"https://a.com","password":"p","path":"a"},"https://b.com"]' } });+ const bulk = seen.find((request) => request.url.pathname === '/links/bulk');+ expect(bulk?.body).toEqual({ domain: 'go.example.com', links: [{ originalURL: 'https://a.com', path: 'a' }, { originalURL: 'https://b.com' }], allowDuplicates: false });+ expect(result).toMatchObject({ createdCount: 1, errorCount: 1, errors: [{ index: 1, originalURL: 'https://b.com', error: 'bad url' }] });+ expect(JSON.stringify(result)).not.toContain('"password"');+ });+ test('get_link returns found=false on 404', async () => {+ stubFetch(replies([{ status: 404, body: { error: 'Domain not found' } }]));+ expect(await run({ action: getLinkAction, props: { linkId: 'lnk_x_y' } })).toEqual({ found: false, link: null });+ });+ test('get_top_links uses POST /top with column=path', async () => {+ const seen = stubFetch((request) => (request.url.pathname === '/api/domains' ? { body: DOMAINS } : { body: [{ score: 9, column: '/promo', displayName: '/promo' }] }));+ const result = await run({ action: getTopLinksAction, props: { domain: 'go.example.com', period: 'last7' } });+ expect(seen[1].url.toString()).toBe('https://statistics.short.io/statistics/domain/101/top');+ expect(seen[1].body).toEqual({ column: 'path', limit: 10, period: 'last7' });+ expect(result).toEqual({ items: [{ path: '/promo', clicks: 9 }], count: 1 });+ });+ test('archive_link fails when Short.io answers success=false', async () => {+ stubFetch(replies([{ body: { success: false, error: 'Link not found' } }]));+ await expect(run({ action: archiveLinkAction, props: { linkId: 'lnk_a_b' } })).rejects.toThrow('Link not found');+ });+});diff --git a/packages/pieces/community/short-io/test/trigger.test.ts b/packages/pieces/community/short-io/test/trigger.test.tsnew file mode 100644index 00000000000..00f4c17ba25--- /dev/null+++ b/packages/pieces/community/short-io/test/trigger.test.ts@@ -0,0 +1,167 @@+import { afterEach, describe, expect, test, vi } from 'vitest';+import { newLinkCreatedTrigger } from '../src/lib/triggers/new-link-created';+import { DOMAIN_PROP, link, memoryStore, stubFetch } from './helpers';+import { AppConnectionType, Store } from '@activepieces/pieces-framework';++const OLD = '2026-09-01T00:00:00.000Z';++function context(store: ReturnType<typeof memoryStore>): TriggerContext {+ return { auth: { type: AppConnectionType.CUSTOM_AUTH, props: { apiKey: 'k' } }, propsValue: { domain: DOMAIN_PROP }, store };+}++function events(value: unknown): Record<string, unknown>[] {+ return Array.isArray(value) ? value.filter((item): item is Record<string, unknown> => item !== null && typeof item === 'object') : [];+}++function ids(value: unknown): unknown[] {+ return events(value).map((event) => event['id']);+}++function makeLink({ id, createdAt, updatedAt }: { id: string; createdAt: string; updatedAt?: string }): Record<string, unknown> {+ return link({ idString: id, createdAt, updatedAt: updatedAt ?? createdAt });+}++function fakeShortIo(db: Record<string, unknown>[]): { requests: () => number } {+ const seen = stubFetch((request) => {+ const direction = request.url.searchParams.get('dateSortOrder') === 'asc' ? -1 : 1;+ const sorted = [...db].sort((a, b) => direction * (Date.parse(String(b['createdAt'])) - Date.parse(String(a['createdAt']))));+ const offset = Number(request.url.searchParams.get('pageToken') ?? '0');+ const limit = Number(request.url.searchParams.get('limit') ?? '150');+ const page = sorted.slice(offset, offset + limit);+ const next = offset + limit < sorted.length ? String(offset + limit) : undefined;+ return { body: { count: sorted.length, links: page, ...(next ? { nextPageToken: next } : {}) } };+ });+ return { requests: () => seen.length };+}++function oldLinks(count: number): Record<string, unknown>[] {+ return Array.from({ length: count }, (_, i) => makeLink({ id: `link_8yXK_0000${String(99999 - i).padStart(5, '0')}`, createdAt: new Date(Date.parse(OLD) - i * 1000).toISOString() }));+}++const trigger: { run(context: TriggerContext): Promise<unknown>; onEnable(context: TriggerContext): Promise<void> } = newLinkCreatedTrigger;++afterEach(() => {+ vi.unstubAllGlobals();+ vi.useRealTimers();+});++describe('new_link_created', () => {+ test('baseline records every link at the newest timestamp, so none of them fire', async () => {+ const db = [...oldLinks(5), ...Array.from({ length: 3 }, (_, i) => makeLink({ id: `link_8yXK_0000tie${i}`, createdAt: OLD }))];+ fakeShortIo(db);+ const store = memoryStore();+ await trigger.onEnable(context(store));+ expect(await trigger.run(context(store))).toEqual([]);+ });++ test('a new link fires once, without the password', async () => {+ const db = oldLinks(300);+ fakeShortIo(db);+ const store = memoryStore();+ await trigger.onEnable(context(store));+ db.push(makeLink({ id: 'link_8yXK_9new1', createdAt: new Date().toISOString() }));+ const first = await trigger.run(context(store));+ expect(ids(first)).toEqual(['link_8yXK_9new1']);+ expect(JSON.stringify(first)).not.toContain('hunter2');+ expect(events(first)[0]).not.toHaveProperty('password');+ expect(await trigger.run(context(store))).toEqual([]);+ });++ test('a future-dated link does not hide links created after it', async () => {+ const db = oldLinks(10);+ fakeShortIo(db);+ const store = memoryStore();+ await trigger.onEnable(context(store));+ db.push(makeLink({ id: 'link_8yXK_9future', createdAt: '2030-01-01T00:00:00.000Z', updatedAt: new Date().toISOString() }));+ expect(ids(await trigger.run(context(store)))).toEqual(['link_8yXK_9future']);+ db.push(makeLink({ id: 'link_8yXK_9zafter', createdAt: new Date().toISOString() }));+ expect(ids(await trigger.run(context(store)))).toEqual(['link_8yXK_9zafter']);+ });++ test('a back-dated link deep in the list fires once; old links never do', async () => {+ const db = oldLinks(2000);+ fakeShortIo(db);+ const store = memoryStore();+ await trigger.onEnable(context(store));+ db.push(makeLink({ id: 'link_8yXK_9backdated', createdAt: '2020-01-01T00:00:00.000Z', updatedAt: new Date().toISOString() }));+ expect(ids(await trigger.run(context(store)))).toEqual(['link_8yXK_9backdated']);+ expect(await trigger.run(context(store))).toEqual([]);+ });++ test('more than 1,500 new links with the same createdAt are resumed on the next poll', async () => {+ const db = oldLinks(10);+ fakeShortIo(db);+ const store = memoryStore();+ await trigger.onEnable(context(store));+ const now = new Date().toISOString();+ db.push(...Array.from({ length: 1600 }, (_, i) => makeLink({ id: `link_8yXK_9burst${String(i).padStart(5, '0')}`, createdAt: now })));+ const first = ids(await trigger.run(context(store)));+ const second = ids(await trigger.run(context(store)));+ expect(first).toHaveLength(1500);+ expect(second).toHaveLength(100);+ expect(new Set([...first, ...second]).size).toBe(1600);+ expect(await trigger.run(context(store))).toEqual([]);+ });++ test('deleting links does not re-emit older ones', async () => {+ const db = oldLinks(400);+ fakeShortIo(db);+ const store = memoryStore();+ await trigger.onEnable(context(store));+ db.splice(0, 50);+ expect(await trigger.run(context(store))).toEqual([]);+ });++ test('a future-dated link does not fire again after 5,000 newer links pushed it out of the seen list', async () => {+ const db = oldLinks(5);+ fakeShortIo(db);+ const store = memoryStore();+ await trigger.onEnable(context(store));+ db.push(makeLink({ id: 'link_8yXK_9future', createdAt: '2030-01-01T00:00:00.000Z', updatedAt: new Date().toISOString() }));+ expect(ids(await trigger.run(context(store)))).toEqual(['link_8yXK_9future']);+ for (let batch = 0; batch < 4; batch++) {+ db.push(...Array.from({ length: 1400 }, (_, i) => makeLink({ id: `link_8yXK_9n${batch}${String(i).padStart(5, '0')}`, createdAt: new Date(Date.now() + batch).toISOString() })));+ expect(ids(await trigger.run(context(store)))).not.toContain('link_8yXK_9future');+ }+ expect(ids(await trigger.run(context(store)))).toEqual([]);+ });++ test('an old link outside the baseline window that gets edited does not fire, while a back-dated new link does', async () => {+ const db = oldLinks(2000);+ fakeShortIo(db);+ const store = memoryStore();+ await trigger.onEnable(context(store));+ db[1900] = { ...db[1900], updatedAt: new Date().toISOString() };+ db.push(makeLink({ id: 'link_8yXK_9new1', createdAt: new Date().toISOString() }));+ db.push(makeLink({ id: 'link_8yXK_9new2', createdAt: new Date().toISOString() }));+ db.push(makeLink({ id: 'link_8yXK_9backdated', createdAt: '2020-01-01T00:00:00.000Z', updatedAt: new Date().toISOString() }));+ expect(ids(await trigger.run(context(store))).sort()).toEqual(['link_8yXK_9backdated', 'link_8yXK_9new1', 'link_8yXK_9new2']);+ });++ test('an existing back-dated link at the oldest end does not fire when edited later', async () => {+ const db = [...oldLinks(2000), makeLink({ id: 'link_8yXK_5existingbackdated', createdAt: '2019-01-01T00:00:00.000Z' })];+ fakeShortIo(db);+ const store = memoryStore();+ await trigger.onEnable(context(store));+ db[2000] = { ...db[2000], updatedAt: new Date().toISOString() };+ db.push(makeLink({ id: 'link_8yXK_9new1', createdAt: new Date().toISOString() }));+ db.push(makeLink({ id: 'link_8yXK_9new2', createdAt: new Date().toISOString() }));+ db.push(makeLink({ id: 'link_8yXK_9backdated', createdAt: '2020-01-01T00:00:00.000Z', updatedAt: new Date().toISOString() }));+ expect(ids(await trigger.run(context(store))).sort()).toEqual(['link_8yXK_9backdated', 'link_8yXK_9new1', 'link_8yXK_9new2']);+ });++ test('migrates from the legacy id list once', async () => {+ const db = [makeLink({ id: 'link_8yXK_9new1', createdAt: '2026-10-02T00:00:00.000Z' }), makeLink({ id: 'link_8yXK_0old1', createdAt: OLD })];+ fakeShortIo(db);+ const store = memoryStore({ 'shortio-last-link-ids': ['link_8yXK_0old1'] });+ expect(ids(await trigger.run(context(store)))).toEqual(['link_8yXK_9new1']);+ expect(store.read('shortio-last-link-ids')).toBeUndefined();+ expect(await trigger.run(context(store))).toEqual([]);+ });+});++type TriggerContext = {+ auth: { type: AppConnectionType.CUSTOM_AUTH; props: { apiKey: string } };+ propsValue: { domain: string };+ store: Store;+};diff --git a/packages/pieces/community/short-io/vitest.config.ts b/packages/pieces/community/short-io/vitest.config.tsnew file mode 100644index 00000000000..79c97261904--- /dev/null+++ b/packages/pieces/community/short-io/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'),+ },+ },+})