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(smartsuite): agent-ready actions, bulk records, members and comments; fix webhook trigger loop (#16426)
Odai Ahmad361570976552
diff --git a/bun.lock b/bun.lockindex 0c62e2d1108..fb5c75d89fa 100644--- a/bun.lock+++ b/bun.lock@@ -8623,7 +8623,7 @@},"packages/pieces/community/smartsuite": {"name": "@activepieces/piece-smartsuite",- "version": "0.2.0",+ "version": "0.3.0","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -8633,6 +8633,7 @@},"devDependencies": {"tslib": "2.6.2",+ "vitest": "3.2.6",},},"packages/pieces/community/smoove": {diff --git a/docs/install/reference/breaking-changes-unreleased.mdx b/docs/install/reference/breaking-changes-unreleased.mdxindex b089ce4912b..2f15170b5a7 100644--- a/docs/install/reference/breaking-changes-unreleased.mdx+++ b/docs/install/reference/breaking-changes-unreleased.mdx@@ -8,6 +8,16 @@ Entries here move to [Breaking Changes](/install/reference/breaking-changes) aut## What has changed?+#### SmartSuite 0.3.0: Upload File returns the file list, and record and selector actions are builder-only++Upload File used to return the record's fields keyed by field label. From SmartSuite 0.3.0 it returns `{ recordId, field, fileName, files }`, where `files` is the field's file list (handle, name and metadata) after the upload.++Create Record, Update Record, Find Records, Get Record, Delete Record and Upload File, and the new actions that pick a solution, table, record, field or member, are now builder-only. AI agents use their twins that take plain IDs and field slugs, such as Get Record (by ID), Create Record (by Table ID), Update Record Fields, List Records and the other `*_by_id` actions.++#### What you need to do++If a later step reads fields from Upload File's output, read the record with Get Record after the upload, or use the new `files` list. Agents that used the builder actions as tools switch to the `*_by_id` twins. Steps keep running on the version they were built with until you upgrade them.+#### Brevo 0.5.0: an unticked unsubscribe toggle no longer re-subscribes the contactOn Create or Update Contact, the two blacklist toggles (now labelled **Unsubscribe From Email** and **Unsubscribe From SMS**) promised that leaving them untouched kept the contact's current setting. A fresh step saves an untouched toggle as `false`, so every run sent `emailBlacklisted: false` and `smsBlacklisted: false` and silently re-subscribed contacts who had opted out. Unsubscribe Contact did the same when one of its toggles was unticked. From 0.5.0 an unticked toggle sends nothing and the contact's setting is left as it is; a ticked toggle still unsubscribes. Unsubscribe Contact now fails with a clear message when nothing is ticked and no list is picked, instead of sending an empty update.diff --git a/packages/pieces/community/smartsuite/package.json b/packages/pieces/community/smartsuite/package.jsonindex 4e41cbe6b1d..7bdf065732a 100644--- a/packages/pieces/community/smartsuite/package.json+++ b/packages/pieces/community/smartsuite/package.json@@ -1,12 +1,13 @@{"name": "@activepieces/piece-smartsuite",- "version": "0.2.0",+ "version": "0.3.0","main": "./dist/src/index.js","types": "./dist/src/index.d.ts","scripts": {"build": "tsc -p tsconfig.lib.json && cp package.json dist/","bundle": "node ../../../../dist/packages/cli/src/index.js pieces bundle",- "lint": "eslint 'src/**/*.ts'"+ "lint": "eslint 'src/**/*.ts'",+ "test": "vitest run"},"dependencies": {"@activepieces/pieces-common": "workspace:*",@@ -16,6 +17,7 @@"@activepieces/core-utils": "workspace:*"},"devDependencies": {- "tslib": "2.6.2"+ "tslib": "2.6.2",+ "vitest": "3.2.6"}}diff --git a/packages/pieces/community/smartsuite/src/i18n/translation.json b/packages/pieces/community/smartsuite/src/i18n/translation.jsonindex 60429f6b785..0de002f74a9 100644--- a/packages/pieces/community/smartsuite/src/i18n/translation.json+++ b/packages/pieces/community/smartsuite/src/i18n/translation.json@@ -9,6 +9,45 @@"Upload File": "Upload File","Find Records": "Find Records","Get a Record": "Get a Record",+ "List Solutions": "List Solutions",+ "Get Solution": "Get Solution",+ "Get Solution (by ID)": "Get Solution (by ID)",+ "List Tables": "List Tables",+ "List Tables (by ID)": "List Tables (by ID)",+ "Get Table Schema": "Get Table Schema",+ "Get Table Schema (by ID)": "Get Table Schema (by ID)",+ "Create Records (Bulk)": "Create Records (Bulk)",+ "Create Records (Bulk, by ID)": "Create Records (Bulk, by ID)",+ "Update Records (Bulk)": "Update Records (Bulk)",+ "Update Records (Bulk, by ID)": "Update Records (Bulk, by ID)",+ "Delete Records (Bulk)": "Delete Records (Bulk)",+ "Delete Records (Bulk, by ID)": "Delete Records (Bulk, by ID)",+ "Create or Update Record": "Create or Update Record",+ "Create or Update Record (by ID)": "Create or Update Record (by ID)",+ "List Deleted Records": "List Deleted Records",+ "List Deleted Records (by ID)": "List Deleted Records (by ID)",+ "Restore Record": "Restore Record",+ "Restore Record (by ID)": "Restore Record (by ID)",+ "List Comments": "List Comments",+ "List Comments (by ID)": "List Comments (by ID)",+ "Add Comment": "Add Comment",+ "Add Comment (by ID)": "Add Comment (by ID)",+ "List Members": "List Members",+ "Get Member": "Get Member",+ "Get Member (by ID)": "Get Member (by ID)",+ "List Teams": "List Teams",+ "Get File Download URLs": "Get File Download URLs",+ "Get File Download URL (by Handle)": "Get File Download URL (by Handle)",+ "Create Table": "Create Table",+ "Create Table (by ID)": "Create Table (by ID)",+ "Add Field": "Add Field",+ "Add Field (by ID)": "Add Field (by ID)",+ "List Records (by Table ID)": "List Records (by Table ID)",+ "Get Record (by ID)": "Get Record (by ID)",+ "Create Record (by Table ID)": "Create Record (by Table ID)",+ "Update Record Fields (by ID)": "Update Record Fields (by ID)",+ "Delete Record (by ID)": "Delete Record (by ID)",+ "Attach File to Record (by ID)": "Attach File to Record (by ID)","Custom API Call": "Custom API Call","Creates a new record in the specified table.": "Creates a new record in the specified table.","Updates an existing record in the specified table": "Updates an existing record in the specified table",@@ -16,14 +55,81 @@"Uploads a file and attaches it to a record.": "Uploads a file and attaches it to a record.","Searches for records in the specified table based on criteria.": "Searches for records in the specified table based on criteria.","Retrieves a specific record by ID": "Retrieves a specific record by ID",+ "Lists the solutions (workspaces of tables) your account can access.": "Lists the solutions (workspaces of tables) your account can access.",+ "Gets the details of one solution.": "Gets the details of one solution.",+ "Gets the details of one solution, by solution ID.": "Gets the details of one solution, by solution ID.",+ "Lists the tables in a solution.": "Lists the tables in a solution.",+ "Lists the tables in a solution, by solution ID.": "Lists the tables in a solution, by solution ID.",+ "Gets a table and its fields (slug, label, type and choices).": "Gets a table and its fields (slug, label, type and choices).",+ "Gets a table and its fields (slug, label, type and choices), by table ID.": "Gets a table and its fields (slug, label, type and choices), by table ID.",+ "Creates up to 25 records in one request.": "Creates up to 25 records in one request.",+ "Creates up to 25 records in one request, by table ID.": "Creates up to 25 records in one request, by table ID.",+ "Updates up to 25 records in one request.": "Updates up to 25 records in one request.",+ "Updates up to 25 records in one request, by table ID.": "Updates up to 25 records in one request, by table ID.",+ "Deletes up to 25 records in one request.": "Deletes up to 25 records in one request.",+ "Deletes up to 25 records in one request, by table ID.": "Deletes up to 25 records in one request, by table ID.",+ "Updates the record whose field matches a value, or creates it when none matches.": "Updates the record whose field matches a value, or creates it when none matches.",+ "Updates the record whose field matches a value, or creates it when none matches, by table ID and field slug.": "Updates the record whose field matches a value, or creates it when none matches, by table ID and field slug.",+ "Lists the records in a solution's trash.": "Lists the records in a solution's trash.",+ "Lists the records in a solution's trash, by solution ID.": "Lists the records in a solution's trash, by solution ID.",+ "Brings a deleted record back from the trash.": "Brings a deleted record back from the trash.",+ "Brings a deleted record back from the trash, by table ID and record ID.": "Brings a deleted record back from the trash, by table ID and record ID.",+ "Lists the comments on a record.": "Lists the comments on a record.",+ "Lists the comments on a record, by record ID.": "Lists the comments on a record, by record ID.",+ "Adds a comment to a record.": "Adds a comment to a record.",+ "Adds a comment to a record, by table ID and record ID.": "Adds a comment to a record, by table ID and record ID.",+ "Lists the members of your SmartSuite workspace.": "Lists the members of your SmartSuite workspace.",+ "Gets one workspace member.": "Gets one workspace member.",+ "Gets one workspace member by member ID.": "Gets one workspace member by member ID.",+ "Lists the teams in your SmartSuite workspace.": "Lists the teams in your SmartSuite workspace.",+ "Gets temporary download links for the files in a record's Files & Images field.": "Gets temporary download links for the files in a record's Files & Images field.",+ "Gets a temporary download link for one file, by its file handle.": "Gets a temporary download link for one file, by its file handle.",+ "Creates a new table in a solution.": "Creates a new table in a solution.",+ "Creates a new table in a solution, by solution ID.": "Creates a new table in a solution, by solution ID.",+ "Adds a new field (column) to a table.": "Adds a new field (column) to a table.",+ "Adds a new field (column) to a table, by table ID.": "Adds a new field (column) to a table, by table ID.",+ "Lists one page of records from a table, with an optional filter and sort.": "Lists one page of records from a table, with an optional filter and sort.",+ "Gets one record by table ID and record ID, keyed by field slug.": "Gets one record by table ID and record ID, keyed by field slug.",+ "Creates a record from a JSON object keyed by field slug.": "Creates a record from a JSON object keyed by field slug.",+ "Updates only the fields given in a JSON object keyed by field slug.": "Updates only the fields given in a JSON object keyed by field slug.",+ "Moves one record to the trash by table ID and record ID.": "Moves one record to the trash by table ID and record ID.",+ "Uploads a file into a Files & Images field of a record, by IDs and field slug.": "Uploads a file into a Files & Images field of a record, by IDs and field slug.","Make a custom API call to a specific endpoint": "Make a custom API call to a specific endpoint","Solution": "Solution","Table": "Table","Fields": "Fields","Record ID": "Record ID",- "Search Field": "Search Field",+ "File Field": "File Field","File": "File",+ "Search Field": "Search Field","Search Value": "Search Value",+ "Max Records": "Max Records",+ "Include Hidden Solutions": "Include Hidden Solutions",+ "Solution ID": "Solution ID",+ "Table ID": "Table ID",+ "Records": "Records",+ "Record IDs": "Record IDs",+ "Match Field": "Match Field",+ "Match Value": "Match Value",+ "Match Field Slug": "Match Field Slug",+ "Deleted Record": "Deleted Record",+ "Record": "Record",+ "Message": "Message",+ "Assign To": "Assign To",+ "Assign To (Member ID)": "Assign To (Member ID)",+ "Limit": "Limit",+ "Offset": "Offset",+ "Member": "Member",+ "Member ID": "Member ID",+ "File Handle": "File Handle",+ "Table Name": "Table Name",+ "Field Label": "Field Label",+ "Field Type": "Field Type",+ "Choices": "Choices",+ "Field Slug": "Field Slug",+ "Filter": "Filter",+ "Sort": "Sort",+ "File Field Slug": "File Field Slug","Method": "Method","Headers": "Headers","Query Parameters": "Query Parameters",@@ -33,13 +139,52 @@"Return Error as Output": "Return Error as Output","Timeout": "Timeout","Follow redirects": "Follow redirects",- "The file to upload": "The file to upload",+ "The Files & Images field to attach the file to.": "The Files & Images field to attach the file to.",+ "The file to upload (up to 100 MB).": "The file to upload (up to 100 MB).",+ "Stop after this many matches (1-10000). Leave empty to return all matches up to 10000; Has More tells you if more exist.": "Stop after this many matches (1-10000). Leave empty to return all matches up to 10000; Has More tells you if more exist.",+ "Also return hidden and system solutions.": "Also return hidden and system solutions.",+ "The SmartSuite solution ID (24 characters). Get it from List Solutions.": "The SmartSuite solution ID (24 characters). Get it from List Solutions.",+ "The SmartSuite table (application) ID. Get it from List Tables.": "The SmartSuite table (application) ID. Get it from List Tables.",+ "JSON array of up to 25 objects keyed by field slug, for example [{\"title\":\"A\"},{\"title\":\"B\"}]. Use Get Table Schema to see the slugs.": "JSON array of up to 25 objects keyed by field slug, for example [{\"title\":\"A\"},{\"title\":\"B\"}]. Use Get Table Schema to see the slugs.",+ "JSON array of up to 25 objects, each with \"id\" and the field slugs to change, for example [{\"id\":\"64f...\",\"status\":{\"value\":\"complete\"}}].": "JSON array of up to 25 objects, each with \"id\" and the field slugs to change, for example [{\"id\":\"64f...\",\"status\":{\"value\":\"complete\"}}].",+ "Up to 25 record IDs to delete.": "Up to 25 record IDs to delete.",+ "The field that identifies the record, for example an email or external ID field.": "The field that identifies the record, for example an email or external ID field.",+ "Slug of the field that identifies the record, for example an email or external ID field. Get slugs from Get Table Schema (by ID).": "Slug of the field that identifies the record, for example an email or external ID field. Get slugs from Get Table Schema (by ID).",+ "JSON object keyed by field slug with the values to set, for example {\"status\":{\"value\":\"complete\"}}.": "JSON object keyed by field slug with the values to set, for example {\"status\":{\"value\":\"complete\"}}.",+ "A record in the trash of the selected table.": "A record in the trash of the selected table.",+ "The record ID. Get it from List Records or a create step.": "The record ID. Get it from List Records or a create step.",+ "Optional member to assign the comment to.": "Optional member to assign the comment to.",+ "Optional member ID to assign the comment to. Get it from List Members.": "Optional member ID to assign the comment to. Get it from List Members.",+ "How many items to return in one call (1-1000, default 100).": "How many items to return in one call (1-1000, default 100).",+ "How many items to skip. Use the previous offset plus the number of items returned to get the next page.": "How many items to skip. Use the previous offset plus the number of items returned to get the next page.",+ "The member ID. Get it from List Members.": "The member ID. Get it from List Members.",+ "The Files & Images field to read.": "The Files & Images field to read.",+ "The \"handle\" of the file, found in the record's Files & Images field.": "The \"handle\" of the file, found in the record's Files & Images field.",+ "Options for a single or multiple select field.": "Options for a single or multiple select field.",+ "Optional key for the field (lowercase letters, digits and _, starting with a letter, up to 30 characters). Generated when empty.": "Optional key for the field (lowercase letters, digits and _, starting with a letter, up to 30 characters). Generated when empty.",+ "SmartSuite filter object: {\"operator\":\"and\"|\"or\",\"fields\":[{\"field\":\"<slug>\",\"comparison\":\"is\",\"value\":\"...\"}]}. Leave empty for all records.": "SmartSuite filter object: {\"operator\":\"and\"|\"or\",\"fields\":[{\"field\":\"<slug>\",\"comparison\":\"is\",\"value\":\"...\"}]}. Leave empty for all records.",+ "Array of {\"field\":\"<slug>\",\"direction\":\"asc\"|\"desc\"}.": "Array of {\"field\":\"<slug>\",\"direction\":\"asc\"|\"desc\"}.",+ "JSON object keyed by field slug, for example {\"title\": \"New task\", \"priority\": \"high\"}.": "JSON object keyed by field slug, for example {\"title\": \"New task\", \"priority\": \"high\"}.",+ "JSON object keyed by field slug with the new values.": "JSON object keyed by field slug with the new values.",+ "Slug of a Files & Images field. Get it from Get Table Schema.": "Slug of a Files & Images field. Get it from Get Table Schema.","Authorization headers are injected automatically from your connection.": "Authorization headers are injected automatically from your connection.","Appended to the URL as ?key=value.": "Appended to the URL as ?key=value.","Enable for files like PDFs, images, etc.": "Enable for files like PDFs, images, etc.","On a failed request, output the error instead of failing the step.": "On a failed request, output the error instead of failing the step.","Seconds to wait for a response. Empty: up to the flow limit (10 min).": "Seconds to wait for a response. Empty: up to the flow limit (10 min).","Follow 3xx redirects instead of returning them as the response.": "Follow 3xx redirects instead of returning them as the response.",+ "Text": "Text",+ "Text Area": "Text Area",+ "Number": "Number",+ "Currency": "Currency",+ "Percent": "Percent",+ "Date": "Date",+ "Yes / No": "Yes / No",+ "Email": "Email",+ "Link": "Link",+ "Single Select": "Single Select",+ "Multiple Select": "Multiple Select",+ "Files & Images": "Files & Images","GET": "GET","POST": "POST","PATCH": "PATCH",diff --git a/packages/pieces/community/smartsuite/src/index.ts b/packages/pieces/community/smartsuite/src/index.tsindex ff9bf0e8be1..4d444c54c2e 100644--- a/packages/pieces/community/smartsuite/src/index.ts+++ b/packages/pieces/community/smartsuite/src/index.ts@@ -1,51 +1,103 @@-import {- createPiece,- PiecePropValueSchema,-} from '@activepieces/pieces-framework';+import { createPiece } from '@activepieces/pieces-framework';import { PieceCategory } from '@activepieces/pieces-framework';+import { createCustomApiCallAction } from '@activepieces/pieces-common';import { smartsuiteAuth } from './lib/auth';+import { SMARTSUITE_API_URL } from './lib/common/constants';+import { smartSuiteClient } from './lib/common/client';-// Actionsimport { createRecord } from './lib/actions/create-record';import { updateRecord } from './lib/actions/update-record';import { deleteRecord } from './lib/actions/delete-record';import { uploadFile } from './lib/actions/upload-file';import { findRecords } from './lib/actions/find-records';import { getRecord } from './lib/actions/get-record';+import { listSolutions } from './lib/actions/list-solutions';+import { getSolution, getSolutionById } from './lib/actions/get-solution';+import { listTables, listTablesById } from './lib/actions/list-tables';+import { getTableSchema, getTableSchemaById } from './lib/actions/get-table-schema';+import { bulkCreateRecords, bulkCreateRecordsById } from './lib/actions/bulk-create-records';+import { bulkUpdateRecords, bulkUpdateRecordsById } from './lib/actions/bulk-update-records';+import { bulkDeleteRecords, bulkDeleteRecordsById } from './lib/actions/bulk-delete-records';+import { upsertRecord, upsertRecordById } from './lib/actions/upsert-record';+import { listDeletedRecords, listDeletedRecordsById } from './lib/actions/list-deleted-records';+import { restoreRecord, restoreRecordById } from './lib/actions/restore-record';+import { listComments, listCommentsById } from './lib/actions/list-comments';+import { addComment, addCommentById } from './lib/actions/add-comment';+import { listMembers } from './lib/actions/list-members';+import { getMember, getMemberById } from './lib/actions/get-member';+import { listTeams } from './lib/actions/list-teams';+import { getFileUrl, getFileUrlByHandle } from './lib/actions/get-file-url';+import { createTable, createTableById } from './lib/actions/create-table';+import { addField, addFieldById } from './lib/actions/add-field';+import { listRecordsAi } from './lib/actions/ai/list-records';+import { getRecordByIdAi } from './lib/actions/ai/get-record-by-id';+import { createRecordByIdAi } from './lib/actions/ai/create-record-by-id';+import { updateRecordFieldsAi } from './lib/actions/ai/update-record-fields';+import { deleteRecordByIdAi } from './lib/actions/ai/delete-record-by-id';+import { attachFileByIdAi } from './lib/actions/ai/attach-file-by-id';-// Triggersimport { newRecord } from './lib/triggers/new-record';import { updatedRecord } from './lib/triggers/updated-record';-import { createCustomApiCallAction } from '@activepieces/pieces-common';-import { SMARTSUITE_API_URL } from './lib/common/constants';export const smartsuite = createPiece({- displayName: 'SmartSuite',- description:- 'Collaborative work management platform combining databases with spreadsheets.',- logoUrl: 'https://cdn.activepieces.com/pieces/smartsuite.png',- categories: [PieceCategory.PRODUCTIVITY],- auth: smartsuiteAuth,- minimumSupportedRelease: '0.30.0',- authors: ['Kunal-Darekar', 'kishanprmr'],- actions: [- createRecord,- updateRecord,- deleteRecord,- uploadFile,- findRecords,- getRecord,- createCustomApiCallAction({- auth: smartsuiteAuth,- baseUrl: () => SMARTSUITE_API_URL,- authMapping: async (auth) => {- const authValue = auth- return {- Authorization: `Token ${auth.props.apiKey}`,- 'ACCOUNT-ID': auth.props.accountId,- };- },- }),- ],- triggers: [newRecord, updatedRecord],+ displayName: 'SmartSuite',+ description: 'Collaborative work management platform combining databases with spreadsheets.',+ logoUrl: 'https://cdn.activepieces.com/pieces/smartsuite.png',+ categories: [PieceCategory.PRODUCTIVITY],+ auth: smartsuiteAuth,+ minimumSupportedRelease: '0.88.2',+ authors: ['Kunal-Darekar', 'kishanprmr'],+ actions: [+ createRecord,+ updateRecord,+ deleteRecord,+ uploadFile,+ findRecords,+ getRecord,+ listSolutions,+ getSolution,+ getSolutionById,+ listTables,+ listTablesById,+ getTableSchema,+ getTableSchemaById,+ bulkCreateRecords,+ bulkCreateRecordsById,+ bulkUpdateRecords,+ bulkUpdateRecordsById,+ bulkDeleteRecords,+ bulkDeleteRecordsById,+ upsertRecord,+ upsertRecordById,+ listDeletedRecords,+ listDeletedRecordsById,+ restoreRecord,+ restoreRecordById,+ listComments,+ listCommentsById,+ addComment,+ addCommentById,+ listMembers,+ getMember,+ getMemberById,+ listTeams,+ getFileUrl,+ getFileUrlByHandle,+ createTable,+ createTableById,+ addField,+ addFieldById,+ listRecordsAi,+ getRecordByIdAi,+ createRecordByIdAi,+ updateRecordFieldsAi,+ deleteRecordByIdAi,+ attachFileByIdAi,+ createCustomApiCallAction({+ auth: smartsuiteAuth,+ baseUrl: () => SMARTSUITE_API_URL,+ authMapping: async (auth) => smartSuiteClient.authHeaders(auth.props),+ }),+ ],+ triggers: [newRecord, updatedRecord],});diff --git a/packages/pieces/community/smartsuite/src/lib/actions/add-comment.ts b/packages/pieces/community/smartsuite/src/lib/actions/add-comment.tsnew file mode 100644index 00000000000..112f52a72cd--- /dev/null+++ b/packages/pieces/community/smartsuite/src/lib/actions/add-comment.ts@@ -0,0 +1,100 @@+import { Property, createAction } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { smartsuiteAuth } from '../auth';+import { smartSuiteClient, SmartSuiteCredentials } from '../common/client';+import { smartSuiteInputs } from '../common/inputs';+import { smartsuiteCommon } from '../common/props';+import { outputSchemas } from '../output-schemas';++async function postComment({+ credentials,+ tableId,+ recordId,+ message,+ assignedTo,+}: {+ credentials: SmartSuiteCredentials;+ tableId: unknown;+ recordId: unknown;+ message: unknown;+ assignedTo: unknown;+}): Promise<Record<string, unknown>> {+ const text = smartSuiteInputs.requireText({ value: message, label: 'Message' });+ const table = smartSuiteInputs.requireText({ value: tableId, label: 'Table' });+ const record = smartSuiteInputs.requireText({ value: recordId, label: 'Record ID' });+ const assignee = typeof assignedTo === 'string' ? assignedTo.trim() : '';+ return smartSuiteClient.request<Record<string, unknown>>({+ credentials,+ method: HttpMethod.POST,+ path: '/comments/',+ body: {+ application: table,+ record,+ assigned_to: assignee.length > 0 ? assignee : null,+ message: smartSuiteInputs.plainTextToDoc(text),+ },+ operation: 'add comment',+ });+}++function messageProp() {+ return Property.LongText({+ displayName: 'Message',+ required: true,+ });+}++export const addComment = createAction({+ name: 'add_comment',+ classification: 'WRITE',+ displayName: 'Add Comment',+ description: 'Adds a comment to a record.',+ audience: 'human',+ aiMetadata: {+ description: 'Builder version with solution, table, record and member pickers; agents should use Add Comment (by ID). Posts a plain-text comment on one SmartSuite record (line breaks become paragraphs). Record followers are notified. Optionally assigns the comment to a member. Returns the comment with its ID. Not idempotent: each call posts another comment.',+ idempotent: false,+ },+ auth: smartsuiteAuth,+ props: {+ solutionId: smartsuiteCommon.solutionId,+ tableId: smartsuiteCommon.tableId,+ recordId: smartsuiteCommon.recordDropdown({ displayName: 'Record' }),+ message: messageProp(),+ assignedTo: smartsuiteCommon.memberDropdown({+ displayName: 'Assign To',+ description: 'Optional member to assign the comment to.',+ required: false,+ }),+ },+ outputSchema: outputSchemas['comment'],+ async run({ auth, propsValue }) {+ return postComment({ credentials: smartSuiteClient.credentialsOf(auth), ...propsValue });+ },+});++export const addCommentById = createAction({+ name: 'add_comment_by_id',+ classification: 'WRITE',+ displayName: 'Add Comment (by ID)',+ description: 'Adds a comment to a record, by table ID and record ID.',+ audience: 'ai',+ aiMetadata: {+ description: 'Posts a plain-text comment on one SmartSuite record (line breaks become paragraphs). Record followers are notified. Optionally assigns the comment to a member. Returns the comment with its ID. Not idempotent: each call posts another comment. Needs the Table ID (List Tables (by ID)) and Record ID (List Records). Assign To takes a member ID from List Members. Check List Comments (by ID) first if a retry could post a duplicate.',+ idempotent: false,+ },+ auth: smartsuiteAuth,+ props: {+ tableId: smartSuiteInputs.aiProps.tableId(),+ recordId: smartSuiteInputs.aiProps.recordId(),+ message: messageProp(),+ assignedTo: Property.ShortText({+ displayName: 'Assign To (Member ID)',+ description: 'Optional member ID to assign the comment to. Get it from List Members.',+ required: false,+ }),+ },+ outputSchema: outputSchemas['comment'],+ async run({ auth, propsValue }) {+ return postComment({ credentials: smartSuiteClient.credentialsOf(auth), ...propsValue });+ },+});diff --git a/packages/pieces/community/smartsuite/src/lib/actions/add-field.ts b/packages/pieces/community/smartsuite/src/lib/actions/add-field.tsnew file mode 100644index 00000000000..dd95f0b28b0--- /dev/null+++ b/packages/pieces/community/smartsuite/src/lib/actions/add-field.ts@@ -0,0 +1,145 @@+import { Property, createAction } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { randomBytes } from 'crypto';+import { smartsuiteAuth } from '../auth';+import { smartSuiteApi } from '../common';+import { smartSuiteClient, SmartSuiteCredentials } from '../common/client';+import { smartSuiteInputs } from '../common/inputs';+import { smartsuiteCommon } from '../common/props';+import { tableSummary } from '../common/tables';+import { outputSchemas } from '../output-schemas';++const FIELD_TYPES = [+ { label: 'Text', value: 'textfield' },+ { label: 'Text Area', value: 'textareafield' },+ { label: 'Number', value: 'numberfield' },+ { label: 'Currency', value: 'currencyfield' },+ { label: 'Percent', value: 'percentfield' },+ { label: 'Date', value: 'datefield' },+ { label: 'Yes / No', value: 'yesnofield' },+ { label: 'Email', value: 'emailfield' },+ { label: 'Link', value: 'linkfield' },+ { label: 'Single Select', value: 'singleselectfield' },+ { label: 'Multiple Select', value: 'multipleselectfield' },+ { label: 'Files & Images', value: 'filefield' },+];+const SELECT_TYPES = ['singleselectfield', 'multipleselectfield'];+const SLUG_PATTERN = /^[a-z][a-z0-9_]{0,29}$/;++async function addOne({+ credentials,+ tableId,+ label,+ fieldType,+ choices,+ slug,+}: {+ credentials: SmartSuiteCredentials;+ tableId: unknown;+ label: unknown;+ fieldType: unknown;+ choices: unknown[] | undefined;+ slug: string | undefined;+}) {+ const fieldLabel = smartSuiteInputs.requireText({ value: label, label: 'Field Label' });+ const type = smartSuiteInputs.requireText({ value: fieldType, label: 'Field Type' });+ if (!FIELD_TYPES.some((option) => option.value === type)) {+ throw new Error(`Field Type must be one of: ${FIELD_TYPES.map((option) => option.value).join(', ')}.`);+ }+ const requestedSlug = slug?.trim();+ if (requestedSlug && !SLUG_PATTERN.test(requestedSlug)) {+ throw new Error('Field Slug must start with a lowercase letter and use only lowercase letters, digits and _ (up to 30 characters).');+ }+ const choiceLabels = (choices ?? []).map((choice) => String(choice ?? '').trim()).filter((choice) => choice.length > 0);+ if (SELECT_TYPES.includes(type) && choiceLabels.length === 0) {+ throw new Error('Select fields need at least one choice.');+ }+ const finalSlug = requestedSlug && requestedSlug.length > 0 ? requestedSlug : `s${randomBytes(5).toString('hex').slice(0, 9)}`;+ const params: Record<string, unknown> = SELECT_TYPES.includes(type)+ ? { choices: choiceLabels.map((choice, index) => ({ label: choice, value: `c${index + 1}${randomBytes(2).toString('hex')}` })) }+ : {};+ await smartSuiteClient.request<unknown>({+ credentials,+ method: HttpMethod.POST,+ path: `/applications/${smartSuiteClient.pathSegment({ value: tableId, label: 'Table' })}/add_field/`,+ body: {+ field: { slug: finalSlug, label: fieldLabel, field_type: type, params },+ field_position: {},+ auto_fill_structure_layout: true,+ },+ operation: 'add field',+ });+ const table = await smartSuiteApi.getTable({ credentials, tableId });+ const added = table.structure.find((field) => field.slug === finalSlug);+ if (!added) {+ throw new Error(`SmartSuite accepted the field but it is not in the table schema yet (slug ${finalSlug}). Check the table before retrying, to avoid a duplicate field.`);+ }+ return { tableId: table.id, field: tableSummary.describeField(added) };+}++function fieldProps() {+ return {+ label: Property.ShortText({+ displayName: 'Field Label',+ required: true,+ }),+ fieldType: Property.StaticDropdown({+ displayName: 'Field Type',+ required: true,+ options: { disabled: false, options: FIELD_TYPES },+ }),+ choices: Property.Array({+ displayName: 'Choices',+ description: 'Options for a single or multiple select field.',+ required: false,+ }),+ slug: Property.ShortText({+ displayName: 'Field Slug',+ description: 'Optional key for the field (lowercase letters, digits and _, starting with a letter, up to 30 characters). Generated when empty.',+ required: false,+ }),+ };+}++export const addField = createAction({+ name: 'add_field',+ classification: 'WRITE',+ displayName: 'Add Field',+ description: 'Adds a new field (column) to a table.',+ audience: 'human',+ aiMetadata: {+ description: 'Builder version with solution and table pickers; agents should use Add Field (by ID). Adds one field: text, text area, number, currency, percent, date, yes/no, email, link, single or multiple select (with choices) or files. Changes the table schema for everyone using it and needs permission to edit the solution. Returns the new field with its slug. Not idempotent: each call adds another field.',+ idempotent: false,+ },+ auth: smartsuiteAuth,+ props: {+ solutionId: smartsuiteCommon.solutionId,+ tableId: smartsuiteCommon.tableId,+ ...fieldProps(),+ },+ outputSchema: outputSchemas['addField'],+ async run({ auth, propsValue }) {+ return addOne({ credentials: smartSuiteClient.credentialsOf(auth), tableId: propsValue.tableId, label: propsValue.label, fieldType: propsValue.fieldType, choices: propsValue.choices, slug: propsValue.slug });+ },+});++export const addFieldById = createAction({+ name: 'add_field_by_id',+ classification: 'WRITE',+ displayName: 'Add Field (by ID)',+ description: 'Adds a new field (column) to a table, by table ID.',+ audience: 'ai',+ aiMetadata: {+ description: 'Adds a field to a SmartSuite table (Table ID from List Tables (by ID)). Adds one field: text, text area, number, currency, percent, date, yes/no, email, link, single or multiple select (with choices) or files. Changes the table schema for everyone using it and needs permission to edit the solution. Returns the new field with its slug. Not idempotent: each call adds another field. Check Get Table Schema (by ID) first so you do not add a field that already exists; use the returned slug in record JSON.',+ idempotent: false,+ },+ auth: smartsuiteAuth,+ props: {+ tableId: smartSuiteInputs.aiProps.tableId(),+ ...fieldProps(),+ },+ outputSchema: outputSchemas['addField'],+ async run({ auth, propsValue }) {+ return addOne({ credentials: smartSuiteClient.credentialsOf(auth), tableId: propsValue.tableId, label: propsValue.label, fieldType: propsValue.fieldType, choices: propsValue.choices, slug: propsValue.slug });+ },+});diff --git a/packages/pieces/community/smartsuite/src/lib/actions/ai/attach-file-by-id.ts b/packages/pieces/community/smartsuite/src/lib/actions/ai/attach-file-by-id.tsnew file mode 100644index 00000000000..37775c76329--- /dev/null+++ b/packages/pieces/community/smartsuite/src/lib/actions/ai/attach-file-by-id.ts@@ -0,0 +1,43 @@+import { Property, createAction } from '@activepieces/pieces-framework';+import { smartsuiteAuth } from '../../auth';+import { smartSuiteClient } from '../../common/client';+import { smartSuiteInputs } from '../../common/inputs';+import { recordFiles } from '../../common/record-files';+import { outputSchemas } from '../../output-schemas';++export const attachFileByIdAi = createAction({+ name: 'attach_file_by_id',+ classification: 'WRITE',+ displayName: 'Attach File to Record (by ID)',+ description: 'Uploads a file into a Files & Images field of a record, by IDs and field slug.',+ audience: 'ai',+ aiMetadata: {+ description: 'Uploads one file (a file URL or file from an earlier step, up to 100 MB) into a Files & Images field of a SmartSuite record, given Table ID, Record ID and the field slug (field_type filefield in Get Table Schema (by ID)). Returns the files now in that field with their handles. Not idempotent: each call adds another attachment.',+ idempotent: false,+ },+ auth: smartsuiteAuth,+ props: {+ tableId: smartSuiteInputs.aiProps.tableId(),+ recordId: smartSuiteInputs.aiProps.recordId(),+ fieldSlug: Property.ShortText({+ displayName: 'File Field Slug',+ description: 'Slug of a Files & Images field. Get it from Get Table Schema.',+ required: true,+ }),+ file: Property.File({+ displayName: 'File',+ description: 'The file to upload (up to 100 MB).',+ required: true,+ }),+ },+ outputSchema: outputSchemas['uploadFile'],+ async run({ auth, propsValue }) {+ return recordFiles.attach({+ credentials: smartSuiteClient.credentialsOf(auth),+ tableId: propsValue.tableId,+ recordId: propsValue.recordId,+ field: smartSuiteInputs.requireText({ value: propsValue.fieldSlug, label: 'File Field Slug' }),+ file: propsValue.file,+ });+ },+});diff --git a/packages/pieces/community/smartsuite/src/lib/actions/ai/create-record-by-id.ts b/packages/pieces/community/smartsuite/src/lib/actions/ai/create-record-by-id.tsnew file mode 100644index 00000000000..608a0d8e09a--- /dev/null+++ b/packages/pieces/community/smartsuite/src/lib/actions/ai/create-record-by-id.ts@@ -0,0 +1,39 @@+import { Property, createAction } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { smartsuiteAuth } from '../../auth';+import { SmartSuiteRecord } from '../../common';+import { smartSuiteClient } from '../../common/client';+import { smartSuiteInputs } from '../../common/inputs';+import { outputSchemas } from '../../output-schemas';++export const createRecordByIdAi = createAction({+ name: 'create_record_by_id',+ classification: 'WRITE',+ displayName: 'Create Record (by Table ID)',+ description: 'Creates a record from a JSON object keyed by field slug.',+ audience: 'ai',+ aiMetadata: {+ description: 'Creates one SmartSuite record. Fields is a JSON object keyed by field slug, in SmartSuite\'s value format: text/number as plain values, single select as the choice value, status as {"value":"<choice>"}, date as {"date":"2026-10-12T00:00:00Z","include_time":false}, linked records/users as arrays of IDs, emails and links as arrays of strings. Get slugs and choice values from Get Table Schema (by ID). Returns the created record with its id. Not idempotent: each call creates another record.',+ idempotent: false,+ },+ auth: smartsuiteAuth,+ props: {+ tableId: smartSuiteInputs.aiProps.tableId(),+ fields: Property.Json({+ displayName: 'Fields',+ description: 'JSON object keyed by field slug, for example {"title": "New task", "priority": "high"}.',+ required: true,+ }),+ },+ outputSchema: outputSchemas['rawRecord'],+ async run({ auth, propsValue }) {+ const fields = smartSuiteInputs.requireObject({ value: propsValue.fields, label: 'Fields' });+ return smartSuiteClient.request<SmartSuiteRecord>({+ credentials: smartSuiteClient.credentialsOf(auth),+ method: HttpMethod.POST,+ path: `/applications/${smartSuiteClient.pathSegment({ value: propsValue.tableId, label: 'Table ID' })}/records/`,+ body: fields,+ operation: 'create record',+ });+ },+});diff --git a/packages/pieces/community/smartsuite/src/lib/actions/ai/delete-record-by-id.ts b/packages/pieces/community/smartsuite/src/lib/actions/ai/delete-record-by-id.tsnew file mode 100644index 00000000000..189d280a3b3--- /dev/null+++ b/packages/pieces/community/smartsuite/src/lib/actions/ai/delete-record-by-id.ts@@ -0,0 +1,41 @@+import { createAction } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { smartsuiteAuth } from '../../auth';+import { smartSuiteClient } from '../../common/client';+import { smartSuiteInputs } from '../../common/inputs';+import { outputSchemas } from '../../output-schemas';++export const deleteRecordByIdAi = createAction({+ name: 'delete_record_by_id',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete Record (by ID)',+ description: 'Moves one record to the trash by table ID and record ID.',+ audience: 'ai',+ aiMetadata: {+ description: 'Moves one SmartSuite record to the solution trash, given the Table ID and Record ID. It can be brought back with Restore Record (by ID). Use Delete Records (Bulk, by ID) for several. Idempotent: deleting a record already in the trash succeeds again, and a record that no longer exists (404) returns alreadyDeleted true.',+ idempotent: true,+ },+ auth: smartsuiteAuth,+ props: {+ tableId: smartSuiteInputs.aiProps.tableId(),+ recordId: smartSuiteInputs.aiProps.recordId(),+ },+ outputSchema: outputSchemas['deleteRecord'],+ async run({ auth, propsValue }) {+ const recordId = smartSuiteInputs.requireText({ value: propsValue.recordId, label: 'Record ID' });+ try {+ await smartSuiteClient.request<unknown>({+ credentials: smartSuiteClient.credentialsOf(auth),+ method: HttpMethod.DELETE,+ path: `/applications/${smartSuiteClient.pathSegment({ value: propsValue.tableId, label: 'Table ID' })}/records/${smartSuiteClient.pathSegment({ value: recordId, label: 'Record ID' })}/`,+ operation: 'delete record',+ });+ return { id: recordId, deleted: true, alreadyDeleted: false };+ } catch (error) {+ if (smartSuiteClient.statusOf(error) === 404) {+ return { id: recordId, deleted: true, alreadyDeleted: true };+ }+ throw error;+ }+ },+});diff --git a/packages/pieces/community/smartsuite/src/lib/actions/ai/get-record-by-id.ts b/packages/pieces/community/smartsuite/src/lib/actions/ai/get-record-by-id.tsnew file mode 100644index 00000000000..3e69cd1ca9e--- /dev/null+++ b/packages/pieces/community/smartsuite/src/lib/actions/ai/get-record-by-id.ts@@ -0,0 +1,33 @@+import { createAction } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { smartsuiteAuth } from '../../auth';+import { SmartSuiteRecord } from '../../common';+import { smartSuiteClient } from '../../common/client';+import { smartSuiteInputs } from '../../common/inputs';+import { outputSchemas } from '../../output-schemas';++export const getRecordByIdAi = createAction({+ name: 'get_record_by_id',+ classification: 'READ',+ displayName: 'Get Record (by ID)',+ description: 'Gets one record by table ID and record ID, keyed by field slug.',+ audience: 'ai',+ aiMetadata: {+ description: 'Returns one SmartSuite record with values keyed by field slug (the same keys you pass to create or update). Needs the Table ID (List Tables (by ID)) and Record ID (List Records). Next: Update Record Fields to change it, List Comments (by ID) for its discussion, or Get File Download URL (by Handle) for file handles. Read-only and idempotent.',+ idempotent: true,+ },+ auth: smartsuiteAuth,+ props: {+ tableId: smartSuiteInputs.aiProps.tableId(),+ recordId: smartSuiteInputs.aiProps.recordId(),+ },+ outputSchema: outputSchemas['rawRecord'],+ async run({ auth, propsValue }) {+ return smartSuiteClient.request<SmartSuiteRecord>({+ credentials: smartSuiteClient.credentialsOf(auth),+ method: HttpMethod.GET,+ path: `/applications/${smartSuiteClient.pathSegment({ value: propsValue.tableId, label: 'Table ID' })}/records/${smartSuiteClient.pathSegment({ value: propsValue.recordId, label: 'Record ID' })}/`,+ operation: 'get record',+ });+ },+});diff --git a/packages/pieces/community/smartsuite/src/lib/actions/ai/list-records.ts b/packages/pieces/community/smartsuite/src/lib/actions/ai/list-records.tsnew file mode 100644index 00000000000..c2d21a7fb5a--- /dev/null+++ b/packages/pieces/community/smartsuite/src/lib/actions/ai/list-records.ts@@ -0,0 +1,53 @@+import { Property, createAction } from '@activepieces/pieces-framework';+import { smartsuiteAuth } from '../../auth';+import { smartSuiteApi } from '../../common';+import { smartSuiteClient } from '../../common/client';+import { smartSuiteInputs } from '../../common/inputs';+import { outputSchemas } from '../../output-schemas';++export const listRecordsAi = createAction({+ name: 'list_records',+ classification: 'SEARCH',+ displayName: 'List Records (by Table ID)',+ description: 'Lists one page of records from a table, with an optional filter and sort.',+ audience: 'ai',+ aiMetadata: {+ description: 'Returns one page of records from a SmartSuite table, keyed by field slug, plus total and hasMore. Filter is SmartSuite filter JSON, for example {"operator":"and","fields":[{"field":"status","comparison":"is","value":"complete"}]}; sort is an array like [{"field":"first_created","direction":"desc"}]. Use Get Table Schema (by ID) to learn field slugs. Page with offset. Read-only and idempotent.',+ idempotent: true,+ },+ auth: smartsuiteAuth,+ props: {+ tableId: smartSuiteInputs.aiProps.tableId(),+ filter: Property.Json({+ displayName: 'Filter',+ description: 'SmartSuite filter object: {"operator":"and"|"or","fields":[{"field":"<slug>","comparison":"is","value":"..."}]}. Leave empty for all records.',+ required: false,+ }),+ sort: Property.Json({+ displayName: 'Sort',+ description: 'Array of {"field":"<slug>","direction":"asc"|"desc"}.',+ required: false,+ }),+ limit: smartSuiteInputs.aiProps.limit(100),+ offset: smartSuiteInputs.aiProps.offset(),+ },+ outputSchema: outputSchemas['recordPage'],+ async run({ auth, propsValue }) {+ const filter = smartSuiteInputs.optionalJson({ value: propsValue.filter, label: 'Filter' });+ if (filter !== undefined && !smartSuiteInputs.isPlainObject(filter)) {+ throw new Error('Filter must be a JSON object with "operator" and "fields".');+ }+ const sort = smartSuiteInputs.optionalJson({ value: propsValue.sort, label: 'Sort' });+ if (sort !== undefined && !Array.isArray(sort)) {+ throw new Error('Sort must be a JSON array of {"field","direction"} objects.');+ }+ return smartSuiteApi.listRecordsPage({+ credentials: smartSuiteClient.credentialsOf(auth),+ tableId: propsValue.tableId,+ filter,+ sort,+ limit: smartSuiteInputs.integerInRange({ value: propsValue.limit, label: 'Limit', min: 1, max: smartSuiteApi.MAX_RECORD_PAGE_SIZE, fallback: 100 }),+ offset: smartSuiteInputs.integerInRange({ value: propsValue.offset, label: 'Offset', min: 0, max: Number.MAX_SAFE_INTEGER, fallback: 0 }),+ });+ },+});diff --git a/packages/pieces/community/smartsuite/src/lib/actions/ai/update-record-fields.ts b/packages/pieces/community/smartsuite/src/lib/actions/ai/update-record-fields.tsnew file mode 100644index 00000000000..df07b156fe4--- /dev/null+++ b/packages/pieces/community/smartsuite/src/lib/actions/ai/update-record-fields.ts@@ -0,0 +1,43 @@+import { Property, createAction } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { smartsuiteAuth } from '../../auth';+import { SmartSuiteRecord } from '../../common';+import { smartSuiteClient } from '../../common/client';+import { smartSuiteInputs } from '../../common/inputs';+import { outputSchemas } from '../../output-schemas';++export const updateRecordFieldsAi = createAction({+ name: 'update_record_fields',+ classification: 'WRITE',+ displayName: 'Update Record Fields (by ID)',+ description: 'Updates only the fields given in a JSON object keyed by field slug.',+ audience: 'ai',+ aiMetadata: {+ description: 'Patches one SmartSuite record. Only the slugs present in Fields are changed; omitted fields keep their value. To clear a field send its empty value ("" for text, [] for lists, null for single values). Same value format as Create Record (by Table ID). Returns the updated record. Idempotent: sending the same fields again leaves the record unchanged.',+ idempotent: true,+ },+ auth: smartsuiteAuth,+ props: {+ tableId: smartSuiteInputs.aiProps.tableId(),+ recordId: smartSuiteInputs.aiProps.recordId(),+ fields: Property.Json({+ displayName: 'Fields',+ description: 'JSON object keyed by field slug with the new values.',+ required: true,+ }),+ },+ outputSchema: outputSchemas['rawRecord'],+ async run({ auth, propsValue }) {+ const fields = smartSuiteInputs.requireObject({ value: propsValue.fields, label: 'Fields' });+ if (Object.keys(fields).length === 0) {+ throw new Error('Fields must contain at least one field slug to update.');+ }+ return smartSuiteClient.request<SmartSuiteRecord>({+ credentials: smartSuiteClient.credentialsOf(auth),+ method: HttpMethod.PATCH,+ path: `/applications/${smartSuiteClient.pathSegment({ value: propsValue.tableId, label: 'Table ID' })}/records/${smartSuiteClient.pathSegment({ value: propsValue.recordId, label: 'Record ID' })}/`,+ body: fields,+ operation: 'update record',+ });+ },+});diff --git a/packages/pieces/community/smartsuite/src/lib/actions/bulk-create-records.ts b/packages/pieces/community/smartsuite/src/lib/actions/bulk-create-records.tsnew file mode 100644index 00000000000..7021a23f4a5--- /dev/null+++ b/packages/pieces/community/smartsuite/src/lib/actions/bulk-create-records.ts@@ -0,0 +1,74 @@+import { Property, createAction } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { smartsuiteAuth } from '../auth';+import { SmartSuiteRecord } from '../common';+import { smartSuiteClient, SmartSuiteCredentials } from '../common/client';+import { smartSuiteInputs } from '../common/inputs';+import { smartsuiteCommon } from '../common/props';+import { outputSchemas } from '../output-schemas';++const MAX_BULK = 25;++async function bulkCreate({ credentials, tableId, records }: { credentials: SmartSuiteCredentials; tableId: unknown; records: unknown }): Promise<{ items: SmartSuiteRecord[]; count: number }> {+ const items = smartSuiteInputs.requireObjectArray({ value: records, label: 'Records', max: MAX_BULK });+ const created = await smartSuiteClient.request<SmartSuiteRecord[]>({+ credentials,+ method: HttpMethod.POST,+ path: `/applications/${smartSuiteClient.pathSegment({ value: tableId, label: 'Table' })}/records/bulk/`,+ body: { items },+ operation: 'bulk create records',+ });+ const list = Array.isArray(created) ? created : [];+ return { items: list, count: list.length };+}++function recordsProp() {+ return Property.Json({+ displayName: 'Records',+ description: `JSON array of up to ${MAX_BULK} objects keyed by field slug, for example [{"title":"A"},{"title":"B"}]. Use Get Table Schema to see the slugs.`,+ required: true,+ });+}++export const bulkCreateRecords = createAction({+ name: 'bulk_create_records',+ classification: 'WRITE',+ displayName: 'Create Records (Bulk)',+ description: `Creates up to ${MAX_BULK} records in one request.`,+ audience: 'human',+ aiMetadata: {+ description: 'Builder version with solution and table pickers; agents should use Create Records (Bulk, by ID). Creates 1-25 records. SmartSuite applies the batch as one request, so it fails or succeeds as a whole. Returns the created records with their ids. Not idempotent: running it again creates duplicates.',+ idempotent: false,+ },+ auth: smartsuiteAuth,+ props: {+ solutionId: smartsuiteCommon.solutionId,+ tableId: smartsuiteCommon.tableId,+ records: recordsProp(),+ },+ outputSchema: outputSchemas['bulkRecords'],+ async run({ auth, propsValue }) {+ return bulkCreate({ credentials: smartSuiteClient.credentialsOf(auth), tableId: propsValue.tableId, records: propsValue.records });+ },+});++export const bulkCreateRecordsById = createAction({+ name: 'bulk_create_records_by_id',+ classification: 'WRITE',+ displayName: 'Create Records (Bulk, by ID)',+ description: `Creates up to ${MAX_BULK} records in one request, by table ID.`,+ audience: 'ai',+ aiMetadata: {+ description: 'Creates 1-25 SmartSuite records in one table (Table ID from List Tables (by ID)) with a single request. Records is a JSON array of objects keyed by field slug; call Get Table Schema (by ID) first for slugs and choice values. SmartSuite applies the batch as one request, so it fails or succeeds as a whole. Returns the created records with their ids. Not idempotent: running it again creates duplicates. Next: Update Records (Bulk, by ID) or Get Record (by ID) with the returned ids.',+ idempotent: false,+ },+ auth: smartsuiteAuth,+ props: {+ tableId: smartSuiteInputs.aiProps.tableId(),+ records: recordsProp(),+ },+ outputSchema: outputSchemas['bulkRecords'],+ async run({ auth, propsValue }) {+ return bulkCreate({ credentials: smartSuiteClient.credentialsOf(auth), tableId: propsValue.tableId, records: propsValue.records });+ },+});diff --git a/packages/pieces/community/smartsuite/src/lib/actions/bulk-delete-records.ts b/packages/pieces/community/smartsuite/src/lib/actions/bulk-delete-records.tsnew file mode 100644index 00000000000..c96e4bc8ab7--- /dev/null+++ b/packages/pieces/community/smartsuite/src/lib/actions/bulk-delete-records.ts@@ -0,0 +1,66 @@+import { Property, createAction } from '@activepieces/pieces-framework';+import { smartsuiteAuth } from '../auth';+import { smartSuiteApi } from '../common';+import { smartSuiteClient, SmartSuiteCredentials } from '../common/client';+import { smartSuiteInputs } from '../common/inputs';+import { smartsuiteCommon } from '../common/props';+import { outputSchemas } from '../output-schemas';++const MAX_BULK = 25;++async function bulkDelete({ credentials, tableId, recordIds }: { credentials: SmartSuiteCredentials; tableId: unknown; recordIds: unknown }): Promise<{ deletedIds: string[]; count: number }> {+ const ids = smartSuiteInputs.requireIdList({ value: recordIds, label: 'Record IDs', max: MAX_BULK });+ const deletedIds = await smartSuiteApi.trashRecords({ credentials, tableId, recordIds: ids });+ return { deletedIds, count: deletedIds.length };+}++function recordIdsProp() {+ return Property.Array({+ displayName: 'Record IDs',+ description: `Up to ${MAX_BULK} record IDs to delete.`,+ required: true,+ });+}++export const bulkDeleteRecords = createAction({+ name: 'bulk_delete_records',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete Records (Bulk)',+ description: `Deletes up to ${MAX_BULK} records in one request.`,+ audience: 'human',+ aiMetadata: {+ description: 'Builder version with solution and table pickers; agents should use Delete Records (Bulk, by ID). Deletes 1-25 records. Moves the records to the solution trash in a single request; they can be brought back with Restore Record. Returns the IDs SmartSuite reports as deleted. Idempotent in effect: deleting records that are already in the trash leaves them deleted.',+ idempotent: true,+ },+ auth: smartsuiteAuth,+ props: {+ solutionId: smartsuiteCommon.solutionId,+ tableId: smartsuiteCommon.tableId,+ recordIds: recordIdsProp(),+ },+ outputSchema: outputSchemas['bulkDelete'],+ async run({ auth, propsValue }) {+ return bulkDelete({ credentials: smartSuiteClient.credentialsOf(auth), tableId: propsValue.tableId, recordIds: propsValue.recordIds });+ },+});++export const bulkDeleteRecordsById = createAction({+ name: 'bulk_delete_records_by_id',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete Records (Bulk, by ID)',+ description: `Deletes up to ${MAX_BULK} records in one request, by table ID.`,+ audience: 'ai',+ aiMetadata: {+ description: 'Deletes 1-25 SmartSuite records (record IDs from List Records) from one table (Table ID from List Tables (by ID)). Moves the records to the solution trash in a single request; they can be brought back with Restore Record. Returns the IDs SmartSuite reports as deleted. Idempotent in effect: deleting records that are already in the trash leaves them deleted. To undo, use List Deleted Records (by ID) then Restore Record (by ID).',+ idempotent: true,+ },+ auth: smartsuiteAuth,+ props: {+ tableId: smartSuiteInputs.aiProps.tableId(),+ recordIds: recordIdsProp(),+ },+ outputSchema: outputSchemas['bulkDelete'],+ async run({ auth, propsValue }) {+ return bulkDelete({ credentials: smartSuiteClient.credentialsOf(auth), tableId: propsValue.tableId, recordIds: propsValue.recordIds });+ },+});diff --git a/packages/pieces/community/smartsuite/src/lib/actions/bulk-update-records.ts b/packages/pieces/community/smartsuite/src/lib/actions/bulk-update-records.tsnew file mode 100644index 00000000000..747f6c5d915--- /dev/null+++ b/packages/pieces/community/smartsuite/src/lib/actions/bulk-update-records.ts@@ -0,0 +1,82 @@+import { Property, createAction } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { smartsuiteAuth } from '../auth';+import { SmartSuiteRecord } from '../common';+import { smartSuiteClient, SmartSuiteCredentials } from '../common/client';+import { smartSuiteInputs } from '../common/inputs';+import { smartsuiteCommon } from '../common/props';+import { outputSchemas } from '../output-schemas';++const MAX_BULK = 25;++async function bulkUpdate({ credentials, tableId, records }: { credentials: SmartSuiteCredentials; tableId: unknown; records: unknown }): Promise<{ items: SmartSuiteRecord[]; count: number }> {+ const items = smartSuiteInputs.requireObjectArray({ value: records, label: 'Records', max: MAX_BULK });+ items.forEach((record, index) => {+ if (typeof record['id'] !== 'string' || record['id'].trim().length === 0) {+ throw new Error(`Records item ${index + 1} needs an "id" with the record ID to update.`);+ }+ if (Object.keys(record).length < 2) {+ throw new Error(`Records item ${index + 1} has no fields to update.`);+ }+ });+ const updated = await smartSuiteClient.request<SmartSuiteRecord[]>({+ credentials,+ method: HttpMethod.PATCH,+ path: `/applications/${smartSuiteClient.pathSegment({ value: tableId, label: 'Table' })}/records/bulk/`,+ body: { items },+ operation: 'bulk update records',+ });+ const list = Array.isArray(updated) ? updated : [];+ return { items: list, count: list.length };+}++function recordsProp() {+ return Property.Json({+ displayName: 'Records',+ description: `JSON array of up to ${MAX_BULK} objects, each with "id" and the field slugs to change, for example [{"id":"64f...","status":{"value":"complete"}}].`,+ required: true,+ });+}++export const bulkUpdateRecords = createAction({+ name: 'bulk_update_records',+ classification: 'WRITE',+ displayName: 'Update Records (Bulk)',+ description: `Updates up to ${MAX_BULK} records in one request.`,+ audience: 'human',+ aiMetadata: {+ description: 'Builder version with solution and table pickers; agents should use Update Records (Bulk, by ID). Updates 1-25 records. Each item has "id" plus the field slugs to change; omitted fields keep their value. Returns the updated records. Idempotent: sending the same values again leaves the records unchanged.',+ idempotent: true,+ },+ auth: smartsuiteAuth,+ props: {+ solutionId: smartsuiteCommon.solutionId,+ tableId: smartsuiteCommon.tableId,+ records: recordsProp(),+ },+ outputSchema: outputSchemas['bulkRecords'],+ async run({ auth, propsValue }) {+ return bulkUpdate({ credentials: smartSuiteClient.credentialsOf(auth), tableId: propsValue.tableId, records: propsValue.records });+ },+});++export const bulkUpdateRecordsById = createAction({+ name: 'bulk_update_records_by_id',+ classification: 'WRITE',+ displayName: 'Update Records (Bulk, by ID)',+ description: `Updates up to ${MAX_BULK} records in one request, by table ID.`,+ audience: 'ai',+ aiMetadata: {+ description: 'Updates 1-25 SmartSuite records in one table (Table ID from List Tables (by ID)) with a single request. Get record ids from List Records and slugs from Get Table Schema (by ID). Each item has "id" plus the field slugs to change; omitted fields keep their value. Returns the updated records. Idempotent: sending the same values again leaves the records unchanged.',+ idempotent: true,+ },+ auth: smartsuiteAuth,+ props: {+ tableId: smartSuiteInputs.aiProps.tableId(),+ records: recordsProp(),+ },+ outputSchema: outputSchemas['bulkRecords'],+ async run({ auth, propsValue }) {+ return bulkUpdate({ credentials: smartSuiteClient.credentialsOf(auth), tableId: propsValue.tableId, records: propsValue.records });+ },+});diff --git a/packages/pieces/community/smartsuite/src/lib/actions/create-record.ts b/packages/pieces/community/smartsuite/src/lib/actions/create-record.tsindex 71815002654..e2cf462a320 100644--- a/packages/pieces/community/smartsuite/src/lib/actions/create-record.ts+++ b/packages/pieces/community/smartsuite/src/lib/actions/create-record.ts@@ -2,16 +2,18 @@ import { createAction } from '@activepieces/pieces-framework';import { HttpMethod } from '@activepieces/pieces-common';import { smartsuiteAuth } from '../auth';import { smartsuiteCommon, formatRecordFields, transformRecordFields } from '../common/props';-import { smartSuiteApiCall, TableStucture } from '../common';+import { smartSuiteApi, SmartSuiteRecord } from '../common';+import { smartSuiteClient } from '../common/client';+import { outputSchemas } from '../output-schemas';export const createRecord = createAction({name: 'create_record',classification: 'WRITE',displayName: 'Create a Record',description: 'Creates a new record in the specified table.',- audience: 'both',+ audience: 'human',aiMetadata: {- description: 'Adds a new record (row) to a SmartSuite table, with field values mapped against the live table schema. Use when an agent needs to insert data into a SmartSuite database; requires the target solution and table, plus the field values to set. Not idempotent — each call creates a separate record.',+ description: 'Adds a new record (row) to a SmartSuite table using form fields built from the table schema; the output is keyed by field label. Agents should use Create Record (by Table ID) instead. Not idempotent: each call creates a separate record.',idempotent: false,},auth: smartsuiteAuth,@@ -20,51 +22,18 @@ export const createRecord = createAction({tableId: smartsuiteCommon.tableId,fields: smartsuiteCommon.tableFields,},+ outputSchema: outputSchemas['labelledRecord'],async run({ auth, propsValue }) {- const { tableId, fields, solutionId } = propsValue;-- const tableResponse = await smartSuiteApiCall<{- structure: TableStucture[];- }>({- apiKey: auth.props.apiKey,- accountId: auth.props.accountId,- method: HttpMethod.GET,- resourceUri: `/applications/${tableId}`,+ const { tableId, fields } = propsValue;+ const credentials = smartSuiteClient.credentialsOf(auth);+ const table = await smartSuiteApi.getTable({ credentials, tableId });+ const response = await smartSuiteClient.request<SmartSuiteRecord>({+ credentials,+ method: HttpMethod.POST,+ path: `/applications/${smartSuiteClient.pathSegment({ value: tableId, label: 'Table' })}/records/`,+ body: formatRecordFields({ tableSchema: table.structure, tableValues: fields ?? {} }),+ operation: 'create record',});- const tableSchema = tableResponse.structure;-- const formattedFields = formatRecordFields(tableSchema, fields);-- try {- const response = await smartSuiteApiCall<Record<string, any>>({- apiKey: auth.props.apiKey,- accountId: auth.props.accountId,- method: HttpMethod.POST,- resourceUri: `/applications/${tableId}/records/`,- body: formattedFields,- });-- const transformedFields = transformRecordFields(tableSchema, response);-- return transformedFields;- } catch (error: any) {- if (error.response?.status === 422) {- throw new Error(- `Invalid request: ${- error.response?.body?.message || 'Missing required fields or invalid data'- }`,- );- }-- if (error.response?.status === 403) {- throw new Error('You do not have permission to create records in this table');- }-- if (error.response?.status === 404) {- throw new Error(`Solution or table not found: ${solutionId}/${tableId}`);- }-- throw new Error(`Failed to create record: ${error.message || 'Unknown error'}`);- }+ return transformRecordFields({ tableSchema: table.structure, tableValues: response });},});diff --git a/packages/pieces/community/smartsuite/src/lib/actions/create-table.ts b/packages/pieces/community/smartsuite/src/lib/actions/create-table.tsnew file mode 100644index 00000000000..7764754a684--- /dev/null+++ b/packages/pieces/community/smartsuite/src/lib/actions/create-table.ts@@ -0,0 +1,74 @@+import { Property, createAction } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { smartsuiteAuth } from '../auth';+import { SmartSuiteTable } from '../common';+import { smartSuiteClient, SmartSuiteCredentials } from '../common/client';+import { smartSuiteInputs } from '../common/inputs';+import { smartsuiteCommon } from '../common/props';+import { tableSummary } from '../common/tables';+import { outputSchemas } from '../output-schemas';++async function create({ credentials, solutionId, name }: { credentials: SmartSuiteCredentials; solutionId: unknown; name: unknown }) {+ const solution = smartSuiteInputs.requireText({ value: solutionId, label: 'Solution' });+ const tableName = smartSuiteInputs.requireText({ value: name, label: 'Table Name' });+ const table = await smartSuiteClient.request<SmartSuiteTable>({+ credentials,+ method: HttpMethod.POST,+ path: '/applications/',+ body: { name: tableName, solution, structure: [] },+ operation: 'create table',+ });+ return {+ ...tableSummary.summarize(table),+ fields: (table.structure ?? []).map((field) => tableSummary.describeField(field)),+ };+}++function nameProp() {+ return Property.ShortText({+ displayName: 'Table Name',+ required: true,+ });+}++export const createTable = createAction({+ name: 'create_table',+ classification: 'WRITE',+ displayName: 'Create Table',+ description: 'Creates a new table in a solution.',+ audience: 'human',+ aiMetadata: {+ description: 'Builder version with a solution picker; agents should use Create Table (by ID). SmartSuite adds its default fields (Title, Description, Assigned To, Status, Due Date, Priority and system fields). Needs permission to change the solution. Returns the table and its fields. Not idempotent: each call creates another table.',+ idempotent: false,+ },+ auth: smartsuiteAuth,+ props: {+ solutionId: smartsuiteCommon.solutionId,+ name: nameProp(),+ },+ outputSchema: outputSchemas['tableSchema'],+ async run({ auth, propsValue }) {+ return create({ credentials: smartSuiteClient.credentialsOf(auth), solutionId: propsValue.solutionId, name: propsValue.name });+ },+});++export const createTableById = createAction({+ name: 'create_table_by_id',+ classification: 'WRITE',+ displayName: 'Create Table (by ID)',+ description: 'Creates a new table in a solution, by solution ID.',+ audience: 'ai',+ aiMetadata: {+ description: 'Creates a new SmartSuite table (application) in a solution (Solution ID from List Solutions). SmartSuite adds its default fields (Title, Description, Assigned To, Status, Due Date, Priority and system fields). Needs permission to change the solution. Returns the table and its fields. Not idempotent: each call creates another table. Check List Tables (by ID) first to avoid a duplicate name. Next: Add Field (by ID) with the returned id.',+ idempotent: false,+ },+ auth: smartsuiteAuth,+ props: {+ solutionId: smartSuiteInputs.aiProps.solutionId(),+ name: nameProp(),+ },+ outputSchema: outputSchemas['tableSchema'],+ async run({ auth, propsValue }) {+ return create({ credentials: smartSuiteClient.credentialsOf(auth), solutionId: propsValue.solutionId, name: propsValue.name });+ },+});diff --git a/packages/pieces/community/smartsuite/src/lib/actions/delete-record.ts b/packages/pieces/community/smartsuite/src/lib/actions/delete-record.tsindex 1bef482bf4f..838e0307c10 100644--- a/packages/pieces/community/smartsuite/src/lib/actions/delete-record.ts+++ b/packages/pieces/community/smartsuite/src/lib/actions/delete-record.ts@@ -1,17 +1,18 @@import { createAction } from '@activepieces/pieces-framework';-import { HttpMethod} from '@activepieces/pieces-common';+import { HttpMethod } from '@activepieces/pieces-common';import { smartsuiteAuth } from '../auth';import { smartsuiteCommon } from '../common/props';-import { smartSuiteApiCall } from '../common';+import { smartSuiteClient } from '../common/client';+import { outputSchemas } from '../output-schemas';export const deleteRecord = createAction({name: 'delete_record',classification: 'DESTRUCTIVE',displayName: 'Delete a Record',description: 'Deletes a record from the specified table',- audience: 'both',+ audience: 'human',aiMetadata: {- description: 'Permanently deletes a single SmartSuite record identified by its record ID from the given solution and table. Use when an agent needs to remove a known record. Idempotent in effect — once the record is gone the call has no further effect, though deleting an already-removed record returns a not-found error.',+ description: 'Moves one SmartSuite record to the solution trash (it can be brought back with Restore Record). Agents should use Delete Record (by ID). Idempotent: deleting a record that is already in the trash succeeds again, and a record that no longer exists at all (404) succeeds with alreadyDeleted true.',idempotent: true,},auth: smartsuiteAuth,@@ -20,28 +21,24 @@ export const deleteRecord = createAction({tableId: smartsuiteCommon.tableId,recordId: smartsuiteCommon.recordId,},+ outputSchema: outputSchemas['deleteRecord'],async run({ auth, propsValue }) {const { tableId, recordId } = propsValue;-+ const recordPath = `/applications/${smartSuiteClient.pathSegment({ value: tableId, label: 'Table' })}/records/${smartSuiteClient.pathSegment({ value: recordId, label: 'Record ID' })}/`;try {- const response = await smartSuiteApiCall<Record<string, any>>({- apiKey: auth.props.apiKey,- accountId: auth.props.accountId,+ const response = await smartSuiteClient.request<unknown>({+ credentials: smartSuiteClient.credentialsOf(auth),method: HttpMethod.DELETE,- resourceUri: `/applications/${tableId}/records/${recordId}/`,+ path: recordPath,+ operation: 'delete record',});-- return response;- } catch (error: any) {- if (error.response?.status === 404) {- throw new Error(`Record with ID ${recordId} not found in table ${tableId}`);+ const vendorFields = response !== null && typeof response === 'object' && !Array.isArray(response) ? response : {};+ return { ...vendorFields, id: String(recordId).trim(), deleted: true, alreadyDeleted: false };+ } catch (error) {+ if (smartSuiteClient.statusOf(error) === 404) {+ return { id: String(recordId).trim(), deleted: true, alreadyDeleted: true };}-- if (error.response?.status === 403) {- throw new Error('You do not have permission to delete this record');- }-- throw new Error(`Failed to delete record: ${error.message || 'Unknown error'}`);+ throw error;}},});diff --git a/packages/pieces/community/smartsuite/src/lib/actions/find-records.ts b/packages/pieces/community/smartsuite/src/lib/actions/find-records.tsindex a0412a1fdc4..32e72afcdfb 100644--- a/packages/pieces/community/smartsuite/src/lib/actions/find-records.ts+++ b/packages/pieces/community/smartsuite/src/lib/actions/find-records.ts@@ -1,142 +1,64 @@-import {- DropdownOption,- Property,- createAction,-} from '@activepieces/pieces-framework';-import { HttpMethod } from '@activepieces/pieces-common';+import { Property, createAction } from '@activepieces/pieces-framework';import { smartsuiteAuth } from '../auth';import { smartsuiteCommon, transformRecordFields } from '../common/props';-import { smartSuiteApiCall, TableStucture } from '../common';+import { smartSuiteApi } from '../common';+import { smartSuiteClient } from '../common/client';+import { smartSuiteInputs } from '../common/inputs';+import { outputSchemas } from '../output-schemas';++const HARD_MAX_RECORDS = 10_000;export const findRecords = createAction({name: 'find_records',classification: 'SEARCH',displayName: 'Find Records',description: 'Searches for records in the specified table based on criteria.',- audience: 'both',+ audience: 'human',aiMetadata: {- description: 'Searches a SmartSuite table for records where a chosen field exactly matches a given value, paging through all results. Use when an agent needs to look up records by a field value (for example to find a record before updating or deleting it); requires the solution, table, the field to match on, and the value to match. Idempotent — it only reads data.',+ description: 'Finds SmartSuite records where one chosen field equals a value, keyed by field label. Agents should use List Records (by Table ID) with a filter instead. Read-only and idempotent.',idempotent: true,},auth: smartsuiteAuth,props: {solutionId: smartsuiteCommon.solutionId,tableId: smartsuiteCommon.tableId,- searchField: Property.Dropdown({- auth: smartsuiteAuth,- displayName: 'Search Field',- required: true,- refreshers: ['tableId'],- options: async ({ auth, tableId }) => {- if (!auth || !tableId) {- return {- disabled: true,- options: [],- placeholder: 'Please connect your account first.',- };- }-- const { apiKey, accountId } = auth.props;-- const response = await smartSuiteApiCall<{- structure: TableStucture[];- }>({- apiKey,- accountId,- method: HttpMethod.GET,- resourceUri: `/applications/${tableId}`,- });-- const options: DropdownOption<string>[] = [];-- for (const field of response.structure) {- if (field.params.is_auto_generated || field.params.system) {- continue;- }-- options.push({ label: field.label, value: field.slug });- }- return {- disabled: false,- options,- };- },- }),+ searchField: smartsuiteCommon.tableFieldDropdown({ displayName: 'Search Field', required: true }),searchValue: Property.ShortText({displayName: 'Search Value',required: true,}),+ maxRecords: Property.Number({+ displayName: 'Max Records',+ description: `Stop after this many matches (1-${HARD_MAX_RECORDS}). Leave empty to return all matches up to ${HARD_MAX_RECORDS}; Has More tells you if more exist.`,+ required: false,+ }),},+ outputSchema: outputSchemas['findRecords'],async run({ auth, propsValue }) {- const { solutionId, tableId, searchField, searchValue } = propsValue;-- try {- const tableResponse = await smartSuiteApiCall<{- structure: TableStucture[];- }>({- apiKey: auth.props.apiKey,- accountId: auth.props.accountId,- method: HttpMethod.GET,- resourceUri: `/applications/${tableId}`,- });- const tableSchema = tableResponse.structure;-- const matchedRecords = [];-- const qs = { limit: 100, offset: 0 };- let hasMore = true;-- do {- const response = await smartSuiteApiCall<{ items: Record<string, any>[] }>({- accountId: auth.props.accountId,- apiKey: auth.props.apiKey,- method: HttpMethod.POST,- resourceUri: `/applications/${tableId}/records/list/`,- query: qs,- body: {- filter: {- operator: 'and',- fields: [- {- field: searchField,- comparison: 'is',- value: searchValue,- },- ],- },- },- });- const items = response.items || [];- matchedRecords.push(...items);-- hasMore = items.length > 0;- if (hasMore) {- qs.offset = Number(qs.offset) + Number(qs.limit);- }- } while (hasMore);-- return {- found: matchedRecords.length > 0,- result: matchedRecords.map((record) => transformRecordFields(tableSchema, record)),- };- } catch (error: any) {- if (error.response?.status === 400) {- throw new Error(- `Invalid filter or sort criteria: ${- error.response?.body?.message || 'Please check your filter JSON format'- }`,- );- }-- if (error.response?.status === 403) {- throw new Error('You do not have permission to access this table');- }-- if (error.response?.status === 404) {- throw new Error(`Solution or table not found: ${solutionId}/${tableId}`);- }-- throw new Error(`Failed to find records: ${error.message || 'Unknown error'}`);- }+ const { tableId, searchField, searchValue } = propsValue;+ const maxRecords = smartSuiteInputs.integerInRange({+ value: propsValue.maxRecords,+ label: 'Max Records',+ min: 1,+ max: HARD_MAX_RECORDS,+ fallback: HARD_MAX_RECORDS,+ });+ const field = smartSuiteInputs.requireText({ value: searchField, label: 'Search Field' });+ const credentials = smartSuiteClient.credentialsOf(auth);+ const table = await smartSuiteApi.getTable({ credentials, tableId });+ const { items, hasMore } = await smartSuiteApi.collectRecords({+ credentials,+ tableId,+ filter: {+ operator: 'and',+ fields: [{ field, comparison: 'is', value: searchValue }],+ },+ maxRecords,+ });+ return {+ found: items.length > 0,+ result: items.map((record) => transformRecordFields({ tableSchema: table.structure, tableValues: record })),+ hasMore,+ };},});diff --git a/packages/pieces/community/smartsuite/src/lib/actions/get-file-url.ts b/packages/pieces/community/smartsuite/src/lib/actions/get-file-url.tsnew file mode 100644index 00000000000..4d34671aff5--- /dev/null+++ b/packages/pieces/community/smartsuite/src/lib/actions/get-file-url.ts@@ -0,0 +1,101 @@+import { Property, createAction } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { smartsuiteAuth } from '../auth';+import { SmartSuiteRecord } from '../common';+import { smartSuiteClient, SmartSuiteCredentials } from '../common/client';+import { smartSuiteInputs } from '../common/inputs';+import { smartsuiteCommon } from '../common/props';+import { outputSchemas } from '../output-schemas';++const MAX_FILES = 50;++async function fileUrl({ credentials, handle }: { credentials: SmartSuiteCredentials; handle: string }): Promise<string> {+ const response = await smartSuiteClient.request<unknown>({+ credentials,+ method: HttpMethod.GET,+ path: `/shared-files/${smartSuiteClient.pathSegment({ value: handle, label: 'File Handle' })}/url/`,+ operation: 'get file URL',+ });+ const url = typeof response === 'string' ? response : smartSuiteInputs.isPlainObject(response) ? response['url'] : undefined;+ if (typeof url !== 'string' || url.length === 0) {+ throw new Error(`SmartSuite returned no download URL for file handle ${handle}.`);+ }+ return url;+}++function fileName(file: Record<string, unknown>): string | null {+ const metadata = file['metadata'];+ const name = smartSuiteInputs.isPlainObject(metadata) ? metadata['filename'] : undefined;+ return typeof name === 'string' ? name : null;+}++export const getFileUrl = createAction({+ name: 'download_record_file',+ classification: 'READ',+ displayName: 'Get File Download URLs',+ description: 'Gets temporary download links for the files in a record\'s Files & Images field.',+ audience: 'human',+ aiMetadata: {+ description: 'Builder version that picks the record and Files & Images field; agents should use Get File Download URL (by Handle). Returns a temporary URL for each file in the field (up to 50). Files are not downloaded. Read-only and idempotent.',+ idempotent: true,+ },+ auth: smartsuiteAuth,+ props: {+ solutionId: smartsuiteCommon.solutionId,+ tableId: smartsuiteCommon.tableId,+ recordId: smartsuiteCommon.recordDropdown({ displayName: 'Record' }),+ field: smartsuiteCommon.tableFieldDropdown({+ displayName: 'File Field',+ description: 'The Files & Images field to read.',+ required: true,+ onlyTypes: ['filefield'],+ }),+ },+ outputSchema: outputSchemas['recordFileUrls'],+ async run({ auth, propsValue }) {+ const credentials = smartSuiteClient.credentialsOf(auth);+ const field = smartSuiteInputs.requireText({ value: propsValue.field, label: 'File Field' });+ const record = await smartSuiteClient.request<SmartSuiteRecord>({+ credentials,+ method: HttpMethod.GET,+ path: `/applications/${smartSuiteClient.pathSegment({ value: propsValue.tableId, label: 'Table' })}/records/${smartSuiteClient.pathSegment({ value: propsValue.recordId, label: 'Record' })}/`,+ operation: 'get record',+ });+ const stored = record[field];+ const entries = (Array.isArray(stored) ? stored : []).filter(smartSuiteInputs.isPlainObject).filter((file) => typeof file['handle'] === 'string');+ if (entries.length > MAX_FILES) {+ throw new Error(`The field holds ${entries.length} files; this action returns at most ${MAX_FILES}. Use Get File Download URL (by Handle) per file.`);+ }+ const files = [];+ for (const file of entries) {+ const handle = String(file['handle']);+ files.push({ handle, name: fileName(file), url: await fileUrl({ credentials, handle }) });+ }+ return { recordId: String(propsValue.recordId), field, files, count: files.length };+ },+});++export const getFileUrlByHandle = createAction({+ name: 'download_record_file_by_handle',+ classification: 'READ',+ displayName: 'Get File Download URL (by Handle)',+ description: 'Gets a temporary download link for one file, by its file handle.',+ audience: 'ai',+ aiMetadata: {+ description: 'Returns a temporary download URL for one SmartSuite file, given its file handle (the "handle" value inside a Files & Images field of a record from Get Record (by ID) or List Records). The file itself is not downloaded; the URL expires, so use it soon. Read-only and idempotent.',+ idempotent: true,+ },+ auth: smartsuiteAuth,+ props: {+ fileHandle: Property.ShortText({+ displayName: 'File Handle',+ description: 'The "handle" of the file, found in the record\'s Files & Images field.',+ required: true,+ }),+ },+ outputSchema: outputSchemas['fileUrl'],+ async run({ auth, propsValue }) {+ const handle = smartSuiteInputs.requireText({ value: propsValue.fileHandle, label: 'File Handle' });+ return { handle, url: await fileUrl({ credentials: smartSuiteClient.credentialsOf(auth), handle }) };+ },+});diff --git a/packages/pieces/community/smartsuite/src/lib/actions/get-member.ts b/packages/pieces/community/smartsuite/src/lib/actions/get-member.tsnew file mode 100644index 00000000000..3742dffa95b--- /dev/null+++ b/packages/pieces/community/smartsuite/src/lib/actions/get-member.ts@@ -0,0 +1,59 @@+import { Property, createAction } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { smartsuiteAuth } from '../auth';+import { smartSuiteClient, SmartSuiteCredentials } from '../common/client';+import { smartsuiteCommon } from '../common/props';+import { outputSchemas } from '../output-schemas';++async function getOne({ credentials, memberId }: { credentials: SmartSuiteCredentials; memberId: unknown }): Promise<Record<string, unknown>> {+ return smartSuiteClient.request<Record<string, unknown>>({+ credentials,+ method: HttpMethod.GET,+ path: `/applications/members/records/${smartSuiteClient.pathSegment({ value: memberId, label: 'Member ID' })}/`,+ operation: 'get member',+ });+}++export const getMember = createAction({+ name: 'get_member',+ classification: 'READ',+ displayName: 'Get Member',+ description: 'Gets one workspace member.',+ audience: 'human',+ aiMetadata: {+ description: 'Builder version with a member picker; agents should use Get Member (by ID). Returns full name, emails, role, job title and time zone. Read-only and idempotent.',+ idempotent: true,+ },+ auth: smartsuiteAuth,+ props: {+ memberId: smartsuiteCommon.memberDropdown({ displayName: 'Member', required: true }),+ },+ outputSchema: outputSchemas['member'],+ async run({ auth, propsValue }) {+ return getOne({ credentials: smartSuiteClient.credentialsOf(auth), memberId: propsValue.memberId });+ },+});++export const getMemberById = createAction({+ name: 'get_member_by_id',+ classification: 'READ',+ displayName: 'Get Member (by ID)',+ description: 'Gets one workspace member by member ID.',+ audience: 'ai',+ aiMetadata: {+ description: 'Returns one SmartSuite workspace member by member ID (the IDs found in user fields, "by" values, comment authors and List Members): full name, emails, role, job title, time zone. Read-only and idempotent.',+ idempotent: true,+ },+ auth: smartsuiteAuth,+ props: {+ memberId: Property.ShortText({+ displayName: 'Member ID',+ description: 'The member ID. Get it from List Members.',+ required: true,+ }),+ },+ outputSchema: outputSchemas['member'],+ async run({ auth, propsValue }) {+ return getOne({ credentials: smartSuiteClient.credentialsOf(auth), memberId: propsValue.memberId });+ },+});diff --git a/packages/pieces/community/smartsuite/src/lib/actions/get-record.ts b/packages/pieces/community/smartsuite/src/lib/actions/get-record.tsindex 08bbe93760c..16ff3f4082c 100644--- a/packages/pieces/community/smartsuite/src/lib/actions/get-record.ts+++ b/packages/pieces/community/smartsuite/src/lib/actions/get-record.ts@@ -2,16 +2,18 @@ import { createAction } from '@activepieces/pieces-framework';import { HttpMethod } from '@activepieces/pieces-common';import { smartsuiteAuth } from '../auth';import { smartsuiteCommon, transformRecordFields } from '../common/props';-import { smartSuiteApiCall, TableStucture } from '../common';+import { smartSuiteApi, SmartSuiteRecord } from '../common';+import { smartSuiteClient } from '../common/client';+import { outputSchemas } from '../output-schemas';export const getRecord = createAction({name: 'get_record',classification: 'READ',displayName: 'Get a Record',description: 'Retrieves a specific record by ID',- audience: 'both',+ audience: 'human',aiMetadata: {- description: 'Fetches a single SmartSuite record by its record ID, with field values resolved against the live table schema. Use when an agent already has a record ID and needs its current field values; requires the solution, table, and record ID. Idempotent — it only reads data.',+ description: 'Fetches a single SmartSuite record by its record ID, with fields keyed by their table label (for example "Title", "Status"). Agents should use Get Record (by ID), which returns values keyed by field slug. Read-only and idempotent.',idempotent: true,},auth: smartsuiteAuth,@@ -20,39 +22,18 @@ export const getRecord = createAction({tableId: smartsuiteCommon.tableId,recordId: smartsuiteCommon.recordId,},+ outputSchema: outputSchemas['labelledRecord'],async run({ auth, propsValue }) {const { tableId, recordId } = propsValue;-- try {- const tableResponse = await smartSuiteApiCall<{- structure: TableStucture[];- }>({- apiKey: auth.props.apiKey,- accountId: auth.props.accountId,- method: HttpMethod.GET,- resourceUri: `/applications/${tableId}`,- });- const tableSchema = tableResponse.structure;- const response = await smartSuiteApiCall<Record<string, any>>({- apiKey: auth.props.apiKey,- accountId: auth.props.accountId,- method: HttpMethod.GET,- resourceUri: `/applications/${tableId}/records/${recordId}/`,- });-- const transformedFields = transformRecordFields(tableSchema, response);-- return transformedFields;- } catch (error: any) {- if (error.response?.status === 403) {- throw new Error('You do not have permission to access this record');- }-- if (error.response?.status === 404) {- throw new Error(`Record with ID ${recordId} not found in table ${tableId}`);- }-- throw new Error(`Failed to get record: ${error.message || 'Unknown error'}`);- }+ const credentials = smartSuiteClient.credentialsOf(auth);+ const recordPath = `/applications/${smartSuiteClient.pathSegment({ value: tableId, label: 'Table' })}/records/${smartSuiteClient.pathSegment({ value: recordId, label: 'Record ID' })}/`;+ const table = await smartSuiteApi.getTable({ credentials, tableId });+ const response = await smartSuiteClient.request<SmartSuiteRecord>({+ credentials,+ method: HttpMethod.GET,+ path: recordPath,+ operation: 'get record',+ });+ return transformRecordFields({ tableSchema: table.structure, tableValues: response });},});diff --git a/packages/pieces/community/smartsuite/src/lib/actions/get-solution.ts b/packages/pieces/community/smartsuite/src/lib/actions/get-solution.tsnew file mode 100644index 00000000000..48c7df520ff--- /dev/null+++ b/packages/pieces/community/smartsuite/src/lib/actions/get-solution.ts@@ -0,0 +1,56 @@+import { createAction } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { smartsuiteAuth } from '../auth';+import { smartSuiteClient, SmartSuiteCredentials } from '../common/client';+import { smartSuiteInputs } from '../common/inputs';+import { smartsuiteCommon } from '../common/props';+import { outputSchemas } from '../output-schemas';++async function getOne({ credentials, solutionId }: { credentials: SmartSuiteCredentials; solutionId: unknown }): Promise<Record<string, unknown>> {+ return smartSuiteClient.request<Record<string, unknown>>({+ credentials,+ method: HttpMethod.GET,+ path: `/solutions/${smartSuiteClient.pathSegment({ value: solutionId, label: 'Solution' })}/`,+ operation: 'get solution',+ });+}++export const getSolution = createAction({+ name: 'get_solution',+ classification: 'READ',+ displayName: 'Get Solution',+ description: 'Gets the details of one solution.',+ audience: 'human',+ aiMetadata: {+ description: 'Builder version with a solution picker; agents should use Get Solution (by ID). Returns the solution name, status, permissions and counts. Read-only and idempotent.',+ idempotent: true,+ },+ auth: smartsuiteAuth,+ props: {+ solutionId: smartsuiteCommon.solutionId,+ },+ outputSchema: outputSchemas['solution'],+ async run({ auth, propsValue }) {+ return getOne({ credentials: smartSuiteClient.credentialsOf(auth), solutionId: propsValue.solutionId });+ },+});++export const getSolutionById = createAction({+ name: 'get_solution_by_id',+ classification: 'READ',+ displayName: 'Get Solution (by ID)',+ description: 'Gets the details of one solution, by solution ID.',+ audience: 'ai',+ aiMetadata: {+ description: 'Returns one SmartSuite solution by its Solution ID from List Solutions (name, status, permissions, counts). Next: List Tables (by ID) for its tables. Read-only and idempotent.',+ idempotent: true,+ },+ auth: smartsuiteAuth,+ props: {+ solutionId: smartSuiteInputs.aiProps.solutionId(),+ },+ outputSchema: outputSchemas['solution'],+ async run({ auth, propsValue }) {+ return getOne({ credentials: smartSuiteClient.credentialsOf(auth), solutionId: propsValue.solutionId });+ },+});diff --git a/packages/pieces/community/smartsuite/src/lib/actions/get-table-schema.ts b/packages/pieces/community/smartsuite/src/lib/actions/get-table-schema.tsnew file mode 100644index 00000000000..ce2dfecd611--- /dev/null+++ b/packages/pieces/community/smartsuite/src/lib/actions/get-table-schema.ts@@ -0,0 +1,57 @@+import { createAction } from '@activepieces/pieces-framework';+import { smartsuiteAuth } from '../auth';+import { smartSuiteApi } from '../common';+import { smartSuiteClient, SmartSuiteCredentials } from '../common/client';+import { smartSuiteInputs } from '../common/inputs';+import { smartsuiteCommon } from '../common/props';+import { tableSummary } from '../common/tables';+import { outputSchemas } from '../output-schemas';++async function describeTable({ credentials, tableId }: { credentials: SmartSuiteCredentials; tableId: unknown }) {+ const table = await smartSuiteApi.getTable({ credentials, tableId });+ return {+ ...tableSummary.summarize(table),+ fields: table.structure.map((field) => tableSummary.describeField(field)),+ };+}++export const getTableSchema = createAction({+ name: 'get_table_schema',+ classification: 'READ',+ displayName: 'Get Table Schema',+ description: 'Gets a table and its fields (slug, label, type and choices).',+ audience: 'human',+ aiMetadata: {+ description: 'Builder version with solution and table pickers; agents should use Get Table Schema (by ID). Returns every field of the table with slug, label, type, required/system flags and choices. Read-only and idempotent.',+ idempotent: true,+ },+ auth: smartsuiteAuth,+ props: {+ solutionId: smartsuiteCommon.solutionId,+ tableId: smartsuiteCommon.tableId,+ },+ outputSchema: outputSchemas['tableSchema'],+ async run({ auth, propsValue }) {+ return describeTable({ credentials: smartSuiteClient.credentialsOf(auth), tableId: propsValue.tableId });+ },+});++export const getTableSchemaById = createAction({+ name: 'get_table_schema_by_id',+ classification: 'READ',+ displayName: 'Get Table Schema (by ID)',+ description: 'Gets a table and its fields (slug, label, type and choices), by table ID.',+ audience: 'ai',+ aiMetadata: {+ description: 'Returns a SmartSuite table (Table ID from List Tables (by ID)) with every field: slug (the key to use in record JSON), label, type, whether it is required or system-managed, the choice values of select/status fields and the linked table of linked-record fields. Call this before List Records, Create Record (by Table ID), Update Record Fields or the bulk actions. Read-only and idempotent.',+ idempotent: true,+ },+ auth: smartsuiteAuth,+ props: {+ tableId: smartSuiteInputs.aiProps.tableId(),+ },+ outputSchema: outputSchemas['tableSchema'],+ async run({ auth, propsValue }) {+ return describeTable({ credentials: smartSuiteClient.credentialsOf(auth), tableId: propsValue.tableId });+ },+});diff --git a/packages/pieces/community/smartsuite/src/lib/actions/list-comments.ts b/packages/pieces/community/smartsuite/src/lib/actions/list-comments.tsnew file mode 100644index 00000000000..44f6a354e0d--- /dev/null+++ b/packages/pieces/community/smartsuite/src/lib/actions/list-comments.ts@@ -0,0 +1,63 @@+import { createAction } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { smartsuiteAuth } from '../auth';+import { smartSuitePaginatedApiCall } from '../common';+import { SmartSuiteCredentials } from '../common/client';+import { smartSuiteInputs } from '../common/inputs';+import { smartsuiteCommon } from '../common/props';+import { outputSchemas } from '../output-schemas';++async function listForRecord({ credentials, recordId }: { credentials: SmartSuiteCredentials; recordId: unknown }) {+ const record = smartSuiteInputs.requireText({ value: recordId, label: 'Record ID' });+ const items = await smartSuitePaginatedApiCall<Record<string, unknown>>({+ apiKey: credentials.apiKey,+ accountId: credentials.accountId,+ method: HttpMethod.GET,+ resourceUri: '/comments/',+ query: { record },+ operation: 'list comments',+ });+ return { items, count: items.length };+}++export const listComments = createAction({+ name: 'list_comments',+ classification: 'SEARCH',+ displayName: 'List Comments',+ description: 'Lists the comments on a record.',+ audience: 'human',+ aiMetadata: {+ description: 'Builder version with solution, table and record pickers; agents should use List Comments (by ID). Returns every comment on the record (author member ID, created time, message HTML and text). Read-only and idempotent.',+ idempotent: true,+ },+ auth: smartsuiteAuth,+ props: {+ solutionId: smartsuiteCommon.solutionId,+ tableId: smartsuiteCommon.tableId,+ recordId: smartsuiteCommon.recordDropdown({ displayName: 'Record' }),+ },+ outputSchema: outputSchemas['commentList'],+ async run({ auth, propsValue }) {+ return listForRecord({ credentials: auth.props, recordId: propsValue.recordId });+ },+});++export const listCommentsById = createAction({+ name: 'list_comments_by_id',+ classification: 'SEARCH',+ displayName: 'List Comments (by ID)',+ description: 'Lists the comments on a record, by record ID.',+ audience: 'ai',+ aiMetadata: {+ description: 'Returns every comment on one SmartSuite record (author member ID, created time, message HTML and text). Needs the Record ID from List Records or Get Record (by ID). Resolve author IDs with Get Member (by ID); reply with Add Comment (by ID). Read-only and idempotent.',+ idempotent: true,+ },+ auth: smartsuiteAuth,+ props: {+ recordId: smartSuiteInputs.aiProps.recordId(),+ },+ outputSchema: outputSchemas['commentList'],+ async run({ auth, propsValue }) {+ return listForRecord({ credentials: auth.props, recordId: propsValue.recordId });+ },+});diff --git a/packages/pieces/community/smartsuite/src/lib/actions/list-deleted-records.ts b/packages/pieces/community/smartsuite/src/lib/actions/list-deleted-records.tsnew file mode 100644index 00000000000..d6b410e643e--- /dev/null+++ b/packages/pieces/community/smartsuite/src/lib/actions/list-deleted-records.ts@@ -0,0 +1,53 @@+import { createAction } from '@activepieces/pieces-framework';+import { smartsuiteAuth } from '../auth';+import { smartSuiteApi } from '../common';+import { smartSuiteClient, SmartSuiteCredentials } from '../common/client';+import { smartSuiteInputs } from '../common/inputs';+import { smartsuiteCommon } from '../common/props';+import { outputSchemas } from '../output-schemas';++async function listDeleted({ credentials, solutionId }: { credentials: SmartSuiteCredentials; solutionId: unknown }): Promise<{ items: Record<string, unknown>[]; count: number }> {+ const id = smartSuiteInputs.requireText({ value: solutionId, label: 'Solution' });+ const items = await smartSuiteApi.listDeletedRecords({ credentials, solutionId: id });+ return { items, count: items.length };+}++export const listDeletedRecords = createAction({+ name: 'list_deleted_records',+ classification: 'SEARCH',+ displayName: 'List Deleted Records',+ description: 'Lists the records in a solution\'s trash.',+ audience: 'human',+ aiMetadata: {+ description: 'Builder version with a solution picker; agents should use List Deleted Records (by ID). Returns the deleted records (trash) of one SmartSuite solution with record ID, title, table and deletion date. Read-only and idempotent.',+ idempotent: true,+ },+ auth: smartsuiteAuth,+ props: {+ solutionId: smartsuiteCommon.solutionId,+ },+ outputSchema: outputSchemas['deletedRecordList'],+ async run({ auth, propsValue }) {+ return listDeleted({ credentials: smartSuiteClient.credentialsOf(auth), solutionId: propsValue.solutionId });+ },+});++export const listDeletedRecordsById = createAction({+ name: 'list_deleted_records_by_id',+ classification: 'SEARCH',+ displayName: 'List Deleted Records (by ID)',+ description: 'Lists the records in a solution\'s trash, by solution ID.',+ audience: 'ai',+ aiMetadata: {+ description: 'Returns the deleted records (trash) of one SmartSuite solution with record ID, title, table and deletion date. Read-only and idempotent. Needs a Solution ID from List Solutions. Next: pass a returned id and application_id to Restore Record (by ID) to bring it back.',+ idempotent: true,+ },+ auth: smartsuiteAuth,+ props: {+ solutionId: smartSuiteInputs.aiProps.solutionId(),+ },+ outputSchema: outputSchemas['deletedRecordList'],+ async run({ auth, propsValue }) {+ return listDeleted({ credentials: smartSuiteClient.credentialsOf(auth), solutionId: propsValue.solutionId });+ },+});diff --git a/packages/pieces/community/smartsuite/src/lib/actions/list-members.ts b/packages/pieces/community/smartsuite/src/lib/actions/list-members.tsnew file mode 100644index 00000000000..dbc143c358c--- /dev/null+++ b/packages/pieces/community/smartsuite/src/lib/actions/list-members.ts@@ -0,0 +1,33 @@+import { createAction } from '@activepieces/pieces-framework';+import { smartsuiteAuth } from '../auth';+import { smartSuiteClient } from '../common/client';+import { smartSuiteInputs } from '../common/inputs';+import { outputSchemas } from '../output-schemas';+import { pagedList } from '../common/paged-list';++export const listMembers = createAction({+ name: 'list_members',+ classification: 'SEARCH',+ displayName: 'List Members',+ description: 'Lists the members of your SmartSuite workspace.',+ audience: 'both',+ aiMetadata: {+ description: 'Returns one page of SmartSuite workspace members (member ID, full name, emails, role, job title). Use member IDs for user fields and comment assignment. Page with offset. Read-only and idempotent.',+ idempotent: true,+ },+ auth: smartsuiteAuth,+ props: {+ limit: smartSuiteInputs.aiProps.limit(100),+ offset: smartSuiteInputs.aiProps.offset(),+ },+ outputSchema: outputSchemas['memberPage'],+ async run({ auth, propsValue }) {+ return pagedList.fetch({+ credentials: smartSuiteClient.credentialsOf(auth),+ path: '/applications/members/records/list/',+ limit: propsValue.limit,+ offset: propsValue.offset,+ operation: 'list members',+ });+ },+});diff --git a/packages/pieces/community/smartsuite/src/lib/actions/list-solutions.ts b/packages/pieces/community/smartsuite/src/lib/actions/list-solutions.tsnew file mode 100644index 00000000000..f1c627a586d--- /dev/null+++ b/packages/pieces/community/smartsuite/src/lib/actions/list-solutions.ts@@ -0,0 +1,38 @@+import { Property, createAction } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { smartsuiteAuth } from '../auth';+import { smartSuitePaginatedApiCall } from '../common';+import { outputSchemas } from '../output-schemas';++export const listSolutions = createAction({+ name: 'list_solutions',+ classification: 'SEARCH',+ displayName: 'List Solutions',+ description: 'Lists the solutions (workspaces of tables) your account can access.',+ audience: 'both',+ aiMetadata: {+ description: 'Returns every SmartSuite solution the connected user can access, with ID, name, status and table/record counts. Use first to find a Solution ID, then List Tables. Read-only and idempotent.',+ idempotent: true,+ },+ auth: smartsuiteAuth,+ props: {+ includeHidden: Property.Checkbox({+ displayName: 'Include Hidden Solutions',+ description: 'Also return hidden and system solutions.',+ required: false,+ defaultValue: false,+ }),+ },+ outputSchema: outputSchemas['solutionList'],+ async run({ auth, propsValue }) {+ const solutions = await smartSuitePaginatedApiCall<Record<string, unknown>>({+ apiKey: auth.props.apiKey,+ accountId: auth.props.accountId,+ method: HttpMethod.GET,+ resourceUri: '/solutions/',+ operation: 'list solutions',+ });+ const items = propsValue.includeHidden ? solutions : solutions.filter((solution) => solution['hidden'] !== true);+ return { items, count: items.length };+ },+});diff --git a/packages/pieces/community/smartsuite/src/lib/actions/list-tables.ts b/packages/pieces/community/smartsuite/src/lib/actions/list-tables.tsnew file mode 100644index 00000000000..ac3901f6b68--- /dev/null+++ b/packages/pieces/community/smartsuite/src/lib/actions/list-tables.ts@@ -0,0 +1,63 @@+import { createAction } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { smartsuiteAuth } from '../auth';+import { smartSuitePaginatedApiCall, SmartSuiteTable } from '../common';+import { SmartSuiteCredentials } from '../common/client';+import { smartSuiteInputs } from '../common/inputs';+import { smartsuiteCommon } from '../common/props';+import { tableSummary } from '../common/tables';+import { outputSchemas } from '../output-schemas';++async function listForSolution({ credentials, solutionId }: { credentials: SmartSuiteCredentials; solutionId: unknown }) {+ const id = smartSuiteInputs.requireText({ value: solutionId, label: 'Solution' });+ const tables = await smartSuitePaginatedApiCall<SmartSuiteTable>({+ apiKey: credentials.apiKey,+ accountId: credentials.accountId,+ method: HttpMethod.GET,+ resourceUri: '/applications/',+ query: { solution: id },+ operation: 'list tables',+ });+ const items = tables.map((table) => tableSummary.summarize(table));+ return { items, count: items.length };+}++export const listTables = createAction({+ name: 'list_tables',+ classification: 'SEARCH',+ displayName: 'List Tables',+ description: 'Lists the tables in a solution.',+ audience: 'human',+ aiMetadata: {+ description: 'Builder version with a solution picker; agents should use List Tables (by ID). Returns the tables of the solution with ID, name, slug and field count. Read-only and idempotent.',+ idempotent: true,+ },+ auth: smartsuiteAuth,+ props: {+ solutionId: smartsuiteCommon.solutionId,+ },+ outputSchema: outputSchemas['tableList'],+ async run({ auth, propsValue }) {+ return listForSolution({ credentials: auth.props, solutionId: propsValue.solutionId });+ },+});++export const listTablesById = createAction({+ name: 'list_tables_by_id',+ classification: 'SEARCH',+ displayName: 'List Tables (by ID)',+ description: 'Lists the tables in a solution, by solution ID.',+ audience: 'ai',+ aiMetadata: {+ description: 'Returns the tables (SmartSuite calls them applications) in one solution, with ID, name, slug and field count. Needs a Solution ID from List Solutions. Next: Get Table Schema (by ID) to learn the field slugs before reading or writing records. Read-only and idempotent.',+ idempotent: true,+ },+ auth: smartsuiteAuth,+ props: {+ solutionId: smartSuiteInputs.aiProps.solutionId(),+ },+ outputSchema: outputSchemas['tableList'],+ async run({ auth, propsValue }) {+ return listForSolution({ credentials: auth.props, solutionId: propsValue.solutionId });+ },+});diff --git a/packages/pieces/community/smartsuite/src/lib/actions/list-teams.ts b/packages/pieces/community/smartsuite/src/lib/actions/list-teams.tsnew file mode 100644index 00000000000..1a1d9f9e0e6--- /dev/null+++ b/packages/pieces/community/smartsuite/src/lib/actions/list-teams.ts@@ -0,0 +1,33 @@+import { createAction } from '@activepieces/pieces-framework';+import { smartsuiteAuth } from '../auth';+import { smartSuiteClient } from '../common/client';+import { smartSuiteInputs } from '../common/inputs';+import { outputSchemas } from '../output-schemas';+import { pagedList } from '../common/paged-list';++export const listTeams = createAction({+ name: 'list_teams',+ classification: 'SEARCH',+ displayName: 'List Teams',+ description: 'Lists the teams in your SmartSuite workspace.',+ audience: 'both',+ aiMetadata: {+ description: 'Returns one page of SmartSuite teams with team ID, name, owner IDs and member IDs. Page with offset. Read-only and idempotent.',+ idempotent: true,+ },+ auth: smartsuiteAuth,+ props: {+ limit: smartSuiteInputs.aiProps.limit(100),+ offset: smartSuiteInputs.aiProps.offset(),+ },+ outputSchema: outputSchemas['teamPage'],+ async run({ auth, propsValue }) {+ return pagedList.fetch({+ credentials: smartSuiteClient.credentialsOf(auth),+ path: '/teams/list/',+ limit: propsValue.limit,+ offset: propsValue.offset,+ operation: 'list teams',+ });+ },+});diff --git a/packages/pieces/community/smartsuite/src/lib/actions/restore-record.ts b/packages/pieces/community/smartsuite/src/lib/actions/restore-record.tsnew file mode 100644index 00000000000..9d9be51d4c2--- /dev/null+++ b/packages/pieces/community/smartsuite/src/lib/actions/restore-record.ts@@ -0,0 +1,61 @@+import { createAction } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { smartsuiteAuth } from '../auth';+import { SmartSuiteRecord } from '../common';+import { smartSuiteClient, SmartSuiteCredentials } from '../common/client';+import { smartSuiteInputs } from '../common/inputs';+import { smartsuiteCommon } from '../common/props';+import { outputSchemas } from '../output-schemas';++async function restore({ credentials, tableId, recordId }: { credentials: SmartSuiteCredentials; tableId: unknown; recordId: unknown }): Promise<SmartSuiteRecord> {+ return smartSuiteClient.request<SmartSuiteRecord>({+ credentials,+ method: HttpMethod.POST,+ path: `/applications/${smartSuiteClient.pathSegment({ value: tableId, label: 'Table' })}/records/${smartSuiteClient.pathSegment({ value: recordId, label: 'Record ID' })}/restore/`,+ body: {},+ operation: 'restore record',+ });+}++export const restoreRecord = createAction({+ name: 'restore_record',+ classification: 'WRITE',+ displayName: 'Restore Record',+ description: 'Brings a deleted record back from the trash.',+ audience: 'human',+ aiMetadata: {+ description: 'Builder version that picks the record from the table trash; agents should use Restore Record (by ID). Restores one deleted SmartSuite record from the solution trash and returns it keyed by field slug. Idempotent: restoring a record that is not deleted leaves it as it is.',+ idempotent: true,+ },+ auth: smartsuiteAuth,+ props: {+ solutionId: smartsuiteCommon.solutionId,+ tableId: smartsuiteCommon.tableId,+ recordId: smartsuiteCommon.deletedRecordDropdown,+ },+ outputSchema: outputSchemas['restoreRecord'],+ async run({ auth, propsValue }) {+ return restore({ credentials: smartSuiteClient.credentialsOf(auth), tableId: propsValue.tableId, recordId: propsValue.recordId });+ },+});++export const restoreRecordById = createAction({+ name: 'restore_record_by_id',+ classification: 'WRITE',+ displayName: 'Restore Record (by ID)',+ description: 'Brings a deleted record back from the trash, by table ID and record ID.',+ audience: 'ai',+ aiMetadata: {+ description: 'Restores one deleted SmartSuite record from the solution trash and returns it keyed by field slug. Idempotent: restoring a record that is not deleted leaves it as it is. Get the Record ID and its Table ID (application_id) from List Deleted Records (by ID). Next: Get Record (by ID) or Update Record Fields.',+ idempotent: true,+ },+ auth: smartsuiteAuth,+ props: {+ tableId: smartSuiteInputs.aiProps.tableId(),+ recordId: smartSuiteInputs.aiProps.recordId(),+ },+ outputSchema: outputSchemas['restoreRecord'],+ async run({ auth, propsValue }) {+ return restore({ credentials: smartSuiteClient.credentialsOf(auth), tableId: propsValue.tableId, recordId: propsValue.recordId });+ },+});diff --git a/packages/pieces/community/smartsuite/src/lib/actions/update-record.ts b/packages/pieces/community/smartsuite/src/lib/actions/update-record.tsindex df867336edb..28538c65a48 100644--- a/packages/pieces/community/smartsuite/src/lib/actions/update-record.ts+++ b/packages/pieces/community/smartsuite/src/lib/actions/update-record.ts@@ -2,16 +2,18 @@ import { createAction } from '@activepieces/pieces-framework';import { HttpMethod } from '@activepieces/pieces-common';import { smartsuiteAuth } from '../auth';import { smartsuiteCommon, formatRecordFields, transformRecordFields } from '../common/props';-import { smartSuiteApiCall, TableStucture } from '../common';+import { smartSuiteApi, SmartSuiteRecord } from '../common';+import { smartSuiteClient } from '../common/client';+import { outputSchemas } from '../output-schemas';export const updateRecord = createAction({name: 'update_record',classification: 'WRITE',displayName: 'Update a Record',description: 'Updates an existing record in the specified table',- audience: 'both',+ audience: 'human',aiMetadata: {- description: 'Patches an existing SmartSuite record identified by its record ID, overwriting only the supplied field values against the live table schema. Use when an agent needs to change fields on a known record; requires the solution, table, record ID, and the fields to set. Idempotent — re-applying the same field values leaves the record in the same state.',+ description: 'Patches an existing SmartSuite record using form fields built from the table schema; only filled-in fields are sent and the output is keyed by field label. Agents should use Update Record Fields (by ID) instead. Idempotent: re-applying the same values leaves the record unchanged.',idempotent: true,},auth: smartsuiteAuth,@@ -21,49 +23,19 @@ export const updateRecord = createAction({recordId: smartsuiteCommon.recordId,fields: smartsuiteCommon.tableFields,},+ outputSchema: outputSchemas['labelledRecord'],async run({ auth, propsValue }) {const { tableId, recordId, fields } = propsValue;-- const tableResponse = await smartSuiteApiCall<{- structure: TableStucture[];- }>({- apiKey: auth.props.apiKey,- accountId: auth.props.accountId,- method: HttpMethod.GET,- resourceUri: `/applications/${tableId}`,+ const credentials = smartSuiteClient.credentialsOf(auth);+ const recordPath = `/applications/${smartSuiteClient.pathSegment({ value: tableId, label: 'Table' })}/records/${smartSuiteClient.pathSegment({ value: recordId, label: 'Record ID' })}/`;+ const table = await smartSuiteApi.getTable({ credentials, tableId });+ const response = await smartSuiteClient.request<SmartSuiteRecord>({+ credentials,+ method: HttpMethod.PATCH,+ path: recordPath,+ body: formatRecordFields({ tableSchema: table.structure, tableValues: fields ?? {} }),+ operation: 'update record',});- const tableSchema = tableResponse.structure;-- const formattedFields = formatRecordFields(tableSchema, fields);-- try {- const response = await smartSuiteApiCall<Record<string, any>>({- apiKey: auth.props.apiKey,- accountId: auth.props.accountId,- method: HttpMethod.PATCH,- resourceUri: `/applications/${tableId}/records/${recordId}/`,- body: formattedFields,- });-- const transformedFields = transformRecordFields(tableSchema, response);-- return transformedFields;- } catch (error: any) {- if (error.response?.status === 422) {- throw new Error(- `Invalid request: ${error.response?.body?.message || 'Invalid data format'}`,- );- }-- if (error.response?.status === 403) {- throw new Error('You do not have permission to update this record');- }-- if (error.response?.status === 404) {- throw new Error(`Record with ID ${recordId} not found in table ${tableId}`);- }-- throw new Error(`Failed to update record: ${error.message || 'Unknown error'}`);- }+ return transformRecordFields({ tableSchema: table.structure, tableValues: response });},});diff --git a/packages/pieces/community/smartsuite/src/lib/actions/upload-file.ts b/packages/pieces/community/smartsuite/src/lib/actions/upload-file.tsindex 22dc6a561e7..31df5609d10 100644--- a/packages/pieces/community/smartsuite/src/lib/actions/upload-file.ts+++ b/packages/pieces/community/smartsuite/src/lib/actions/upload-file.ts@@ -1,23 +1,18 @@-import {- DropdownOption,- PiecePropValueSchema,- Property,- createAction,-} from '@activepieces/pieces-framework';-import { HttpMethod, httpClient } from '@activepieces/pieces-common';+import { Property, createAction } from '@activepieces/pieces-framework';import { smartsuiteAuth } from '../auth';-import { smartsuiteCommon, transformRecordFields } from '../common/props';-import { smartSuiteApiCall, TableStucture } from '../common';-import FormData from 'form-data';+import { smartsuiteCommon } from '../common/props';+import { smartSuiteClient } from '../common/client';+import { recordFiles } from '../common/record-files';+import { outputSchemas } from '../output-schemas';export const uploadFile = createAction({name: 'upload_file',classification: 'WRITE',displayName: 'Upload File',description: 'Uploads a file and attaches it to a record.',- audience: 'both',+ audience: 'human',aiMetadata: {- description: 'Uploads a file and attaches it to a file-type field on an existing SmartSuite record. Use when an agent needs to add an attachment or image to a known record; requires the solution, table, record ID, a target field that is a file field, and the file contents. Not idempotent — each call appends another attachment to the field.',+ description: 'Uploads a file to a Files & Images field picked from the table schema, then returns the files now in that field. Agents should use Attach File to Record (by ID). Not idempotent: each call adds another attachment.',idempotent: false,},auth: smartsuiteAuth,@@ -25,105 +20,21 @@ export const uploadFile = createAction({solutionId: smartsuiteCommon.solutionId,tableId: smartsuiteCommon.tableId,recordId: smartsuiteCommon.recordId,- field: Property.Dropdown({- auth: smartsuiteAuth,- displayName: 'Search Field',+ field: smartsuiteCommon.tableFieldDropdown({+ displayName: 'File Field',+ description: 'The Files & Images field to attach the file to.',required: true,- refreshers: ['tableId'],- options: async ({ auth, tableId }) => {- if (!auth || !tableId) {- return {- disabled: true,- options: [],- placeholder: 'Please connect your account first.',- };- }-- const { apiKey, accountId } = auth.props;-- const response = await smartSuiteApiCall<{- structure: TableStucture[];- }>({- apiKey,- accountId,- method: HttpMethod.GET,- resourceUri: `/applications/${tableId}`,- });-- const options: DropdownOption<string>[] = [];-- for (const field of response.structure) {- if (field.field_type === 'filefield') {- options.push({ label: field.label, value: field.slug });- }- }- return {- disabled: false,- options,- };- },+ onlyTypes: ['filefield'],}),file: Property.File({displayName: 'File',- description: 'The file to upload',+ description: 'The file to upload (up to 100 MB).',required: true,}),},+ outputSchema: outputSchemas['uploadFile'],async run({ auth, propsValue }) {const { recordId, field, tableId, file } = propsValue;- try {- const formData = new FormData();-- formData.append('files', Buffer.from(file.base64, 'base64'), file.filename);-- const response = await httpClient.sendRequest({- method: HttpMethod.POST,- url: `https://app.smartsuite.com/api/v1/recordfiles/${tableId}/${recordId}/${field}/`,- body: formData,- headers: {- ...formData.getHeaders(),- Authorization: `Token ${auth.props.apiKey}`,- 'ACCOUNT-ID': auth.props.accountId,- },- });-- const tableResponse = await smartSuiteApiCall<{- structure: TableStucture[];- }>({- apiKey: auth.props.apiKey,- accountId: auth.props.accountId,- method: HttpMethod.GET,- resourceUri: `/applications/${tableId}`,- });- const tableSchema = tableResponse.structure;-- const formattedFields = transformRecordFields(tableSchema, response.body);-- return formattedFields;- } catch (error: any) {- if (error.response?.status === 400) {- throw new Error(- `Invalid file format or size: ${- error.response?.body?.message || 'File may be too large or in an unsupported format'- }`,- );- }-- if (error.response?.status === 403) {- throw new Error('You do not have permission to upload files to this record');- }-- if (error.response?.status === 404) {- throw new Error(- `Record with ID ${recordId} not found or field ${field} is not a file field`,- );- }-- if (error.response?.status === 413) {- throw new Error('File is too large. SmartSuite has file size limits');- }-- throw new Error(`Failed to upload file: ${error.message || 'Unknown error'}`);- }+ return recordFiles.attach({ credentials: smartSuiteClient.credentialsOf(auth), tableId, recordId, field, file });},});diff --git a/packages/pieces/community/smartsuite/src/lib/actions/upsert-record.ts b/packages/pieces/community/smartsuite/src/lib/actions/upsert-record.tsnew file mode 100644index 00000000000..b3d611b01d3--- /dev/null+++ b/packages/pieces/community/smartsuite/src/lib/actions/upsert-record.ts@@ -0,0 +1,130 @@+import { Property, createAction } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { smartsuiteAuth } from '../auth';+import { smartSuiteApi, SmartSuiteRecord } from '../common';+import { smartSuiteClient, SmartSuiteCredentials } from '../common/client';+import { smartSuiteInputs } from '../common/inputs';+import { formatRecordFields, smartsuiteCommon } from '../common/props';+import { outputSchemas } from '../output-schemas';++async function upsert({+ credentials,+ tableId,+ matchField,+ matchValue,+ createMatchValue,+ fields,+}: {+ credentials: SmartSuiteCredentials;+ tableId: unknown;+ matchField: string;+ matchValue: string;+ createMatchValue: unknown;+ fields: Record<string, unknown>;+}): Promise<{ action: 'created' | 'updated'; record: SmartSuiteRecord }> {+ const tableSegment = smartSuiteClient.pathSegment({ value: tableId, label: 'Table' });+ const matches = await smartSuiteApi.listRecordsPage({+ credentials,+ tableId,+ filter: { operator: 'and', fields: [{ field: matchField, comparison: 'is', value: matchValue }] },+ limit: 2,+ offset: 0,+ });+ if (matches.items.length > 1) {+ throw new Error(`More than one record has ${matchField} = "${matchValue}", so nothing was changed. Use a field with unique values.`);+ }+ const existing = matches.items[0];+ if (existing && typeof existing['id'] === 'string') {+ const record = await smartSuiteClient.request<SmartSuiteRecord>({+ credentials,+ method: HttpMethod.PATCH,+ path: `/applications/${tableSegment}/records/${smartSuiteClient.pathSegment({ value: existing['id'], label: 'Record ID' })}/`,+ body: fields,+ operation: 'update record',+ });+ return { action: 'updated', record };+ }+ const record = await smartSuiteClient.request<SmartSuiteRecord>({+ credentials,+ method: HttpMethod.POST,+ path: `/applications/${tableSegment}/records/`,+ body: { [matchField]: createMatchValue, ...fields },+ operation: 'create record',+ });+ return { action: 'created', record };+}++export const upsertRecord = createAction({+ name: 'upsert_record',+ classification: 'WRITE',+ displayName: 'Create or Update Record',+ description: 'Updates the record whose field matches a value, or creates it when none matches.',+ audience: 'human',+ aiMetadata: {+ description: 'Builder version with solution, table and field pickers; agents should use Create or Update Record (by ID). One match: patches it. No match: creates a record with the match value (formatted for the field type, for example an array for email fields) plus the fields. More than one match: fails without changing anything. Not atomic: two runs at the same moment can both create. Idempotent for sequential runs with the same input.',+ idempotent: true,+ },+ auth: smartsuiteAuth,+ props: {+ solutionId: smartsuiteCommon.solutionId,+ tableId: smartsuiteCommon.tableId,+ matchField: smartsuiteCommon.tableFieldDropdown({+ displayName: 'Match Field',+ description: 'The field that identifies the record, for example an email or external ID field.',+ required: true,+ }),+ matchValue: Property.ShortText({+ displayName: 'Match Value',+ required: true,+ }),+ fields: smartsuiteCommon.tableFields,+ },+ outputSchema: outputSchemas['upsertRecord'],+ async run({ auth, propsValue }) {+ const matchField = smartSuiteInputs.requireText({ value: propsValue.matchField, label: 'Match Field' });+ const matchValue = smartSuiteInputs.requireText({ value: propsValue.matchValue, label: 'Match Value' });+ const credentials = smartSuiteClient.credentialsOf(auth);+ const table = await smartSuiteApi.getTable({ credentials, tableId: propsValue.tableId });+ const fields = formatRecordFields({ tableSchema: table.structure, tableValues: propsValue.fields ?? {} });+ const formattedMatch = formatRecordFields({ tableSchema: table.structure, tableValues: { [matchField]: matchValue } });+ const createMatchValue = matchField in formattedMatch ? formattedMatch[matchField] : matchValue;+ return upsert({ credentials, tableId: propsValue.tableId, matchField, matchValue, createMatchValue, fields });+ },+});++export const upsertRecordById = createAction({+ name: 'upsert_record_by_id',+ classification: 'WRITE',+ displayName: 'Create or Update Record (by ID)',+ description: 'Updates the record whose field matches a value, or creates it when none matches, by table ID and field slug.',+ audience: 'ai',+ aiMetadata: {+ description: 'Looks for a record in the table (Table ID from List Tables) whose Match Field (slug from Get Table Schema (by ID)) equals Match Value. One match: patches it. No match: creates a record with the match value plus the fields. More than one match: fails without changing anything. Not atomic: two runs at the same moment can both create. Idempotent for sequential runs with the same input. If the match field needs another value format, such as an array for email fields, put it in Fields too; Fields wins. Returns action (created/updated) and the record; use its id with Get Record (by ID) or Add Comment (by ID).',+ idempotent: true,+ },+ auth: smartsuiteAuth,+ props: {+ tableId: smartSuiteInputs.aiProps.tableId(),+ matchField: Property.ShortText({+ displayName: 'Match Field Slug',+ description: 'Slug of the field that identifies the record, for example an email or external ID field. Get slugs from Get Table Schema (by ID).',+ required: true,+ }),+ matchValue: Property.ShortText({+ displayName: 'Match Value',+ required: true,+ }),+ fields: Property.Json({+ displayName: 'Fields',+ description: 'JSON object keyed by field slug with the values to set, for example {"status":{"value":"complete"}}.',+ required: true,+ }),+ },+ outputSchema: outputSchemas['upsertRecord'],+ async run({ auth, propsValue }) {+ const matchField = smartSuiteInputs.requireText({ value: propsValue.matchField, label: 'Match Field' });+ const matchValue = smartSuiteInputs.requireText({ value: propsValue.matchValue, label: 'Match Value' });+ const fields = smartSuiteInputs.requireObject({ value: propsValue.fields, label: 'Fields' });+ return upsert({ credentials: smartSuiteClient.credentialsOf(auth), tableId: propsValue.tableId, matchField, matchValue, createMatchValue: matchValue, fields });+ },+});diff --git a/packages/pieces/community/smartsuite/src/lib/auth.ts b/packages/pieces/community/smartsuite/src/lib/auth.tsindex 0ba1c0ab690..5efb77e1146 100644--- a/packages/pieces/community/smartsuite/src/lib/auth.ts+++ b/packages/pieces/community/smartsuite/src/lib/auth.ts@@ -1,40 +1,45 @@import { PieceAuth, Property } from '@activepieces/pieces-framework';import { HttpMethod } from '@activepieces/pieces-common';-import { smartSuiteApiCall } from './common';+import { smartSuiteClient } from './common/client';export const smartsuiteAuth = PieceAuth.CustomAuth({- description: `+ description: `You can obtain API key by navigate to **My Profile->API Key** from top-right corner.You can obtain Account ID from browser URL.For example, if smartsuite workspace URL is https://app.smartsuite.com/xyz/home, your Account ID is **xyz**.`,- required: true,- props: {- apiKey: PieceAuth.SecretText({- displayName: 'API Key',- required: true,- }),- accountId: Property.ShortText({- displayName: 'Account ID',- required: true,- }),- },- validate: async ({ auth }) => {- try {- await smartSuiteApiCall({- apiKey: auth.apiKey,- accountId: auth.accountId,- method: HttpMethod.GET,- resourceUri: '/solutions',- });-- return {- valid: true,- };- } catch (e) {- return {- valid: false,- error: 'Invalid Credentials.',- };- }- },+ required: true,+ props: {+ apiKey: PieceAuth.SecretText({+ displayName: 'API Key',+ required: true,+ }),+ accountId: Property.ShortText({+ displayName: 'Account ID',+ required: true,+ }),+ },+ validate: async ({ auth }) => {+ try {+ await smartSuiteClient.request<unknown>({+ credentials: { apiKey: auth.apiKey, accountId: auth.accountId },+ method: HttpMethod.GET,+ path: '/solutions/',+ operation: 'check credentials',+ });+ return { valid: true };+ } catch (error) {+ return { valid: false, error: validationMessage(error) };+ }+ },});++function validationMessage(error: unknown): string {+ const status = smartSuiteClient.statusOf(error);+ if (status === 401 || status === 403) {+ return 'Invalid Credentials. Check the API key and the Account ID.';+ }+ if (status === 402) {+ return 'This SmartSuite workspace has no API access: its trial or plan has expired or does not include the API.';+ }+ return `Could not reach SmartSuite to check the credentials: ${error instanceof Error ? error.message : String(error)}`;+}diff --git a/packages/pieces/community/smartsuite/src/lib/common/client.ts b/packages/pieces/community/smartsuite/src/lib/common/client.tsnew file mode 100644index 00000000000..82bae26e919--- /dev/null+++ b/packages/pieces/community/smartsuite/src/lib/common/client.ts@@ -0,0 +1,208 @@+import { HttpMethod, HttpRequest, httpClient } from '@activepieces/pieces-common';+import { SMARTSUITE_API_URL, SMARTSUITE_WEBHOOKS_API_URL } from './constants';++const REQUEST_TIMEOUT_MS = 60_000;+const RATE_LIMIT_RETRY_DELAYS_MS = [2_000, 5_000];+const MAX_ERROR_TEXT = 500;++export class SmartSuiteApiError extends Error {+ readonly status: number;+ readonly responseBody: unknown;++ constructor({ operation, status, responseBody }: { operation: string; status: number; responseBody: unknown }) {+ super(`SmartSuite ${operation} failed (${status}): ${describeStatus({ status, responseBody })}`);+ this.name = 'SmartSuiteApiError';+ this.status = status;+ this.responseBody = responseBody;+ }+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return value !== null && typeof value === 'object' && !Array.isArray(value);+}++function vendorMessage(responseBody: unknown): string {+ if (typeof responseBody === 'string' && responseBody.length > 0) {+ return responseBody.slice(0, MAX_ERROR_TEXT);+ }+ if (isRecord(responseBody)) {+ for (const key of ['message', 'msg', 'detail', 'error']) {+ const value = responseBody[key];+ if (typeof value === 'string' && value.length > 0) {+ return value.slice(0, MAX_ERROR_TEXT);+ }+ }+ return JSON.stringify(responseBody).slice(0, MAX_ERROR_TEXT);+ }+ if (Array.isArray(responseBody)) {+ return JSON.stringify(responseBody).slice(0, MAX_ERROR_TEXT);+ }+ return 'no details returned';+}++function describeStatus({ status, responseBody }: { status: number; responseBody: unknown }): string {+ const detail = vendorMessage(responseBody);+ switch (status) {+ case 401:+ return `the API key or Account ID is invalid. ${detail}`;+ case 402:+ return `this SmartSuite workspace has no API access (the trial or paid plan has expired or does not include the API). ${detail}`;+ case 403:+ return `you do not have permission for this solution, table or record. ${detail}`;+ case 404:+ return `not found. Check the IDs you passed. ${detail}`;+ case 429:+ return `SmartSuite rate limit or monthly API quota reached; try again later. ${detail}`;+ default:+ return detail;+ }+}++function statusOf(error: unknown): number | undefined {+ if (error instanceof SmartSuiteApiError) {+ return error.status;+ }+ if (!isRecord(error) && !(error instanceof Error)) {+ return undefined;+ }+ const response: unknown = Reflect.get(error, 'response');+ if (isRecord(response) && typeof response['status'] === 'number') {+ return response['status'];+ }+ return undefined;+}++function responseOf(error: unknown): Record<string, unknown> | undefined {+ if (!isRecord(error) && !(error instanceof Error)) {+ return undefined;+ }+ const response: unknown = Reflect.get(error, 'response');+ return isRecord(response) ? response : undefined;+}++function pathSegment({ value, label }: { value: unknown; label: string }): string {+ if (value === undefined || value === null) {+ throw new Error(`${label} is required.`);+ }+ const text = String(value).trim();+ if (text.length === 0) {+ throw new Error(`${label} is required.`);+ }+ if (text === '.' || text === '..') {+ throw new Error(`${label} "${text}" is not a valid SmartSuite ID.`);+ }+ return encodeURIComponent(text);+}++function toQueryParams(query: Record<string, SmartSuiteQueryValue> | undefined): Record<string, string> {+ if (!query) {+ return {};+ }+ const result: Record<string, string> = {};+ for (const [key, value] of Object.entries(query)) {+ if (value !== undefined && value !== null && value !== '') {+ result[key] = String(value);+ }+ }+ return result;+}++function authHeaders(credentials: SmartSuiteCredentials): Record<string, string> {+ return {+ Authorization: `Token ${credentials.apiKey.trim()}`,+ 'ACCOUNT-ID': credentials.accountId.trim(),+ };+}++function sleep(ms: number): Promise<void> {+ return new Promise((resolve) => setTimeout(resolve, ms));+}++async function smartSuiteRequest<T>({+ credentials,+ method,+ path,+ operation,+ query,+ body,+ api = 'rest',+ headers,+ wait = sleep,+ deadlineAt,+}: SmartSuiteRequest): Promise<T> {+ const baseUrl = api === 'webhooks' ? SMARTSUITE_WEBHOOKS_API_URL : SMARTSUITE_API_URL;+ const request: HttpRequest = {+ method,+ url: `${baseUrl}${path}`,+ headers: authHeaders(credentials),+ queryParams: toQueryParams(query),+ timeout: REQUEST_TIMEOUT_MS,+ followRedirects: false,+ };+ if (body !== undefined) {+ request.body = body;+ request.headers = { ...request.headers, ...(headers ?? { 'Content-Type': 'application/json' }) };+ }+ for (let attempt = 0; ; attempt++) {+ if (deadlineAt !== undefined) {+ const remaining = deadlineAt - Date.now();+ if (remaining <= 0) {+ throw new Error(`SmartSuite ${operation} ran past its time budget.`);+ }+ request.timeout = Math.min(REQUEST_TIMEOUT_MS, remaining);+ }+ try {+ const response = await httpClient.sendRequest<T>(request);+ if (response.status >= 300) {+ throw new SmartSuiteApiError({ operation, status: response.status, responseBody: response.body });+ }+ return response.body;+ } catch (error) {+ if (error instanceof SmartSuiteApiError) {+ throw error;+ }+ const status = statusOf(error);+ if (status === undefined) {+ throw error;+ }+ const retryFits = deadlineAt === undefined || Date.now() + RATE_LIMIT_RETRY_DELAYS_MS[attempt] < deadlineAt;+ if (status === 429 && attempt < RATE_LIMIT_RETRY_DELAYS_MS.length && retryFits) {+ await wait(RATE_LIMIT_RETRY_DELAYS_MS[attempt]);+ continue;+ }+ throw new SmartSuiteApiError({ operation, status, responseBody: responseOf(error)?.['body'] });+ }+ }+}++function credentialsOf(auth: { props: SmartSuiteCredentials }): SmartSuiteCredentials {+ return { apiKey: auth.props.apiKey, accountId: auth.props.accountId };+}++export const smartSuiteClient = {+ request: smartSuiteRequest,+ pathSegment,+ statusOf,+ authHeaders,+ credentialsOf,+};++export type SmartSuiteCredentials = {+ apiKey: string;+ accountId: string;+};++export type SmartSuiteQueryValue = string | number | boolean | undefined | null;++export type SmartSuiteRequest = {+ credentials: SmartSuiteCredentials;+ method: HttpMethod;+ path: string;+ operation: string;+ query?: Record<string, SmartSuiteQueryValue>;+ body?: unknown;+ api?: 'rest' | 'webhooks';+ headers?: Record<string, string>;+ wait?: (ms: number) => Promise<void>;+ deadlineAt?: number;+};diff --git a/packages/pieces/community/smartsuite/src/lib/common/index.ts b/packages/pieces/community/smartsuite/src/lib/common/index.tsindex b94e4af2b52..6759fb306fb 100644--- a/packages/pieces/community/smartsuite/src/lib/common/index.ts+++ b/packages/pieces/community/smartsuite/src/lib/common/index.ts@@ -1,104 +1,212 @@-import {- httpClient,- HttpMessageBody,- HttpMethod,- HttpRequest,- QueryParams,-} from '@activepieces/pieces-common';-import { SMARTSUITE_API_URL } from './constants';-import { isNil } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { smartSuiteClient, SmartSuiteCredentials, SmartSuiteQueryValue } from './client';-export type SmartSuiteApiCallParams = {- apiKey: string;- accountId: string;- method: HttpMethod;- resourceUri: string;- query?: Record<string, string | number | string[] | undefined>;- body?: any;+const PAGE_SIZE = 100;+const MAX_LIST_PAGES = 50;+const MAX_RECORD_PAGE_SIZE = 1000;++async function smartSuiteApiCall<T>({+ apiKey,+ accountId,+ method,+ resourceUri,+ query,+ body,+ operation,+}: SmartSuiteApiCallParams): Promise<T> {+ return smartSuiteClient.request<T>({+ credentials: { apiKey, accountId },+ method,+ path: resourceUri,+ query,+ body,+ operation: operation ?? `${method} ${resourceUri.split('?')[0]}`,+ });+}++async function smartSuitePaginatedApiCall<T>(params: SmartSuiteApiCallParams): Promise<T[]> {+ const collected: T[] = [];+ for (let page = 0; page < MAX_LIST_PAGES; page++) {+ const response = await smartSuiteApiCall<unknown>({+ ...params,+ query: { ...(params.query ?? {}), limit: PAGE_SIZE, offset: page * PAGE_SIZE },+ });+ const { items, hasNext } = readListPage<T>(response);+ collected.push(...items);+ if (!hasNext || items.length === 0) {+ return collected;+ }+ }+ throw new Error(`SmartSuite returned more than ${MAX_LIST_PAGES * PAGE_SIZE} items for ${params.operation ?? 'this list'}, so the list would be incomplete. Narrow it down (for example per record or per solution) or use Custom API Call with limit and offset.`);+}++function readListPage<T>(response: unknown): { items: T[]; hasNext: boolean } {+ if (Array.isArray(response)) {+ return { items: response, hasNext: false };+ }+ if (isPlainObject(response)) {+ const results = response['results'] ?? response['items'];+ const items: T[] = Array.isArray(results) ? results : [];+ const next = response['next'];+ return { items, hasNext: typeof next === 'string' && next.length > 0 };+ }+ return { items: [], hasNext: false };+}++async function getTable({ credentials, tableId }: { credentials: SmartSuiteCredentials; tableId: unknown }): Promise<SmartSuiteTable> {+ return smartSuiteClient.request<SmartSuiteTable>({+ credentials,+ method: HttpMethod.GET,+ path: `/applications/${smartSuiteClient.pathSegment({ value: tableId, label: 'Table ID' })}/`,+ operation: 'get table',+ });+}++async function listRecordsPage({+ credentials,+ tableId,+ filter,+ sort,+ limit,+ offset,+}: {+ credentials: SmartSuiteCredentials;+ tableId: unknown;+ filter?: unknown;+ sort?: unknown;+ limit: number;+ offset: number;+}): Promise<RecordPage> {+ const body: Record<string, unknown> = {};+ if (filter !== undefined) {+ body['filter'] = filter;+ }+ if (sort !== undefined) {+ body['sort'] = sort;+ }+ const response = await smartSuiteClient.request<{ items?: SmartSuiteRecord[]; total?: number }>({+ credentials,+ method: HttpMethod.POST,+ path: `/applications/${smartSuiteClient.pathSegment({ value: tableId, label: 'Table ID' })}/records/list/`,+ query: { limit, offset },+ body,+ operation: 'list records',+ });+ const items = response.items ?? [];+ const total = typeof response.total === 'number' ? response.total : undefined;+ const hasMore = total !== undefined ? offset + items.length < total : items.length === limit;+ return { items, total: total ?? null, offset, limit, hasMore: hasMore && items.length > 0 };+}++async function collectRecords({+ credentials,+ tableId,+ filter,+ sort,+ maxRecords,+}: {+ credentials: SmartSuiteCredentials;+ tableId: unknown;+ filter?: unknown;+ sort?: unknown;+ maxRecords: number;+}): Promise<{ items: SmartSuiteRecord[]; hasMore: boolean; total: number | null }> {+ const collected: SmartSuiteRecord[] = [];+ let offset = 0;+ let total: number | null = null;+ while (collected.length < maxRecords) {+ const limit = Math.min(MAX_RECORD_PAGE_SIZE, maxRecords - collected.length);+ const page = await listRecordsPage({ credentials, tableId, filter, sort, limit, offset });+ collected.push(...page.items);+ total = page.total;+ if (!page.hasMore) {+ return { items: collected, hasMore: false, total };+ }+ offset += page.items.length;+ }+ return { items: collected, hasMore: true, total };+}++async function listDeletedRecords({ credentials, solutionId }: { credentials: SmartSuiteCredentials; solutionId: string }): Promise<Record<string, unknown>[]> {+ const response = await smartSuiteClient.request<unknown>({+ credentials,+ method: HttpMethod.POST,+ path: '/deleted-records/',+ query: { preview: true },+ body: { solution_id: solutionId },+ operation: 'list deleted records',+ });+ return readListPage<Record<string, unknown>>(response).items;+}++async function trashRecords({ credentials, tableId, recordIds }: { credentials: SmartSuiteCredentials; tableId: unknown; recordIds: string[] }): Promise<string[]> {+ const deleted = await smartSuiteClient.request<SmartSuiteRecord[]>({+ credentials,+ method: HttpMethod.PATCH,+ path: `/applications/${smartSuiteClient.pathSegment({ value: tableId, label: 'Table' })}/records/bulk_delete/`,+ body: { items: recordIds },+ operation: 'bulk delete records',+ });+ return Array.isArray(deleted) ? deleted.map((record) => record['id']).filter((id): id is string => typeof id === 'string') : [];+}++function isPlainObject(value: unknown): value is Record<string, unknown> {+ return value !== null && typeof value === 'object' && !Array.isArray(value);+}++export const smartSuiteApi = {+ getTable,+ listRecordsPage,+ collectRecords,+ readListPage,+ listDeletedRecords,+ trashRecords,+ isPlainObject,+ MAX_RECORD_PAGE_SIZE,};-export type PaginatedResponse<T> = {- results: T[];- count: number;- next?: string;- previous?: string;+export { smartSuiteApiCall, smartSuitePaginatedApiCall };++export type SmartSuiteApiCallParams = {+ apiKey: string;+ accountId: string;+ method: HttpMethod;+ resourceUri: string;+ query?: Record<string, SmartSuiteQueryValue>;+ body?: unknown;+ operation?: string;};export type TableStucture = {- slug: string;- label: string;- field_type: string;- params: {- is_auto_generated: boolean;- system: boolean;- choices?: { label: string; value: string }[];- };+ slug: string;+ label: string;+ field_type: string;+ params: {+ is_auto_generated?: boolean;+ system?: boolean;+ required?: boolean;+ primary?: boolean;+ linked_application?: string;+ choices?: { label: string; value: string }[];+ };};-export async function smartSuiteApiCall<T extends HttpMessageBody>({- apiKey,- accountId,- method,- resourceUri,- query,- body,-}: SmartSuiteApiCallParams): Promise<T> {- const qs: QueryParams = {};-- if (query) {- for (const [key, value] of Object.entries(query)) {- if (value !== null && value !== undefined) {- qs[key] = String(value);- }- }- }-- const request: HttpRequest = {- method,- url: SMARTSUITE_API_URL + resourceUri,- headers: {- Authorization: `Token ${apiKey}`,- 'ACCOUNT-ID': accountId,- },- queryParams: qs,- body,- };-- const response = await httpClient.sendRequest<T>(request);- return response.body;-}+export type SmartSuiteTable = {+ id: string;+ name: string;+ slug?: string;+ solution?: string;+ status?: string;+ primary_field?: string;+ structure: TableStucture[];+};-export async function smartSuitePaginatedApiCall<T extends HttpMessageBody>({- apiKey,- accountId,- method,- resourceUri,- query,- body,-}: SmartSuiteApiCallParams): Promise<T[]> {- const qs = { ...(query || {}), limit: 100, offset: 0 };-- const resultData: T[] = [];- let hasMore = true;-- do {- const response = await smartSuiteApiCall<PaginatedResponse<T>>({- accountId,- apiKey,- method,- resourceUri,- query: qs,- body,- });-- const items = response.results || [];- resultData.push(...items);-- hasMore = !!response.next && items.length > 0;- if (hasMore) {- qs.offset = Number(qs.offset) + Number(qs.limit);- }- } while (hasMore);-- return resultData;-}+export type SmartSuiteRecord = Record<string, unknown>;++export type RecordPage = {+ items: SmartSuiteRecord[];+ total: number | null;+ offset: number;+ limit: number;+ hasMore: boolean;+};diff --git a/packages/pieces/community/smartsuite/src/lib/common/inputs.ts b/packages/pieces/community/smartsuite/src/lib/common/inputs.tsnew file mode 100644index 00000000000..c46c39f2eee--- /dev/null+++ b/packages/pieces/community/smartsuite/src/lib/common/inputs.ts@@ -0,0 +1,148 @@+import { Property } from '@activepieces/pieces-framework';++function parseJsonValue({ value, label }: { value: unknown; label: string }): unknown {+ if (typeof value !== 'string') {+ return value;+ }+ const text = value.trim();+ if (text.length === 0) {+ return undefined;+ }+ try {+ return JSON.parse(text);+ } catch {+ throw new Error(`${label} must be valid JSON.`);+ }+}++function requireObject({ value, label }: { value: unknown; label: string }): Record<string, unknown> {+ const parsed = parseJsonValue({ value, label });+ if (!isPlainObject(parsed)) {+ throw new Error(`${label} must be a JSON object, for example {"title": "My record"}.`);+ }+ return parsed;+}++function optionalJson({ value, label }: { value: unknown; label: string }): unknown {+ if (value === undefined || value === null) {+ return undefined;+ }+ const parsed = parseJsonValue({ value, label });+ if (isPlainObject(parsed) && Object.keys(parsed).length === 0) {+ return undefined;+ }+ if (Array.isArray(parsed) && parsed.length === 0) {+ return undefined;+ }+ return parsed;+}++function requireObjectArray({ value, label, max }: { value: unknown; label: string; max: number }): Record<string, unknown>[] {+ const parsed = parseJsonValue({ value, label });+ if (!Array.isArray(parsed) || parsed.length === 0) {+ throw new Error(`${label} must be a non-empty JSON array of objects.`);+ }+ if (parsed.length > max) {+ throw new Error(`${label} can hold at most ${max} items per call; got ${parsed.length}.`);+ }+ return parsed.map((item, index) => {+ if (!isPlainObject(item)) {+ throw new Error(`${label} item ${index + 1} must be a JSON object.`);+ }+ return item;+ });+}++function requireIdList({ value, label, max }: { value: unknown; label: string; max: number }): string[] {+ const raw = Array.isArray(value) ? value : typeof value === 'string' ? value.split(',') : [];+ const ids = raw.map((item) => String(item ?? '').trim()).filter((item) => item.length > 0);+ if (ids.length === 0) {+ throw new Error(`${label} must contain at least one ID.`);+ }+ if (ids.length > max) {+ throw new Error(`${label} can hold at most ${max} IDs per call; got ${ids.length}.`);+ }+ return Array.from(new Set(ids));+}++function requireText({ value, label }: { value: unknown; label: string }): string {+ const text = value === undefined || value === null ? '' : String(value).trim();+ if (text.length === 0) {+ throw new Error(`${label} is required.`);+ }+ return text;+}++function integerInRange({ value, label, min, max, fallback }: { value: unknown; label: string; min: number; max: number; fallback: number }): number {+ if (value === undefined || value === null || value === '') {+ return fallback;+ }+ const number = Number(value);+ if (!Number.isInteger(number) || number < min || number > max) {+ throw new Error(`${label} must be a whole number from ${min} to ${max}.`);+ }+ return number;+}++function plainTextToDoc(text: string): Record<string, unknown> {+ return {+ data: {+ type: 'doc',+ content: text.split(/\r?\n/).map((line) => ({+ type: 'paragraph',+ content: line.length > 0 ? [{ type: 'text', text: line }] : [],+ })),+ },+ };+}++function isPlainObject(value: unknown): value is Record<string, unknown> {+ return value !== null && typeof value === 'object' && !Array.isArray(value);+}++const aiProps = {+ solutionId: (required = true) =>+ Property.ShortText({+ displayName: 'Solution ID',+ description: 'The SmartSuite solution ID (24 characters). Get it from List Solutions.',+ required,+ }),+ tableId: () =>+ Property.ShortText({+ displayName: 'Table ID',+ description: 'The SmartSuite table (application) ID. Get it from List Tables.',+ required: true,+ }),+ recordId: () =>+ Property.ShortText({+ displayName: 'Record ID',+ description: 'The record ID. Get it from List Records or a create step.',+ required: true,+ }),+ limit: (fallback: number) =>+ Property.Number({+ displayName: 'Limit',+ description: `How many items to return in one call (1-1000, default ${fallback}).`,+ required: false,+ defaultValue: fallback,+ }),+ offset: () =>+ Property.Number({+ displayName: 'Offset',+ description: 'How many items to skip. Use the previous offset plus the number of items returned to get the next page.',+ required: false,+ defaultValue: 0,+ }),+};++export const smartSuiteInputs = {+ requireObject,+ optionalJson,+ requireObjectArray,+ requireIdList,+ requireText,+ integerInRange,+ plainTextToDoc,+ isPlainObject,+ aiProps,+};diff --git a/packages/pieces/community/smartsuite/src/lib/common/paged-list.ts b/packages/pieces/community/smartsuite/src/lib/common/paged-list.tsnew file mode 100644index 00000000000..a22f36fa4d0--- /dev/null+++ b/packages/pieces/community/smartsuite/src/lib/common/paged-list.ts@@ -0,0 +1,45 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { smartSuiteClient, SmartSuiteCredentials } from './client';+import { smartSuiteInputs } from './inputs';++const MAX_PAGE_SIZE = 1000;+const DEFAULT_PAGE_SIZE = 100;++async function fetch({+ credentials,+ path,+ limit,+ offset,+ operation,+}: {+ credentials: SmartSuiteCredentials;+ path: string;+ limit: unknown;+ offset: unknown;+ operation: string;+}): Promise<PagedList> {+ const pageSize = smartSuiteInputs.integerInRange({ value: limit, label: 'Limit', min: 1, max: MAX_PAGE_SIZE, fallback: DEFAULT_PAGE_SIZE });+ const start = smartSuiteInputs.integerInRange({ value: offset, label: 'Offset', min: 0, max: Number.MAX_SAFE_INTEGER, fallback: 0 });+ const response = await smartSuiteClient.request<{ items?: Record<string, unknown>[]; total?: number }>({+ credentials,+ method: HttpMethod.POST,+ path,+ query: { limit: pageSize, offset: start },+ body: {},+ operation,+ });+ const items = response.items ?? [];+ const total = typeof response.total === 'number' ? response.total : null;+ const hasMore = items.length > 0 && (total !== null ? start + items.length < total : items.length === pageSize);+ return { items, total, offset: start, limit: pageSize, hasMore };+}++export const pagedList = { fetch };++export type PagedList = {+ items: Record<string, unknown>[];+ total: number | null;+ offset: number;+ limit: number;+ hasMore: boolean;+};diff --git a/packages/pieces/community/smartsuite/src/lib/common/props.ts b/packages/pieces/community/smartsuite/src/lib/common/props.tsindex fb73c870c0f..c98978d9a65 100644--- a/packages/pieces/community/smartsuite/src/lib/common/props.ts+++ b/packages/pieces/community/smartsuite/src/lib/common/props.ts@@ -1,8 +1,9 @@-import { Property, DynamicPropsValue, PiecePropValueSchema } from '@activepieces/pieces-framework';+import { Property, DynamicPropsValue, DropdownOption } from '@activepieces/pieces-framework';import { HttpMethod } from '@activepieces/pieces-common';-import { smartSuiteApiCall, smartSuitePaginatedApiCall, TableStucture } from '.';+import { smartSuiteApi, smartSuitePaginatedApiCall, TableStucture } from '.';import { smartsuiteAuth } from '../auth';import { isNil } from '@activepieces/pieces-framework';+import { pagedList } from './paged-list';export const smartsuiteCommon = {solutionId: Property.Dropdown({@@ -15,40 +16,29 @@ export const smartsuiteCommon = {return {disabled: true,options: [],- placeholder: 'Please enter your API key first.',+ placeholder: 'Please connect your SmartSuite account first.',};}-const { apiKey, accountId } = auth.props;-try {- const response = await smartSuitePaginatedApiCall<{- name: string;- id: string;- hidden: boolean;- }>({+ const solutions = await smartSuitePaginatedApiCall<{ name: string; id: string; hidden?: boolean }>({apiKey,accountId,method: HttpMethod.GET,- resourceUri: '/solutions',+ resourceUri: '/solutions/',+ operation: 'list solutions',});-return {disabled: false,- options: response+ options: solutions.filter((solution) => !solution.hidden)- .map((solution) => {- return {- label: solution.name,- value: solution.id,- };- }),+ .map((solution) => ({ label: solution.name, value: solution.id })),};} catch (error) {return {disabled: true,options: [],- placeholder: 'Error fetching solutions. Please check your API key.',+ placeholder: `Could not load solutions: ${errorText(error)}`,};}},@@ -60,50 +50,66 @@ export const smartsuiteCommon = {required: true,refreshers: ['solutionId'],options: async ({ auth, solutionId }) => {- if (!auth || !solutionId) {- return {- disabled: true,- options: [],- placeholder: solutionId- ? 'Please select a solution first.'- : 'Please enter your API key first.',- };+ if (!auth) {+ return { disabled: true, options: [], placeholder: 'Please connect your SmartSuite account first.' };+ }+ if (!solutionId) {+ return { disabled: true, options: [], placeholder: 'Please select a solution first.' };}-const { apiKey, accountId } = auth.props;-try {- const response = await smartSuitePaginatedApiCall<{- id: string;- name: string;- }>({+ const tables = await smartSuitePaginatedApiCall<{ id: string; name: string }>({apiKey,accountId,method: HttpMethod.GET,- resourceUri: '/applications',- query: {- solution: solutionId as string,- },+ resourceUri: '/applications/',+ query: { solution: String(solutionId) },+ operation: 'list tables',});-return {disabled: false,- options: response.map((table) => {- return {- label: table.name,- value: table.id,- };- }),+ options: tables.map((table) => ({ label: table.name, value: table.id })),};} catch (error) {return {disabled: true,options: [],- placeholder: 'Error fetching tables. Please check your permissions.',+ placeholder: `Could not load tables: ${errorText(error)}`,};}},}),++ tableFieldDropdown: ({ displayName, description, required, onlyTypes }: { displayName: string; description?: string; required: boolean; onlyTypes?: string[] }) =>+ Property.Dropdown({+ auth: smartsuiteAuth,+ displayName,+ description,+ required,+ refreshers: ['solutionId', 'tableId'],+ options: async ({ auth, tableId }) => {+ if (!auth) {+ return { disabled: true, options: [], placeholder: 'Please connect your SmartSuite account first.' };+ }+ if (!tableId) {+ return { disabled: true, options: [], placeholder: 'Please select a table first.' };+ }+ try {+ const table = await smartSuiteApi.getTable({ credentials: auth.props, tableId });+ const options: DropdownOption<string>[] = table.structure+ .filter((field) =>+ onlyTypes+ ? onlyTypes.includes(field.field_type)+ : !field.params.is_auto_generated && !field.params.system,+ )+ .map((field) => ({ label: field.label, value: field.slug }));+ return { disabled: false, options };+ } catch (error) {+ return { disabled: true, options: [], placeholder: `Could not load fields: ${errorText(error)}` };+ }+ },+ }),+tableFields: Property.DynamicProperties({auth: smartsuiteAuth,displayName: 'Fields',@@ -116,14 +122,7 @@ export const smartsuiteCommon = {const { apiKey, accountId } = auth.props;try {- const response = await smartSuiteApiCall<{- structure: TableStucture[];- }>({- apiKey,- accountId,- method: HttpMethod.GET,- resourceUri: `/applications/${tableId}`,- });+ const response = await smartSuiteApi.getTable({ credentials: { apiKey, accountId }, tableId });const fieldProperties: DynamicPropsValue = {};@@ -245,7 +244,11 @@ export const smartsuiteCommon = {return fieldProperties;} catch (error) {- return {};+ return {+ loadError: Property.MarkDown({+ value: `Could not load the table fields: ${errorText(error)}`,+ }),+ };}},}),@@ -254,13 +257,122 @@ export const smartsuiteCommon = {displayName: 'Record ID',required: true,}),++ recordDropdown: ({ displayName, description }: { displayName: string; description?: string }) =>+ Property.Dropdown({+ auth: smartsuiteAuth,+ displayName,+ description,+ required: true,+ refreshers: ['solutionId', 'tableId'],+ options: async ({ auth, tableId }) => {+ if (!auth) {+ return { disabled: true, options: [], placeholder: 'Please connect your SmartSuite account first.' };+ }+ if (!tableId) {+ return { disabled: true, options: [], placeholder: 'Please select a table first.' };+ }+ try {+ const page = await smartSuiteApi.listRecordsPage({+ credentials: auth.props,+ tableId,+ sort: [{ field: 'last_updated', direction: 'desc' }],+ limit: RECORD_OPTIONS_LIMIT,+ offset: 0,+ });+ const options: DropdownOption<string>[] = page.items+ .filter((record) => typeof record['id'] === 'string')+ .map((record) => ({ label: optionLabel({ primary: record['title'], fallback: String(record['id']) }), value: String(record['id']) }));+ return {+ disabled: false,+ options,+ placeholder: page.hasMore ? `Showing the ${RECORD_OPTIONS_LIMIT} most recently updated records.` : undefined,+ };+ } catch (error) {+ return { disabled: true, options: [], placeholder: `Could not load records: ${errorText(error)}` };+ }+ },+ }),++ deletedRecordDropdown: Property.Dropdown({+ auth: smartsuiteAuth,+ displayName: 'Deleted Record',+ description: 'A record in the trash of the selected table.',+ required: true,+ refreshers: ['solutionId', 'tableId'],+ options: async ({ auth, solutionId, tableId }) => {+ if (!auth) {+ return { disabled: true, options: [], placeholder: 'Please connect your SmartSuite account first.' };+ }+ if (!solutionId || !tableId) {+ return { disabled: true, options: [], placeholder: 'Please select a solution and table first.' };+ }+ try {+ const deleted = await smartSuiteApi.listDeletedRecords({ credentials: auth.props, solutionId: String(solutionId) });+ const options: DropdownOption<string>[] = deleted+ .filter((record) => record['application_id'] === tableId && typeof record['id'] === 'string')+ .map((record) => ({ label: optionLabel({ primary: record['title'], fallback: String(record['id']) }), value: String(record['id']) }));+ return { disabled: false, options, placeholder: options.length === 0 ? 'The trash of this table is empty.' : undefined };+ } catch (error) {+ return { disabled: true, options: [], placeholder: `Could not load deleted records: ${errorText(error)}` };+ }+ },+ }),++ memberDropdown: ({ displayName, description, required }: { displayName: string; description?: string; required: boolean }) =>+ Property.Dropdown({+ auth: smartsuiteAuth,+ displayName,+ description,+ required,+ refreshers: [],+ options: async ({ auth }) => {+ if (!auth) {+ return { disabled: true, options: [], placeholder: 'Please connect your SmartSuite account first.' };+ }+ try {+ const page = await pagedList.fetch({+ credentials: auth.props,+ path: '/applications/members/records/list/',+ limit: MEMBER_OPTIONS_LIMIT,+ offset: 0,+ operation: 'list members',+ });+ const options: DropdownOption<string>[] = page.items+ .filter((member) => typeof member['id'] === 'string')+ .map((member) => ({ label: memberLabel(member), value: String(member['id']) }));+ return { disabled: false, options };+ } catch (error) {+ return { disabled: true, options: [], placeholder: `Could not load members: ${errorText(error)}` };+ }+ },+ }),};-export function formatRecordFields(- tableSchema: TableStucture[],- tableValues: Record<string, any>,-): Record<string, any> {- const formattedFields: Record<string, any> = {};+const RECORD_OPTIONS_LIMIT = 100;+const MEMBER_OPTIONS_LIMIT = 1000;++function optionLabel({ primary, fallback }: { primary: unknown; fallback: string }): string {+ return typeof primary === 'string' && primary.trim().length > 0 ? primary : fallback;+}++function memberLabel(member: Record<string, unknown>): string {+ const fullName = member['full_name'];+ const name = fullName !== null && typeof fullName === 'object' ? Reflect.get(fullName, 'sys_root') : undefined;+ const emails = member['email'];+ const email = Array.isArray(emails) && typeof emails[0] === 'string' ? emails[0] : undefined;+ const base = optionLabel({ primary: name, fallback: email ?? String(member['id']) });+ return email && base !== email ? `${base} (${email})` : base;+}++function formatRecordFields({+ tableSchema,+ tableValues,+}: {+ tableSchema: TableStucture[];+ tableValues: Record<string, unknown>;+}): Record<string, unknown> {+ const formattedFields: Record<string, unknown> = {};const fieldMap: Record<string, string> = tableSchema.reduce((acc, field) => {acc[field.slug] = field.field_type;@@ -346,16 +458,19 @@ export function formatRecordFields(return formattedFields;}-export function transformRecordFields(- tableSchema: TableStucture[],- tableValues: Record<string, any>,-) {+function transformRecordFields({+ tableSchema,+ tableValues,+}: {+ tableSchema: TableStucture[];+ tableValues: Record<string, unknown>;+}) {const fieldMap: Record<string, string> = tableSchema.reduce((acc, field) => {acc[field.slug] = field.label;return acc;}, {} as Record<string, string>);- const transformedFields: Record<string, any> = {};+ const transformedFields: Record<string, unknown> = {};for (const [slug, value] of Object.entries(tableValues)) {const label = fieldMap[slug] ?? slug;@@ -364,3 +479,9 @@ export function transformRecordFields(return transformedFields;}++function errorText(error: unknown): string {+ return error instanceof Error ? error.message : String(error);+}++export { formatRecordFields, transformRecordFields };diff --git a/packages/pieces/community/smartsuite/src/lib/common/record-files.ts b/packages/pieces/community/smartsuite/src/lib/common/record-files.tsnew file mode 100644index 00000000000..62342f749cf--- /dev/null+++ b/packages/pieces/community/smartsuite/src/lib/common/record-files.ts@@ -0,0 +1,63 @@+import { HttpMethod } from '@activepieces/pieces-common';+import FormData from 'form-data';+import { SmartSuiteRecord } from '.';+import { smartSuiteClient, SmartSuiteCredentials } from './client';++const MAX_UPLOAD_BYTES = 100 * 1024 * 1024;++async function attach({+ credentials,+ tableId,+ recordId,+ field,+ file,+}: {+ credentials: SmartSuiteCredentials;+ tableId: unknown;+ recordId: unknown;+ field: unknown;+ file: { base64: string; filename: string };+}): Promise<AttachResult> {+ const tableSegment = smartSuiteClient.pathSegment({ value: tableId, label: 'Table' });+ const recordSegment = smartSuiteClient.pathSegment({ value: recordId, label: 'Record ID' });+ const fieldSegment = smartSuiteClient.pathSegment({ value: field, label: 'File Field' });+ const data = Buffer.from(file.base64, 'base64');+ if (data.length === 0) {+ throw new Error('The file is empty.');+ }+ if (data.length > MAX_UPLOAD_BYTES) {+ throw new Error(`The file is ${data.length} bytes; the limit for this action is ${MAX_UPLOAD_BYTES} bytes (100 MB).`);+ }+ const formData = new FormData();+ formData.append('files', data, file.filename);+ await smartSuiteClient.request<unknown>({+ credentials,+ method: HttpMethod.POST,+ path: `/recordfiles/${tableSegment}/${recordSegment}/${fieldSegment}/`,+ body: formData,+ headers: formData.getHeaders(),+ operation: 'upload file',+ });+ const record = await smartSuiteClient.request<SmartSuiteRecord>({+ credentials,+ method: HttpMethod.GET,+ path: `/applications/${tableSegment}/records/${recordSegment}/`,+ operation: 'get record after upload',+ });+ const files = record[String(field)];+ return {+ recordId: String(recordId).trim(),+ field: String(field),+ fileName: file.filename,+ files: Array.isArray(files) ? files : [],+ };+}++export const recordFiles = { attach, MAX_UPLOAD_BYTES };++export type AttachResult = {+ recordId: string;+ field: string;+ fileName: string;+ files: unknown[];+};diff --git a/packages/pieces/community/smartsuite/src/lib/common/tables.ts b/packages/pieces/community/smartsuite/src/lib/common/tables.tsnew file mode 100644index 00000000000..8fd34f3fba1--- /dev/null+++ b/packages/pieces/community/smartsuite/src/lib/common/tables.ts@@ -0,0 +1,49 @@+import { SmartSuiteTable, TableStucture } from '.';++function summarize(table: SmartSuiteTable): TableSummary {+ return {+ id: table.id,+ name: table.name,+ slug: table.slug ?? null,+ solution: table.solution ?? null,+ status: table.status ?? null,+ primary_field: table.primary_field ?? null,+ fields_count: Array.isArray(table.structure) ? table.structure.length : null,+ };+}++function describeField(field: TableStucture): FieldSummary {+ return {+ slug: field.slug,+ label: field.label,+ field_type: field.field_type,+ required: field.params?.required === true,+ system: field.params?.system === true || field.params?.is_auto_generated === true,+ linked_table_id: field.params?.linked_application ?? null,+ choices: Array.isArray(field.params?.choices)+ ? field.params.choices.map((choice) => ({ label: choice.label, value: choice.value }))+ : [],+ };+}++export const tableSummary = { summarize, describeField };++export type TableSummary = {+ id: string;+ name: string;+ slug: string | null;+ solution: string | null;+ status: string | null;+ primary_field: string | null;+ fields_count: number | null;+};++export type FieldSummary = {+ slug: string;+ label: string;+ field_type: string;+ required: boolean;+ system: boolean;+ linked_table_id: string | null;+ choices: { label: string; value: string }[];+};diff --git a/packages/pieces/community/smartsuite/src/lib/common/webhook.ts b/packages/pieces/community/smartsuite/src/lib/common/webhook.tsnew file mode 100644index 00000000000..cd216fcb4d9--- /dev/null+++ b/packages/pieces/community/smartsuite/src/lib/common/webhook.ts@@ -0,0 +1,264 @@+import { HttpMethod, httpClient } from '@activepieces/pieces-common';+import { API_ENDPOINTS } from './constants';+import { smartSuiteClient, SmartSuiteCredentials } from './client';++const EVENTS_PAGE_SIZE = 50;+const MAX_EVENT_PAGES = 20;+const MAX_SEEN_EVENT_IDS = 500;+const RECENT_RECORDS_LIMIT = 5;+const PULL_BUDGET_MS = 15_000;+const CONTINUATION_TIMEOUT_MS = 5_000;+const MIN_PAGE_BUDGET_MS = 2_000;++async function createWebhook({+ credentials,+ solutionId,+ tableId,+ kind,+ webhookUrl,+}: {+ credentials: SmartSuiteCredentials;+ solutionId: string;+ tableId: string;+ kind: string;+ webhookUrl: string;+}): Promise<string> {+ const response = await smartSuiteClient.request<{ webhook?: { webhook_id?: string } }>({+ credentials,+ api: 'webhooks',+ method: HttpMethod.POST,+ path: API_ENDPOINTS.CREATE_WEBHOOK,+ body: {+ webhook: {+ filter: { applications: { application_ids: [tableId] } },+ kinds: [kind],+ locator: { account_id: credentials.accountId.trim(), solution_id: solutionId },+ notification_status: { enabled: { url: webhookUrl } },+ },+ },+ operation: 'create webhook',+ });+ const webhookId = response?.webhook?.webhook_id;+ if (typeof webhookId !== 'string' || webhookId.length === 0) {+ throw new Error('SmartSuite created the webhook but returned no webhook ID.');+ }+ return webhookId;+}++async function deleteWebhook({ credentials, webhookId }: { credentials: SmartSuiteCredentials; webhookId: string }): Promise<void> {+ try {+ await smartSuiteClient.request<unknown>({+ credentials,+ api: 'webhooks',+ method: HttpMethod.POST,+ path: API_ENDPOINTS.DELETE_WEBHOOK,+ body: { webhook_id: webhookId },+ operation: 'delete webhook',+ });+ } catch (error) {+ if (smartSuiteClient.statusOf(error) !== 404) {+ throw error;+ }+ }+}++async function enable({+ credentials,+ store,+ storeKey,+ solutionId,+ tableId,+ kind,+ webhookUrl,+}: {+ credentials: SmartSuiteCredentials;+ store: TriggerStore;+ storeKey: string;+ solutionId: string;+ tableId: string;+ kind: string;+ webhookUrl: string;+}): Promise<void> {+ const webhookId = await createWebhook({ credentials, solutionId, tableId, kind, webhookUrl });+ try {+ await store.put(storeKey, webhookId);+ await store.put(PAGE_TOKEN_KEY, '');+ await store.put(SEEN_EVENTS_KEY, []);+ } catch (error) {+ await deleteWebhook({ credentials, webhookId }).catch(() => undefined);+ throw error;+ }+}++async function disable({ credentials, store, storeKey }: { credentials: SmartSuiteCredentials; store: TriggerStore; storeKey: string }): Promise<void> {+ const webhookId = await store.get<string>(storeKey);+ if (typeof webhookId === 'string' && webhookId.length > 0) {+ await deleteWebhook({ credentials, webhookId });+ }+ await store.delete(storeKey);+ await store.delete(PAGE_TOKEN_KEY);+ await store.delete(SEEN_EVENTS_KEY);+}++async function pullNewEvents({+ credentials,+ store,+ storeKey,+ payload,+ webhookUrl,+}: {+ credentials: SmartSuiteCredentials;+ store: TriggerStore;+ storeKey: string;+ payload: unknown;+ webhookUrl: string;+}): Promise<SmartSuiteEvent[]> {+ const notifiedWebhookId = await ownNotificationWebhookId({ store, storeKey, payload });+ if (notifiedWebhookId === undefined) {+ return [];+ }+ const startToken = (await store.get<string>(PAGE_TOKEN_KEY)) ?? '';+ const seen = new Set((await store.get<string[]>(SEEN_EVENTS_KEY)) ?? []);+ const deadlineAt = Date.now() + PULL_BUDGET_MS;+ const collected: SmartSuiteEvent[] = [];+ let pageToken = startToken;+ let lastToken = startToken;+ let readToEnd = false;+ for (let page = 0; page < MAX_EVENT_PAGES; page++) {+ if (page > 0 && deadlineAt - Date.now() < MIN_PAGE_BUDGET_MS) {+ break;+ }+ const response = await smartSuiteClient.request<{ events?: SmartSuiteEvent[]; next_page_token?: string }>({+ credentials,+ api: 'webhooks',+ method: HttpMethod.POST,+ path: API_ENDPOINTS.LIST_EVENTS,+ body: { webhook_id: notifiedWebhookId, page_size: EVENTS_PAGE_SIZE, page_token: pageToken },+ operation: 'list webhook events',+ deadlineAt,+ });+ const events = response?.events ?? [];+ collected.push(...events);+ const next = response?.next_page_token ?? '';+ if (next.length > 0) {+ lastToken = next;+ }+ if (events.length === 0 || next.length === 0 || next === pageToken) {+ readToEnd = true;+ break;+ }+ pageToken = next;+ }+ const fresh = collected.filter((event) => {+ const key = eventKey(event);+ if (seen.has(key)) {+ return false;+ }+ seen.add(key);+ return true;+ });+ if (!readToEnd) {+ await requestContinuation({ webhookUrl, webhookId: notifiedWebhookId });+ }+ const storedToken = (await store.get<string>(PAGE_TOKEN_KEY)) ?? '';+ const storedNow = (await store.get<string[]>(SEEN_EVENTS_KEY)) ?? [];+ const claimedElsewhere = new Set(storedNow);+ const unclaimed = fresh.filter((event) => !claimedElsewhere.has(eventKey(event)));+ const merged = Array.from(new Set([...storedNow, ...seen]));+ const nextToken = cursorToStore({ stored: storedToken, start: startToken, mine: lastToken });+ if (nextToken !== storedToken) {+ await store.put(PAGE_TOKEN_KEY, nextToken);+ }+ await store.put(SEEN_EVENTS_KEY, merged.slice(-MAX_SEEN_EVENT_IDS));+ return unclaimed;+}++async function requestContinuation({ webhookUrl, webhookId }: { webhookUrl: string; webhookId: string }): Promise<void> {+ await httpClient.sendRequest({+ method: HttpMethod.POST,+ url: webhookUrl,+ headers: { 'Content-Type': 'application/json' },+ body: { webhookId, continuation: true },+ timeout: CONTINUATION_TIMEOUT_MS,+ });+}++function cursorToStore({ stored, start, mine }: { stored: string; start: string; mine: string }): string {+ if (stored === start) {+ return mine;+ }+ if (/^\d+$/.test(stored) && /^\d+$/.test(mine) && BigInt(mine) > BigInt(stored)) {+ return mine;+ }+ return stored;+}++async function ownNotificationWebhookId({ store, storeKey, payload }: { store: TriggerStore; storeKey: string; payload: unknown }): Promise<string | undefined> {+ const notifiedWebhookId = notificationWebhookId(payload);+ const ownWebhookId = await store.get<string>(storeKey);+ if (!notifiedWebhookId || (ownWebhookId && notifiedWebhookId !== ownWebhookId)) {+ return undefined;+ }+ return notifiedWebhookId;+}++function notificationWebhookId(payload: unknown): string | undefined {+ if (!isRecord(payload)) {+ return undefined;+ }+ const id = payload['webhookId'] ?? payload['webhook_id'];+ return typeof id === 'string' && id.length > 0 ? id : undefined;+}++function dedupeKeyOf(event: SmartSuiteEvent): string {+ return `smartsuite:${eventKey(event)}`;+}++function eventKey(event: SmartSuiteEvent): string {+ for (const key of ['event_id', 'id']) {+ const value = event[key];+ if (typeof value === 'string' && value.length > 0) {+ return value;+ }+ }+ const data = recordOf(event);+ const lastUpdated = isRecord(data['last_updated']) ? data['last_updated']['on'] : undefined;+ return `${String(data['id'] ?? '')}:${String(lastUpdated ?? '')}:${String(event['event_type'] ?? event['kind'] ?? '')}`;+}++function recordOf(event: SmartSuiteEvent): Record<string, unknown> {+ const eventData = event['record_event_data'];+ if (isRecord(eventData) && isRecord(eventData['data'])) {+ return eventData['data'];+ }+ return {};+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return value !== null && typeof value === 'object' && !Array.isArray(value);+}++const PAGE_TOKEN_KEY = 'pageToken';+const SEEN_EVENTS_KEY = 'seenEventIds';++export const smartSuiteWebhooks = {+ enable,+ disable,+ pullNewEvents,+ ownNotificationWebhookId,+ recordOf,+ dedupeKeyOf,+ deleteWebhook,+ RECENT_RECORDS_LIMIT,+ MAX_EVENT_PAGES,+ MAX_SEEN_EVENT_IDS,+ PULL_BUDGET_MS,+};++export type SmartSuiteEvent = Record<string, unknown>;++export type TriggerStore = {+ put: <T>(key: string, value: T) => Promise<T>;+ get: <T>(key: string) => Promise<T | null>;+ delete: (key: string) => Promise<void>;+};diff --git a/packages/pieces/community/smartsuite/src/lib/output-schemas.ts b/packages/pieces/community/smartsuite/src/lib/output-schemas.tsnew file mode 100644index 00000000000..5969f7c6e01--- /dev/null+++ b/packages/pieces/community/smartsuite/src/lib/output-schemas.ts@@ -0,0 +1,205 @@+import { OutputSchema } from '@activepieces/pieces-framework';++type Field = OutputSchema['fields'][number];++const actorChildren: Field[] = [+ { key: 'on', label: 'At', format: 'datetime' },+ { key: 'by', label: 'By (Member ID)' },+];++const rawRecordFields: Field[] = [+ { key: 'id', label: 'Record ID', description: 'Use this to get, update or delete the record in a later step.' },+ { key: 'title', label: 'Title' },+ { key: 'application_id', label: 'Table ID' },+ { key: 'application_slug', label: 'Table Slug' },+ { key: 'first_created', label: 'First Created', children: actorChildren },+ { key: 'last_updated', label: 'Last Updated', children: actorChildren },+ { key: 'autonumber', label: 'Auto Number', format: 'number' },+ { key: 'comments_count', label: 'Open Comments', format: 'number' }, { key: 'all_fields', label: 'All Fields', value: '', dynamicKey: true, description: 'Every field of the record keyed by field slug, including the fields specific to your table.' },+];++const labelledRecordFields: Field[] = [+ { key: 'id', label: 'Record ID', description: 'Use this to get, update or delete the record in a later step.' },+ { key: 'Title', label: 'Title', description: 'The record title. Other fields are keyed by their label in your table, so they differ from table to table.' },+ { key: 'application_id', label: 'Table ID' },+ { key: 'application_slug', label: 'Table Slug' },+ { key: 'First Created', label: 'First Created', children: actorChildren },+ { key: 'Last Updated', label: 'Last Updated', children: actorChildren }, { key: 'all_fields', label: 'All Fields', value: '', dynamicKey: true, description: 'Every field of the record keyed by its label, including the fields specific to your table.' },+];++const solutionFields: Field[] = [+ { key: 'id', label: 'Solution ID' },+ { key: 'name', label: 'Name' },+ { key: 'slug', label: 'Slug' },+ { key: 'status', label: 'Status' },+ { key: 'hidden', label: 'Hidden', format: 'boolean' },+ { key: 'applications_count', label: 'Tables', format: 'number' },+ { key: 'records_count', label: 'Records', format: 'number' },+ { key: 'members_count', label: 'Members', format: 'number' },+ { key: 'created', label: 'Created', format: 'datetime' },+ { key: 'updated', label: 'Updated', format: 'datetime' },+];++const tableSummaryFields: Field[] = [+ { key: 'id', label: 'Table ID' },+ { key: 'name', label: 'Name' },+ { key: 'slug', label: 'Slug' },+ { key: 'solution', label: 'Solution ID' },+ { key: 'status', label: 'Status' },+ { key: 'primary_field', label: 'Primary Field Slug' },+ { key: 'fields_count', label: 'Fields', format: 'number' },+];++const tableFieldFields: Field[] = [+ { key: 'slug', label: 'Field Slug', description: 'Use this key when you pass field values to create, update or list records.' },+ { key: 'label', label: 'Label' },+ { key: 'field_type', label: 'Field Type' },+ { key: 'required', label: 'Required', format: 'boolean' },+ { key: 'system', label: 'System Field', format: 'boolean', description: 'System fields are set by SmartSuite and cannot be written.' },+ { key: 'linked_table_id', label: 'Linked Table ID' },+ {+ key: 'choices',+ label: 'Choices',+ listItems: [+ { key: 'label', label: 'Label' },+ { key: 'value', label: 'Value', description: 'Pass this value (not the label) when you set a select or status field.' },+ ],+ },+];++const listMeta: Field[] = [+ { key: 'total', label: 'Total Matches', format: 'number', description: 'Total number of matching items reported by SmartSuite.' },+ { key: 'offset', label: 'Offset', format: 'number' },+ { key: 'limit', label: 'Limit', format: 'number' },+ { key: 'hasMore', label: 'Has More', format: 'boolean', description: 'True when more items exist; call again with offset + number of items returned.' },+];++const memberFields: Field[] = [+ { key: 'id', label: 'Member ID' },+ { key: 'full_name', label: 'Full Name', children: [{ key: 'sys_root', label: 'Full Name' }, { key: 'first_name', label: 'First Name' }, { key: 'last_name', label: 'Last Name' }] },+ { key: 'email', label: 'Emails' },+ { key: 'job_title', label: 'Job Title' },+ { key: 'role', label: 'Role' },+ { key: 'type', label: 'Type' },+ { key: 'timezone', label: 'Time Zone' },+ { key: 'status', label: 'Status', children: [{ key: 'value', label: 'Value' }] },+];++const teamFields: Field[] = [+ { key: 'id', label: 'Team ID' },+ { key: 'name', label: 'Name' },+ { key: 'owners', label: 'Owner IDs' },+ { key: 'members', label: 'Member IDs' },+];++const commentFields: Field[] = [+ { key: 'id', label: 'Comment ID' },+ { key: 'record', label: 'Record ID' },+ { key: 'application', label: 'Table ID' },+ { key: 'solution', label: 'Solution ID' },+ { key: 'member', label: 'Author (Member ID)' },+ { key: 'created_on', label: 'Created On', format: 'datetime' },+ { key: 'message', label: 'Message', children: [{ key: 'html', label: 'HTML' }, { key: 'preview', label: 'Preview' }] },+ { key: 'parent_comment', label: 'Parent Comment ID' },+ { key: 'assigned_to', label: 'Assigned To' },+];++const deletedRecordFields: Field[] = [+ { key: 'id', label: 'Record ID' },+ { key: 'title', label: 'Title' },+ { key: 'application_id', label: 'Table ID' },+ { key: 'application_name', label: 'Table Name' },+ { key: 'solution_id', label: 'Solution ID' },+ { key: 'deleted_by', label: 'Deleted By (Member ID)' },+ { key: 'deleted_date', label: 'Deleted Date', children: [{ key: 'date', label: 'Date', format: 'datetime' }] },+];++export const outputSchemas: Record<string, OutputSchema> = {+ labelledRecord: { fields: labelledRecordFields },+ rawRecord: { fields: rawRecordFields },+ findRecords: {+ fields: [+ { key: 'found', label: 'Found', format: 'boolean' },+ { key: 'result', label: 'Records', listItems: labelledRecordFields },+ { key: 'hasMore', label: 'Has More', format: 'boolean', description: 'True when Max Records was reached and more matches exist.' },+ ],+ },+ recordPage: {+ fields: [{ key: 'items', label: 'Records', listItems: rawRecordFields }, ...listMeta],+ },+ deleteRecord: {+ fields: [+ { key: 'id', label: 'Record ID' },+ { key: 'deleted', label: 'Deleted', format: 'boolean' },+ { key: 'alreadyDeleted', label: 'Already Deleted', format: 'boolean', description: 'True when SmartSuite no longer knows the record (404). A record already in the trash is deleted again and reports false.' },+ ],+ },+ uploadFile: {+ fields: [+ { key: 'recordId', label: 'Record ID' },+ { key: 'field', label: 'File Field Slug' },+ { key: 'fileName', label: 'File Name' },+ {+ key: 'files',+ label: 'Files In Field',+ listItems: [+ { key: 'handle', label: 'File Handle', description: 'Pass this to Get File Download URL.' },+ { key: 'metadata', label: 'Metadata', children: [{ key: 'filename', label: 'File Name' }, { key: 'mimetype', label: 'MIME Type' }, { key: 'size', label: 'Size (bytes)', format: 'number' }] },+ { key: 'created_on', label: 'Created On', format: 'datetime' },+ ],+ },+ ],+ },+ solutionList: { fields: [{ key: 'items', label: 'Solutions', listItems: solutionFields }, { key: 'count', label: 'Count', format: 'number' }] },+ solution: { fields: solutionFields },+ tableList: { fields: [{ key: 'items', label: 'Tables', listItems: tableSummaryFields }, { key: 'count', label: 'Count', format: 'number' }] },+ tableSchema: { fields: [...tableSummaryFields, { key: 'fields', label: 'Fields', listItems: tableFieldFields }] },+ bulkRecords: { fields: [{ key: 'items', label: 'Records', listItems: rawRecordFields }, { key: 'count', label: 'Count', format: 'number' }] },+ bulkDelete: {+ fields: [+ { key: 'deletedIds', label: 'Deleted Record IDs' },+ { key: 'count', label: 'Count', format: 'number' },+ ],+ },+ upsertRecord: {+ fields: [+ { key: 'action', label: 'Action', description: 'created or updated.' },+ { key: 'record', label: 'Record', children: rawRecordFields },+ ],+ },+ deletedRecordList: { fields: [{ key: 'items', label: 'Deleted Records', listItems: deletedRecordFields }, { key: 'count', label: 'Count', format: 'number' }] },+ commentList: { fields: [{ key: 'items', label: 'Comments', listItems: commentFields }, { key: 'count', label: 'Count', format: 'number' }] },+ comment: { fields: commentFields },+ memberPage: { fields: [{ key: 'items', label: 'Members', listItems: memberFields }, ...listMeta] },+ member: { fields: memberFields },+ teamPage: { fields: [{ key: 'items', label: 'Teams', listItems: teamFields }, ...listMeta] },+ fileUrl: {+ fields: [+ { key: 'handle', label: 'File Handle' },+ { key: 'url', label: 'Download URL', format: 'url', description: 'A temporary link to the file. It expires, so use it soon.' },+ ],+ },+ recordFileUrls: {+ fields: [+ { key: 'recordId', label: 'Record ID' },+ { key: 'field', label: 'File Field Slug' },+ {+ key: 'files',+ label: 'Files',+ listItems: [+ { key: 'handle', label: 'File Handle' },+ { key: 'name', label: 'File Name' },+ { key: 'url', label: 'Download URL', format: 'url', description: 'A temporary link to the file. It expires, so use it soon.' },+ ],+ },+ { key: 'count', label: 'Count', format: 'number' },+ ],+ },+ addField: {+ fields: [+ { key: 'tableId', label: 'Table ID' },+ { key: 'field', label: 'Field', children: tableFieldFields },+ ],+ },+ restoreRecord: { fields: rawRecordFields },+};diff --git a/packages/pieces/community/smartsuite/src/lib/triggers/new-record.ts b/packages/pieces/community/smartsuite/src/lib/triggers/new-record.tsindex 2d0c5e18ca6..cedf6673e05 100644--- a/packages/pieces/community/smartsuite/src/lib/triggers/new-record.ts+++ b/packages/pieces/community/smartsuite/src/lib/triggers/new-record.ts@@ -1,9 +1,11 @@-import { TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';-import { HttpMethod, httpClient } from '@activepieces/pieces-common';+import { DEDUPE_KEY_PROPERTY, TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';import { smartsuiteAuth } from '../auth';import { smartsuiteCommon, transformRecordFields } from '../common/props';-import { SMARTSUITE_WEBHOOKS_API_URL, API_ENDPOINTS, WEBHOOK_EVENTS } from '../common/constants';-import { smartSuiteApiCall, TableStucture } from '../common';+import { WEBHOOK_EVENTS } from '../common/constants';+import { smartSuiteApi } from '../common';+import { smartSuiteClient } from '../common/client';+import { smartSuiteWebhooks } from '../common/webhook';+import { outputSchemas } from '../output-schemas';export const newRecord = createTrigger({name: 'new_record',@@ -11,7 +13,7 @@ export const newRecord = createTrigger({displayName: 'New Record',description: 'Triggers when a new record is created in the specified table',aiMetadata: {- description: 'Fires when a new record is created in the specified SmartSuite solution and table, delivering the created record. Use to start a flow whenever a row is added to that table.',+ description: 'Fires when a new record is created in the specified SmartSuite solution and table, delivering the created record keyed by field label. Use to start a flow whenever a row is added to that table.',},type: TriggerStrategy.WEBHOOK,auth: smartsuiteAuth,@@ -19,141 +21,61 @@ export const newRecord = createTrigger({solutionId: smartsuiteCommon.solutionId,tableId: smartsuiteCommon.tableId,},+ outputSchema: outputSchemas['labelledRecord'],async onEnable(context) {- const { solutionId, tableId } = context.propsValue;-- const response = await httpClient.sendRequest({- method: HttpMethod.POST,- url: `${SMARTSUITE_WEBHOOKS_API_URL}${API_ENDPOINTS.CREATE_WEBHOOK}`,- body: {- webhook: {- filter: {- applications: {- application_ids: [tableId],- },- },- kinds: [WEBHOOK_EVENTS.RECORD_CREATED],- locator: {- account_id: context.auth.props.accountId, // This will be filled by SmartSuite based on the API key- solution_id: solutionId,- },- notification_status: {- enabled: {- url: context.webhookUrl,- },- },- },- },- headers: {- Authorization: `Token ${context.auth.props.apiKey}`,- 'ACCOUNT-ID': context.auth.props.accountId,- },+ await smartSuiteWebhooks.enable({+ credentials: smartSuiteClient.credentialsOf(context.auth),+ store: context.store,+ storeKey: 'new_record',+ solutionId: String(context.propsValue.solutionId),+ tableId: String(context.propsValue.tableId),+ kind: WEBHOOK_EVENTS.RECORD_CREATED,+ webhookUrl: context.webhookUrl,});- await context.store.put('new_record', response.body.webhook.webhook_id);},async onDisable(context) {- const webhookId = await context.store.get('new_record');-- if (webhookId) {- await httpClient.sendRequest({- method: HttpMethod.POST,- url: `${SMARTSUITE_WEBHOOKS_API_URL}${API_ENDPOINTS.DELETE_WEBHOOK}`,- body: {- webhook_id: webhookId,- },- headers: {- Authorization: `Token ${context.auth.props.apiKey}`,- 'ACCOUNT-ID': context.auth.props.accountId,- },- });- }+ await smartSuiteWebhooks.disable({+ credentials: smartSuiteClient.credentialsOf(context.auth),+ store: context.store,+ storeKey: 'new_record',+ });},async test(context) {- const { tableId } = context.propsValue;- const response = await smartSuiteApiCall<{ items: Record<string, any>[] }>({- accountId: context.auth.props.accountId,- apiKey: context.auth.props.apiKey,- method: HttpMethod.POST,- resourceUri: `/applications/${tableId}/records/list/`,- query: { limit: '5', offset: '0' },- });- const items = response.items || [];-- const tableResponse = await smartSuiteApiCall<{- structure: TableStucture[];- }>({- apiKey: context.auth.props.apiKey,- accountId: context.auth.props.accountId,- method: HttpMethod.GET,- resourceUri: `/applications/${context.propsValue.tableId}`,+ const credentials = smartSuiteClient.credentialsOf(context.auth);+ const table = await smartSuiteApi.getTable({ credentials, tableId: context.propsValue.tableId });+ const page = await smartSuiteApi.listRecordsPage({+ credentials,+ tableId: context.propsValue.tableId,+ sort: [{ field: 'first_created', direction: 'desc' }],+ limit: smartSuiteWebhooks.RECENT_RECORDS_LIMIT,+ offset: 0,});- const tableSchema = tableResponse.structure;-- return items.map((item) => transformRecordFields(tableSchema, item));+ return page.items.map((item) => transformRecordFields({ tableSchema: table.structure, tableValues: item }));},async run(context) {- const webhookPayload = context.payload.body as {- webhookId: string;- locator: {- accountId: string;- solutionId: string;- };- };-- let pageToken = (await context.store.get('pageToken')) ?? '';-- if (!webhookPayload || !webhookPayload.webhookId || !webhookPayload.locator) {+ const credentials = smartSuiteClient.credentialsOf(context.auth);+ if ((await smartSuiteWebhooks.ownNotificationWebhookId({ store: context.store, storeKey: 'new_record', payload: context.payload.body })) === undefined) {return [];}-- const events = [];-- let hasMore = true;-- do {- const response = await httpClient.sendRequest<{- events: { record_event_data: { data: Record<string, any> } }[];- next_page_token: string;- }>({- method: HttpMethod.POST,- url: `${SMARTSUITE_WEBHOOKS_API_URL}${API_ENDPOINTS.LIST_EVENTS}`,- body: {- webhook_id: webhookPayload.webhookId,- page_size: '50',- page_token: pageToken,- },- headers: {- Authorization: `Token ${context.auth.props.apiKey}`,- 'ACCOUNT-ID': context.auth.props.accountId,- },- });-- pageToken = response.body.next_page_token;-- const items = response.body.events ?? [];-- events.push(...items);-- hasMore = items.length > 0;- } while (hasMore);-- await context.store.put('pageToken', pageToken);-- const tableResponse = await smartSuiteApiCall<{- structure: TableStucture[];- }>({- apiKey: context.auth.props.apiKey,- accountId: context.auth.props.accountId,- method: HttpMethod.GET,- resourceUri: `/applications/${context.propsValue.tableId}`,+ const table = await smartSuiteApi.getTable({ credentials, tableId: context.propsValue.tableId });+ const events = await smartSuiteWebhooks.pullNewEvents({+ credentials,+ store: context.store,+ storeKey: 'new_record',+ payload: context.payload.body,+ webhookUrl: context.webhookUrl,});- const tableSchema = tableResponse.structure;-- return events.map((event) => transformRecordFields(tableSchema, event.record_event_data.data));+ if (events.length === 0) {+ return [];+ }+ return events.map((event) => ({+ ...transformRecordFields({ tableSchema: table.structure, tableValues: smartSuiteWebhooks.recordOf(event) }),+ [DEDUPE_KEY_PROPERTY]: smartSuiteWebhooks.dedupeKeyOf(event),+ }));},sampleData: {diff --git a/packages/pieces/community/smartsuite/src/lib/triggers/updated-record.ts b/packages/pieces/community/smartsuite/src/lib/triggers/updated-record.tsindex f1471613c69..16cdc50cb97 100644--- a/packages/pieces/community/smartsuite/src/lib/triggers/updated-record.ts+++ b/packages/pieces/community/smartsuite/src/lib/triggers/updated-record.ts@@ -1,13 +1,11 @@-import { TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';-import { HttpMethod, httpClient } from '@activepieces/pieces-common';+import { DEDUPE_KEY_PROPERTY, TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';import { smartsuiteAuth } from '../auth';import { smartsuiteCommon, transformRecordFields } from '../common/props';-import {- SMARTSUITE_WEBHOOKS_API_URL,- API_ENDPOINTS,- WEBHOOK_EVENTS,-} from '../common/constants';-import { smartSuiteApiCall, TableStucture } from '../common';+import { WEBHOOK_EVENTS } from '../common/constants';+import { smartSuiteApi } from '../common';+import { smartSuiteClient } from '../common/client';+import { smartSuiteWebhooks } from '../common/webhook';+import { outputSchemas } from '../output-schemas';export const updatedRecord = createTrigger({name: 'updated_record',@@ -15,7 +13,7 @@ export const updatedRecord = createTrigger({displayName: 'Updated Record',description: 'Triggers when a record is updated in the specified table.',aiMetadata: {- description: 'Fires when an existing record is updated in the specified SmartSuite solution and table, delivering the changed record. Use to start a flow whenever a row in that table is modified.',+ description: 'Fires when an existing record is updated in the specified SmartSuite solution and table, delivering the changed record keyed by field label. Use to start a flow whenever a row in that table is modified.',},type: TriggerStrategy.WEBHOOK,auth: smartsuiteAuth,@@ -23,141 +21,61 @@ export const updatedRecord = createTrigger({solutionId: smartsuiteCommon.solutionId,tableId: smartsuiteCommon.tableId,},+ outputSchema: outputSchemas['labelledRecord'],async onEnable(context) {- const { solutionId, tableId } = context.propsValue;-- const response = await httpClient.sendRequest({- method: HttpMethod.POST,- url: `${SMARTSUITE_WEBHOOKS_API_URL}${API_ENDPOINTS.CREATE_WEBHOOK}`,- body: {- webhook: {- filter: {- applications: {- application_ids: [tableId],- },- },- kinds: [WEBHOOK_EVENTS.RECORD_UPDATED],- locator: {- account_id: context.auth.props.accountId, // This will be filled by SmartSuite based on the API key- solution_id: solutionId,- },- notification_status: {- enabled: {- url: context.webhookUrl,- },- },- },- },- headers: {- Authorization: `Token ${context.auth.props.apiKey}`,- 'ACCOUNT-ID': context.auth.props.accountId,- },+ await smartSuiteWebhooks.enable({+ credentials: smartSuiteClient.credentialsOf(context.auth),+ store: context.store,+ storeKey: 'updated_record',+ solutionId: String(context.propsValue.solutionId),+ tableId: String(context.propsValue.tableId),+ kind: WEBHOOK_EVENTS.RECORD_UPDATED,+ webhookUrl: context.webhookUrl,});- await context.store.put('updated_record', response.body.webhook.webhook_id);},async onDisable(context) {-- const webhookId = await context.store.get('updated_record');-- if (webhookId) {- await httpClient.sendRequest({- method: HttpMethod.POST,- url: `${SMARTSUITE_WEBHOOKS_API_URL}${API_ENDPOINTS.DELETE_WEBHOOK}`,- body: {- webhook_id: webhookId,- },- headers: {- Authorization: `Token ${context.auth.props.apiKey}`,- 'ACCOUNT-ID': context.auth.props.accountId,- },- });- }- },- async test(context) {- const { tableId } = context.propsValue;- const response = await smartSuiteApiCall<{ items: Record<string, any>[] }>({- accountId: context.auth.props.accountId,- apiKey: context.auth.props.apiKey,- method: HttpMethod.POST,- resourceUri: `/applications/${tableId}/records/list/`,- query: { limit: '5', offset: '0' },+ await smartSuiteWebhooks.disable({+ credentials: smartSuiteClient.credentialsOf(context.auth),+ store: context.store,+ storeKey: 'updated_record',});- const items = response.items || [];+ },- const tableResponse = await smartSuiteApiCall<{- structure: TableStucture[];- }>({- apiKey: context.auth.props.apiKey,- accountId: context.auth.props.accountId,- method: HttpMethod.GET,- resourceUri: `/applications/${context.propsValue.tableId}`,+ async test(context) {+ const credentials = smartSuiteClient.credentialsOf(context.auth);+ const table = await smartSuiteApi.getTable({ credentials, tableId: context.propsValue.tableId });+ const page = await smartSuiteApi.listRecordsPage({+ credentials,+ tableId: context.propsValue.tableId,+ sort: [{ field: 'last_updated', direction: 'desc' }],+ limit: smartSuiteWebhooks.RECENT_RECORDS_LIMIT,+ offset: 0,});- const tableSchema = tableResponse.structure;-- return items.map((item) => transformRecordFields(tableSchema, item));+ return page.items.map((item) => transformRecordFields({ tableSchema: table.structure, tableValues: item }));},async run(context) {- const webhookPayload = context.payload.body as {- webhookId: string;- locator: {- accountId: string;- solutionId: string;- };- };-- let pageToken = (await context.store.get('pageToken')) ?? '';-- if (!webhookPayload || !webhookPayload.webhookId || !webhookPayload.locator) {+ const credentials = smartSuiteClient.credentialsOf(context.auth);+ if ((await smartSuiteWebhooks.ownNotificationWebhookId({ store: context.store, storeKey: 'updated_record', payload: context.payload.body })) === undefined) {return [];}-- const events = [];-- let hasMore = true;-- do {- const response = await httpClient.sendRequest<{- events: { record_event_data: { data: Record<string, any> } }[];- next_page_token: string;- }>({- method: HttpMethod.POST,- url: `${SMARTSUITE_WEBHOOKS_API_URL}${API_ENDPOINTS.LIST_EVENTS}`,- body: {- webhook_id: webhookPayload.webhookId,- page_size: '50',- page_token: pageToken,- },- headers: {- Authorization: `Token ${context.auth.props.apiKey}`,- 'ACCOUNT-ID': context.auth.props.accountId,- },- });-- pageToken = response.body.next_page_token;-- const items = response.body.events ?? [];-- events.push(...items);-- hasMore = items.length > 0;- } while (hasMore);-- await context.store.put('pageToken', pageToken);-- const tableResponse = await smartSuiteApiCall<{- structure: TableStucture[];- }>({- apiKey: context.auth.props.apiKey,- accountId: context.auth.props.accountId,- method: HttpMethod.GET,- resourceUri: `/applications/${context.propsValue.tableId}`,+ const table = await smartSuiteApi.getTable({ credentials, tableId: context.propsValue.tableId });+ const events = await smartSuiteWebhooks.pullNewEvents({+ credentials,+ store: context.store,+ storeKey: 'updated_record',+ payload: context.payload.body,+ webhookUrl: context.webhookUrl,});- const tableSchema = tableResponse.structure;-- return events.map((event) => transformRecordFields(tableSchema, event.record_event_data.data));+ if (events.length === 0) {+ return [];+ }+ return events.map((event) => ({+ ...transformRecordFields({ tableSchema: table.structure, tableValues: smartSuiteWebhooks.recordOf(event) }),+ [DEDUPE_KEY_PROPERTY]: smartSuiteWebhooks.dedupeKeyOf(event),+ }));},sampleData: {diff --git a/packages/pieces/community/smartsuite/test/actions.test.ts b/packages/pieces/community/smartsuite/test/actions.test.tsnew file mode 100644index 00000000000..128364c0c62--- /dev/null+++ b/packages/pieces/community/smartsuite/test/actions.test.ts@@ -0,0 +1,331 @@+import { afterEach, describe, expect, test, vi } from 'vitest';+import { findRecords } from '../src/lib/actions/find-records';+import { deleteRecord } from '../src/lib/actions/delete-record';+import { createRecord } from '../src/lib/actions/create-record';+import { upsertRecord, upsertRecordById } from '../src/lib/actions/upsert-record';+import { bulkCreateRecords } from '../src/lib/actions/bulk-create-records';+import { bulkUpdateRecords } from '../src/lib/actions/bulk-update-records';+import { bulkDeleteRecords } from '../src/lib/actions/bulk-delete-records';+import { listSolutions } from '../src/lib/actions/list-solutions';+import { getTableSchema } from '../src/lib/actions/get-table-schema';+import { addComment, addCommentById } from '../src/lib/actions/add-comment';+import { addField } from '../src/lib/actions/add-field';+import { getFileUrl, getFileUrlByHandle } from '../src/lib/actions/get-file-url';+import { listMembers } from '../src/lib/actions/list-members';+import { listRecordsAi } from '../src/lib/actions/ai/list-records';+import { updateRecordFieldsAi } from '../src/lib/actions/ai/update-record-fields';+import { createRecordByIdAi } from '../src/lib/actions/ai/create-record-by-id';+import { deleteRecordByIdAi } from '../src/lib/actions/ai/delete-record-by-id';+import { attachFileByIdAi } from '../src/lib/actions/ai/attach-file-by-id';+import { smartsuite } from '../src/index';+import { field, run, SeenRequest, stubFetch } from './helpers';+++const TABLE = {+ id: 't1',+ name: 'Tasks',+ slug: 'sx',+ solution: 's1',+ structure: [+ { slug: 'title', label: 'Title', field_type: 'recordtitlefield', params: { required: true } },+ { slug: 's_sel', label: 'Stage', field_type: 'singleselectfield', params: { choices: [{ label: 'New', value: 'new', value_color: '#fff' }] } },+ { slug: 'first_created', label: 'First Created', field_type: 'firstcreatedfield', params: { system: true } },+ ],+};++afterEach(() => {+ vi.unstubAllGlobals();+});++describe('find_records', () => {+ test('stops when total is reached (no extra empty call) and maps labels', async () => {+ const seen = stubFetch((request: SeenRequest) =>+ request.path.endsWith('/records/list/') ? { body: { items: [{ id: 'r1', title: 'A' }], total: 1 } } : { body: TABLE },+ );+ const result = await run(findRecords)({ tableId: 't1', searchField: 'title', searchValue: 'A' });+ expect(result).toEqual({ found: true, result: [{ id: 'r1', Title: 'A' }], hasMore: false });+ expect(seen.filter((r) => r.path.endsWith('/records/list/'))).toHaveLength(1);+ expect(seen[1].body).toEqual({ filter: { operator: 'and', fields: [{ field: 'title', comparison: 'is', value: 'A' }] } });+ });+ test('Max Records caps paging and reports hasMore', async () => {+ const seen = stubFetch((request: SeenRequest) =>+ request.path.endsWith('/records/list/')+ ? { body: { items: Array.from({ length: Number(request.query.get('limit')) }, (_, i) => ({ id: `r${i}` })), total: 50 } }+ : { body: TABLE },+ );+ const result = await run(findRecords)({ tableId: 't1', searchField: 'title', searchValue: 'A', maxRecords: 3 });+ expect(field({ value: result, key: 'result' })).toHaveLength(3);+ expect(field({ value: result, key: 'hasMore' })).toBe(true);+ expect(seen[1].query.get('limit')).toBe('3');+ });+ test('rejects a Max Records out of range before any request', async () => {+ const seen = stubFetch(() => ({ body: {} }));+ await expect(run(findRecords)({ tableId: 't1', searchField: 'title', searchValue: 'A', maxRecords: 0 })).rejects.toThrow(/Max Records/);+ expect(seen).toHaveLength(0);+ });+});++describe('record writes', () => {+ test('create_record formats select and returns label keys', async () => {+ const seen = stubFetch((request: SeenRequest) => (request.method === 'POST' ? { status: 201, body: { id: 'r1', title: 'A', s_sel: 'new' } } : { body: TABLE }));+ await expect(run(createRecord)({ tableId: 't1', fields: { title: 'A', s_sel: 'new' } })).resolves.toEqual({ id: 'r1', Title: 'A', Stage: 'new' });+ expect(seen[1].path).toBe('/applications/t1/records/');+ expect(seen[1].body).toEqual({ title: 'A', s_sel: 'new' });+ });+ test('delete_record treats 404 as already deleted', async () => {+ stubFetch(() => ({ status: 404, body: { detail: 'Not found.' } }));+ await expect(run(deleteRecord)({ tableId: 't1', recordId: 'r1' })).resolves.toEqual({ id: 'r1', deleted: true, alreadyDeleted: true });+ });+ test('delete_record rethrows 403', async () => {+ stubFetch(() => ({ status: 403, body: { detail: 'nope' } }));+ await expect(run(deleteRecord)({ tableId: 't1', recordId: 'r1' })).rejects.toMatchObject({ status: 403 });+ });+ test('record IDs are path-encoded', async () => {+ const seen = stubFetch(() => ({ body: {} }));+ await run(deleteRecord)({ tableId: 't1', recordId: '../solutions' });+ expect(seen[0].url).toContain('/records/..%2Fsolutions/');+ });+ test('update_record_fields sends exactly the given slugs, nulls included', async () => {+ const seen = stubFetch(() => ({ body: { id: 'r1' } }));+ await run(updateRecordFieldsAi)({ tableId: 't1', recordId: 'r1', fields: { s_sel: null, title: '' } });+ expect(seen[0].method).toBe('PATCH');+ expect(seen[0].body).toEqual({ s_sel: null, title: '' });+ });+ test('update_record_fields refuses an empty object', async () => {+ const seen = stubFetch(() => ({ body: {} }));+ await expect(run(updateRecordFieldsAi)({ tableId: 't1', recordId: 'r1', fields: {} })).rejects.toThrow(/at least one/);+ expect(seen).toHaveLength(0);+ });+ test('create_record_by_id parses JSON strings and rejects arrays', async () => {+ const seen = stubFetch(() => ({ status: 201, body: { id: 'r1' } }));+ await run(createRecordByIdAi)({ tableId: 't1', fields: '{"title":"A"}' });+ expect(seen[0].body).toEqual({ title: 'A' });+ await expect(run(createRecordByIdAi)({ tableId: 't1', fields: [] })).rejects.toThrow(/JSON object/);+ });+});++describe('upsert_record', () => {+ test('updates the single match', async () => {+ const seen = stubFetch((request: SeenRequest) => (request.path.endsWith('/records/list/') ? { body: { items: [{ id: 'r1' }], total: 1 } } : { body: { id: 'r1' } }));+ await expect(run(upsertRecordById)({ tableId: 't1', matchField: 'title', matchValue: 'A', fields: { s_sel: 'new' } })).resolves.toMatchObject({ action: 'updated' });+ expect(seen[1]).toMatchObject({ method: 'PATCH', path: '/applications/t1/records/r1/', body: { s_sel: 'new' } });+ });+ test('creates with the match value when none match', async () => {+ const seen = stubFetch((request: SeenRequest) => (request.path.endsWith('/records/list/') ? { body: { items: [], total: 0 } } : { status: 201, body: { id: 'r2' } }));+ await expect(run(upsertRecordById)({ tableId: 't1', matchField: 'title', matchValue: 'A', fields: { s_sel: 'new' } })).resolves.toMatchObject({ action: 'created' });+ expect(seen[1]).toMatchObject({ method: 'POST', body: { title: 'A', s_sel: 'new' } });+ });+ test('refuses to change anything when more than one record matches', async () => {+ const seen = stubFetch(() => ({ body: { items: [{ id: 'a' }, { id: 'b' }], total: 2 } }));+ await expect(run(upsertRecordById)({ tableId: 't1', matchField: 'title', matchValue: 'A', fields: {} })).rejects.toThrow(/More than one/);+ expect(seen).toHaveLength(1);+ });+});++describe('bulk', () => {+ test('bulk create wraps items and enforces the 25 cap', async () => {+ const seen = stubFetch(() => ({ status: 201, body: [{ id: 'a' }, { id: 'b' }] }));+ await expect(run(bulkCreateRecords)({ tableId: 't1', records: [{ title: 'a' }, { title: 'b' }] })).resolves.toMatchObject({ count: 2 });+ expect(seen[0]).toMatchObject({ method: 'POST', path: '/applications/t1/records/bulk/', body: { items: [{ title: 'a' }, { title: 'b' }] } });+ await expect(run(bulkCreateRecords)({ tableId: 't1', records: Array.from({ length: 26 }, () => ({})) })).rejects.toThrow(/at most 25/);+ });+ test('bulk update needs an id per item', async () => {+ stubFetch(() => ({ body: [] }));+ await expect(run(bulkUpdateRecords)({ tableId: 't1', records: [{ title: 'x' }] })).rejects.toThrow(/needs an "id"/);+ });+ test('bulk delete refuses an empty list and dedupes IDs', async () => {+ const seen = stubFetch(() => ({ body: [{ id: 'a' }] }));+ await expect(run(bulkDeleteRecords)({ tableId: 't1', recordIds: [] })).rejects.toThrow(/at least one/);+ await expect(run(bulkDeleteRecords)({ tableId: 't1', recordIds: ['a', 'a', ' '] })).resolves.toEqual({ deletedIds: ['a'], count: 1 });+ expect(seen[0]).toMatchObject({ method: 'PATCH', path: '/applications/t1/records/bulk_delete/', body: { items: ['a'] } });+ });+});++describe('schema and workspace', () => {+ test('list_solutions hides hidden solutions by default', async () => {+ stubFetch(() => ({ body: [{ id: 'a', hidden: true }, { id: 'b', hidden: false }] }));+ await expect(run(listSolutions)({})).resolves.toEqual({ items: [{ id: 'b', hidden: false }], count: 1 });+ });+ test('get_table_schema returns slugs, system flag and choice values', async () => {+ stubFetch(() => ({ body: TABLE }));+ const result = await run(getTableSchema)({ tableId: 't1' });+ expect(result).toMatchObject({ fields: [{ slug: 'title' }, { slug: 's_sel', choices: [{ label: 'New', value: 'new' }] }, { slug: 'first_created', system: true }] });+ });+ test('add_comment builds a doc message without mentions', async () => {+ const seen = stubFetch(() => ({ status: 201, body: { id: 'c1' } }));+ await run(addCommentById)({ tableId: 't1', recordId: 'r1', message: 'hi\nthere' });+ expect(seen[0].body).toEqual({+ application: 't1',+ record: 'r1',+ assigned_to: null,+ message: { data: { type: 'doc', content: [{ type: 'paragraph', content: [{ type: 'text', text: 'hi' }] }, { type: 'paragraph', content: [{ type: 'text', text: 'there' }] }] } },+ });+ });+ test('add_field posts the field and returns it from the refreshed schema', async () => {+ const seen = stubFetch((request: SeenRequest) =>+ request.method === 'POST' ? { body: null } : { body: { ...TABLE, structure: [...TABLE.structure, { slug: 'amount', label: 'Amount', field_type: 'numberfield', params: {} }] } },+ );+ await expect(run(addField)({ tableId: 't1', label: 'Amount', fieldType: 'numberfield', slug: 'amount' })).resolves.toMatchObject({ field: { slug: 'amount', field_type: 'numberfield' } });+ expect(seen[0]).toMatchObject({ path: '/applications/t1/add_field/', body: { field: { slug: 'amount', label: 'Amount', field_type: 'numberfield', params: {} } } });+ });+ test('add_field validates select choices and slug', async () => {+ stubFetch(() => ({ body: {} }));+ await expect(run(addField)({ tableId: 't1', label: 'S', fieldType: 'singleselectfield' })).rejects.toThrow(/at least one choice/);+ await expect(run(addField)({ tableId: 't1', label: 'S', fieldType: 'textfield', slug: 'Bad Slug' })).rejects.toThrow(/Field Slug/);+ });+ test('get file url reads url from the response', async () => {+ const seen = stubFetch(() => ({ body: { url: 'https://files.smartsuite.com/x' } }));+ await expect(run(getFileUrlByHandle)({ fileHandle: 'h1' })).resolves.toEqual({ handle: 'h1', url: 'https://files.smartsuite.com/x' });+ expect(seen[0].path).toBe('/shared-files/h1/url/');+ });+ test('list_members pages with total', async () => {+ const seen = stubFetch(() => ({ body: { items: [{ id: 'm1' }], total: 3 } }));+ await expect(run(listMembers)({ limit: 1, offset: 1 })).resolves.toEqual({ items: [{ id: 'm1' }], total: 3, offset: 1, limit: 1, hasMore: true });+ expect(seen[0].query.get('offset')).toBe('1');+ });+ test('list_records validates filter and sort', async () => {+ stubFetch(() => ({ body: { items: [], total: 0 } }));+ await expect(run(listRecordsAi)({ tableId: 't1', filter: [1] })).rejects.toThrow(/Filter/);+ await expect(run(listRecordsAi)({ tableId: 't1', sort: { a: 1 } })).rejects.toThrow(/Sort/);+ await expect(run(listRecordsAi)({ tableId: 't1', limit: 5000 })).rejects.toThrow(/Limit/);+ });+});++describe('ai twins', () => {+ test('delete_record_by_id 404 = already deleted, path encoded', async () => {+ const seen = stubFetch(() => ({ status: 404, body: { detail: 'Not found.' } }));+ await expect(run(deleteRecordByIdAi)({ tableId: 't 1', recordId: 'r1' })).resolves.toEqual({ id: 'r1', deleted: true, alreadyDeleted: true });+ expect(seen[0]).toMatchObject({ method: 'DELETE', path: '/applications/t%201/records/r1/' });+ });+ test('attach_file_by_id uploads multipart to the field and returns the field files', async () => {+ const seen = stubFetch((request: SeenRequest) => (request.method === 'POST' ? { body: null } : { body: { id: 'r1', s_file: [{ handle: 'h1' }] } }));+ await expect(+ run(attachFileByIdAi)({ tableId: 't1', recordId: 'r1', fieldSlug: 's_file', file: { base64: Buffer.from('hi').toString('base64'), filename: 'a.txt' } }),+ ).resolves.toEqual({ recordId: 'r1', field: 's_file', fileName: 'a.txt', files: [{ handle: 'h1' }] });+ expect(seen[0].path).toBe('/recordfiles/t1/r1/s_file/');+ });+ test('attach_file_by_id refuses an empty file before any request', async () => {+ const seen = stubFetch(() => ({ body: {} }));+ await expect(run(attachFileByIdAi)({ tableId: 't1', recordId: 'r1', fieldSlug: 's_file', file: { base64: '', filename: 'a.txt' } })).rejects.toThrow(/empty/);+ expect(seen).toHaveLength(0);+ });+});++describe('human twins share the helper', () => {+ test('upsert_record formats builder fields with the table schema', async () => {+ const seen = stubFetch((request: SeenRequest) => {+ if (request.path.endsWith('/records/list/')) return { body: { items: [], total: 0 } };+ if (request.method === 'POST') return { status: 201, body: { id: 'r9' } };+ return { body: TABLE };+ });+ await expect(run(upsertRecord)({ solutionId: 's1', tableId: 't1', matchField: 'title', matchValue: 'A', fields: { s_sel: 'new', first_created: '' } })).resolves.toEqual({ action: 'created', record: { id: 'r9' } });+ expect(seen[2]).toMatchObject({ method: 'POST', path: '/applications/t1/records/', body: { title: 'A', s_sel: 'new' } });+ });+ test('upsert_record formats the match value for the field type when it creates', async () => {+ const emailTable = { ...TABLE, structure: [...TABLE.structure, { slug: 's_email', label: 'Email', field_type: 'emailfield', params: {} }] };+ const seen = stubFetch((request: SeenRequest) => {+ if (request.path.endsWith('/records/list/')) return { body: { items: [], total: 0 } };+ if (request.method === 'POST') return { status: 201, body: { id: 'r9' } };+ return { body: emailTable };+ });+ await run(upsertRecord)({ solutionId: 's1', tableId: 't1', matchField: 's_email', matchValue: '[email protected]', fields: {} });+ expect(seen[1].body).toMatchObject({ filter: { fields: [{ field: 's_email', comparison: 'is', value: '[email protected]' }] } });+ expect(seen[2].body).toEqual({ s_email: ['[email protected]'] });+ });+ test('add_comment sends the picked member as assignee', async () => {+ const seen = stubFetch(() => ({ status: 201, body: { id: 'c1' } }));+ await run(addComment)({ solutionId: 's1', tableId: 't1', recordId: 'r1', message: 'hi', assignedTo: 'm1' });+ expect(seen[0].body).toMatchObject({ application: 't1', record: 'r1', assigned_to: 'm1' });+ });+ test('download_record_file returns a URL per file in the picked field', async () => {+ const seen = stubFetch((request: SeenRequest) =>+ request.path.startsWith('/shared-files/')+ ? { body: { url: `https://files.smartsuite.com/${request.path.split('/')[2]}` } }+ : { body: { id: 'r1', s_file: [{ handle: 'h1', metadata: { filename: 'a.txt' } }, { handle: 'h2' }] } },+ );+ await expect(run(getFileUrl)({ solutionId: 's1', tableId: 't1', recordId: 'r1', field: 's_file' })).resolves.toEqual({+ recordId: 'r1',+ field: 's_file',+ files: [+ { handle: 'h1', name: 'a.txt', url: 'https://files.smartsuite.com/h1' },+ { handle: 'h2', name: null, url: 'https://files.smartsuite.com/h2' },+ ],+ count: 2,+ });+ expect(seen[0].path).toBe('/applications/t1/records/r1/');+ });+});++describe('list limits', () => {+ test('a list longer than the page cap fails instead of returning a partial list', async () => {+ stubFetch((request: SeenRequest) => ({ body: { results: [{ id: request.query.get('offset') }], next: 'more' } }));+ await expect(run(listSolutions)({})).rejects.toThrow(/more than 5000 items/);+ });+});++describe('piece metadata', () => {+ test('record schemas expose every table field through a dynamic map', () => {+ for (const name of ['create_record', 'get_record_by_id']) {+ const action = Object.values(smartsuite.actions()).find((a) => a.name === name);+ expect(action?.outputSchema?.fields, name).toContainEqual(expect.objectContaining({ value: '', dynamicKey: true }));+ }+ });++ test('every action has outputSchema, aiMetadata and classification', () => {+ const actions = Object.values(smartsuite.actions()).filter((a) => a.name !== 'custom_api_call');+ expect(actions).toHaveLength(45);+ for (const action of actions) {+ expect(action.outputSchema, action.name).toBeDefined();+ expect(action.aiMetadata?.description, action.name).toBeTruthy();+ expect(action.classification, action.name).toBeTruthy();+ }+ for (const action of actions.filter((a) => a.audience !== 'human')) {+ for (const [key, prop] of Object.entries(action.props)) {+ expect(['DROPDOWN', 'DYNAMIC', 'MULTI_SELECT_DROPDOWN'], `${action.name}.${key}`).not.toContain(prop.type);+ }+ }+ const human = actions.filter((a) => a.audience === 'human');+ const ai = actions.filter((a) => a.audience === 'ai');+ expect(actions.filter((a) => a.audience === 'both').map((a) => a.name).sort()).toEqual(['list_members', 'list_solutions', 'list_teams']);+ expect(ai.map((a) => a.name).sort()).toEqual(AI_ACTIONS);+ expect(human.map((a) => a.name).sort()).toEqual(HUMAN_ACTIONS);+ for (const action of human) {+ const pickers = Object.entries(action.props).filter(([key]) => ['solutionId', 'tableId', 'memberId'].includes(key));+ expect(pickers.length, action.name).toBeGreaterThan(0);+ for (const [key, prop] of pickers) {+ expect(prop.type, `${action.name}.${key}`).toBe('DROPDOWN');+ }+ }+ for (const action of ai) {+ expect(action.aiMetadata?.description, action.name).toMatch(/\(by (ID|Table ID|Handle)\)|\(Bulk, by ID\)|List Records|List Solutions|List Members|Update Record Fields/);+ }+ });+});++const AI_ACTIONS = [+ 'add_comment_by_id',+ 'add_field_by_id',+ 'attach_file_by_id',+ 'bulk_create_records_by_id',+ 'bulk_delete_records_by_id',+ 'bulk_update_records_by_id',+ 'create_record_by_id',+ 'create_table_by_id',+ 'delete_record_by_id',+ 'download_record_file_by_handle',+ 'get_member_by_id',+ 'get_record_by_id',+ 'get_solution_by_id',+ 'get_table_schema_by_id',+ 'list_comments_by_id',+ 'list_deleted_records_by_id',+ 'list_records',+ 'list_tables_by_id',+ 'restore_record_by_id',+ 'update_record_fields',+ 'upsert_record_by_id',+];++const HUMAN_ACTIONS = AI_ACTIONS.map((name) =>+ ({ attach_file_by_id: 'upload_file', list_records: 'find_records', update_record_fields: 'update_record', download_record_file_by_handle: 'download_record_file' })[name] ?? name.replace(/_by_id$/, ''),+).sort();diff --git a/packages/pieces/community/smartsuite/test/client.test.ts b/packages/pieces/community/smartsuite/test/client.test.tsnew file mode 100644index 00000000000..782d2f7193f--- /dev/null+++ b/packages/pieces/community/smartsuite/test/client.test.ts@@ -0,0 +1,103 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { afterEach, describe, expect, test, vi } from 'vitest';+import { smartSuiteClient, SmartSuiteApiError } from '../src/lib/common/client';+import { smartSuitePaginatedApiCall } from '../src/lib/common';+import { smartsuiteAuth } from '../src/lib/auth';+import { replies, stubFetch } from './helpers';++const credentials = { apiKey: ' key-123 ', accountId: ' acct1 ' };++afterEach(() => {+ vi.unstubAllGlobals();+});++describe('client', () => {+ test('sends trimmed token and account headers to the REST host', async () => {+ const seen = stubFetch(() => ({ body: { ok: true } }));+ await smartSuiteClient.request({ credentials, method: HttpMethod.GET, path: '/solutions/', operation: 'x' });+ expect(seen[0].url).toBe('https://app.smartsuite.com/api/v1/solutions/');+ expect(seen[0].headers.get('authorization')).toBe('Token key-123');+ expect(seen[0].headers.get('account-id')).toBe('acct1');+ });+ test('webhooks api goes to the webhooks host', async () => {+ const seen = stubFetch(() => ({ body: {} }));+ await smartSuiteClient.request({ credentials, api: 'webhooks', method: HttpMethod.POST, path: '/ListEvents', body: {}, operation: 'x' });+ expect(seen[0].url).toBe('https://webhooks.smartsuite.com/smartsuite.webhooks.engine.Webhooks/ListEvents');+ });+ test('errors carry status and responseBody, never body, and the vendor message', async () => {+ stubFetch(() => ({ status: 422, body: { message: 'Field x is required' } }));+ const error = await smartSuiteClient+ .request({ credentials, method: HttpMethod.POST, path: '/applications/t/records/', body: {}, operation: 'create record' })+ .catch((e: unknown) => e);+ expect(error).toBeInstanceOf(SmartSuiteApiError);+ expect(error).toMatchObject({ status: 422, responseBody: { message: 'Field x is required' } });+ expect(error).not.toHaveProperty('body');+ expect(error).toHaveProperty('message', expect.stringContaining('Field x is required'));+ });+ test('402 explains the plan has no API access', async () => {+ stubFetch(() => ({ status: 402, body: { code: 'PAYMENT_REQUIRED' } }));+ await expect(smartSuiteClient.request({ credentials, method: HttpMethod.GET, path: '/solutions/', operation: 'list' })).rejects.toThrow(/no API access/);+ });+ test('retries 429 at most twice with a short backoff', async () => {+ const seen = stubFetch(replies([{ status: 429 }, { status: 429 }, { status: 429 }]));+ const waits: number[] = [];+ await expect(+ smartSuiteClient.request({ credentials, method: HttpMethod.GET, path: '/x', operation: 'x', wait: async (ms) => { waits.push(ms); } }),+ ).rejects.toMatchObject({ status: 429 });+ expect(seen).toHaveLength(3);+ expect(waits).toEqual([2_000, 5_000]);+ });+ test('with a deadline it skips a 429 retry that would not fit and never starts a request past it', async () => {+ const seen = stubFetch(replies([{ status: 429 }, { status: 429 }]));+ const waits: number[] = [];+ await expect(+ smartSuiteClient.request({ credentials, method: HttpMethod.GET, path: '/x', operation: 'x', deadlineAt: Date.now() + 4_000, wait: async (ms) => { waits.push(ms); } }),+ ).rejects.toMatchObject({ status: 429 });+ expect(waits).toEqual([2_000]);+ expect(seen).toHaveLength(2);+ await expect(smartSuiteClient.request({ credentials, method: HttpMethod.GET, path: '/x', operation: 'x', deadlineAt: Date.now() - 1 })).rejects.toThrow(/time budget/);+ expect(seen).toHaveLength(2);+ });+ test('pathSegment encodes and rejects empty or dot segments', () => {+ expect(smartSuiteClient.pathSegment({ value: 'a/b?c', label: 'ID' })).toBe('a%2Fb%3Fc');+ expect(() => smartSuiteClient.pathSegment({ value: ' ', label: 'ID' })).toThrow('ID is required.');+ expect(() => smartSuiteClient.pathSegment({ value: '..', label: 'ID' })).toThrow(/not a valid/);+ });+});++describe('paginated list (dropdowns)', () => {+ test('accepts a plain array (live /solutions/ shape) with one request', async () => {+ const seen = stubFetch(() => ({ body: [{ id: 's1', name: 'A' }, { id: 's2', name: 'B' }] }));+ const items = await smartSuitePaginatedApiCall({ apiKey: 'k', accountId: 'a', method: HttpMethod.GET, resourceUri: '/solutions/' });+ expect(items).toEqual([{ id: 's1', name: 'A' }, { id: 's2', name: 'B' }]);+ expect(seen).toHaveLength(1);+ });+ test('follows {results,next} pages and stops when next is null', async () => {+ const seen = stubFetch(replies([{ body: { results: [{ id: 1 }], next: 'x' } }, { body: { results: [{ id: 2 }], next: null } }]));+ const items = await smartSuitePaginatedApiCall({ apiKey: 'k', accountId: 'a', method: HttpMethod.GET, resourceUri: '/comments/' });+ expect(items).toHaveLength(2);+ expect(seen[1].query.get('offset')).toBe('100');+ });+});++describe('auth validate', () => {+ const validate = (params: { auth: { apiKey: string; accountId: string } }): Promise<unknown> => {+ const fn: unknown = Reflect.get(smartsuiteAuth, 'validate');+ if (typeof fn !== 'function') {+ throw new Error('validate missing');+ }+ return Promise.resolve(fn(params));+ };+ test('401 = invalid credentials', async () => {+ stubFetch(() => ({ status: 401, body: {} }));+ await expect(validate({ auth: { apiKey: 'k', accountId: 'a' } })).resolves.toMatchObject({ valid: false, error: expect.stringMatching(/Invalid Credentials/) });+ });+ test('402 = plan has no API access', async () => {+ stubFetch(() => ({ status: 402, body: {} }));+ await expect(validate({ auth: { apiKey: 'k', accountId: 'a' } })).resolves.toMatchObject({ valid: false, error: expect.stringMatching(/no API access/) });+ });+ test('200 = valid', async () => {+ stubFetch(() => ({ body: [] }));+ await expect(validate({ auth: { apiKey: 'k', accountId: 'a' } })).resolves.toEqual({ valid: true });+ });+});diff --git a/packages/pieces/community/smartsuite/test/helpers.ts b/packages/pieces/community/smartsuite/test/helpers.tsnew file mode 100644index 00000000000..b33017dad0c--- /dev/null+++ b/packages/pieces/community/smartsuite/test/helpers.ts@@ -0,0 +1,86 @@+import { vi } from 'vitest';++export type SeenRequest = {+ url: string;+ method: string;+ path: string;+ query: URLSearchParams;+ headers: Headers;+ body: unknown;+};++export type FakeReply = {+ status?: number;+ body?: unknown;+ 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 | Request, init?: RequestInit) => {+ const url = input instanceof Request ? input.url : String(input);+ const parsed = new URL(url);+ const rawBody = typeof init?.body === 'string' ? init.body : null;+ const request: SeenRequest = {+ url,+ method: (init?.method ?? 'GET').toUpperCase(),+ path: parsed.pathname.replace('/api/v1', ''),+ query: parsed.searchParams,+ headers: new Headers(init?.headers),+ body: rawBody ? JSON.parse(rawBody) : null,+ };+ seen.push(request);+ const reply = respond(request, seen.length - 1);+ return new Response(JSON.stringify(reply.body ?? {}), {+ status: reply.status ?? 200,+ 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 AUTH = { type: 'CUSTOM_AUTH', props: { apiKey: ' key-123 ', accountId: 'acct1' } };++export function memoryStore(initial: Record<string, unknown> = {}): MemoryStore {+ const data = new Map<string, string>(Object.entries(initial).map(([key, value]) => [key, JSON.stringify(value)]));+ return {+ snapshot: (): Record<string, unknown> => Object.fromEntries(Array.from(data.entries()).map(([key, raw]) => [key, 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 run(action: Runnable) {+ return (propsValue: Record<string, unknown>): Promise<unknown> => action.run({ auth: AUTH, propsValue });+}++export function field({ value, key }: { value: unknown; key: string }): unknown {+ return value !== null && typeof value === 'object' ? Reflect.get(value, key) : undefined;+}++export type MemoryStore = {+ snapshot: () => Record<string, unknown>;+ put: <T>(key: string, value: T) => Promise<T>;+ get: <T>(key: string) => Promise<T | null>;+ delete: (key: string) => Promise<void>;+};++type TestActionContext = { auth: typeof AUTH; propsValue: Record<string, unknown> };++type Runnable = { run(context: TestActionContext): Promise<unknown> };diff --git a/packages/pieces/community/smartsuite/test/trigger.test.ts b/packages/pieces/community/smartsuite/test/trigger.test.tsnew file mode 100644index 00000000000..076db71b91e--- /dev/null+++ b/packages/pieces/community/smartsuite/test/trigger.test.ts@@ -0,0 +1,226 @@+import { afterEach, describe, expect, test, vi } from 'vitest';+import { newRecord } from '../src/lib/triggers/new-record';+import { updatedRecord } from '../src/lib/triggers/updated-record';+import { AUTH, memoryStore, MemoryStore, SeenRequest, stubFetch } from './helpers';++const TABLE = { id: 't1', name: 'T', structure: [{ slug: 'title', label: 'Title', field_type: 'recordtitlefield', params: {} }] };++type Hooks = {+ onEnable(c: unknown): Promise<unknown>;+ onDisable(c: unknown): Promise<unknown>;+ run(c: unknown): Promise<unknown[]>;+ test(c: unknown): Promise<unknown[]>;+};+const hooks: Hooks = newRecord;+const updatedHooks: Hooks = updatedRecord;++function ctx({ store, body }: { store: MemoryStore; body?: unknown }) {+ return { auth: AUTH, propsValue: { solutionId: 's1', tableId: 't1' }, store, webhookUrl: 'https://hook.example/x', payload: { body } };+}++function event({ id, recordId }: { id: string; recordId: string }) {+ return { event_id: id, record_event_data: { data: { id: recordId, title: `rec ${recordId}` } } };+}++afterEach(() => {+ vi.unstubAllGlobals();+});++describe('webhook triggers', () => {+ test('onEnable creates the webhook for the table and stores its id', async () => {+ const seen = stubFetch(() => ({ body: { webhook: { webhook_id: 'w1' } } }));+ const store = memoryStore();+ await hooks.onEnable(ctx({ store }));+ expect(seen[0].path).toContain('/CreateWebhook');+ expect(seen[0].body).toMatchObject({ webhook: { kinds: ['RECORD_CREATED'], filter: { applications: { application_ids: ['t1'] } }, notification_status: { enabled: { url: 'https://hook.example/x' } } } });+ expect(store.snapshot()['new_record']).toBe('w1');+ });+ test('onEnable deletes the webhook when storing its id fails', async () => {+ const seen = stubFetch(() => ({ body: { webhook: { webhook_id: 'w1' } } }));+ const store = memoryStore();+ store.put = async () => { throw new Error('store down'); };+ await expect(hooks.onEnable(ctx({ store }))).rejects.toThrow('store down');+ expect(seen[1].path).toContain('/DeleteWebhook');+ expect(seen[1].body).toEqual({ webhook_id: 'w1' });+ });+ test('onDisable treats 404 as already deleted and clears the store', async () => {+ stubFetch(() => ({ status: 404, body: { code: 'not_found', msg: 'webhook not found' } }));+ const store = memoryStore({ new_record: 'w1', pageToken: 'p', seenEventIds: ['a'] });+ await expect(hooks.onDisable(ctx({ store }))).resolves.toBeUndefined();+ expect(store.snapshot()).toEqual({});+ });+ test('onDisable keeps the id when delete fails for another reason', async () => {+ stubFetch(() => ({ status: 500, body: {} }));+ const store = memoryStore({ new_record: 'w1' });+ await expect(hooks.onDisable(ctx({ store }))).rejects.toThrow();+ expect(store.snapshot()['new_record']).toBe('w1');+ });+ test('run stops when the last page has events and an empty token (no restart from the first event)', async () => {+ const seen = stubFetch((request: SeenRequest) => {+ if (request.path.includes('ListEvents')) {+ return { body: { events: [event({ id: 'e1', recordId: 'r1' })], next_page_token: '' } };+ }+ return { body: TABLE };+ });+ const store = memoryStore({ new_record: 'w1', pageToken: 'p0' });+ const result = await hooks.run(ctx({ store, body: { webhookId: 'w1', locator: {} } }));+ expect(result).toEqual([{ id: 'r1', Title: 'rec r1', _dedupe_key: 'smartsuite:e1' }]);+ expect(seen.filter((r) => r.path.includes('ListEvents'))).toHaveLength(1);+ expect(store.snapshot()['pageToken']).toBe('p0');+ });+ test('run follows tokens, caps pages and never loops forever', async () => {+ let n = 0;+ stubFetch((request: SeenRequest) => {+ if (request.path.includes('ListEvents')) {+ n++;+ return { body: { events: [event({ id: `e${n}`, recordId: `r${n}` })], next_page_token: `p${n}` } };+ }+ return { body: TABLE };+ });+ const store = memoryStore({ new_record: 'w1' });+ const result = await hooks.run(ctx({ store, body: { webhookId: 'w1' } }));+ expect(n).toBe(20);+ expect(result).toHaveLength(20);+ expect(store.snapshot()['pageToken']).toBe('p20');+ });+ test('run drops events already emitted (dedupe by event id) and bounds the seen list', async () => {+ stubFetch((request: SeenRequest) =>+ request.path.includes('ListEvents') ? { body: { events: [event({ id: 'e1', recordId: 'r1' }), event({ id: 'e2', recordId: 'r2' })] } } : { body: TABLE },+ );+ const store = memoryStore({ new_record: 'w1', seenEventIds: ['e1'] });+ const result = await hooks.run(ctx({ store, body: { webhookId: 'w1' } }));+ expect(result).toEqual([{ id: 'r2', Title: 'rec r2', _dedupe_key: 'smartsuite:e2' }]);+ expect(store.snapshot()['seenEventIds']).toEqual(['e1', 'e2']);+ });+ test('overlapping runs both deliver, and each event carries one dedupe key so the platform starts one run per event', async () => {+ stubFetch((request: SeenRequest) =>+ request.path.includes('ListEvents') ? { body: { events: [event({ id: 'e1', recordId: 'r1' }), event({ id: 'e2', recordId: 'r2' })], next_page_token: 'p1' } } : { body: TABLE },+ );+ const store = memoryStore({ new_record: 'w1' });+ const [first, second] = await Promise.all([+ hooks.run(ctx({ store, body: { webhookId: 'w1' } })),+ hooks.run(ctx({ store, body: { webhookId: 'w1' } })),+ ]);+ expect(first).toHaveLength(2);+ const keys = [...first, ...second].map((payload) => (typeof payload === 'object' && payload !== null && '_dedupe_key' in payload ? payload['_dedupe_key'] : undefined));+ expect(new Set(keys)).toEqual(new Set(['smartsuite:e1', 'smartsuite:e2']));+ expect(store.snapshot()['pageToken']).toBe('p1');+ expect(store.snapshot()['seenEventIds']).toEqual(['e1', 'e2']);+ });+ test('the seen list keeps IDs another run stored while this run was reading', async () => {+ const store = memoryStore({ new_record: 'w1', seenEventIds: ['e0'] });+ stubFetch((request: SeenRequest) => {+ if (request.path.includes('ListEvents')) {+ void store.put('seenEventIds', ['e0', 'e9']);+ return { body: { events: [event({ id: 'e1', recordId: 'r1' })] } };+ }+ return { body: TABLE };+ });+ await expect(hooks.run(ctx({ store, body: { webhookId: 'w1' } }))).resolves.toHaveLength(1);+ expect(store.snapshot()['seenEventIds']).toEqual(['e0', 'e9', 'e1']);+ });+ test('a notification is never answered empty because of state left by an earlier run', async () => {+ stubFetch((request: SeenRequest) =>+ request.path.includes('ListEvents') ? { body: { events: [event({ id: 'e1', recordId: 'r1' })] } } : { body: TABLE },+ );+ const store = memoryStore({ new_record: 'w1', pullClaim: { owner: 'crashed', at: Date.now() } });+ await expect(hooks.run(ctx({ store, body: { webhookId: 'w1' } }))).resolves.toEqual([{ id: 'r1', Title: 'rec r1', _dedupe_key: 'smartsuite:e1' }]);+ });+ test('run stops paging at its 15 s budget, pings its own webhook URL to continue, and the next run resumes from the stored cursor', async () => {+ vi.useFakeTimers({ toFake: ['Date'] });+ const pageTokens: unknown[] = [];+ let n = 0;+ const seen = stubFetch((request: SeenRequest) => {+ if (request.url.startsWith('https://hook.example/')) return { body: {} };+ if (!request.path.includes('ListEvents')) return { body: TABLE };+ pageTokens.push(typeof request.body === 'object' && request.body !== null && 'page_token' in request.body ? request.body['page_token'] : undefined);+ vi.setSystemTime(Date.now() + 7_000);+ n++;+ return { body: { events: [event({ id: `e${n}`, recordId: `r${n}` })], next_page_token: `${100 + n}` } };+ });+ const store = memoryStore({ new_record: 'w1', pageToken: '100' });+ const started = Date.now();+ const first = await hooks.run(ctx({ store, body: { webhookId: 'w1' } }));+ expect(first).toHaveLength(2);+ expect(pageTokens).toEqual(['100', '101']);+ expect(Date.now() - started).toBeLessThan(20_000);+ expect(store.snapshot()['pageToken']).toBe('102');+ const pings = seen.filter((r) => r.url.startsWith('https://hook.example/'));+ expect(pings).toHaveLength(1);+ expect(pings[0]).toMatchObject({ method: 'POST', body: { webhookId: 'w1', continuation: true } });+ const second = await hooks.run(ctx({ store, body: pings[0].body }));+ expect(pageTokens[2]).toBe('102');+ expect(second.map((payload) => (typeof payload === 'object' && payload !== null && 'id' in payload ? payload['id'] : undefined))).toEqual(['r3', 'r4']);+ vi.useRealTimers();+ });+ test('if the continuation ping fails the run fails and the cursor stays put', async () => {+ vi.useFakeTimers({ toFake: ['Date'] });+ stubFetch((request: SeenRequest) => {+ if (request.url.startsWith('https://hook.example/')) return { status: 500, body: {} };+ if (!request.path.includes('ListEvents')) return { body: TABLE };+ vi.setSystemTime(Date.now() + 7_000);+ return { body: { events: [event({ id: `e${Date.now()}`, recordId: 'r' })], next_page_token: `${Date.now()}` } };+ });+ const store = memoryStore({ new_record: 'w1', pageToken: '100' });+ await expect(hooks.run(ctx({ store, body: { webhookId: 'w1' } }))).rejects.toThrow();+ expect(store.snapshot()['pageToken']).toBe('100');+ expect(store.snapshot()['seenEventIds']).toBeUndefined();+ vi.useRealTimers();+ });+ test('events another run recorded while this run was fetching are not emitted again', async () => {+ const store = memoryStore({ new_record: 'w1' });+ stubFetch((request: SeenRequest) => {+ if (request.path.includes('ListEvents')) {+ void store.put('seenEventIds', ['e1']);+ return { body: { events: [event({ id: 'e1', recordId: 'r1' }), event({ id: 'e2', recordId: 'r2' })] } };+ }+ return { body: TABLE };+ });+ await expect(hooks.run(ctx({ store, body: { webhookId: 'w1' } }))).resolves.toEqual([{ id: 'r2', Title: 'rec r2', _dedupe_key: 'smartsuite:e2' }]);+ expect(store.snapshot()['seenEventIds']).toEqual(['e1', 'e2']);+ });+ test.each([+ { format: 'numeric', start: '100', other: '120', mine: '110' },+ { format: 'opaque', start: 'tokA', other: 'tokC', mine: 'tokB' },+ ])('an older run finishing last never moves the cursor back ($format tokens)', async ({ start, other, mine }) => {+ const store = memoryStore({ new_record: 'w1', pageToken: start });+ stubFetch((request: SeenRequest) => {+ if (request.path.includes('ListEvents')) {+ void store.put('pageToken', other);+ return { body: { events: [event({ id: 'e1', recordId: 'r1' })], next_page_token: mine } };+ }+ return { body: TABLE };+ });+ await hooks.run(ctx({ store, body: { webhookId: 'w1' } }));+ expect(store.snapshot()['pageToken']).toBe(other);+ });+ test('a run that started from the stored cursor advances it with any token format', async () => {+ const store = memoryStore({ new_record: 'w1', pageToken: 'tokA' });+ stubFetch((request: SeenRequest) =>+ request.path.includes('ListEvents') ? { body: { events: [event({ id: 'e1', recordId: 'r1' })], next_page_token: 'tokB' } } : { body: TABLE },+ );+ await hooks.run(ctx({ store, body: { webhookId: 'w1' } }));+ expect(store.snapshot()['pageToken']).toBe('tokB');+ });++ test('run ignores notifications for another webhook', async () => {+ const seen = stubFetch(() => ({ body: {} }));+ const store = memoryStore({ new_record: 'w1' });+ await expect(hooks.run(ctx({ store, body: { webhookId: 'other' } }))).resolves.toEqual([]);+ expect(seen).toHaveLength(0);+ });+ test('test returns the newest records first', async () => {+ const seen = stubFetch((request: SeenRequest) => (request.path.endsWith('/records/list/') ? { body: { items: [{ id: 'r9', title: 'x' }], total: 1 } } : { body: TABLE }));+ await expect(hooks.test(ctx({ store: memoryStore() }))).resolves.toEqual([{ id: 'r9', Title: 'x' }]);+ const list = seen.find((r) => r.path.endsWith('/records/list/'));+ expect(list?.body).toEqual({ sort: [{ field: 'first_created', direction: 'desc' }] });+ expect(list?.query.get('limit')).toBe('5');+ });+ test('updated_record subscribes to RECORD_UPDATED', async () => {+ const seen = stubFetch(() => ({ body: { webhook: { webhook_id: 'w2' } } }));+ const store = memoryStore();+ await updatedHooks.onEnable(ctx({ store }));+ expect(seen[0].body).toMatchObject({ webhook: { kinds: ['RECORD_UPDATED'] } });+ expect(store.snapshot()['updated_record']).toBe('w2');+ });+});diff --git a/packages/pieces/community/smartsuite/vitest.config.ts b/packages/pieces/community/smartsuite/vitest.config.tsnew file mode 100644index 00000000000..79c97261904--- /dev/null+++ b/packages/pieces/community/smartsuite/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'),+ },+ },+})