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(nifty): manage tasks, projects and milestones, and trigger flows on new or completed tasks (#16128)
Odai Ahmad44758733243c
diff --git a/bun.lock b/bun.lockindex ae65b49df4d..c79aeb70e2e 100644--- a/bun.lock+++ b/bun.lock@@ -6351,7 +6351,7 @@},"packages/pieces/community/nifty": {"name": "@activepieces/piece-nifty",- "version": "0.2.1",+ "version": "0.3.0","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -6360,6 +6360,7 @@},"devDependencies": {"tslib": "2.6.2",+ "vitest": "3.2.6",},},"packages/pieces/community/ninety": {diff --git a/packages/pieces/community/nifty/package.json b/packages/pieces/community/nifty/package.jsonindex d9915d102e0..fa5d8d9c7cb 100644--- a/packages/pieces/community/nifty/package.json+++ b/packages/pieces/community/nifty/package.json@@ -1,12 +1,13 @@{"name": "@activepieces/piece-nifty",- "version": "0.2.1",+ "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:*",@@ -15,6 +16,7 @@"@activepieces/core-utils": "workspace:*"},"devDependencies": {+ "vitest": "3.2.6","tslib": "2.6.2"}}diff --git a/packages/pieces/community/nifty/src/i18n/translation.json b/packages/pieces/community/nifty/src/i18n/translation.jsonindex 998ba90f0b8..1c36e4ee2cb 100644--- a/packages/pieces/community/nifty/src/i18n/translation.json+++ b/packages/pieces/community/nifty/src/i18n/translation.json@@ -2,8 +2,48 @@"Project management made simple": "Project management made simple","\n# How to add a new connection\n1. Login to your nifty account at https://niftypm.com/\n2. From your account settings, click on App Center\n3. After that click on Integrate with API\n4. Then Create a new app\n5. Select the Name and Description you want\n6. copy the redirect url from the piece and fill the url field ( without https:// )\n7. check out Milestones , Subtasks , Projects , Statuses , Tasks and Portfolios\n8. copy the client id and client secret and paste them in the piece\n": "\n# How to add a new connection\n1. Login to your nifty account at https://niftypm.com/\n2. From your account settings, click on App Center\n3. After that click on Integrate with API\n4. Then Create a new app\n5. Select the Name and Description you want\n6. copy the redirect url from the piece and fill the url field ( without https:// )\n7. check out Milestones , Subtasks , Projects , Statuses , Tasks and Portfolios\n8. copy the client id and client secret and paste them in the piece\n","Create Task": "Create Task",+ "Update Task": "Update Task",+ "Complete or Reopen Task": "Complete or Reopen Task",+ "Delete Task": "Delete Task",+ "Get Task": "Get Task",+ "Find Tasks": "Find Tasks",+ "Add Task Assignees": "Add Task Assignees",+ "Remove Task Assignees": "Remove Task Assignees",+ "Create Project": "Create Project",+ "Update Project": "Update Project",+ "Get Project": "Get Project",+ "Find Projects": "Find Projects",+ "Create Milestone": "Create Milestone",+ "List Statuses": "List Statuses",+ "List Milestones and Lists": "List Milestones and Lists",+ "List Members": "List Members",+ "Create Task (AI)": "Create Task (AI)",+ "Update Task (AI)": "Update Task (AI)",+ "Create Project (AI)": "Create Project (AI)",+ "Update Project (AI)": "Update Project (AI)",+ "Create Milestone or List (AI)": "Create Milestone or List (AI)","Custom API Call": "Custom API Call",- "Create a task in nitfy": "Create a task in nitfy",+ "Create a task in Nifty.": "Create a task in Nifty.",+ "Change the name, description, status, milestone, dates or story points of a task.": "Change the name, description, status, milestone, dates or story points of a task.",+ "Mark a task as complete, or reopen a completed task.": "Mark a task as complete, or reopen a completed task.",+ "Permanently delete a task.": "Permanently delete a task.",+ "Get a task by its ID.": "Get a task by its ID.",+ "List tasks filtered by project, status, milestone, assignee, completion or due date, one page at a time.": "List tasks filtered by project, status, milestone, assignee, completion or due date, one page at a time.",+ "Assign members to a task, keeping the current assignees.": "Assign members to a task, keeping the current assignees.",+ "Unassign members from a task, keeping the other assignees.": "Unassign members from a task, keeping the other assignees.",+ "Create a new project.": "Create a new project.",+ "Rename a project, change its description, access or view, or archive it.": "Rename a project, change its description, access or view, or archive it.",+ "Get a project by its ID.": "Get a project by its ID.",+ "Find projects by name, optionally in one portfolio.": "Find projects by name, optionally in one portfolio.",+ "Create a dated milestone, or a plain task list, in a project.": "Create a dated milestone, or a plain task list, in a project.",+ "List the status columns of a project.": "List the status columns of a project.",+ "List the milestones and task lists of a project.": "List the milestones and task lists of a project.",+ "List the members of your Nifty workspace.": "List the members of your Nifty workspace.",+ "Creates a task from IDs. Built for AI agents.": "Creates a task from IDs. Built for AI agents.",+ "Updates a task by ID. Built for AI agents.": "Updates a task by ID. Built for AI agents.",+ "Creates a project. Built for AI agents.": "Creates a project. Built for AI agents.",+ "Updates a project by ID. Built for AI agents.": "Updates a project by ID. Built for AI agents.",+ "Creates a milestone or task list from a project ID. Built for AI agents.": "Creates a milestone or task list from a project ID. Built for AI agents.","Make a custom API call to a specific endpoint": "Make a custom API call to a specific endpoint","Portfolio": "Portfolio","Project": "Project",@@ -11,25 +51,119 @@"Milestone": "Milestone","Task Name": "Task Name","Task Description": "Task Description",+ "Parent Task": "Parent Task",+ "Start Date": "Start Date",+ "Due Date": "Due Date",+ "Assignees": "Assignees",+ "Task": "Task",+ "New Name": "New Name",+ "New Description": "New Description",+ "Clear Description": "Clear Description",+ "Clear Start Date": "Clear Start Date",+ "Clear Due Date": "Clear Due Date",+ "Story Points": "Story Points",+ "Action": "Action",+ "Markdown": "Markdown",+ "Task ID": "Task ID",+ "Project ID": "Project ID",+ "Status ID": "Status ID",+ "Milestone or List ID": "Milestone or List ID",+ "Assignee Member ID": "Assignee Member ID",+ "Completion": "Completion",+ "Include Subtasks": "Include Subtasks",+ "Include Archived": "Include Archived",+ "Due From": "Due From",+ "Due To": "Due To",+ "Limit": "Limit",+ "Offset": "Offset",+ "Member IDs": "Member IDs",+ "Project Name": "Project Name",+ "Description": "Description",+ "Access Type": "Access Type",+ "Default Tasks View": "Default Tasks View",+ "Archive": "Archive",+ "Name Contains": "Name Contains",+ "Portfolio ID": "Portfolio ID",+ "Name": "Name",+ "End Date": "End Date",+ "Create as List": "Create as List",+ "Kind": "Kind",+ "Include Removed Members": "Include Removed Members",+ "Parent Task ID": "Parent Task ID",+ "Assignee IDs": "Assignee IDs","Method": "Method","Headers": "Headers","Query Parameters": "Query Parameters","Body Type": "Body Type","Body": "Body",- "Response is Binary ?": "Response is Binary ?",- "No Error on Failure": "No Error on Failure",- "Timeout (in seconds)": "Timeout (in seconds)",+ "Response is Binary": "Response is Binary",+ "Return Error as Output": "Return Error as Output",+ "Timeout": "Timeout","Follow redirects": "Follow redirects",+ "Optional. Narrows the project list to one portfolio. Leave empty to pick from all your projects.": "Optional. Narrows the project list to one portfolio. Leave empty to pick from all your projects.",+ "The board column the task starts in.": "The board column the task starts in.",+ "Optional. When empty, Nifty puts the task in the project default list.": "Optional. When empty, Nifty puts the task in the project default list.",+ "Optional. Pick a task to create this one as its subtask.": "Optional. Pick a task to create this one as its subtask.",+ "Optional. Members to assign to the task.": "Optional. Members to assign to the task.",+ "Move the task to this status column.": "Move the task to this status column.",+ "Move the task to this milestone or list.": "Move the task to this milestone or list.",+ "Deleting a task is permanent and cannot be undone in Nifty.": "Deleting a task is permanent and cannot be undone in Nifty.",+ "The task ID, e.g. from a trigger or Find Tasks (not the short key like ANP-1).": "The task ID, e.g. from a trigger or Find Tasks (not the short key like ANP-1).",+ "Only works together with a Project ID.": "Only works together with a Project ID.",+ "Set together with Due To.": "Set together with Due To.",+ "Set together with Due From.": "Set together with Due From.",+ "1 to 1000. Default 100.": "1 to 1000. Default 100.",+ "Use next_offset from the previous page.": "Use next_offset from the previous page.",+ "Member IDs from List Members.": "Member IDs from List Members.",+ "Optional. When empty, Nifty uses your default portfolio.": "Optional. When empty, Nifty uses your default portfolio.",+ "Up to 100 characters.": "Up to 100 characters.",+ "Nifty does not allow blanking a project description through the API.": "Nifty does not allow blanking a project description through the API.",+ "Required for a milestone.": "Required for a milestone.",+ "Turn on to create a plain task list without dates instead of a milestone.": "Turn on to create a plain task list without dates instead of a milestone.",+ "ID of the status (board column) the task starts in. It also sets the project. Get it from List Statuses.": "ID of the status (board column) the task starts in. It also sets the project. Get it from List Statuses.",+ "Optional. When empty, Nifty uses the project default list.": "Optional. When empty, Nifty uses the project default list.",+ "Optional. Creates the task as a subtask of this task.": "Optional. Creates the task as a subtask of this task.",+ "ISO 8601, e.g. 2026-10-20.": "ISO 8601, e.g. 2026-10-20.",+ "ISO 8601, e.g. 2026-10-27.": "ISO 8601, e.g. 2026-10-27.",+ "Optional member IDs from List Members.": "Optional member IDs from List Members.",+ "Moves the task to this status column. Get it from List Statuses.": "Moves the task to this status column. Get it from List Statuses.",+ "Optional. The portfolio field (subteam) of any existing project shows the ID.": "Optional. The portfolio field (subteam) of any existing project shows the ID.","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.",+ "Mark complete": "Mark complete",+ "Reopen": "Reopen",+ "Any": "Any",+ "Open only": "Open only",+ "Completed only": "Completed only",+ "Public (everyone in the workspace can find and join)": "Public (everyone in the workspace can find and join)",+ "Workspace (every workspace member is a member)": "Workspace (every workspace member is a member)",+ "Limited (only invited members)": "Limited (only invited members)",+ "Table": "Table",+ "Kanban": "Kanban",+ "Swimlane": "Swimlane",+ "Timeline": "Timeline",+ "Leave unchanged": "Leave unchanged",+ "Unarchive": "Unarchive",+ "Milestones and lists": "Milestones and lists",+ "Milestones only": "Milestones only",+ "Lists only": "Lists only","GET": "GET","POST": "POST","PATCH": "PATCH","PUT": "PUT","DELETE": "DELETE","HEAD": "HEAD",- "None": "None",- "JSON": "JSON",- "Form Data": "Form Data",- "Raw": "Raw"+ "New Task": "New Task",+ "Task Completed": "Task Completed",+ "New Project": "New Project",+ "Triggers when a task is created, in one project or in any project you can see.": "Triggers when a task is created, in one project or in any project you can see.",+ "Triggers when a task is marked complete.": "Triggers when a task is marked complete.",+ "Triggers when a new project appears in your Nifty workspace.": "Triggers when a new project appears in your Nifty workspace.",+ "Optional. Leave empty to watch every project (subtasks are then not included).": "Optional. Leave empty to watch every project (subtasks are then not included).",+ "Also trigger for new subtasks. Only works when a project is selected.": "Also trigger for new subtasks. Only works when a project is selected.",+ "Also trigger for completed subtasks. Only works when a project is selected.": "Also trigger for completed subtasks. Only works when a project is selected."}\ No newline at end of filediff --git a/packages/pieces/community/nifty/src/index.ts b/packages/pieces/community/nifty/src/index.tsindex cfb63e30602..13bf16da7ec 100644--- a/packages/pieces/community/nifty/src/index.ts+++ b/packages/pieces/community/nifty/src/index.ts@@ -1,43 +1,69 @@import { createCustomApiCallAction } from '@activepieces/pieces-common';-import {- createPiece,- OAuth2PropertyValue,- PieceAuth,-} from '@activepieces/pieces-framework';-import { PieceCategory } from '@activepieces/pieces-framework';+import { createPiece, PieceCategory } from '@activepieces/pieces-framework';import { createTask } from './lib/actions/create-task';+import { updateTask } from './lib/actions/update-task';+import { completeTask } from './lib/actions/complete-task';+import { deleteTask } from './lib/actions/delete-task';+import { getTask } from './lib/actions/get-task';+import { findTasks } from './lib/actions/find-tasks';+import { addTaskAssignees } from './lib/actions/add-task-assignees';+import { removeTaskAssignees } from './lib/actions/remove-task-assignees';+import { createProject } from './lib/actions/create-project';+import { updateProject } from './lib/actions/update-project';+import { getProject } from './lib/actions/get-project';+import { findProjects } from './lib/actions/find-projects';+import { createMilestone } from './lib/actions/create-milestone';+import { listStatuses } from './lib/actions/list-statuses';+import { listMilestones } from './lib/actions/list-milestones';+import { listMembers } from './lib/actions/list-members';+import { niftyTaskCreate } from './lib/actions/ai/task-create';+import { niftyTaskUpdate } from './lib/actions/ai/task-update';+import { niftyProjectCreate } from './lib/actions/ai/project-create';+import { niftyProjectUpdate } from './lib/actions/ai/project-update';+import { niftyMilestoneCreate } from './lib/actions/ai/milestone-create';+import { newTask } from './lib/triggers/new-task';+import { taskCompleted } from './lib/triggers/task-completed';+import { newProject } from './lib/triggers/new-project';import { niftyAuth } from './lib/auth';--const mddescription = `-# How to add a new connection-1. Login to your nifty account at https://niftypm.com/-2. From your account settings, click on App Center-3. After that click on Integrate with API-4. Then Create a new app-5. Select the Name and Description you want-6. copy the redirect url from the piece and fill the url field ( without https:// )-7. check out Milestones , Subtasks , Projects , Statuses , Tasks and Portfolios-8. copy the client id and client secret and paste them in the piece-`;+import { niftyClient } from './lib/common/client';export const nifty = createPiece({displayName: 'Nifty',description: 'Project management made simple',-auth: niftyAuth,- minimumSupportedRelease: '0.30.0',+ minimumSupportedRelease: '0.88.2',logoUrl: 'https://cdn.activepieces.com/pieces/nifty.png',categories: [PieceCategory.PRODUCTIVITY],- authors: ["kishanprmr","MoShizzle","abuaboud"],+ authors: ['kishanprmr', 'MoShizzle', 'abuaboud'],actions: [createTask,+ updateTask,+ completeTask,+ deleteTask,+ getTask,+ findTasks,+ addTaskAssignees,+ removeTaskAssignees,+ createProject,+ updateProject,+ getProject,+ findProjects,+ createMilestone,+ listStatuses,+ listMilestones,+ listMembers,+ niftyTaskCreate,+ niftyTaskUpdate,+ niftyProjectCreate,+ niftyProjectUpdate,+ niftyMilestoneCreate,createCustomApiCallAction({- baseUrl: () => 'https://openapi.niftypm.com/api/v1.0',+ baseUrl: () => niftyClient.BASE_URL,auth: niftyAuth,authMapping: async (auth) => ({- Authorization: `Bearer ${(auth as OAuth2PropertyValue).access_token}`,+ Authorization: `Bearer ${auth.access_token}`,}),}),],- triggers: [],+ triggers: [newTask, taskCompleted, newProject],});diff --git a/packages/pieces/community/nifty/src/lib/actions/add-task-assignees.ts b/packages/pieces/community/nifty/src/lib/actions/add-task-assignees.tsnew file mode 100644index 00000000000..56fc727cb5b--- /dev/null+++ b/packages/pieces/community/nifty/src/lib/actions/add-task-assignees.ts@@ -0,0 +1,35 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { niftyAuth } from '../auth';+import { niftyOps } from '../common/operations';+import { assigneesOutputSchema } from '../output-schemas';++export const addTaskAssignees = createAction({+ auth: niftyAuth,+ name: 'add_task_assignees',+ displayName: 'Add Task Assignees',+ description: 'Assign members to a task, keeping the current assignees.',+ audience: 'both',+ classification: 'WRITE',+ aiMetadata: {+ description:+ "Adds one or more members to a Nifty task's assignees without touching the others. Use after List Members to get member IDs; requires task_id and at least one member ID. Idempotent: adding someone already assigned changes nothing.",+ idempotent: true,+ },+ props: {+ task_id: Property.ShortText({ displayName: 'Task ID', required: true }),+ member_ids: Property.Array({+ displayName: 'Member IDs',+ description: 'Member IDs from List Members.',+ required: true,+ }),+ },+ outputSchema: assigneesOutputSchema,+ async run(context) {+ return niftyOps.changeAssignees({+ auth: context.auth,+ taskId: context.propsValue.task_id,+ memberIds: context.propsValue.member_ids,+ mode: 'add',+ });+ },+});diff --git a/packages/pieces/community/nifty/src/lib/actions/ai/milestone-create.ts b/packages/pieces/community/nifty/src/lib/actions/ai/milestone-create.tsnew file mode 100644index 00000000000..dfdaba040ce--- /dev/null+++ b/packages/pieces/community/nifty/src/lib/actions/ai/milestone-create.ts@@ -0,0 +1,46 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { niftyAuth } from '../../auth';+import { niftyOps } from '../../common/operations';+import { milestoneOutputSchema } from '../../output-schemas';++export const niftyMilestoneCreate = createAction({+ auth: niftyAuth,+ name: 'nifty_milestone_create',+ displayName: 'Create Milestone or List (AI)',+ description: 'Creates a milestone or task list from a project ID. Built for AI agents.',+ audience: 'ai',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Creates either a dated milestone (shown on the project roadmap, needs start_date and end_date) or a plain task list (create_as_list true, dates optional) in a Nifty project. Use before creating tasks that should sit under a milestone; requires project_id and name. Not idempotent: each call creates another milestone or list.',+ idempotent: false,+ },+ props: {+ project_id: Property.ShortText({ displayName: 'Project ID', required: true }),+ name: Property.ShortText({ displayName: 'Name', required: true }),+ description: Property.LongText({ displayName: 'Description', required: false }),+ start_date: Property.DateTime({ displayName: 'Start Date', description: 'Required for a milestone.', required: false }),+ end_date: Property.DateTime({ displayName: 'End Date', description: 'Required for a milestone.', required: false }),+ create_as_list: Property.Checkbox({+ displayName: 'Create as List',+ description: 'Turn on to create a plain task list without dates instead of a milestone.',+ required: false,+ defaultValue: false,+ }),+ },+ outputSchema: milestoneOutputSchema,+ async run(context) {+ const p = context.propsValue;+ return niftyOps.createMilestone({+ auth: context.auth,+ input: {+ projectId: p.project_id,+ name: p.name,+ description: p.description,+ start: p.start_date,+ end: p.end_date,+ createAsList: p.create_as_list,+ },+ });+ },+});diff --git a/packages/pieces/community/nifty/src/lib/actions/ai/project-create.ts b/packages/pieces/community/nifty/src/lib/actions/ai/project-create.tsnew file mode 100644index 00000000000..c1e69e0d0d1--- /dev/null+++ b/packages/pieces/community/nifty/src/lib/actions/ai/project-create.ts@@ -0,0 +1,51 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { niftyAuth } from '../../auth';+import { NIFTY_ACCESS_TYPE_OPTIONS, NIFTY_TASK_VIEW_OPTIONS, niftyOps } from '../../common/operations';+import { projectOutputSchema } from '../../output-schemas';++export const niftyProjectCreate = createAction({+ auth: niftyAuth,+ name: 'nifty_project_create',+ displayName: 'Create Project (AI)',+ description: 'Creates a project. Built for AI agents.',+ audience: 'ai',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Creates a Nifty project, optionally in a given portfolio (otherwise the workspace default), with a description, access level (public, workspace or limited) and default task view (table, kanban, swimlane or timeline). Use when an agent must start a new project; requires name. Not idempotent: each call creates another project.',+ idempotent: false,+ },+ props: {+ name: Property.ShortText({ displayName: 'Name', description: 'Up to 100 characters.', required: true }),+ portfolio_id: Property.ShortText({+ displayName: 'Portfolio ID',+ description: 'Optional. The portfolio field (subteam) of any existing project shows the ID.',+ required: false,+ }),+ description: Property.LongText({ displayName: 'Description', required: false }),+ access_type: Property.StaticDropdown({+ displayName: 'Access Type',+ required: false,+ options: { options: NIFTY_ACCESS_TYPE_OPTIONS },+ }),+ default_tasks_view: Property.StaticDropdown({+ displayName: 'Default Tasks View',+ required: false,+ options: { options: NIFTY_TASK_VIEW_OPTIONS },+ }),+ },+ outputSchema: projectOutputSchema,+ async run(context) {+ const p = context.propsValue;+ return niftyOps.createProject({+ auth: context.auth,+ input: {+ name: p.name,+ portfolioId: p.portfolio_id,+ description: p.description,+ accessType: p.access_type,+ defaultTasksView: p.default_tasks_view,+ },+ });+ },+});diff --git a/packages/pieces/community/nifty/src/lib/actions/ai/project-update.ts b/packages/pieces/community/nifty/src/lib/actions/ai/project-update.tsnew file mode 100644index 00000000000..201d7479c2d--- /dev/null+++ b/packages/pieces/community/nifty/src/lib/actions/ai/project-update.ts@@ -0,0 +1,54 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { niftyAuth } from '../../auth';+import { NIFTY_ACCESS_TYPE_OPTIONS, NIFTY_ARCHIVE_OPTIONS, NIFTY_TASK_VIEW_OPTIONS, niftyOps } from '../../common/operations';+import { projectOutputSchema } from '../../output-schemas';++export const niftyProjectUpdate = createAction({+ auth: niftyAuth,+ name: 'nifty_project_update',+ displayName: 'Update Project (AI)',+ description: 'Updates a project by ID. Built for AI agents.',+ audience: 'ai',+ classification: 'WRITE',+ aiMetadata: {+ description:+ "Updates a Nifty project's name, description, access level or default task view, or archives/unarchives it; only the fields you pass change. Archiving hides the project but keeps its tasks and is undone with unarchive. Nifty cannot blank a project description. Requires project_id and at least one change. Idempotent.",+ idempotent: true,+ },+ props: {+ project_id: Property.ShortText({ displayName: 'Project ID', required: true }),+ name: Property.ShortText({ displayName: 'Name', required: false }),+ description: Property.LongText({ displayName: 'Description', required: false }),+ access_type: Property.StaticDropdown({+ displayName: 'Access Type',+ required: false,+ options: { options: NIFTY_ACCESS_TYPE_OPTIONS },+ }),+ default_tasks_view: Property.StaticDropdown({+ displayName: 'Default Tasks View',+ required: false,+ options: { options: NIFTY_TASK_VIEW_OPTIONS },+ }),+ archive: Property.StaticDropdown({+ displayName: 'Archive',+ required: false,+ defaultValue: 'unchanged',+ options: { options: NIFTY_ARCHIVE_OPTIONS },+ }),+ },+ outputSchema: projectOutputSchema,+ async run(context) {+ const p = context.propsValue;+ return niftyOps.updateProject({+ auth: context.auth,+ input: {+ projectId: p.project_id,+ name: p.name,+ description: p.description,+ accessType: p.access_type,+ defaultTasksView: p.default_tasks_view,+ archive: p.archive,+ },+ });+ },+});diff --git a/packages/pieces/community/nifty/src/lib/actions/ai/task-create.ts b/packages/pieces/community/nifty/src/lib/actions/ai/task-create.tsnew file mode 100644index 00000000000..f469330e17b--- /dev/null+++ b/packages/pieces/community/nifty/src/lib/actions/ai/task-create.ts@@ -0,0 +1,63 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { niftyAuth } from '../../auth';+import { niftyOps } from '../../common/operations';+import { taskOutputSchema } from '../../output-schemas';++export const niftyTaskCreate = createAction({+ auth: niftyAuth,+ name: 'nifty_task_create',+ displayName: 'Create Task (AI)',+ description: 'Creates a task from IDs. Built for AI agents.',+ audience: 'ai',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Creates a task in a Nifty project by placing it in a status column (status_id decides the project), optionally in a milestone or list, as a subtask of another task, with start/due dates, story points and assignees. Use for agents adding work items by ID; get status_id from List Statuses, milestone_id from List Milestones and member IDs from List Members. Requires status_id and name. Not idempotent: each call creates a new task.',+ idempotent: false,+ },+ props: {+ status_id: Property.ShortText({+ displayName: 'Status ID',+ description: 'ID of the status (board column) the task starts in. It also sets the project. Get it from List Statuses.',+ required: true,+ }),+ name: Property.ShortText({ displayName: 'Name', required: true }),+ description: Property.LongText({ displayName: 'Description', required: false }),+ milestone_id: Property.ShortText({+ displayName: 'Milestone or List ID',+ description: 'Optional. When empty, Nifty uses the project default list.',+ required: false,+ }),+ parent_task_id: Property.ShortText({+ displayName: 'Parent Task ID',+ description: 'Optional. Creates the task as a subtask of this task.',+ required: false,+ }),+ start_date: Property.DateTime({ displayName: 'Start Date', description: 'ISO 8601, e.g. 2026-10-20.', required: false }),+ due_date: Property.DateTime({ displayName: 'Due Date', description: 'ISO 8601, e.g. 2026-10-27.', required: false }),+ story_points: Property.Number({ displayName: 'Story Points', required: false }),+ assignee_ids: Property.Array({+ displayName: 'Assignee IDs',+ description: 'Optional member IDs from List Members.',+ required: false,+ }),+ },+ outputSchema: taskOutputSchema,+ async run(context) {+ const p = context.propsValue;+ return niftyOps.createTask({+ auth: context.auth,+ input: {+ statusId: p.status_id,+ name: p.name,+ description: p.description,+ milestoneId: p.milestone_id,+ parentTaskId: p.parent_task_id,+ startDate: p.start_date,+ dueDate: p.due_date,+ storyPoints: p.story_points,+ assigneeIds: p.assignee_ids,+ },+ });+ },+});diff --git a/packages/pieces/community/nifty/src/lib/actions/ai/task-update.ts b/packages/pieces/community/nifty/src/lib/actions/ai/task-update.tsnew file mode 100644index 00000000000..78aaa680c30--- /dev/null+++ b/packages/pieces/community/nifty/src/lib/actions/ai/task-update.ts@@ -0,0 +1,64 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { niftyAuth } from '../../auth';+import { NIFTY_COMPLETION_OPTIONS, niftyOps } from '../../common/operations';+import { taskOutputSchema } from '../../output-schemas';++export const niftyTaskUpdate = createAction({+ auth: niftyAuth,+ name: 'nifty_task_update',+ displayName: 'Update Task (AI)',+ description: 'Updates a task by ID. Built for AI agents.',+ audience: 'ai',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Changes fields on an existing Nifty task by ID: name, description, status column, milestone/list, start and due dates, story points, and completion (complete or reopen). Only the fields you pass change; use the clear options to blank the description or a date, and Add/Remove Task Assignees for people. Requires task_id and at least one change. Idempotent: repeating the same update leaves the task in the same state.',+ idempotent: true,+ },+ props: {+ task_id: Property.ShortText({ displayName: 'Task ID', required: true }),+ name: Property.ShortText({ displayName: 'Name', required: false }),+ description: Property.LongText({ displayName: 'Description', required: false }),+ clear_description: Property.Checkbox({ displayName: 'Clear Description', required: false, defaultValue: false }),+ status_id: Property.ShortText({+ displayName: 'Status ID',+ description: 'Moves the task to this status column. Get it from List Statuses.',+ required: false,+ }),+ milestone_id: Property.ShortText({ displayName: 'Milestone or List ID', required: false }),+ start_date: Property.DateTime({ displayName: 'Start Date', required: false }),+ clear_start_date: Property.Checkbox({ displayName: 'Clear Start Date', required: false, defaultValue: false }),+ due_date: Property.DateTime({ displayName: 'Due Date', required: false }),+ clear_due_date: Property.Checkbox({ displayName: 'Clear Due Date', required: false, defaultValue: false }),+ story_points: Property.Number({ displayName: 'Story Points', required: false }),+ completion: Property.StaticDropdown({+ displayName: 'Completion',+ required: false,+ defaultValue: 'unchanged',+ options: {+ options: NIFTY_COMPLETION_OPTIONS,+ },+ }),+ },+ outputSchema: taskOutputSchema,+ async run(context) {+ const p = context.propsValue;+ return niftyOps.updateTask({+ auth: context.auth,+ input: {+ taskId: p.task_id,+ name: p.name,+ description: p.description,+ clearDescription: p.clear_description,+ statusId: p.status_id,+ milestoneId: p.milestone_id,+ startDate: p.start_date,+ clearStartDate: p.clear_start_date,+ dueDate: p.due_date,+ clearDueDate: p.clear_due_date,+ storyPoints: p.story_points,+ completion: p.completion,+ },+ });+ },+});diff --git a/packages/pieces/community/nifty/src/lib/actions/complete-task.ts b/packages/pieces/community/nifty/src/lib/actions/complete-task.tsnew file mode 100644index 00000000000..b4340bb341b--- /dev/null+++ b/packages/pieces/community/nifty/src/lib/actions/complete-task.ts@@ -0,0 +1,43 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { niftyAuth } from '../auth';+import { niftyProps } from '../common';+import { niftyOps } from '../common/operations';+import { taskOutputSchema } from '../output-schemas';++export const completeTask = createAction({+ auth: niftyAuth,+ name: 'complete_task',+ displayName: 'Complete or Reopen Task',+ description: 'Mark a task as complete, or reopen a completed task.',+ audience: 'human',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Marks a Nifty task complete or reopens it, picked from cascading project and task dropdowns (agents: use nifty_task_update with completion). Idempotent: completing an already completed task leaves it completed.',+ idempotent: true,+ },+ props: {+ portfolio: niftyProps.portfolio({ required: false }),+ project: niftyProps.project({ required: true }),+ task: niftyProps.task({ required: true }),+ action: Property.StaticDropdown({+ displayName: 'Action',+ required: true,+ defaultValue: 'complete',+ options: {+ options: [+ { label: 'Mark complete', value: 'complete' },+ { label: 'Reopen', value: 'reopen' },+ ],+ },+ }),+ },+ outputSchema: taskOutputSchema,+ async run(context) {+ const { task, action } = context.propsValue;+ if (action !== 'complete' && action !== 'reopen') {+ throw new Error(`Action must be "complete" or "reopen", got "${String(action)}".`);+ }+ return niftyOps.setTaskCompletion({ auth: context.auth, taskId: task, completed: action === 'complete' });+ },+});diff --git a/packages/pieces/community/nifty/src/lib/actions/create-milestone.ts b/packages/pieces/community/nifty/src/lib/actions/create-milestone.tsnew file mode 100644index 00000000000..35a51eecc8f--- /dev/null+++ b/packages/pieces/community/nifty/src/lib/actions/create-milestone.ts@@ -0,0 +1,48 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { niftyAuth } from '../auth';+import { niftyProps } from '../common';+import { niftyOps } from '../common/operations';+import { milestoneOutputSchema } from '../output-schemas';++export const createMilestone = createAction({+ auth: niftyAuth,+ name: 'create_milestone',+ displayName: 'Create Milestone',+ description: 'Create a dated milestone, or a plain task list, in a project.',+ audience: 'human',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Creates a milestone (needs start and end dates) or a plain task list in a Nifty project picked from a dropdown (agents: use nifty_milestone_create). Not idempotent: each call creates another milestone.',+ idempotent: false,+ },+ props: {+ portfolio: niftyProps.portfolio({ required: false }),+ project: niftyProps.project({ required: true }),+ name: Property.ShortText({ displayName: 'Name', required: true }),+ description: Property.LongText({ displayName: 'Description', required: false }),+ start_date: Property.DateTime({ displayName: 'Start Date', description: 'Required for a milestone.', required: false }),+ end_date: Property.DateTime({ displayName: 'End Date', description: 'Required for a milestone.', required: false }),+ create_as_list: Property.Checkbox({+ displayName: 'Create as List',+ description: 'Turn on to create a plain task list without dates instead of a milestone.',+ required: false,+ defaultValue: false,+ }),+ },+ outputSchema: milestoneOutputSchema,+ async run(context) {+ const p = context.propsValue;+ return niftyOps.createMilestone({+ auth: context.auth,+ input: {+ projectId: p.project,+ name: p.name,+ description: p.description,+ start: p.start_date,+ end: p.end_date,+ createAsList: p.create_as_list,+ },+ });+ },+});diff --git a/packages/pieces/community/nifty/src/lib/actions/create-project.ts b/packages/pieces/community/nifty/src/lib/actions/create-project.tsnew file mode 100644index 00000000000..389d9f92a83--- /dev/null+++ b/packages/pieces/community/nifty/src/lib/actions/create-project.ts@@ -0,0 +1,51 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { niftyAuth } from '../auth';+import { niftyProps } from '../common';+import { NIFTY_ACCESS_TYPE_OPTIONS, NIFTY_TASK_VIEW_OPTIONS, niftyOps } from '../common/operations';+import { projectOutputSchema } from '../output-schemas';++export const createProject = createAction({+ auth: niftyAuth,+ name: 'create_project',+ displayName: 'Create Project',+ description: 'Create a new project.',+ audience: 'human',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Creates a Nifty project, optionally in a portfolio picked from a dropdown (agents: use nifty_project_create). Not idempotent: each call creates another project.',+ idempotent: false,+ },+ props: {+ portfolio: niftyProps.portfolio({+ required: false,+ description: 'Optional. When empty, Nifty uses your default portfolio.',+ }),+ name: Property.ShortText({ displayName: 'Project Name', description: 'Up to 100 characters.', required: true }),+ description: Property.LongText({ displayName: 'Description', required: false }),+ access_type: Property.StaticDropdown({+ displayName: 'Access Type',+ required: false,+ options: { options: NIFTY_ACCESS_TYPE_OPTIONS },+ }),+ default_tasks_view: Property.StaticDropdown({+ displayName: 'Default Tasks View',+ required: false,+ options: { options: NIFTY_TASK_VIEW_OPTIONS },+ }),+ },+ outputSchema: projectOutputSchema,+ async run(context) {+ const p = context.propsValue;+ return niftyOps.createProject({+ auth: context.auth,+ input: {+ name: p.name,+ portfolioId: p.portfolio,+ description: p.description,+ accessType: p.access_type,+ defaultTasksView: p.default_tasks_view,+ },+ });+ },+});diff --git a/packages/pieces/community/nifty/src/lib/actions/create-task.ts b/packages/pieces/community/nifty/src/lib/actions/create-task.tsindex 66c6a7d80d7..48c4cae16ab 100644--- a/packages/pieces/community/nifty/src/lib/actions/create-task.ts+++ b/packages/pieces/community/nifty/src/lib/actions/create-task.ts@@ -1,47 +1,72 @@import { createAction, Property } from '@activepieces/pieces-framework';-import { HttpMethod } from '@activepieces/pieces-common';-import { nitfyCommon, callNitfyApi } from '../common';+import { niftyProps } from '../common';+import { niftyOps } from '../common/operations';import { niftyAuth } from '../auth';+import { createTaskArrayOutputSchema } from '../output-schemas';export const createTask = createAction({name: 'create_task',classification: 'WRITE',auth: niftyAuth,displayName: 'Create Task',- description: 'Create a task in nitfy',- audience: 'both',- aiMetadata: { description: 'Creates a new task in Nifty under a chosen project, status (task group), and optional milestone. Use when an agent needs to add a work item to a Nifty project; requires a task name and a target status. Not idempotent — each call creates a separate task even with identical input.', idempotent: false },+ description: 'Create a task in Nifty.',+ audience: 'human',+ aiMetadata: {+ description:+ 'Creates a new task in Nifty in a chosen project and status column, optionally in a milestone or list, as a subtask, with dates and assignees, picked from dropdowns (agents: use nifty_task_create, which takes IDs). Requires a task name and a status. Not idempotent: each call creates a separate task even with identical input.',+ idempotent: false,+ },props: {- portfolio: nitfyCommon.portfolio,- project: nitfyCommon.project,- status: nitfyCommon.status,- milestone: nitfyCommon.milestone,+ portfolio: niftyProps.portfolio({ required: false }),+ project: niftyProps.project({ required: true }),+ status: niftyProps.status({ required: true, description: 'The board column the task starts in.' }),+ milestone: niftyProps.milestone({+ required: false,+ description: 'Optional. When empty, Nifty puts the task in the project default list.',+ }),task_name: Property.ShortText({displayName: 'Task Name',required: true,}),task_description: Property.LongText({- displayName: 'Task Description',- required: false,+ displayName: 'Task Description',+ required: false,+ }),+ parent_task: niftyProps.task({+ required: false,+ displayName: 'Parent Task',+ description: 'Optional. Pick a task to create this one as its subtask.',+ }),+ start_date: Property.DateTime({+ displayName: 'Start Date',+ required: false,+ }),+ due_date: Property.DateTime({+ displayName: 'Due Date',+ required: false,+ }),+ assignees: niftyProps.members({+ required: false,+ displayName: 'Assignees',+ description: 'Optional. Members to assign to the task.',}),},+ outputSchema: createTaskArrayOutputSchema,async run(context) {- const authentication = context.auth;- const accessToken = authentication.access_token;- const status = context.propsValue.status;- const task_name = context.propsValue.task_name;- const task_description = context.propsValue.task_description;- const milestone = context.propsValue.milestone;-- const response = (- await callNitfyApi(HttpMethod.POST, 'tasks', accessToken, {+ const { status, task_name, task_description, milestone, parent_task, start_date, due_date, assignees } = context.propsValue;+ const task = await niftyOps.createTask({+ auth: context.auth,+ input: {+ statusId: status,name: task_name,- task_group_id: status,description: task_description,- milestone_id: milestone,- })- ).body;-- return [response];+ milestoneId: milestone,+ parentTaskId: parent_task,+ startDate: start_date,+ dueDate: due_date,+ assigneeIds: assignees,+ },+ });+ return [task];},});diff --git a/packages/pieces/community/nifty/src/lib/actions/delete-task.ts b/packages/pieces/community/nifty/src/lib/actions/delete-task.tsnew file mode 100644index 00000000000..af87f4c1782--- /dev/null+++ b/packages/pieces/community/nifty/src/lib/actions/delete-task.ts@@ -0,0 +1,31 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { niftyAuth } from '../auth';+import { niftyProps } from '../common';+import { niftyOps } from '../common/operations';+import { deleteTaskOutputSchema } from '../output-schemas';++export const deleteTask = createAction({+ auth: niftyAuth,+ name: 'delete_task',+ displayName: 'Delete Task',+ description: 'Permanently delete a task.',+ audience: 'human',+ classification: 'DESTRUCTIVE',+ aiMetadata: {+ description:+ 'Permanently deletes a Nifty task picked from project and task dropdowns; it cannot be undone. Prefer Complete or Reopen Task when the work should stay on record. Idempotent in end state: a repeat call fails with not found because the task is already gone.',+ idempotent: true,+ },+ props: {+ warning: Property.MarkDown({+ value: 'Deleting a task is permanent and cannot be undone in Nifty.',+ }),+ portfolio: niftyProps.portfolio({ required: false }),+ project: niftyProps.project({ required: true }),+ task: niftyProps.task({ required: true }),+ },+ outputSchema: deleteTaskOutputSchema,+ async run(context) {+ return niftyOps.deleteTask({ auth: context.auth, taskId: context.propsValue.task });+ },+});diff --git a/packages/pieces/community/nifty/src/lib/actions/find-projects.ts b/packages/pieces/community/nifty/src/lib/actions/find-projects.tsnew file mode 100644index 00000000000..e217c58b0ac--- /dev/null+++ b/packages/pieces/community/nifty/src/lib/actions/find-projects.ts@@ -0,0 +1,49 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { niftyAuth } from '../auth';+import { niftyClient } from '../common/client';+import { findProjectsOutputSchema } from '../output-schemas';++export const findProjects = createAction({+ auth: niftyAuth,+ name: 'find_projects',+ displayName: 'Find Projects',+ description: 'Find projects by name, optionally in one portfolio.',+ audience: 'both',+ classification: 'SEARCH',+ aiMetadata: {+ description:+ 'Lists the Nifty projects you can see, optionally only those whose name contains a text (case-insensitive), in one portfolio, or archived ones too. Leave the name empty to list them all. Use to get the project_id that task, status and milestone actions need. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ name_contains: Property.ShortText({ displayName: 'Name Contains', required: false }),+ portfolio_id: Property.ShortText({ displayName: 'Portfolio ID', required: false }),+ include_archived: Property.Checkbox({ displayName: 'Include Archived', required: false, defaultValue: false }),+ },+ outputSchema: findProjectsOutputSchema,+ async run(context) {+ const p = context.propsValue;+ const portfolioId = niftyClient.optionalId({ value: p.portfolio_id, label: 'Portfolio ID' });+ const needle = typeof p.name_contains === 'string' ? p.name_contains.trim().toLowerCase() : '';+ const active = await niftyClient.listAll({+ auth: context.auth,+ path: 'projects',+ key: 'projects',+ query: { subteam_id: portfolioId },+ });+ const archived =+ p.include_archived === true+ ? await niftyClient.listAll({+ auth: context.auth,+ path: 'projects',+ key: 'projects',+ query: { subteam_id: portfolioId, archived: true },+ })+ : { items: [], truncated: false };+ const matches = [...active.items, ...archived.items]+ .filter((project) => portfolioId === undefined || niftyClient.text({ record: project, key: 'subteam' }) === portfolioId)+ .filter((project) => needle.length === 0 || niftyClient.text({ record: project, key: 'name' }).toLowerCase().includes(needle))+ .map(niftyClient.cleanProject);+ return { items: matches, truncated: active.truncated || archived.truncated };+ },+});diff --git a/packages/pieces/community/nifty/src/lib/actions/find-tasks.ts b/packages/pieces/community/nifty/src/lib/actions/find-tasks.tsnew file mode 100644index 00000000000..d770f3dd83e--- /dev/null+++ b/packages/pieces/community/nifty/src/lib/actions/find-tasks.ts@@ -0,0 +1,89 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { niftyAuth } from '../auth';+import { niftyClient } from '../common/client';+import { findTasksOutputSchema } from '../output-schemas';++export const findTasks = createAction({+ auth: niftyAuth,+ name: 'find_tasks',+ displayName: 'Find Tasks',+ description: 'List tasks filtered by project, status, milestone, assignee, completion or due date, one page at a time.',+ audience: 'both',+ classification: 'SEARCH',+ aiMetadata: {+ description:+ 'Lists Nifty tasks filtered by project, status, milestone/list, assignee, completion and a due-date window, one page at a time (pass next_offset to continue while has_more is true). Subtasks are only included when a project_id is given. Use to locate a task_id before updating, completing or deleting. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ project_id: Property.ShortText({ displayName: 'Project ID', required: false }),+ status_id: Property.ShortText({ displayName: 'Status ID', required: false }),+ milestone_id: Property.ShortText({ displayName: 'Milestone or List ID', required: false }),+ assignee_id: Property.ShortText({ displayName: 'Assignee Member ID', required: false }),+ completion: Property.StaticDropdown({+ displayName: 'Completion',+ required: false,+ defaultValue: 'any',+ options: {+ options: [+ { label: 'Any', value: 'any' },+ { label: 'Open only', value: 'open' },+ { label: 'Completed only', value: 'completed' },+ ],+ },+ }),+ include_subtasks: Property.Checkbox({+ displayName: 'Include Subtasks',+ description: 'Only works together with a Project ID.',+ required: false,+ defaultValue: false,+ }),+ include_archived: Property.Checkbox({ displayName: 'Include Archived', required: false, defaultValue: false }),+ due_from: Property.DateTime({ displayName: 'Due From', description: 'Set together with Due To.', required: false }),+ due_to: Property.DateTime({ displayName: 'Due To', description: 'Set together with Due From.', required: false }),+ limit: Property.Number({ displayName: 'Limit', description: '1 to 1000. Default 100.', required: false, defaultValue: 100 }),+ offset: Property.Number({ displayName: 'Offset', description: 'Use next_offset from the previous page.', required: false, defaultValue: 0 }),+ },+ outputSchema: findTasksOutputSchema,+ async run(context) {+ const p = context.propsValue;+ const projectId = niftyClient.optionalId({ value: p.project_id, label: 'Project ID' });+ const dueFrom = niftyClient.optionalIsoDate({ value: p.due_from, label: 'Due From' });+ const dueTo = niftyClient.optionalIsoDate({ value: p.due_to, label: 'Due To' });+ if ((dueFrom === undefined) !== (dueTo === undefined)) {+ throw new Error('Set both Due From and Due To, or neither. Nifty ignores a one-sided due-date window.');+ }+ if (p.include_subtasks === true && projectId === undefined) {+ throw new Error('Include Subtasks needs a Project ID: Nifty only returns subtasks for one project at a time.');+ }+ const limit = niftyClient.optionalNumber({ value: p.limit, label: 'Limit', min: 1, max: 1000, integer: true }) ?? 100;+ const offset = niftyClient.optionalNumber({ value: p.offset, label: 'Offset', min: 0, max: Number.MAX_SAFE_INTEGER, integer: true }) ?? 0;+ const completion = p.completion ?? 'any';+ if (completion !== 'any' && completion !== 'open' && completion !== 'completed') {+ throw new Error(`Completion must be any, open or completed, got "${String(completion)}".`);+ }+ const page = await niftyClient.listPage({+ auth: context.auth,+ path: 'tasks',+ key: 'tasks',+ limit,+ offset,+ query: {+ project_id: projectId,+ task_group_id: niftyClient.optionalId({ value: p.status_id, label: 'Status ID' }),+ milestone_id: niftyClient.optionalId({ value: p.milestone_id, label: 'Milestone ID' }),+ member_id: niftyClient.optionalId({ value: p.assignee_id, label: 'Assignee Member ID' }),+ completed: completion === 'any' ? undefined : completion === 'completed',+ include_subtasks: p.include_subtasks === true ? true : undefined,+ include_archived: p.include_archived === true ? true : undefined,+ from: dueFrom,+ to: dueTo,+ },+ });+ return {+ items: page.items,+ has_more: page.hasMore,+ next_offset: page.hasMore ? offset + page.items.length : null,+ };+ },+});diff --git a/packages/pieces/community/nifty/src/lib/actions/get-project.ts b/packages/pieces/community/nifty/src/lib/actions/get-project.tsnew file mode 100644index 00000000000..11b0ef9238a--- /dev/null+++ b/packages/pieces/community/nifty/src/lib/actions/get-project.ts@@ -0,0 +1,25 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { niftyAuth } from '../auth';+import { niftyOps } from '../common/operations';+import { projectOutputSchema } from '../output-schemas';++export const getProject = createAction({+ auth: niftyAuth,+ name: 'get_project',+ displayName: 'Get Project',+ description: 'Get a project by its ID.',+ audience: 'both',+ classification: 'READ',+ aiMetadata: {+ description:+ 'Returns one Nifty project by ID with its portfolio, access level, default view, archive state, owner and progress. Use to check a project before creating tasks or milestones in it. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ project_id: Property.ShortText({ displayName: 'Project ID', required: true }),+ },+ outputSchema: projectOutputSchema,+ async run(context) {+ return niftyOps.getProject({ auth: context.auth, projectId: context.propsValue.project_id });+ },+});diff --git a/packages/pieces/community/nifty/src/lib/actions/get-task.ts b/packages/pieces/community/nifty/src/lib/actions/get-task.tsnew file mode 100644index 00000000000..4e11bafc52e--- /dev/null+++ b/packages/pieces/community/nifty/src/lib/actions/get-task.ts@@ -0,0 +1,29 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { niftyAuth } from '../auth';+import { niftyOps } from '../common/operations';+import { taskOutputSchema } from '../output-schemas';++export const getTask = createAction({+ auth: niftyAuth,+ name: 'get_task',+ displayName: 'Get Task',+ description: 'Get a task by its ID.',+ audience: 'both',+ classification: 'READ',+ aiMetadata: {+ description:+ 'Returns one Nifty task by ID with its status, milestone/list, parent task, dates, completion, assignee IDs and subtask counts. Use after a trigger or search to read current details before updating. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ task_id: Property.ShortText({+ displayName: 'Task ID',+ description: 'The task ID, e.g. from a trigger or Find Tasks (not the short key like ANP-1).',+ required: true,+ }),+ },+ outputSchema: taskOutputSchema,+ async run(context) {+ return niftyOps.getTask({ auth: context.auth, taskId: context.propsValue.task_id });+ },+});diff --git a/packages/pieces/community/nifty/src/lib/actions/list-members.ts b/packages/pieces/community/nifty/src/lib/actions/list-members.tsnew file mode 100644index 00000000000..94c4c3bf80b--- /dev/null+++ b/packages/pieces/community/nifty/src/lib/actions/list-members.ts@@ -0,0 +1,26 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { niftyAuth } from '../auth';+import { listMembers as fetchMembers } from '../common';+import { listMembersOutputSchema } from '../output-schemas';++export const listMembers = createAction({+ auth: niftyAuth,+ name: 'list_members',+ displayName: 'List Members',+ description: 'List the members of your Nifty workspace.',+ audience: 'both',+ classification: 'SEARCH',+ aiMetadata: {+ description:+ 'Lists the members of the Nifty workspace with their member ID, name, email and role; removed members are left out unless asked for. Use to get the member IDs that assignee options need. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ include_removed: Property.Checkbox({ displayName: 'Include Removed Members', required: false, defaultValue: false }),+ },+ outputSchema: listMembersOutputSchema,+ async run(context) {+ const items = await fetchMembers({ auth: context.auth, includeRemoved: context.propsValue.include_removed === true });+ return { items };+ },+});diff --git a/packages/pieces/community/nifty/src/lib/actions/list-milestones.ts b/packages/pieces/community/nifty/src/lib/actions/list-milestones.tsnew file mode 100644index 00000000000..85ce3f7df1f--- /dev/null+++ b/packages/pieces/community/nifty/src/lib/actions/list-milestones.ts@@ -0,0 +1,46 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { niftyAuth } from '../auth';+import { listMilestones as fetchMilestones } from '../common';+import { niftyClient } from '../common/client';+import { listMilestonesOutputSchema } from '../output-schemas';++export const listMilestones = createAction({+ auth: niftyAuth,+ name: 'list_milestones',+ displayName: 'List Milestones and Lists',+ description: 'List the milestones and task lists of a project.',+ audience: 'both',+ classification: 'SEARCH',+ aiMetadata: {+ description:+ 'Lists the dated milestones and plain task lists of a Nifty project, or only one kind. Use to get the milestone_id for creating or moving tasks. Requires project_id. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ project_id: Property.ShortText({ displayName: 'Project ID', required: true }),+ kind: Property.StaticDropdown({+ displayName: 'Kind',+ required: false,+ defaultValue: 'all',+ options: {+ options: [+ { label: 'Milestones and lists', value: 'all' },+ { label: 'Milestones only', value: 'milestones' },+ { label: 'Lists only', value: 'lists' },+ ],+ },+ }),+ },+ outputSchema: listMilestonesOutputSchema,+ async run(context) {+ const projectId = niftyClient.requireId({ value: context.propsValue.project_id, label: 'Project ID' });+ const kind = context.propsValue.kind ?? 'all';+ if (kind !== 'all' && kind !== 'milestones' && kind !== 'lists') {+ throw new Error(`Kind must be all, milestones or lists, got "${String(kind)}".`);+ }+ const items = await fetchMilestones({ auth: context.auth, projectId });+ return {+ items: items.filter((m) => kind === 'all' || (kind === 'lists') === (m['is_list'] === true)),+ };+ },+});diff --git a/packages/pieces/community/nifty/src/lib/actions/list-statuses.ts b/packages/pieces/community/nifty/src/lib/actions/list-statuses.tsnew file mode 100644index 00000000000..438a0d61900--- /dev/null+++ b/packages/pieces/community/nifty/src/lib/actions/list-statuses.ts@@ -0,0 +1,33 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { niftyAuth } from '../auth';+import { listStatuses as fetchStatuses } from '../common';+import { niftyClient } from '../common/client';+import { listStatusesOutputSchema } from '../output-schemas';++export const listStatuses = createAction({+ auth: niftyAuth,+ name: 'list_statuses',+ displayName: 'List Statuses',+ description: 'List the status columns of a project.',+ audience: 'both',+ classification: 'SEARCH',+ aiMetadata: {+ description:+ 'Lists every status (board column) of a Nifty project in board order. Use to get the status_id that Create Task and Update Task need. Requires project_id. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ project_id: Property.ShortText({ displayName: 'Project ID', required: true }),+ include_archived: Property.Checkbox({ displayName: 'Include Archived', required: false, defaultValue: false }),+ },+ outputSchema: listStatusesOutputSchema,+ async run(context) {+ const projectId = niftyClient.requireId({ value: context.propsValue.project_id, label: 'Project ID' });+ const items = await fetchStatuses({+ auth: context.auth,+ projectId,+ includeArchived: context.propsValue.include_archived === true,+ });+ return { items };+ },+});diff --git a/packages/pieces/community/nifty/src/lib/actions/remove-task-assignees.ts b/packages/pieces/community/nifty/src/lib/actions/remove-task-assignees.tsnew file mode 100644index 00000000000..97355e3d863--- /dev/null+++ b/packages/pieces/community/nifty/src/lib/actions/remove-task-assignees.ts@@ -0,0 +1,35 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { niftyAuth } from '../auth';+import { niftyOps } from '../common/operations';+import { assigneesOutputSchema } from '../output-schemas';++export const removeTaskAssignees = createAction({+ auth: niftyAuth,+ name: 'remove_task_assignees',+ displayName: 'Remove Task Assignees',+ description: 'Unassign members from a task, keeping the other assignees.',+ audience: 'both',+ classification: 'WRITE',+ aiMetadata: {+ description:+ "Removes one or more members from a Nifty task's assignees and leaves the others in place; the task itself is kept. Requires task_id and at least one member ID. Idempotent: removing someone not assigned changes nothing.",+ idempotent: true,+ },+ props: {+ task_id: Property.ShortText({ displayName: 'Task ID', required: true }),+ member_ids: Property.Array({+ displayName: 'Member IDs',+ description: 'Member IDs from List Members.',+ required: true,+ }),+ },+ outputSchema: assigneesOutputSchema,+ async run(context) {+ return niftyOps.changeAssignees({+ auth: context.auth,+ taskId: context.propsValue.task_id,+ memberIds: context.propsValue.member_ids,+ mode: 'remove',+ });+ },+});diff --git a/packages/pieces/community/nifty/src/lib/actions/update-project.ts b/packages/pieces/community/nifty/src/lib/actions/update-project.tsnew file mode 100644index 00000000000..58d19e0aec8--- /dev/null+++ b/packages/pieces/community/nifty/src/lib/actions/update-project.ts@@ -0,0 +1,60 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { niftyAuth } from '../auth';+import { niftyProps } from '../common';+import { NIFTY_ACCESS_TYPE_OPTIONS, NIFTY_ARCHIVE_OPTIONS, NIFTY_TASK_VIEW_OPTIONS, niftyOps } from '../common/operations';+import { projectOutputSchema } from '../output-schemas';++export const updateProject = createAction({+ auth: niftyAuth,+ name: 'update_project',+ displayName: 'Update Project',+ description: 'Rename a project, change its description, access or view, or archive it.',+ audience: 'human',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Updates a Nifty project picked from a dropdown (agents: use nifty_project_update): name, description, access level, default view, or archive/unarchive. Only filled fields change. Idempotent.',+ idempotent: true,+ },+ props: {+ portfolio: niftyProps.portfolio({ required: false }),+ project: niftyProps.project({ required: true, includeArchived: true }),+ name: Property.ShortText({ displayName: 'New Name', required: false }),+ description: Property.LongText({+ displayName: 'New Description',+ description: 'Nifty does not allow blanking a project description through the API.',+ required: false,+ }),+ access_type: Property.StaticDropdown({+ displayName: 'Access Type',+ required: false,+ options: { options: NIFTY_ACCESS_TYPE_OPTIONS },+ }),+ default_tasks_view: Property.StaticDropdown({+ displayName: 'Default Tasks View',+ required: false,+ options: { options: NIFTY_TASK_VIEW_OPTIONS },+ }),+ archive: Property.StaticDropdown({+ displayName: 'Archive',+ required: false,+ defaultValue: 'unchanged',+ options: { options: NIFTY_ARCHIVE_OPTIONS },+ }),+ },+ outputSchema: projectOutputSchema,+ async run(context) {+ const p = context.propsValue;+ return niftyOps.updateProject({+ auth: context.auth,+ input: {+ projectId: p.project,+ name: p.name,+ description: p.description,+ accessType: p.access_type,+ defaultTasksView: p.default_tasks_view,+ archive: p.archive,+ },+ });+ },+});diff --git a/packages/pieces/community/nifty/src/lib/actions/update-task.ts b/packages/pieces/community/nifty/src/lib/actions/update-task.tsnew file mode 100644index 00000000000..b12444ca681--- /dev/null+++ b/packages/pieces/community/nifty/src/lib/actions/update-task.ts@@ -0,0 +1,54 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { niftyAuth } from '../auth';+import { niftyProps } from '../common';+import { niftyOps } from '../common/operations';+import { taskOutputSchema } from '../output-schemas';++export const updateTask = createAction({+ auth: niftyAuth,+ name: 'update_task',+ displayName: 'Update Task',+ description: 'Change the name, description, status, milestone, dates or story points of a task.',+ audience: 'human',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Updates fields on a Nifty task picked from cascading project and task dropdowns (agents: use nifty_task_update, which takes IDs). Only the fields you fill change; clear options blank the description or a date. Idempotent: repeating the same update leaves the task in the same state.',+ idempotent: true,+ },+ props: {+ portfolio: niftyProps.portfolio({ required: false }),+ project: niftyProps.project({ required: true }),+ task: niftyProps.task({ required: true }),+ name: Property.ShortText({ displayName: 'New Name', required: false }),+ description: Property.LongText({ displayName: 'New Description', required: false }),+ clear_description: Property.Checkbox({ displayName: 'Clear Description', required: false, defaultValue: false }),+ status: niftyProps.status({ required: false, description: 'Move the task to this status column.' }),+ milestone: niftyProps.milestone({ required: false, description: 'Move the task to this milestone or list.' }),+ start_date: Property.DateTime({ displayName: 'Start Date', required: false }),+ clear_start_date: Property.Checkbox({ displayName: 'Clear Start Date', required: false, defaultValue: false }),+ due_date: Property.DateTime({ displayName: 'Due Date', required: false }),+ clear_due_date: Property.Checkbox({ displayName: 'Clear Due Date', required: false, defaultValue: false }),+ story_points: Property.Number({ displayName: 'Story Points', required: false }),+ },+ outputSchema: taskOutputSchema,+ async run(context) {+ const p = context.propsValue;+ return niftyOps.updateTask({+ auth: context.auth,+ input: {+ taskId: p.task,+ name: p.name,+ description: p.description,+ clearDescription: p.clear_description,+ statusId: p.status,+ milestoneId: p.milestone,+ startDate: p.start_date,+ clearStartDate: p.clear_start_date,+ dueDate: p.due_date,+ clearDueDate: p.clear_due_date,+ storyPoints: p.story_points,+ },+ });+ },+});diff --git a/packages/pieces/community/nifty/src/lib/common/client.ts b/packages/pieces/community/nifty/src/lib/common/client.tsnew file mode 100644index 00000000000..923a215edb9--- /dev/null+++ b/packages/pieces/community/nifty/src/lib/common/client.ts@@ -0,0 +1,319 @@+import {+ AuthenticationType,+ httpClient,+ HttpMethod,+ HttpResponse,+ QueryParams,+} from '@activepieces/pieces-common';+import { AppConnectionValueForAuthProperty } from '@activepieces/pieces-framework';+import { niftyAuth } from '../auth';++const BASE_URL = 'https://openapi.niftypm.com/api/v1.0';+const PAGE_SIZE = 1000;+const MAX_PAGES = 10;+const MAX_ID_LENGTH = 128;+const ID_FORBIDDEN = /[/?#\\\s]/;+const PROJECT_HIDDEN_KEYS = [+ 'zoom_id',+ 'zoom_password',+ 'zoom_join_url',+ 'webex_id',+ 'webex_password',+ 'webex_join_url',+];+const MEMBER_KEYS = ['id', 'user_id', 'name', 'email', 'initials', 'role', 'pending', 'removed'];++export class NiftyApiError extends Error {+ readonly status: number;+ readonly responseBody: unknown;++ constructor({ status, message, responseBody }: { status: number; message: string; responseBody: unknown }) {+ super(message);+ this.name = 'NiftyApiError';+ this.status = status;+ this.responseBody = responseBody;+ }+}++function isRecord(value: unknown): value is NiftyRecord {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+}++function vendorMessage(body: unknown): string {+ if (isRecord(body)) {+ const message = typeof body['message'] === 'string' ? body['message'] : '';+ const errors = Array.isArray(body['errors'])+ ? body['errors']+ .filter(isRecord)+ .map((e) => (typeof e['message'] === 'string' ? e['message'] : ''))+ .filter((m) => m.length > 0)+ : [];+ const detail = errors.length > 0 ? ` (${errors.join('; ')})` : '';+ if (message.length > 0) {+ return `${trimTrailingPeriods(message)}${detail}`;+ }+ }+ if (typeof body === 'string' && body.length > 0) {+ return body.slice(0, 300);+ }+ return 'no details returned';+}++function trimTrailingPeriods(message: string): string {+ let end = message.length;+ while (end > 0 && (message[end - 1] === '.' || message[end - 1] === ' ')) {+ end--;+ }+ return message.slice(0, end);+}++function statusSentence({ status, detail }: { status: number; detail: string }): string {+ switch (status) {+ case 400:+ return `Nifty rejected the request (400): ${detail}. Check the values you entered.`;+ case 401:+ return `Nifty did not accept the connection (401): ${detail}. Reconnect your Nifty account.`;+ case 403:+ return `Nifty refused access (403): ${detail}. The record may not exist, may be in a project you are not a member of, or this connection was not granted access to this kind of data.`;+ case 404:+ return `Nifty could not find the record (404): ${detail}. It may have been deleted, or the ID is wrong.`;+ case 429:+ return `Nifty rate limit reached (429): ${detail}. Wait a minute and try again.`;+ default:+ return `Nifty request failed with HTTP ${status}: ${detail}.`;+ }+}++function toNiftyError(error: unknown): unknown {+ const response = isRecord(error) && isRecord(error['response']) ? error['response'] : undefined;+ const status = response?.['status'];+ if (typeof status !== 'number') {+ return error;+ }+ const responseBody = response?.['body'];+ return new NiftyApiError({+ status,+ responseBody,+ message: statusSentence({ status, detail: vendorMessage(responseBody) }),+ });+}++function assertRelativePath(path: string): void {+ if (path.length === 0 || path.startsWith('/') || path.includes('://') || path.includes('..') || path.includes('\\')) {+ throw new Error(`Refusing to call an unexpected Nifty path: "${path}".`);+ }+}++async function request({+ auth,+ method,+ path,+ query,+ body,+}: {+ auth: NiftyAuth;+ method: HttpMethod;+ path: string;+ query?: Record<string, string | number | boolean | undefined>;+ body?: unknown;+}): Promise<HttpResponse<unknown>> {+ assertRelativePath(path);+ const queryParams: QueryParams = {};+ for (const [key, value] of Object.entries(query ?? {})) {+ if (value !== undefined) {+ queryParams[key] = String(value);+ }+ }+ try {+ return await httpClient.sendRequest<unknown>({+ method,+ url: `${BASE_URL}/${path}`,+ queryParams,+ body,+ authentication: {+ type: AuthenticationType.BEARER_TOKEN,+ token: auth.access_token,+ },+ });+ } catch (error) {+ throw toNiftyError(error);+ }+}++async function requestRecord(params: Parameters<typeof request>[0]): Promise<NiftyRecord> {+ const response = await request(params);+ if (!isRecord(response.body)) {+ throw new Error(`Nifty returned an unexpected response for ${params.path}: ${JSON.stringify(response.body).slice(0, 200)}`);+ }+ return response.body;+}++function extractItems({ body, key }: { body: unknown; key: string | null }): NiftyRecord[] {+ const list = key === null ? body : isRecord(body) ? body[key] : undefined;+ if (!Array.isArray(list)) {+ throw new Error(`Nifty returned an unexpected list response: ${JSON.stringify(body).slice(0, 200)}`);+ }+ return list.filter(isRecord);+}++async function listPage({+ auth,+ path,+ key,+ query,+ limit,+ offset,+}: {+ auth: NiftyAuth;+ path: string;+ key: string;+ query?: Record<string, string | number | boolean | undefined>;+ limit: number;+ offset: number;+}): Promise<{ items: NiftyRecord[]; hasMore: boolean }> {+ const response = await request({ auth, method: HttpMethod.GET, path, query: { ...query, limit, offset } });+ const items = extractItems({ body: response.body, key });+ return { items, hasMore: items.length >= limit };+}++async function listAll({+ auth,+ path,+ key,+ query,+ maxPages = MAX_PAGES,+}: {+ auth: NiftyAuth;+ path: string;+ key: string;+ query?: Record<string, string | number | boolean | undefined>;+ maxPages?: number;+}): Promise<{ items: NiftyRecord[]; truncated: boolean }> {+ const items: NiftyRecord[] = [];+ for (let page = 0; page < maxPages; page++) {+ const result = await listPage({ auth, path, key, query, limit: PAGE_SIZE, offset: page * PAGE_SIZE });+ items.push(...result.items);+ if (!result.hasMore) {+ return { items, truncated: false };+ }+ }+ return { items, truncated: true };+}++function requireId({ value, label }: { value: unknown; label: string }): string {+ const id = typeof value === 'string' ? value.trim() : typeof value === 'number' ? String(value) : '';+ if (id.length === 0) {+ throw new Error(`${label} is required.`);+ }+ if (id.length > MAX_ID_LENGTH || ID_FORBIDDEN.test(id)) {+ throw new Error(`${label} "${id.slice(0, 80)}" is not a valid Nifty ID. Pass the ID exactly as Nifty returns it, e.g. HjGDVlaejN.`);+ }+ return id;+}++function optionalId({ value, label }: { value: unknown; label: string }): string | undefined {+ if (value === undefined || value === null || value === '') {+ return undefined;+ }+ return requireId({ value, label });+}++function idList({ value, label }: { value: unknown; label: string }): string[] {+ const raw = Array.isArray(value) ? value : value === undefined || value === null || value === '' ? [] : [value];+ const ids = raw+ .flatMap((item) => (typeof item === 'string' ? item.split(',') : [item]))+ .filter((item) => !(typeof item === 'string' && item.trim() === ''))+ .map((item) => requireId({ value: item, label }));+ return [...new Set(ids)];+}++function segment(id: string): string {+ return encodeURIComponent(id);+}++function optionalText(value: unknown): string | undefined {+ if (typeof value !== 'string') {+ return undefined;+ }+ return value.length > 0 ? value : undefined;+}++function requireName({ value, label, max }: { value: unknown; label: string; max: number }): string {+ const name = typeof value === 'string' ? value.trim() : '';+ if (name.length === 0) {+ throw new Error(`${label} is required.`);+ }+ if (name.length > max) {+ throw new Error(`${label} is too long (${name.length} characters, the maximum is ${max}).`);+ }+ return name;+}++function optionalName({ value, label, max }: { value: unknown; label: string; max: number }): string | undefined {+ if (value === undefined || value === null || (typeof value === 'string' && value.trim() === '')) {+ return undefined;+ }+ return requireName({ value, label, max });+}++function optionalIsoDate({ value, label }: { value: unknown; label: string }): string | undefined {+ if (value === undefined || value === null || value === '') {+ return undefined;+ }+ const text = typeof value === 'string' ? value.trim() : '';+ const parsed = Date.parse(text);+ if (text.length === 0 || Number.isNaN(parsed)) {+ throw new Error(`${label} "${String(value)}" is not a valid date. Use ISO 8601, e.g. 2026-10-20 or 2026-10-20T09:00:00Z.`);+ }+ return new Date(parsed).toISOString();+}++function optionalNumber({ value, label, min, max, integer }: { value: unknown; label: string; min: number; max: number; integer: boolean }): number | undefined {+ if (value === undefined || value === null || value === '') {+ return undefined;+ }+ const n = typeof value === 'number' ? value : Number(String(value).trim());+ if (!Number.isFinite(n) || n < min || n > max || (integer && !Number.isInteger(n))) {+ throw new Error(`${label} must be ${integer ? 'a whole number' : 'a number'} from ${min} to ${max}, got "${String(value)}".`);+ }+ return n;+}++function cleanProject(project: NiftyRecord): NiftyRecord {+ return Object.fromEntries(Object.entries(project).filter(([key]) => !PROJECT_HIDDEN_KEYS.includes(key)));+}++function cleanMember(member: NiftyRecord): NiftyRecord {+ return Object.fromEntries(MEMBER_KEYS.filter((key) => key in member).map((key) => [key, member[key]]));+}++function text({ record, key }: { record: NiftyRecord; key: string }): string {+ const value = record[key];+ return typeof value === 'string' ? value : typeof value === 'number' ? String(value) : '';+}++export const niftyClient = {+ BASE_URL,+ PAGE_SIZE,+ MAX_PAGES,+ isRecord,+ request,+ requestRecord,+ listPage,+ listAll,+ requireId,+ optionalId,+ idList,+ segment,+ optionalText,+ requireName,+ optionalName,+ optionalIsoDate,+ optionalNumber,+ cleanProject,+ cleanMember,+ text,+};++export type NiftyAuth = AppConnectionValueForAuthProperty<typeof niftyAuth>;+export type NiftyRecord = Record<string, unknown>;diff --git a/packages/pieces/community/nifty/src/lib/common/index.ts b/packages/pieces/community/nifty/src/lib/common/index.tsindex 16ae8421b64..b9850d46b45 100644--- a/packages/pieces/community/nifty/src/lib/common/index.ts+++ b/packages/pieces/community/nifty/src/lib/common/index.ts@@ -1,217 +1,249 @@-import { Property, OAuth2PropertyValue } from '@activepieces/pieces-framework';-import {- HttpMethod,- HttpMessageBody,- HttpResponse,- httpClient,- AuthenticationType,-} from '@activepieces/pieces-common';+import { DropdownState, Property } from '@activepieces/pieces-framework';import { niftyAuth } from '../auth';+import { NiftyApiError, NiftyAuth, niftyClient, NiftyRecord } from './client';-export const nitfyCommon = {- portfolio: Property.Dropdown({-auth:niftyAuth,- displayName: 'Portfolio',- required: true,- refreshers: [],- options: async ({ auth }) => {- const authentication = auth as OAuth2PropertyValue;- if (!authentication) {- return {- disabled: true,- placeholder: 'connect your account first',- options: [],- };- }- const accessToken = authentication.access_token;-- const response = (- await callNitfyApi<{- subteams: {- id: string;- name: string;- }[];- items: boolean;- hasMore: boolean;- }>(HttpMethod.GET, 'subteams', accessToken, undefined)- ).body;-- return {- disabled: false,- options: response.subteams.map((team) => {- return {- label: team.name,- value: team.id,- };- }),- };- },- }),- project: Property.Dropdown({-auth:niftyAuth,- displayName: 'Project',- required: true,- refreshers: ['portfolio'],- options: async ({ auth, portfolio }) => {- const authentication = auth as OAuth2PropertyValue;- if (!authentication) {- return {- disabled: true,- placeholder: 'connect your account first',- options: [],- };- }- if (!portfolio) {- return {- disabled: true,- placeholder: 'Select portfolio first',- options: [],- };- }-- const accessToken = authentication.access_token;- const response = (- await callNitfyApi<{- projects: {- id: string;- name: string;- subteam: string;- }[];- hasMore: boolean;- }>(HttpMethod.GET, `projects`, accessToken, undefined)- ).body;+export const niftyProps = {+ portfolio<R extends boolean>({ required, description }: { required: R; description?: string }) {+ return Property.Dropdown<string, R, typeof niftyAuth>({+ auth: niftyAuth,+ displayName: 'Portfolio',+ description: description ?? 'Optional. Narrows the project list to one portfolio. Leave empty to pick from all your projects.',+ required,+ refreshers: [],+ options: async ({ auth }) => {+ if (!auth) {+ return disabled('Connect your Nifty account first');+ }+ return loadOptions({+ what: 'portfolios',+ load: async () => {+ const { items } = await niftyClient.listAll({ auth, path: 'subteams', key: 'subteams' });+ return items.map((team) => ({ label: niftyClient.text({ record: team, key: 'name' }), value: niftyClient.text({ record: team, key: 'id' }) }));+ },+ onForbidden: 'Portfolios are not available on this connection. Leave this empty to pick from all your projects.',+ });+ },+ });+ },+ project<R extends boolean>({ required, description, includeArchived = false }: { required: R; description?: string; includeArchived?: boolean }) {+ return Property.Dropdown<string, R, typeof niftyAuth>({+ auth: niftyAuth,+ displayName: 'Project',+ description,+ required,+ refreshers: ['portfolio'],+ options: async ({ auth, portfolio }) => {+ if (!auth) {+ return disabled('Connect your Nifty account first');+ }+ const portfolioId = typeof portfolio === 'string' && portfolio.length > 0 ? portfolio : undefined;+ return loadOptions({+ what: 'projects',+ load: async () => {+ const items = await listProjects({ auth, portfolioId, includeArchived });+ return items+ .filter((project) => portfolioId === undefined || niftyClient.text({ record: project, key: 'subteam' }) === portfolioId)+ .map((project) => ({+ label: projectLabel(project),+ value: niftyClient.text({ record: project, key: 'id' }),+ }));+ },+ });+ },+ });+ },+ status<R extends boolean>({ required, description }: { required: R; description?: string }) {+ return Property.Dropdown<string, R, typeof niftyAuth>({+ auth: niftyAuth,+ displayName: 'Status',+ description,+ required,+ refreshers: ['project'],+ options: async ({ auth, project }) => {+ if (!auth) {+ return disabled('Connect your Nifty account first');+ }+ if (typeof project !== 'string' || project.length === 0) {+ return disabled('Select a project first');+ }+ return loadOptions({+ what: 'statuses',+ load: async () => {+ const items = await listStatuses({ auth, projectId: project, includeArchived: false });+ return items.map((status) => ({ label: niftyClient.text({ record: status, key: 'name' }), value: niftyClient.text({ record: status, key: 'id' }) }));+ },+ });+ },+ });+ },+ milestone<R extends boolean>({ required, description }: { required: R; description?: string }) {+ return Property.Dropdown<string, R, typeof niftyAuth>({+ auth: niftyAuth,+ displayName: 'Milestone',+ description,+ required,+ refreshers: ['project'],+ options: async ({ auth, project }) => {+ if (!auth) {+ return disabled('Connect your Nifty account first');+ }+ if (typeof project !== 'string' || project.length === 0) {+ return disabled('Select a project first');+ }+ return loadOptions({+ what: 'milestones',+ load: async () => {+ const items = await listMilestones({ auth, projectId: project });+ return items.map((milestone) => ({+ label: milestone['is_list'] === true ? `${niftyClient.text({ record: milestone, key: 'name' })} (list)` : niftyClient.text({ record: milestone, key: 'name' }),+ value: niftyClient.text({ record: milestone, key: 'id' }),+ }));+ },+ });+ },+ });+ },+ task<R extends boolean>({ required, displayName, description }: { required: R; displayName?: string; description?: string }) {+ return Property.Dropdown<string, R, typeof niftyAuth>({+ auth: niftyAuth,+ displayName: displayName ?? 'Task',+ description,+ required,+ refreshers: ['project'],+ options: async ({ auth, project }) => {+ if (!auth) {+ return disabled('Connect your Nifty account first');+ }+ if (typeof project !== 'string' || project.length === 0) {+ return disabled('Select a project first');+ }+ return loadOptions({+ what: 'tasks',+ load: async () => {+ const { items } = await niftyClient.listAll({+ auth,+ path: 'tasks',+ key: 'tasks',+ query: { project_id: project, include_subtasks: true },+ });+ return items.map((task) => ({ label: taskLabel(task), value: niftyClient.text({ record: task, key: 'id' }) }));+ },+ });+ },+ });+ },+ members<R extends boolean>({ required, displayName, description }: { required: R; displayName: string; description?: string }) {+ return Property.MultiSelectDropdown<string, R, typeof niftyAuth>({+ auth: niftyAuth,+ displayName,+ description,+ required,+ refreshers: [],+ options: async ({ auth }) => {+ if (!auth) {+ return disabled('Connect your Nifty account first');+ }+ return loadOptions({+ what: 'members',+ load: async () => {+ const items = await listMembers({ auth, includeRemoved: false });+ return items.map((member) => ({ label: memberLabel(member), value: niftyClient.text({ record: member, key: 'id' }) }));+ },+ });+ },+ });+ },+};- response.projects = response.projects.filter((project) => {- return project.subteam == portfolio;- });+export async function listProjects({+ auth,+ portfolioId,+ includeArchived,+}: {+ auth: NiftyAuth;+ portfolioId: string | undefined;+ includeArchived: boolean;+}): Promise<NiftyRecord[]> {+ const active = await niftyClient.listAll({ auth, path: 'projects', key: 'projects', query: { subteam_id: portfolioId } });+ if (!includeArchived) {+ return active.items;+ }+ const archived = await niftyClient.listAll({+ auth,+ path: 'projects',+ key: 'projects',+ query: { subteam_id: portfolioId, archived: true },+ });+ return [...active.items, ...archived.items];+}- return {- disabled: false,- options: response.projects.map((project) => {- return {- label: project.name,- value: project.id,- };- }),- };- },- }),- status: Property.Dropdown({-auth:niftyAuth,- displayName: 'Status',- required: true,- refreshers: ['project'],- options: async ({ auth, project }) => {- const authentication = auth as OAuth2PropertyValue;- if (!authentication) {- return {- disabled: true,- placeholder: 'connect your account first',- options: [],- };- }- if (!project) {- return {- disabled: true,- placeholder: 'Select portfolio first',- options: [],- };- }+export async function listStatuses({ auth, projectId, includeArchived }: { auth: NiftyAuth; projectId: string; includeArchived: boolean }): Promise<NiftyRecord[]> {+ const { items } = await niftyClient.listAll({+ auth,+ path: 'taskgroups',+ key: 'items',+ query: { project_id: projectId, archived: includeArchived ? undefined : false },+ });+ return items;+}- const accessToken = authentication.access_token;+export async function listMilestones({ auth, projectId }: { auth: NiftyAuth; projectId: string }): Promise<NiftyRecord[]> {+ const { items } = await niftyClient.listAll({+ auth,+ path: 'milestones',+ key: 'items',+ query: { project_id: projectId, is_list: true },+ });+ return items;+}- const response = (- await callNitfyApi<{- items: {- id: string;- name: string;- }[];- hasMore: boolean;- }>(- HttpMethod.GET,- `taskgroups?project_id=${project}&archived=false`,- accessToken,- undefined- )- ).body;+export async function listMembers({ auth, includeRemoved }: { auth: NiftyAuth; includeRemoved: boolean }): Promise<NiftyRecord[]> {+ const { items } = await niftyClient.listAll({ auth, path: 'members', key: 'items' });+ return items.filter((member) => includeRemoved || member['removed'] !== true).map(niftyClient.cleanMember);+}- return {- disabled: false,- options: response.items.map((list) => {- return {- label: list.name,- value: list.id,- };- }),- };- },- }),- milestone: Property.Dropdown({-auth:niftyAuth,- displayName: 'Milestone',- required: true,- refreshers: ['project'],- options: async ({ auth, project }) => {- const authentication = auth as OAuth2PropertyValue;- if (!authentication) {- return {- disabled: true,- placeholder: 'connect your account first',- options: [],- };- }- if (!project) {- return {- disabled: true,- placeholder: 'Select project first',- options: [],- };- }+function disabled(placeholder: string): DropdownState<string> {+ return { disabled: true, placeholder, options: [] };+}- const accessToken = authentication.access_token;+async function loadOptions({+ what,+ load,+ onForbidden,+}: {+ what: string;+ load: () => Promise<{ label: string; value: string }[]>;+ onForbidden?: string;+}): Promise<DropdownState<string>> {+ try {+ const options = await load();+ if (options.length === 0) {+ return { disabled: false, placeholder: `No ${what} found`, options: [] };+ }+ return { disabled: false, options };+ } catch (error) {+ if (onForbidden && error instanceof NiftyApiError && error.status === 403) {+ return disabled(onForbidden);+ }+ const reason = error instanceof Error ? error.message : String(error);+ return disabled(`Could not load ${what}: ${reason.slice(0, 200)}`);+ }+}- const response = (- await callNitfyApi<{- items: {- id: string;- name: string;- task_group: string;- }[];- hasMore: boolean;- }>(- HttpMethod.GET,- `milestones?project_id=${project}&is_list=true`,- accessToken,- undefined- )- ).body;+function projectLabel(project: NiftyRecord): string {+ const name = niftyClient.text({ record: project, key: 'name' });+ return project['archived'] === true ? `${name} (archived)` : name;+}- return {- disabled: false,- options: response.items.map((list) => {- return {- label: list.name,- value: list.id,- };- }),- };- },- }),-};+function taskLabel(task: NiftyRecord): string {+ const niceId = niftyClient.text({ record: task, key: 'nice_id' });+ const name = niftyClient.text({ record: task, key: 'name' });+ const base = niceId.length > 0 ? `${niceId} ${name}` : name;+ return task['completed'] === true ? `${base} (completed)` : base;+}-export async function callNitfyApi<T extends HttpMessageBody>(- method: HttpMethod,- apiUrl: string,- accessToken: string,- body: any | undefined-): Promise<HttpResponse<T>> {- return await httpClient.sendRequest<T>({- method: method,- url: `https://openapi.niftypm.com/api/v1.0/${apiUrl}`,- authentication: {- type: AuthenticationType.BEARER_TOKEN,- token: accessToken,- },- body: body,- });+function memberLabel(member: NiftyRecord): string {+ const name = niftyClient.text({ record: member, key: 'name' });+ const email = niftyClient.text({ record: member, key: 'email' });+ return email.length > 0 ? `${name} (${email})` : name;}diff --git a/packages/pieces/community/nifty/src/lib/common/operations.ts b/packages/pieces/community/nifty/src/lib/common/operations.tsnew file mode 100644index 00000000000..2c7900e67f1--- /dev/null+++ b/packages/pieces/community/nifty/src/lib/common/operations.ts@@ -0,0 +1,326 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { NiftyAuth, niftyClient, NiftyRecord } from './client';++export const niftyOps = {+ async createTask({ auth, input }: { auth: NiftyAuth; input: TaskCreateInput }): Promise<NiftyRecord> {+ const body = buildTaskCreateBody(input);+ return niftyClient.requestRecord({ auth, method: HttpMethod.POST, path: 'tasks', body });+ },++ async getTask({ auth, taskId }: { auth: NiftyAuth; taskId: unknown }): Promise<NiftyRecord> {+ const id = niftyClient.requireId({ value: taskId, label: 'Task ID' });+ return niftyClient.requestRecord({ auth, method: HttpMethod.GET, path: `tasks/${niftyClient.segment(id)}` });+ },++ async updateTask({ auth, input }: { auth: NiftyAuth; input: TaskUpdateInput }): Promise<NiftyRecord> {+ const id = niftyClient.requireId({ value: input.taskId, label: 'Task ID' });+ const body = buildTaskUpdateBody(input);+ const completion = parseCompletion(input.completion);+ if (Object.keys(body).length === 0 && completion === undefined) {+ throw new Error('Nothing to update: set at least one field, a clear option, or a completion change.');+ }+ if (Object.keys(body).length > 0) {+ await niftyClient.request({ auth, method: HttpMethod.PUT, path: `tasks/${niftyClient.segment(id)}`, body });+ }+ if (completion !== undefined) {+ await setCompletion({ auth, taskId: id, completed: completion });+ }+ return niftyOps.getTask({ auth, taskId: id });+ },++ async setTaskCompletion({ auth, taskId, completed }: { auth: NiftyAuth; taskId: unknown; completed: boolean }): Promise<NiftyRecord> {+ const id = niftyClient.requireId({ value: taskId, label: 'Task ID' });+ await setCompletion({ auth, taskId: id, completed });+ return niftyOps.getTask({ auth, taskId: id });+ },++ async deleteTask({ auth, taskId }: { auth: NiftyAuth; taskId: unknown }): Promise<{ id: string; deleted: boolean; message: string }> {+ const id = niftyClient.requireId({ value: taskId, label: 'Task' });+ const response = await niftyClient.request({ auth, method: HttpMethod.DELETE, path: `tasks/${niftyClient.segment(id)}` });+ const message = niftyClient.isRecord(response.body) ? niftyClient.text({ record: response.body, key: 'message' }) : '';+ return { id, deleted: true, message };+ },++ async changeAssignees({+ auth,+ taskId,+ memberIds,+ mode,+ }: {+ auth: NiftyAuth;+ taskId: unknown;+ memberIds: unknown;+ mode: 'add' | 'remove';+ }): Promise<{ task_id: string; member_ids: string[]; task: NiftyRecord }> {+ const id = niftyClient.requireId({ value: taskId, label: 'Task ID' });+ const ids = niftyClient.idList({ value: memberIds, label: 'Member ID' });+ if (ids.length === 0) {+ throw new Error('Give at least one member ID. Use List Members to find them.');+ }+ await niftyClient.request({+ auth,+ method: mode === 'add' ? HttpMethod.PUT : HttpMethod.DELETE,+ path: `tasks/${niftyClient.segment(id)}/assignees`,+ body: { assignees: ids },+ });+ const task = await niftyOps.getTask({ auth, taskId: id });+ return { task_id: id, member_ids: ids, task };+ },++ async createProject({ auth, input }: { auth: NiftyAuth; input: ProjectCreateInput }): Promise<NiftyRecord> {+ const body = dropUndefined({+ name: niftyClient.requireName({ value: input.name, label: 'Project name', max: 100 }),+ subteam_id: niftyClient.optionalId({ value: input.portfolioId, label: 'Portfolio ID' }),+ description: niftyClient.optionalText(input.description),+ access_type: parseChoice({ value: input.accessType, label: 'Access type', allowed: ACCESS_TYPES }),+ default_tasks_view: parseChoice({ value: input.defaultTasksView, label: 'Default tasks view', allowed: TASK_VIEWS }),+ });+ const project = await niftyClient.requestRecord({ auth, method: HttpMethod.POST, path: 'projects', body });+ return niftyClient.cleanProject(project);+ },++ async getProject({ auth, projectId }: { auth: NiftyAuth; projectId: unknown }): Promise<NiftyRecord> {+ const id = niftyClient.requireId({ value: projectId, label: 'Project ID' });+ const project = await niftyClient.requestRecord({ auth, method: HttpMethod.GET, path: `projects/${niftyClient.segment(id)}` });+ return niftyClient.cleanProject(project);+ },++ async updateProject({ auth, input }: { auth: NiftyAuth; input: ProjectUpdateInput }): Promise<NiftyRecord> {+ const id = niftyClient.requireId({ value: input.projectId, label: 'Project ID' });+ const archived = parseArchive(input.archive);+ const body = dropUndefined({+ name: niftyClient.optionalName({ value: input.name, label: 'Project name', max: 100 }),+ description: niftyClient.optionalText(input.description),+ access_type: parseChoice({ value: input.accessType, label: 'Access type', allowed: ACCESS_TYPES }),+ default_tasks_view: parseChoice({ value: input.defaultTasksView, label: 'Default tasks view', allowed: TASK_VIEWS }),+ archived: archived === undefined ? undefined : String(archived),+ });+ if (Object.keys(body).length === 0) {+ throw new Error('Nothing to update: set at least one field or an archive change.');+ }+ await niftyClient.request({ auth, method: HttpMethod.PUT, path: `projects/${niftyClient.segment(id)}`, body });+ return niftyOps.getProject({ auth, projectId: id });+ },++ async createMilestone({ auth, input }: { auth: NiftyAuth; input: MilestoneCreateInput }): Promise<NiftyRecord> {+ const projectId = niftyClient.requireId({ value: input.projectId, label: 'Project ID' });+ const name = niftyClient.requireName({ value: input.name, label: 'Name', max: 255 });+ const isList = input.createAsList === true;+ const start = niftyClient.optionalIsoDate({ value: input.start, label: 'Start date' });+ const end = niftyClient.optionalIsoDate({ value: input.end, label: 'End date' });+ if (!isList && (start === undefined || end === undefined)) {+ throw new Error('A milestone needs both a start date and an end date. To create a plain task list without dates, turn on "Create as list".');+ }+ if (start !== undefined && end !== undefined && Date.parse(start) > Date.parse(end)) {+ throw new Error('The start date must be on or before the end date.');+ }+ const body = dropUndefined({+ project_id: projectId,+ name,+ description: niftyClient.optionalText(input.description) ?? '',+ start,+ end,+ is_list: isList ? true : undefined,+ });+ const created = await niftyClient.requestRecord({ auth, method: HttpMethod.POST, path: 'milestones', body });+ const id = niftyClient.text({ record: created, key: 'id' });+ if (id.length === 0) {+ throw new Error(`Nifty did not return the new milestone ID: ${JSON.stringify(created).slice(0, 200)}`);+ }+ try {+ return await niftyClient.requestRecord({ auth, method: HttpMethod.GET, path: `milestones/${niftyClient.segment(id)}` });+ } catch (error) {+ return {+ id,+ name,+ project: projectId,+ is_list: isList,+ start: start ?? null,+ end: end ?? null,+ read_back_error: error instanceof Error ? error.message : String(error),+ };+ }+ },++ buildTaskCreateBody,+};++function buildTaskCreateBody(input: TaskCreateInput): Record<string, unknown> {+ const assignees = niftyClient.idList({ value: input.assigneeIds, label: 'Assignee ID' });+ const start = niftyClient.optionalIsoDate({ value: input.startDate, label: 'Start date' });+ const due = niftyClient.optionalIsoDate({ value: input.dueDate, label: 'Due date' });+ assertDateOrder({ start, due });+ return dropUndefined({+ name: niftyClient.requireName({ value: input.name, label: 'Task name', max: 1024 }),+ task_group_id: niftyClient.requireId({ value: input.statusId, label: 'Status ID' }),+ description: niftyClient.optionalText(input.description),+ milestone_id: niftyClient.optionalId({ value: input.milestoneId, label: 'Milestone ID' }),+ task_id: niftyClient.optionalId({ value: input.parentTaskId, label: 'Parent task ID' }),+ start_date: start,+ due_date: due,+ story_points: niftyClient.optionalNumber({ value: input.storyPoints, label: 'Story points', min: 0, max: 1000, integer: false }),+ assignees: assignees.length > 0 ? assignees : undefined,+ });+}++function buildTaskUpdateBody(input: TaskUpdateInput): Record<string, unknown> {+ const start = niftyClient.optionalIsoDate({ value: input.startDate, label: 'Start date' });+ const due = niftyClient.optionalIsoDate({ value: input.dueDate, label: 'Due date' });+ const description = niftyClient.optionalText(input.description);+ assertNotBoth({ value: description, clear: input.clearDescription, label: 'Description' });+ assertNotBoth({ value: start, clear: input.clearStartDate, label: 'Start date' });+ assertNotBoth({ value: due, clear: input.clearDueDate, label: 'Due date' });+ assertDateOrder({ start, due });+ return dropUndefined({+ name: niftyClient.optionalName({ value: input.name, label: 'Task name', max: 1024 }),+ description: input.clearDescription === true ? '' : description,+ task_group_id: niftyClient.optionalId({ value: input.statusId, label: 'Status ID' }),+ milestone_id: niftyClient.optionalId({ value: input.milestoneId, label: 'Milestone ID' }),+ start_date: input.clearStartDate === true ? null : start,+ due_date: input.clearDueDate === true ? null : due,+ story_points: niftyClient.optionalNumber({ value: input.storyPoints, label: 'Story points', min: 0, max: 1000, integer: false }),+ });+}++async function setCompletion({ auth, taskId, completed }: { auth: NiftyAuth; taskId: string; completed: boolean }): Promise<void> {+ await niftyClient.request({+ auth,+ method: HttpMethod.POST,+ path: `tasks/${niftyClient.segment(taskId)}/complete`,+ body: { completed },+ });+}++function parseCompletion(value: unknown): boolean | undefined {+ if (value === undefined || value === null || value === '' || value === 'unchanged') {+ return undefined;+ }+ if (value === 'complete') {+ return true;+ }+ if (value === 'reopen') {+ return false;+ }+ throw new Error(`Completion must be "unchanged", "complete" or "reopen", got "${String(value)}".`);+}++function parseArchive(value: unknown): boolean | undefined {+ if (value === undefined || value === null || value === '' || value === 'unchanged') {+ return undefined;+ }+ if (value === 'archive') {+ return true;+ }+ if (value === 'unarchive') {+ return false;+ }+ throw new Error(`Archive must be "unchanged", "archive" or "unarchive", got "${String(value)}".`);+}++function parseChoice({ value, label, allowed }: { value: unknown; label: string; allowed: readonly string[] }): string | undefined {+ if (value === undefined || value === null || value === '') {+ return undefined;+ }+ const choice = typeof value === 'string' ? value.trim() : '';+ if (!allowed.includes(choice)) {+ throw new Error(`${label} must be one of ${allowed.join(', ')}, got "${String(value)}".`);+ }+ return choice;+}++function assertNotBoth({ value, clear, label }: { value: unknown; clear: unknown; label: string }): void {+ if (value !== undefined && clear === true) {+ throw new Error(`${label}: either give a new value or turn on the clear option, not both.`);+ }+}++function assertDateOrder({ start, due }: { start: string | undefined; due: string | undefined }): void {+ if (start !== undefined && due !== undefined && Date.parse(start) > Date.parse(due)) {+ throw new Error('The start date must be on or before the due date.');+ }+}++function dropUndefined(record: Record<string, unknown>): Record<string, unknown> {+ return Object.fromEntries(Object.entries(record).filter(([, value]) => value !== undefined));+}++const ACCESS_TYPES = ['public', 'limited', 'workspace'] as const;+const TASK_VIEWS = ['table', 'kanban', 'swimlane', 'timeline'] as const;++export const NIFTY_ACCESS_TYPE_OPTIONS = [+ { label: 'Public (everyone in the workspace can find and join)', value: 'public' },+ { label: 'Workspace (every workspace member is a member)', value: 'workspace' },+ { label: 'Limited (only invited members)', value: 'limited' },+];++export const NIFTY_TASK_VIEW_OPTIONS = [+ { label: 'Table', value: 'table' },+ { label: 'Kanban', value: 'kanban' },+ { label: 'Swimlane', value: 'swimlane' },+ { label: 'Timeline', value: 'timeline' },+];++export const NIFTY_ARCHIVE_OPTIONS = [+ { label: 'Leave unchanged', value: 'unchanged' },+ { label: 'Archive', value: 'archive' },+ { label: 'Unarchive', value: 'unarchive' },+];++export const NIFTY_COMPLETION_OPTIONS = [+ { label: 'Leave unchanged', value: 'unchanged' },+ { label: 'Mark complete', value: 'complete' },+ { label: 'Reopen', value: 'reopen' },+];++export type TaskCreateInput = {+ statusId: unknown;+ name: unknown;+ description?: unknown;+ milestoneId?: unknown;+ parentTaskId?: unknown;+ startDate?: unknown;+ dueDate?: unknown;+ storyPoints?: unknown;+ assigneeIds?: unknown;+};++export type TaskUpdateInput = {+ taskId: unknown;+ name?: unknown;+ description?: unknown;+ clearDescription?: unknown;+ statusId?: unknown;+ milestoneId?: unknown;+ startDate?: unknown;+ clearStartDate?: unknown;+ dueDate?: unknown;+ clearDueDate?: unknown;+ storyPoints?: unknown;+ completion?: unknown;+};++export type ProjectCreateInput = {+ name: unknown;+ portfolioId?: unknown;+ description?: unknown;+ accessType?: unknown;+ defaultTasksView?: unknown;+};++export type ProjectUpdateInput = {+ projectId: unknown;+ name?: unknown;+ description?: unknown;+ accessType?: unknown;+ defaultTasksView?: unknown;+ archive?: unknown;+};++export type MilestoneCreateInput = {+ projectId: unknown;+ name: unknown;+ description?: unknown;+ start?: unknown;+ end?: unknown;+ createAsList?: unknown;+};diff --git a/packages/pieces/community/nifty/src/lib/common/polling.ts b/packages/pieces/community/nifty/src/lib/common/polling.tsnew file mode 100644index 00000000000..aadc96172eb--- /dev/null+++ b/packages/pieces/community/nifty/src/lib/common/polling.ts@@ -0,0 +1,208 @@+import { NiftyAuth, niftyClient, NiftyRecord } from './client';++export const niftyPolling = {+ fingerprint({ values }: { values: Array<string | boolean | null> }): string {+ return JSON.stringify(values);+ },++ readTimeState({ value, fp }: { value: unknown; fp: string }): TimeState | null {+ if (typeof value !== 'object' || value === null) {+ return null;+ }+ if (!('fp' in value) || value.fp !== fp || !('cp' in value) || typeof value.cp !== 'string') {+ return null;+ }+ if (!('seen' in value) || !isStringArray(value.seen)) {+ return null;+ }+ return { fp, cp: value.cp, seen: value.seen };+ },++ readIdState({ value, fp }: { value: unknown; fp: string }): IdState | null {+ if (typeof value !== 'object' || value === null || !('fp' in value) || value.fp !== fp) {+ return null;+ }+ if (!('known' in value) || !isStringArray(value.known) || !('dropped' in value) || !isStringArray(value.dropped)) {+ return null;+ }+ return { fp, known: value.known, dropped: value.dropped };+ },++ advanceTimeCursor({+ cursor,+ items,+ timeOf,+ keyOf,+ }: {+ cursor: TimeCursor;+ items: NiftyRecord[];+ timeOf: (item: NiftyRecord) => string;+ keyOf: (item: NiftyRecord) => string;+ }): { emit: NiftyRecord[]; cursor: TimeCursor } {+ const checkpoint = Date.parse(cursor.cp);+ const seen = new Set(cursor.seen);+ const unique = new Map<string, NiftyRecord>();+ for (const item of items) {+ const time = Date.parse(timeOf(item));+ if (Number.isNaN(time)) {+ continue;+ }+ const key = keyOf(item);+ const isNew = time > checkpoint || (time === checkpoint && !seen.has(key));+ if (isNew && !unique.has(key)) {+ unique.set(key, item);+ }+ }+ const emit = [...unique.values()].sort((a, b) => Date.parse(timeOf(a)) - Date.parse(timeOf(b)));+ if (emit.length === 0) {+ return { emit, cursor: { cp: cursor.cp, seen: cursor.seen } };+ }+ const newest = Date.parse(timeOf(emit[emit.length - 1]));+ const atNewest = emit.filter((item) => Date.parse(timeOf(item)) === newest).map(keyOf);+ const carried = newest === checkpoint ? cursor.seen : [];+ return {+ emit,+ cursor: {+ cp: new Date(newest).toISOString(),+ seen: [...carried, ...atNewest].slice(-MAX_SEEN),+ },+ };+ },++ coverScannedWindow({ cursor, scannedTo }: { cursor: TimeCursor; scannedTo: string }): TimeCursor {+ const covered = Date.parse(scannedTo) - 1;+ if (Date.parse(cursor.cp) >= covered) {+ return cursor;+ }+ return { cp: new Date(covered).toISOString(), seen: [] };+ },++ seedTimeCursor({+ items,+ timeOf,+ keyOf,+ now,+ }: {+ items: NiftyRecord[];+ timeOf: (item: NiftyRecord) => string;+ keyOf: (item: NiftyRecord) => string;+ now: string;+ }): TimeCursor {+ const times = items.map((item) => Date.parse(timeOf(item))).filter((t) => !Number.isNaN(t));+ if (times.length === 0) {+ return { cp: now, seen: [] };+ }+ const newest = times.reduce((max, t) => (t > max ? t : max), times[0]);+ return {+ cp: new Date(newest).toISOString(),+ seen: items+ .filter((item) => Date.parse(timeOf(item)) === newest)+ .map(keyOf)+ .slice(-MAX_SEEN),+ };+ },++ advanceIdSet({+ known,+ dropped,+ items,+ truncated,+ }: {+ known: string[];+ dropped: string[];+ items: NiftyRecord[];+ truncated: boolean;+ }): { emit: NiftyRecord[]; known: string[]; dropped: string[] } {+ const remembered = new Set([...known, ...dropped]);+ const visible: string[] = [];+ const visibleSet = new Set<string>();+ const emit: NiftyRecord[] = [];+ for (const item of items) {+ const id = niftyClient.text({ record: item, key: 'id' });+ if (id.length === 0 || visibleSet.has(id)) {+ continue;+ }+ visibleSet.add(id);+ visible.push(id);+ if (!remembered.has(id)) {+ emit.push(item);+ }+ }+ if (truncated) {+ const emittedIds = emit.map((item) => niftyClient.text({ record: item, key: 'id' }));+ return { emit, known: [...known, ...emittedIds].slice(-MAX_KNOWN_IDS), dropped };+ }+ const nowDropped = known.filter((id) => !visibleSet.has(id));+ const stillDropped = dropped.filter((id) => !visibleSet.has(id));+ return { emit, known: visible, dropped: [...stillDropped, ...nowDropped].slice(-MAX_DROPPED_IDS) };+ },++ async readWindow({+ from,+ to,+ fetchWindow,+ }: {+ from: string;+ to: string;+ fetchWindow: (window: { from: string; to: string }) => Promise<{ items: NiftyRecord[]; truncated: boolean }>;+ }): Promise<{ items: NiftyRecord[]; scannedTo: string; narrowed: boolean }> {+ const start = Date.parse(from);+ let end = Date.parse(to);+ for (let step = 0; step < MAX_NARROWING_STEPS; step++) {+ const windowEnd = new Date(end).toISOString();+ const result = await fetchWindow({ from, to: windowEnd });+ if (!result.truncated) {+ return { items: result.items, scannedTo: windowEnd, narrowed: step > 0 };+ }+ const span = end - start;+ if (span <= MIN_WINDOW_MS) {+ break;+ }+ end = start + Math.floor(span / 2);+ }+ throw new Error(+ `Nifty returned more than ${niftyClient.PAGE_SIZE * niftyClient.MAX_PAGES} completed tasks in one second after ${from}, so they cannot all be read. No completions were skipped; the trigger will retry on the next poll.`+ );+ },++ async fetchTasks({+ auth,+ projectId,+ includeSubtasks,+ extraQuery,+ }: {+ auth: NiftyAuth;+ projectId: string | undefined;+ includeSubtasks: boolean;+ extraQuery?: Record<string, string | number | boolean | undefined>;+ }): Promise<{ items: NiftyRecord[]; truncated: boolean }> {+ const { items, truncated } = await niftyClient.listAll({+ auth,+ path: 'tasks',+ key: 'tasks',+ query: {+ project_id: projectId,+ include_subtasks: projectId !== undefined && includeSubtasks ? true : undefined,+ ...extraQuery,+ },+ });+ return {+ items: items.filter((task) => includeSubtasks || niftyClient.text({ record: task, key: 'task' }).length === 0),+ truncated,+ };+ },+};++function isStringArray(value: unknown): value is string[] {+ return Array.isArray(value) && value.every((item) => typeof item === 'string');+}++const MAX_SEEN = 200;+const MAX_KNOWN_IDS = 20000;+const MAX_DROPPED_IDS = 1000;+const MAX_NARROWING_STEPS = 40;+const MIN_WINDOW_MS = 1000;++export type TimeCursor = { cp: string; seen: string[] };+export type TimeState = TimeCursor & { fp: string };+export type IdState = { fp: string; known: string[]; dropped: string[] };diff --git a/packages/pieces/community/nifty/src/lib/output-schemas.ts b/packages/pieces/community/nifty/src/lib/output-schemas.tsnew file mode 100644index 00000000000..8e378c12163--- /dev/null+++ b/packages/pieces/community/nifty/src/lib/output-schemas.ts@@ -0,0 +1,138 @@+import { OutputSchema, OutputSchemaField } from '@activepieces/pieces-framework';++const taskFields: OutputSchemaField[] = [+ { key: 'id', label: 'Task ID' },+ { key: 'nice_id', label: 'Task Key', description: 'Short project-prefixed key shown in Nifty, e.g. ANP-1.' },+ { key: 'name', label: 'Name' },+ { key: 'description', label: 'Description' },+ { key: 'project', label: 'Project ID' },+ { key: 'task_group', label: 'Status ID', description: 'The status (board column) the task is in.' },+ { key: 'milestone', label: 'Milestone or List ID', description: 'Not present on subtasks.' },+ { key: 'task', label: 'Parent Task ID', description: 'Only present on subtasks.' },+ { key: 'completed', label: 'Completed', format: 'boolean' },+ { key: 'completed_on', label: 'Completed On', format: 'datetime', description: 'Only present on completed tasks.' },+ { key: 'completed_by', label: 'Completed By (Member ID)', description: 'Only present on completed tasks.' },+ { key: 'archived', label: 'Archived', format: 'boolean' },+ { key: 'start_date', label: 'Start Date', format: 'datetime' },+ { key: 'due_date', label: 'Due Date', format: 'datetime' },+ { key: 'story_points', label: 'Story Points' },+ { key: 'assignees', label: 'Assignee IDs' },+ { key: 'labels', label: 'Label IDs' },+ { key: 'subscribers', label: 'Subscriber IDs' },+ { key: 'total_subtasks', label: 'Subtasks', format: 'number', description: 'Not present on subtasks.' },+ { key: 'completed_subtasks', label: 'Completed Subtasks', format: 'number', description: 'Not present on subtasks.' },+ { key: 'comments', label: 'Comments', format: 'number' },+ { key: 'created_at', label: 'Created At', format: 'datetime' },+ { key: 'created_by', label: 'Created By (Member ID)' },+];++const projectFields: OutputSchemaField[] = [+ { key: 'id', label: 'Project ID' },+ { key: 'nice_id', label: 'Project Key' },+ { key: 'name', label: 'Name' },+ { key: 'description', label: 'Description' },+ { key: 'subteam', label: 'Portfolio ID' },+ { key: 'access_type', label: 'Access Type' },+ { key: 'default_tasks_view', label: 'Default Tasks View' },+ { key: 'archived', label: 'Archived', format: 'boolean' },+ { key: 'owner', label: 'Owner (Member ID)' },+ { key: 'progress', label: 'Progress', format: 'number', description: 'Share of completed tasks, from 0 to 1.' },+ { key: 'total_story_points', label: 'Total Story Points', format: 'number' },+ { key: 'completed_story_points', label: 'Completed Story Points', format: 'number' },+ { key: 'email', label: 'Project Email', format: 'email', description: 'Email address that forwards messages into the project discussion.' },+ { key: 'color', label: 'Color' },+];++const milestoneFields: OutputSchemaField[] = [+ { key: 'id', label: 'Milestone or List ID' },+ { key: 'name', label: 'Name' },+ { key: 'description', label: 'Description' },+ { key: 'is_list', label: 'Is Plain List', format: 'boolean', description: 'True for a task list without dates, false for a dated milestone.' },+ { key: 'project', label: 'Project ID' },+ { key: 'start', label: 'Start', format: 'datetime' },+ { key: 'end', label: 'End', format: 'datetime' },+ { key: 'archived', label: 'Archived', format: 'boolean' },+ { key: 'created_at', label: 'Created At', format: 'datetime' },+ { key: 'created_by', label: 'Created By (Member ID)' },+ {+ key: 'statistic',+ label: 'Task Statistics',+ children: [+ { key: 'total', label: 'Total Tasks', format: 'number' },+ { key: 'completed', label: 'Completed Tasks', format: 'number' },+ { key: 'overdue', label: 'Overdue Tasks', format: 'number' },+ ],+ },+];++const statusFields: OutputSchemaField[] = [+ { key: 'id', label: 'Status ID' },+ { key: 'name', label: 'Name' },+ { key: 'project', label: 'Project ID' },+ { key: 'order', label: 'Order', format: 'number' },+ { key: 'color', label: 'Color' },+];++const memberFields: OutputSchemaField[] = [+ { key: 'id', label: 'Member ID', description: 'Use this ID for assignees.' },+ { key: 'name', label: 'Name' },+ { key: 'email', label: 'Email', format: 'email' },+ { key: 'initials', label: 'Initials' },+ { key: 'role', label: 'Role' },+ { key: 'pending', label: 'Invite Pending', format: 'boolean' },+ { key: 'removed', label: 'Removed', format: 'boolean' },+];++export const taskOutputSchema: OutputSchema = { fields: taskFields };++export const createTaskArrayOutputSchema: OutputSchema = {+ fields: [{ key: 'task', label: 'Created Task', value: '', listItems: taskFields }],+ itemLabel: '{name}',+};++export const projectOutputSchema: OutputSchema = { fields: projectFields };++export const milestoneOutputSchema: OutputSchema = { fields: milestoneFields };++export const deleteTaskOutputSchema: OutputSchema = {+ fields: [+ { key: 'id', label: 'Deleted Task ID' },+ { key: 'deleted', label: 'Deleted', format: 'boolean' },+ { key: 'message', label: 'Message' },+ ],+};++export const assigneesOutputSchema: OutputSchema = {+ fields: [+ { key: 'task_id', label: 'Task ID' },+ { key: 'member_ids', label: 'Member IDs Sent' },+ { key: 'task', label: 'Task (after the change)', children: taskFields },+ ],+};++export const findTasksOutputSchema: OutputSchema = {+ fields: [+ { key: 'items', label: 'Tasks', labelKey: 'name', listItems: taskFields },+ { key: 'has_more', label: 'More Pages', format: 'boolean', description: 'True when this page was full. Call again with next_offset to read the next page; the next page can be empty.' },+ { key: 'next_offset', label: 'Next Offset', format: 'number' },+ ],+};++export const findProjectsOutputSchema: OutputSchema = {+ fields: [+ { key: 'items', label: 'Projects', labelKey: 'name', listItems: projectFields },+ { key: 'truncated', label: 'Truncated', format: 'boolean', description: 'True when the workspace has more projects than one call can read; narrow with a portfolio.' },+ ],+};++export const listStatusesOutputSchema: OutputSchema = {+ fields: [{ key: 'items', label: 'Statuses', labelKey: 'name', listItems: statusFields }],+};++export const listMilestonesOutputSchema: OutputSchema = {+ fields: [{ key: 'items', label: 'Milestones and Lists', labelKey: 'name', listItems: milestoneFields }],+};++export const listMembersOutputSchema: OutputSchema = {+ fields: [{ key: 'items', label: 'Members', labelKey: 'name', listItems: memberFields }],+};diff --git a/packages/pieces/community/nifty/src/lib/triggers/new-project.ts b/packages/pieces/community/nifty/src/lib/triggers/new-project.tsnew file mode 100644index 00000000000..2a3c1bebbff--- /dev/null+++ b/packages/pieces/community/nifty/src/lib/triggers/new-project.ts@@ -0,0 +1,85 @@+import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';+import { niftyAuth } from '../auth';+import { niftyProps } from '../common';+import { NiftyAuth, niftyClient, NiftyRecord } from '../common/client';+import { IdState, niftyPolling } from '../common/polling';+import { projectOutputSchema } from '../output-schemas';+import { PROJECT_SAMPLE } from './sample-data';++export const newProject = createTrigger({+ auth: niftyAuth,+ name: 'new_project',+ displayName: 'New Project',+ description: 'Triggers when a new project appears in your Nifty workspace.',+ classification: 'READ',+ aiMetadata: {+ description:+ 'Fires once per Nifty project that newly appears in the list the connection can see, optionally only in one portfolio, including projects you are newly added to. Projects that already existed when the flow was turned on do not fire.',+ },+ props: {+ portfolio: niftyProps.portfolio({ required: false }),+ },+ outputSchema: projectOutputSchema,+ sampleData: PROJECT_SAMPLE,+ type: TriggerStrategy.POLLING,+ async onEnable(context) {+ const fp = fingerprintOf({ portfolio: context.propsValue.portfolio });+ const stored = niftyPolling.readIdState({ value: await context.store.get<unknown>(KNOWN_KEY), fp });+ if (context.isRepublish && stored) {+ return;+ }+ await context.store.put(KNOWN_KEY, await seed({ auth: context.auth, portfolio: context.propsValue.portfolio }));+ },+ async onDisable() {+ return;+ },+ async test(context) {+ const { items } = await fetchProjects({ auth: context.auth, portfolio: context.propsValue.portfolio });+ return items.slice(-5).reverse();+ },+ async run(context) {+ const fp = fingerprintOf({ portfolio: context.propsValue.portfolio });+ const stored = niftyPolling.readIdState({ value: await context.store.get<unknown>(KNOWN_KEY), fp });+ if (!stored) {+ await context.store.put(KNOWN_KEY, await seed({ auth: context.auth, portfolio: context.propsValue.portfolio }));+ return [];+ }+ const { items, truncated } = await fetchProjects({ auth: context.auth, portfolio: context.propsValue.portfolio });+ const result = niftyPolling.advanceIdSet({ known: stored.known, dropped: stored.dropped, items, truncated });+ const next: IdState = { fp, known: result.known, dropped: result.dropped };+ await context.store.put(KNOWN_KEY, next);+ return result.emit;+ },+});++async function seed({ auth, portfolio }: { auth: NiftyAuth; portfolio: string | undefined }): Promise<IdState> {+ const { items } = await fetchProjects({ auth, portfolio });+ return {+ fp: fingerprintOf({ portfolio }),+ known: items.map((p) => niftyClient.text({ record: p, key: 'id' })).filter((id) => id.length > 0),+ dropped: [],+ };+}++async function fetchProjects({+ auth,+ portfolio,+}: {+ auth: NiftyAuth;+ portfolio: string | undefined;+}): Promise<{ items: NiftyRecord[]; truncated: boolean }> {+ const portfolioId = niftyClient.optionalId({ value: portfolio, label: 'Portfolio' });+ const { items, truncated } = await niftyClient.listAll({ auth, path: 'projects', key: 'projects', query: { subteam_id: portfolioId } });+ return {+ items: items+ .filter((project) => portfolioId === undefined || niftyClient.text({ record: project, key: 'subteam' }) === portfolioId)+ .map(niftyClient.cleanProject),+ truncated,+ };+}++function fingerprintOf({ portfolio }: { portfolio: string | undefined }): string {+ return niftyPolling.fingerprint({ values: [niftyClient.optionalId({ value: portfolio, label: 'Portfolio' }) ?? null] });+}++const KNOWN_KEY = 'nifty_new_project_known_ids';diff --git a/packages/pieces/community/nifty/src/lib/triggers/new-task.ts b/packages/pieces/community/nifty/src/lib/triggers/new-task.tsnew file mode 100644index 00000000000..7bc0a8c8c9b--- /dev/null+++ b/packages/pieces/community/nifty/src/lib/triggers/new-task.ts@@ -0,0 +1,96 @@+import { createTrigger, Property, TriggerStrategy } from '@activepieces/pieces-framework';+import { niftyAuth } from '../auth';+import { niftyProps } from '../common';+import { NiftyAuth, niftyClient, NiftyRecord } from '../common/client';+import { niftyPolling, TimeState } from '../common/polling';+import { taskOutputSchema } from '../output-schemas';+import { TASK_SAMPLE } from './sample-data';++export const newTask = createTrigger({+ auth: niftyAuth,+ name: 'new_task',+ displayName: 'New Task',+ description: 'Triggers when a task is created, in one project or in any project you can see.',+ classification: 'READ',+ aiMetadata: {+ description:+ 'Fires once per newly created Nifty task, either in one chosen project or across every project the connection can see; subtasks are only seen when a project is chosen. Polls the task list and remembers the newest creation time, so tasks created while the flow was off are not replayed.',+ },+ props: {+ portfolio: niftyProps.portfolio({ required: false }),+ project: niftyProps.project({+ required: false,+ description: 'Optional. Leave empty to watch every project (subtasks are then not included).',+ }),+ include_subtasks: Property.Checkbox({+ displayName: 'Include Subtasks',+ description: 'Also trigger for new subtasks. Only works when a project is selected.',+ required: false,+ defaultValue: true,+ }),+ },+ outputSchema: taskOutputSchema,+ sampleData: TASK_SAMPLE,+ type: TriggerStrategy.POLLING,+ async onEnable(context) {+ const fp = fingerprintOf({ propsValue: context.propsValue });+ const stored = niftyPolling.readTimeState({ value: await context.store.get<unknown>(CURSOR_KEY), fp });+ if (context.isRepublish && stored) {+ return;+ }+ await context.store.put(CURSOR_KEY, await seed({ auth: context.auth, propsValue: context.propsValue }));+ },+ async onDisable() {+ return;+ },+ async test(context) {+ const { items } = await loadTasks({ auth: context.auth, propsValue: context.propsValue });+ return [...items].sort((a, b) => Date.parse(createdAt(b)) - Date.parse(createdAt(a))).slice(0, 5);+ },+ async run(context) {+ const fp = fingerprintOf({ propsValue: context.propsValue });+ const stored = niftyPolling.readTimeState({ value: await context.store.get<unknown>(CURSOR_KEY), fp });+ if (!stored) {+ await context.store.put(CURSOR_KEY, await seed({ auth: context.auth, propsValue: context.propsValue }));+ return [];+ }+ const { items } = await loadTasks({ auth: context.auth, propsValue: context.propsValue });+ const { emit, cursor } = niftyPolling.advanceTimeCursor({ cursor: stored, items, timeOf: createdAt, keyOf: idOf });+ await context.store.put(CURSOR_KEY, { ...cursor, fp });+ return emit;+ },+});++async function loadTasks({ auth, propsValue }: { auth: NiftyAuth; propsValue: TriggerProps }): Promise<{ items: NiftyRecord[]; truncated: boolean }> {+ return niftyPolling.fetchTasks({+ auth,+ projectId: projectIdOf({ propsValue }),+ includeSubtasks: propsValue.include_subtasks !== false,+ });+}++async function seed({ auth, propsValue }: { auth: NiftyAuth; propsValue: TriggerProps }): Promise<TimeState> {+ const { items } = await loadTasks({ auth, propsValue });+ const cursor = niftyPolling.seedTimeCursor({ items, timeOf: createdAt, keyOf: idOf, now: new Date().toISOString() });+ return { ...cursor, fp: fingerprintOf({ propsValue }) };+}++function projectIdOf({ propsValue }: { propsValue: TriggerProps }): string | undefined {+ return niftyClient.optionalId({ value: propsValue.project, label: 'Project' });+}++function fingerprintOf({ propsValue }: { propsValue: TriggerProps }): string {+ return niftyPolling.fingerprint({ values: [projectIdOf({ propsValue }) ?? null, propsValue.include_subtasks !== false] });+}++function createdAt(task: NiftyRecord): string {+ return niftyClient.text({ record: task, key: 'created_at' });+}++function idOf(task: NiftyRecord): string {+ return niftyClient.text({ record: task, key: 'id' });+}++const CURSOR_KEY = 'nifty_new_task_cursor';++type TriggerProps = { project?: string; include_subtasks?: boolean };diff --git a/packages/pieces/community/nifty/src/lib/triggers/sample-data.ts b/packages/pieces/community/nifty/src/lib/triggers/sample-data.tsnew file mode 100644index 00000000000..ca465c977cb--- /dev/null+++ b/packages/pieces/community/nifty/src/lib/triggers/sample-data.ts@@ -0,0 +1,46 @@+export const TASK_SAMPLE = {+ id: 'HjGDVlaejN',+ nice_id: 'ANP-1',+ name: 'Prepare launch checklist',+ description: 'List everything we need before launch.',+ created_at: '2026-10-05T13:04:32.278Z',+ created_by: '81wbAVYMye',+ archived: false,+ completed: false,+ due_date: '2026-10-20T00:00:00.000Z',+ start_date: '2026-10-06T00:00:00.000Z',+ task_group: 'jiA!cEfY03',+ project: 'mvxI3LynBI',+ milestone: 'JSkRUQiJ_6',+ assignees: ['81wbAVYMye'],+ subscribers: ['81wbAVYMye'],+ labels: [],+ total_subtasks: 0,+ completed_subtasks: 0,+ comments: 0,+ story_points: '3',+};++export const COMPLETED_TASK_SAMPLE = {+ ...TASK_SAMPLE,+ completed: true,+ completed_on: '2026-10-05T13:04:59.623Z',+ completed_by: '81wbAVYMye',+};++export const PROJECT_SAMPLE = {+ id: 'mvxI3LynBI',+ nice_id: 'ANP',+ name: 'Website Relaunch',+ description: 'Everything for the new website.',+ color: '#FF735F',+ archived: false,+ default_tasks_view: 'table',+ access_type: 'public',+ owner: '81wbAVYMye',+ subteam: 'heSYcmGCH2',+ progress: 0,+ total_story_points: 0,+ completed_story_points: 0,+ email: '[email protected]',+};diff --git a/packages/pieces/community/nifty/src/lib/triggers/task-completed.ts b/packages/pieces/community/nifty/src/lib/triggers/task-completed.tsnew file mode 100644index 00000000000..beb5ede7d68--- /dev/null+++ b/packages/pieces/community/nifty/src/lib/triggers/task-completed.ts@@ -0,0 +1,113 @@+import { createTrigger, Property, TriggerStrategy } from '@activepieces/pieces-framework';+import { niftyAuth } from '../auth';+import { niftyProps } from '../common';+import { NiftyAuth, niftyClient, NiftyRecord } from '../common/client';+import { niftyPolling, TimeState } from '../common/polling';+import { taskOutputSchema } from '../output-schemas';+import { COMPLETED_TASK_SAMPLE } from './sample-data';++export const taskCompleted = createTrigger({+ auth: niftyAuth,+ name: 'task_completed',+ displayName: 'Task Completed',+ description: 'Triggers when a task is marked complete.',+ classification: 'READ',+ aiMetadata: {+ description:+ 'Fires once per Nifty task completion, in one chosen project or across every project the connection can see; subtasks are only seen when a project is chosen. A task that is reopened and completed again fires again. Completions that happened while the flow was off are not replayed.',+ },+ props: {+ portfolio: niftyProps.portfolio({ required: false }),+ project: niftyProps.project({+ required: false,+ description: 'Optional. Leave empty to watch every project (subtasks are then not included).',+ }),+ include_subtasks: Property.Checkbox({+ displayName: 'Include Subtasks',+ description: 'Also trigger for completed subtasks. Only works when a project is selected.',+ required: false,+ defaultValue: true,+ }),+ },+ outputSchema: taskOutputSchema,+ sampleData: COMPLETED_TASK_SAMPLE,+ type: TriggerStrategy.POLLING,+ async onEnable(context) {+ const fp = fingerprintOf({ propsValue: context.propsValue });+ const stored = niftyPolling.readTimeState({ value: await context.store.get<unknown>(CURSOR_KEY), fp });+ if (context.isRepublish && stored) {+ return;+ }+ await context.store.put(CURSOR_KEY, await seed({ auth: context.auth, propsValue: context.propsValue }));+ },+ async onDisable() {+ return;+ },+ async test(context) {+ const { items } = await fetchCompleted({ auth: context.auth, propsValue: context.propsValue, window: undefined });+ return [...items].sort((a, b) => Date.parse(completedOn(b)) - Date.parse(completedOn(a))).slice(0, 5);+ },+ async run(context) {+ const fp = fingerprintOf({ propsValue: context.propsValue });+ const stored = niftyPolling.readTimeState({ value: await context.store.get<unknown>(CURSOR_KEY), fp });+ if (!stored) {+ await context.store.put(CURSOR_KEY, await seed({ auth: context.auth, propsValue: context.propsValue }));+ return [];+ }+ const scan = await niftyPolling.readWindow({+ from: stored.cp,+ to: new Date(Date.now() + WINDOW_AHEAD_MS).toISOString(),+ fetchWindow: (window) => fetchCompleted({ auth: context.auth, propsValue: context.propsValue, window }),+ });+ const { emit, cursor } = niftyPolling.advanceTimeCursor({ cursor: stored, items: scan.items, timeOf: completedOn, keyOf: completionKey });+ const next = scan.narrowed ? niftyPolling.coverScannedWindow({ cursor, scannedTo: scan.scannedTo }) : cursor;+ await context.store.put(CURSOR_KEY, { ...next, fp });+ return emit;+ },+});++async function fetchCompleted({+ auth,+ propsValue,+ window,+}: {+ auth: NiftyAuth;+ propsValue: TriggerProps;+ window: { from: string; to: string } | undefined;+}): Promise<{ items: NiftyRecord[]; truncated: boolean }> {+ const range = window === undefined ? {} : { completed_from: window.from, completed_to: window.to };+ const { items, truncated } = await niftyPolling.fetchTasks({+ auth,+ projectId: projectIdOf({ propsValue }),+ includeSubtasks: propsValue.include_subtasks !== false,+ extraQuery: { completed: true, order: 'completedOn:DESC', ...range },+ });+ return { items: items.filter((task) => task['completed'] === true), truncated };+}++async function seed({ auth, propsValue }: { auth: NiftyAuth; propsValue: TriggerProps }): Promise<TimeState> {+ const { items } = await fetchCompleted({ auth, propsValue, window: undefined });+ const cursor = niftyPolling.seedTimeCursor({ items, timeOf: completedOn, keyOf: completionKey, now: new Date().toISOString() });+ return { ...cursor, fp: fingerprintOf({ propsValue }) };+}++function projectIdOf({ propsValue }: { propsValue: TriggerProps }): string | undefined {+ return niftyClient.optionalId({ value: propsValue.project, label: 'Project' });+}++function fingerprintOf({ propsValue }: { propsValue: TriggerProps }): string {+ return niftyPolling.fingerprint({ values: [projectIdOf({ propsValue }) ?? null, propsValue.include_subtasks !== false] });+}++function completedOn(task: NiftyRecord): string {+ return niftyClient.text({ record: task, key: 'completed_on' });+}++function completionKey(task: NiftyRecord): string {+ return `${niftyClient.text({ record: task, key: 'id' })}:${completedOn(task)}`;+}++const CURSOR_KEY = 'nifty_task_completed_cursor';+const WINDOW_AHEAD_MS = 24 * 60 * 60 * 1000;++type TriggerProps = { project?: string; include_subtasks?: boolean };diff --git a/packages/pieces/community/nifty/test/actions.test.ts b/packages/pieces/community/nifty/test/actions.test.tsnew file mode 100644index 00000000000..241a7459d1a--- /dev/null+++ b/packages/pieces/community/nifty/test/actions.test.ts@@ -0,0 +1,302 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { nifty } from '../src/index';+import { createTask } from '../src/lib/actions/create-task';+import { niftyTaskCreate } from '../src/lib/actions/ai/task-create';+import { niftyTaskUpdate } from '../src/lib/actions/ai/task-update';+import { niftyProjectCreate } from '../src/lib/actions/ai/project-create';+import { niftyProjectUpdate } from '../src/lib/actions/ai/project-update';+import { niftyMilestoneCreate } from '../src/lib/actions/ai/milestone-create';+import { completeTask } from '../src/lib/actions/complete-task';+import { deleteTask } from '../src/lib/actions/delete-task';+import { addTaskAssignees } from '../src/lib/actions/add-task-assignees';+import { removeTaskAssignees } from '../src/lib/actions/remove-task-assignees';+import { findTasks } from '../src/lib/actions/find-tasks';+import { findProjects } from '../src/lib/actions/find-projects';+import { listMilestones } from '../src/lib/actions/list-milestones';+import { listMembers } from '../src/lib/actions/list-members';+import { created, httpError, ok, runAction, task } from './helpers';++const sendRequest = vi.fn();++vi.mock('@activepieces/pieces-common', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@activepieces/pieces-common')>();+ return { ...actual, httpClient: { sendRequest: (...args: unknown[]) => sendRequest(...args) } };+});++beforeEach(() => {+ sendRequest.mockReset();+});++function call(index: number) {+ return sendRequest.mock.calls[index][0];+}++describe('piece metadata', () => {+ it('every action has audience, classification and aiMetadata; triggers are READ with sample data', () => {+ for (const action of Object.values(nifty.actions())) {+ if (action.name === 'custom_api_call') continue;+ expect(action.audience, action.name).toBeDefined();+ expect(action.classification, action.name).toBeDefined();+ expect(action.aiMetadata?.description, action.name).toBeTruthy();+ }+ for (const trigger of Object.values(nifty.triggers())) {+ expect(trigger.classification).toBe('READ');+ expect(trigger.sampleData).toBeTruthy();+ expect(trigger.aiMetadata?.description).toBeTruthy();+ }+ expect(nifty.minimumSupportedRelease).toBe('0.88.2');+ });++ it('keeps create_task prop keys and makes milestone and portfolio optional', () => {+ expect(Object.keys(createTask.props)).toEqual(+ expect.arrayContaining(['portfolio', 'project', 'status', 'milestone', 'task_name', 'task_description'])+ );+ expect(createTask.props.milestone.required).toBe(false);+ expect(createTask.props.portfolio.required).toBe(false);+ expect(createTask.audience).toBe('human');+ expect(deleteTask.audience).toBe('human');+ expect(deleteTask.classification).toBe('DESTRUCTIVE');+ });+});++describe('Create Task (existing)', () => {+ it('creates without a milestone and still returns an array', async () => {+ sendRequest.mockResolvedValueOnce(created(task({ id: 'new' })));+ const result = await runAction({+ action: createTask,+ propsValue: { project: 'p1', status: 's1', task_name: ' Write docs ', task_description: undefined, milestone: undefined },+ });+ expect(call(0).method).toBe(HttpMethod.POST);+ expect(call(0).url).toBe('https://openapi.niftypm.com/api/v1.0/tasks');+ expect(call(0).body).toEqual({ name: 'Write docs', task_group_id: 's1' });+ expect(result).toEqual([task({ id: 'new' })]);+ });++ it('sends the new optional fields', async () => {+ sendRequest.mockResolvedValueOnce(created(task({})));+ await runAction({+ action: createTask,+ propsValue: {+ project: 'p1',+ status: 's1',+ milestone: 'm1',+ task_name: 'Sub',+ parent_task: 'parent',+ start_date: '2026-10-06T00:00:00.000Z',+ due_date: '2026-10-20T00:00:00.000Z',+ assignees: ['u1'],+ },+ });+ expect(call(0).body).toEqual({+ name: 'Sub',+ task_group_id: 's1',+ milestone_id: 'm1',+ task_id: 'parent',+ start_date: '2026-10-06T00:00:00.000Z',+ due_date: '2026-10-20T00:00:00.000Z',+ assignees: ['u1'],+ });+ });+});++describe('Create Task (AI)', () => {+ it('validates before any request', async () => {+ await expect(runAction({ action: niftyTaskCreate, propsValue: { status_id: 's1', name: ' ' } })).rejects.toThrow('Task name is required');+ await expect(+ runAction({ action: niftyTaskCreate, propsValue: { status_id: 's1', name: 'x', start_date: '2026-10-10', due_date: '2026-10-01' } })+ ).rejects.toThrow('start date must be on or before');+ expect(sendRequest).not.toHaveBeenCalled();+ });++ it('returns the created task object', async () => {+ sendRequest.mockResolvedValueOnce(created(task({ id: 'ai' })));+ const result = await runAction({ action: niftyTaskCreate, propsValue: { status_id: 's1', name: 'x', story_points: 2, assignee_ids: ['u1', 'u1'] } });+ expect(call(0).body).toEqual({ name: 'x', task_group_id: 's1', story_points: 2, assignees: ['u1'] });+ expect(result).toEqual(task({ id: 'ai' }));+ });+});++describe('Update Task (AI)', () => {+ it('refuses an empty update', async () => {+ await expect(runAction({ action: niftyTaskUpdate, propsValue: { task_id: 't1', completion: 'unchanged' } })).rejects.toThrow('Nothing to update');+ expect(sendRequest).not.toHaveBeenCalled();+ });++ it('sends only set fields, null for cleared dates, then completes and re-reads', async () => {+ sendRequest+ .mockResolvedValueOnce(ok({ message: 'Succesfully edited task' }))+ .mockResolvedValueOnce(created({ message: 'Successfully changed task state' }))+ .mockResolvedValueOnce(ok(task({ completed: true })));+ const result = await runAction({+ action: niftyTaskUpdate,+ propsValue: { task_id: 't1', name: 'New', clear_due_date: true, clear_description: true, status_id: 's2', completion: 'complete' },+ });+ expect(call(0).method).toBe(HttpMethod.PUT);+ expect(call(0).url).toBe('https://openapi.niftypm.com/api/v1.0/tasks/t1');+ expect(call(0).body).toEqual({ name: 'New', description: '', task_group_id: 's2', due_date: null });+ expect(call(1).url).toBe('https://openapi.niftypm.com/api/v1.0/tasks/t1/complete');+ expect(call(1).body).toEqual({ completed: true });+ expect(call(2).method).toBe(HttpMethod.GET);+ expect(result).toEqual(task({ completed: true }));+ });++ it('rejects a value together with its clear option', async () => {+ await expect(+ runAction({ action: niftyTaskUpdate, propsValue: { task_id: 't1', due_date: '2026-10-01', clear_due_date: true } })+ ).rejects.toThrow('not both');+ });++ it('reopens without a PUT when only completion changes', async () => {+ sendRequest.mockResolvedValueOnce(created({ message: 'ok' })).mockResolvedValueOnce(ok(task({})));+ await runAction({ action: niftyTaskUpdate, propsValue: { task_id: 't1', completion: 'reopen' } });+ expect(sendRequest).toHaveBeenCalledTimes(2);+ expect(call(0).body).toEqual({ completed: false });+ });+});++describe('Complete or Reopen Task', () => {+ it('posts completed=true and returns the task', async () => {+ sendRequest.mockResolvedValueOnce(created({ message: 'ok' })).mockResolvedValueOnce(ok(task({ completed: true })));+ const result = await runAction({ action: completeTask, propsValue: { project: 'p1', task: 't!1', action: 'complete' } });+ expect(call(0).url).toBe('https://openapi.niftypm.com/api/v1.0/tasks/t!1/complete');+ expect(result).toMatchObject({ completed: true });+ });+});++describe('Delete Task', () => {+ it('returns the id after deleting', async () => {+ sendRequest.mockResolvedValueOnce(ok({ message: 'Successfully removed task' }));+ const result = await runAction({ action: deleteTask, propsValue: { project: 'p1', task: 't1' } });+ expect(call(0).method).toBe(HttpMethod.DELETE);+ expect(result).toEqual({ id: 't1', deleted: true, message: 'Successfully removed task' });+ });++ it('fails on a missing task', async () => {+ sendRequest.mockRejectedValueOnce(httpError({ status: 404, body: { message: 'This task has been deleted or no longer exists.' } }));+ await expect(runAction({ action: deleteTask, propsValue: { project: 'p1', task: 't1' } })).rejects.toThrow('(404)');+ });+});++describe('Assignees', () => {+ it('add uses PUT and remove uses DELETE with only the given ids, then re-reads', async () => {+ sendRequest.mockResolvedValueOnce(ok({ message: 'ok' })).mockResolvedValueOnce(ok(task({ assignees: ['u1'] })));+ const added = await runAction({ action: addTaskAssignees, propsValue: { task_id: 't1', member_ids: ['u1'] } });+ expect(call(0)).toMatchObject({ method: HttpMethod.PUT, body: { assignees: ['u1'] } });+ expect(added).toEqual({ task_id: 't1', member_ids: ['u1'], task: task({ assignees: ['u1'] }) });+ sendRequest.mockResolvedValueOnce(ok({ message: 'ok' })).mockResolvedValueOnce(ok(task({ assignees: [] })));+ await runAction({ action: removeTaskAssignees, propsValue: { task_id: 't1', member_ids: ['u1'] } });+ expect(call(2)).toMatchObject({ method: HttpMethod.DELETE, url: 'https://openapi.niftypm.com/api/v1.0/tasks/t1/assignees' });+ });++ it('refuses an empty member list', async () => {+ await expect(runAction({ action: addTaskAssignees, propsValue: { task_id: 't1', member_ids: [] } })).rejects.toThrow('at least one member');+ });+});++describe('Projects', () => {+ it('create sends only given fields and strips meeting passwords', async () => {+ sendRequest.mockResolvedValueOnce(created({ id: 'p9', name: 'X', zoom_password: 'secret' }));+ const result = await runAction({ action: niftyProjectCreate, propsValue: { name: 'X', access_type: 'limited' } });+ expect(call(0).body).toEqual({ name: 'X', access_type: 'limited' });+ expect(result).toEqual({ id: 'p9', name: 'X' });+ });++ it('create rejects an unknown access type', async () => {+ await expect(runAction({ action: niftyProjectCreate, propsValue: { name: 'X', access_type: 'private' } })).rejects.toThrow('Access type must be one of');+ });++ it('update sends archived as the string Nifty expects and re-reads', async () => {+ sendRequest.mockResolvedValueOnce(ok({ message: 'ok', id: 'p1' })).mockResolvedValueOnce(ok({ id: 'p1', archived: true }));+ await runAction({ action: niftyProjectUpdate, propsValue: { project_id: 'p1', archive: 'archive' } });+ expect(call(0).body).toEqual({ archived: 'true' });+ expect(call(1).url).toBe('https://openapi.niftypm.com/api/v1.0/projects/p1');+ });++ it('update refuses no changes', async () => {+ await expect(runAction({ action: niftyProjectUpdate, propsValue: { project_id: 'p1', archive: 'unchanged' } })).rejects.toThrow('Nothing to update');+ });++ it('find merges archived projects only when asked and filters by name', async () => {+ sendRequest+ .mockResolvedValueOnce(ok({ projects: [{ id: 'a', name: 'Alpha' }, { id: 'b', name: 'Beta' }] }))+ .mockResolvedValueOnce(ok({ projects: [{ id: 'c', name: 'Alpha old', archived: true }] }));+ const result = await runAction({ action: findProjects, propsValue: { name_contains: 'alpha', include_archived: true } });+ expect(call(1).queryParams).toMatchObject({ archived: 'true' });+ expect(result).toEqual({+ items: [+ { id: 'a', name: 'Alpha' },+ { id: 'c', name: 'Alpha old', archived: true },+ ],+ truncated: false,+ });+ });+});++describe('Milestones', () => {+ it('requires both dates for a milestone', async () => {+ await expect(runAction({ action: niftyMilestoneCreate, propsValue: { project_id: 'p1', name: 'M', start_date: '2026-10-06' } })).rejects.toThrow(+ 'needs both a start date and an end date'+ );+ expect(sendRequest).not.toHaveBeenCalled();+ });++ it('creates a list without dates and returns the read-back record', async () => {+ sendRequest.mockResolvedValueOnce(created({ message: 'ok', id: 'm1' })).mockResolvedValueOnce(ok({ id: 'm1', name: 'L', is_list: true }));+ const result = await runAction({ action: niftyMilestoneCreate, propsValue: { project_id: 'p1', name: 'L', create_as_list: true } });+ expect(call(0).body).toEqual({ project_id: 'p1', name: 'L', description: '', is_list: true });+ expect(result).toEqual({ id: 'm1', name: 'L', is_list: true });+ });++ it('reports a failed read-back instead of failing after the create', async () => {+ sendRequest.mockResolvedValueOnce(created({ message: 'ok', id: 'm1' })).mockRejectedValueOnce(httpError({ status: 500, body: 'oops' }));+ const result = await runAction({+ action: niftyMilestoneCreate,+ propsValue: { project_id: 'p1', name: 'M', start_date: '2026-10-06', end_date: '2026-10-20' },+ });+ expect(result).toMatchObject({ id: 'm1', name: 'M', read_back_error: expect.stringContaining('500') });+ });++ it('list filters by kind', async () => {+ sendRequest.mockResolvedValueOnce(ok({ items: [{ id: 'm', is_list: false }, { id: 'l', is_list: true }] }));+ const result = await runAction({ action: listMilestones, propsValue: { project_id: 'p1', kind: 'milestones' } });+ expect(result).toEqual({ items: [{ id: 'm', is_list: false }] });+ });+});++describe('Find Tasks', () => {+ it('maps filters to v1 query params and reports paging', async () => {+ sendRequest.mockResolvedValueOnce(ok({ tasks: [task({ id: 'a' }), task({ id: 'b' })], hasMore: true }));+ const result = await runAction({+ action: findTasks,+ propsValue: { project_id: 'p1', status_id: 's1', completion: 'open', include_subtasks: true, limit: 2, offset: 4, due_from: '2026-10-01', due_to: '2026-10-31' },+ });+ expect(call(0).queryParams).toEqual({+ project_id: 'p1',+ task_group_id: 's1',+ completed: 'false',+ include_subtasks: 'true',+ from: '2026-10-01T00:00:00.000Z',+ to: '2026-10-31T00:00:00.000Z',+ limit: '2',+ offset: '4',+ });+ expect(result).toMatchObject({ has_more: true, next_offset: 6 });+ });++ it('refuses a one-sided due window and subtasks without a project', async () => {+ await expect(runAction({ action: findTasks, propsValue: { due_from: '2026-10-01' } })).rejects.toThrow('Set both Due From and Due To');+ await expect(runAction({ action: findTasks, propsValue: { include_subtasks: true } })).rejects.toThrow('needs a Project ID');+ });+});++describe('List Members', () => {+ it('uses the paged envelope, hides removed members and curates fields', async () => {+ sendRequest.mockResolvedValueOnce(+ ok({ items: [{ id: 'u1', name: 'A', email: '[email protected]', theme: 'dark' }, { id: 'u2', name: 'B', removed: true }], hasMore: false })+ );+ const result = await runAction({ action: listMembers, propsValue: {} });+ expect(call(0).queryParams).toEqual({ limit: '1000', offset: '0' });+ expect(result).toEqual({ items: [{ id: 'u1', name: 'A', email: '[email protected]' }] });+ });+});diff --git a/packages/pieces/community/nifty/test/client.test.ts b/packages/pieces/community/nifty/test/client.test.tsnew file mode 100644index 00000000000..3e9c0def22b--- /dev/null+++ b/packages/pieces/community/nifty/test/client.test.ts@@ -0,0 +1,159 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { NiftyApiError, niftyClient } from '../src/lib/common/client';+import { niftyProps } from '../src/lib/common';+import { httpError, ok, testAuth } from './helpers';++const sendRequest = vi.fn();++vi.mock('@activepieces/pieces-common', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@activepieces/pieces-common')>();+ return { ...actual, httpClient: { sendRequest: (...args: unknown[]) => sendRequest(...args) } };+});++beforeEach(() => {+ sendRequest.mockReset();+});++describe('request', () => {+ it('sends a bearer token to the constant v1 host and drops undefined query values', async () => {+ sendRequest.mockResolvedValueOnce(ok({ id: 'x' }));+ await niftyClient.request({ auth: testAuth(), method: HttpMethod.GET, path: 'tasks/abc', query: { a: 1, b: undefined, c: true } });+ const req = sendRequest.mock.calls[0][0];+ expect(req.url).toBe('https://openapi.niftypm.com/api/v1.0/tasks/abc');+ expect(req.queryParams).toEqual({ a: '1', c: 'true' });+ expect(req.authentication).toEqual({ type: 'BEARER_TOKEN', token: 'tok_test' });+ });++ it.each(['/tasks', 'https://evil.io/x', '../oauth', 'tasks\\x'])('refuses unexpected path %s', async (path) => {+ await expect(niftyClient.request({ auth: testAuth(), method: HttpMethod.GET, path })).rejects.toThrow('unexpected Nifty path');+ expect(sendRequest).not.toHaveBeenCalled();+ });++ it('maps a 403 to an access sentence with responseBody and no body field', async () => {+ sendRequest.mockRejectedValueOnce(httpError({ status: 403, body: { message: 'Forbidden resource', code: 403 } }));+ const error = await niftyClient.request({ auth: testAuth(), method: HttpMethod.GET, path: 'subteams' }).catch((e: unknown) => e);+ expect(error).toBeInstanceOf(NiftyApiError);+ expect(error).toMatchObject({ status: 403, responseBody: { message: 'Forbidden resource', code: 403 } });+ expect(error).not.toHaveProperty('body');+ expect(String(error)).toContain('Nifty refused access (403): Forbidden resource.');+ expect(String(error)).not.toContain('invalid credentials');+ });++ it('includes field errors and trims the vendor period on 400 and 404', async () => {+ sendRequest.mockRejectedValueOnce(+ httpError({ status: 400, body: { message: 'Validation failed: archived', errors: [{ message: 'archived must be true or false' }] } })+ );+ await expect(niftyClient.request({ auth: testAuth(), method: HttpMethod.PUT, path: 'projects/p' })).rejects.toThrow(+ 'Nifty rejected the request (400): Validation failed: archived (archived must be true or false).'+ );+ sendRequest.mockRejectedValueOnce(httpError({ status: 404, body: { message: 'This task has been deleted or no longer exists.' } }));+ await expect(niftyClient.request({ auth: testAuth(), method: HttpMethod.GET, path: 'tasks/x' })).rejects.toThrow(+ 'Nifty could not find the record (404): This task has been deleted or no longer exists. It may'+ );+ });++ it('rethrows non-HTTP errors unchanged', async () => {+ const boom = new Error('socket hang up');+ sendRequest.mockRejectedValueOnce(boom);+ await expect(niftyClient.request({ auth: testAuth(), method: HttpMethod.GET, path: 'tasks' })).rejects.toBe(boom);+ });+});++describe('listAll', () => {+ it('pages with limit 1000 and offset until a short page', async () => {+ const full = Array.from({ length: 1000 }, (_, i) => ({ id: `p${i}` }));+ sendRequest.mockResolvedValueOnce(ok({ projects: full, hasMore: true })).mockResolvedValueOnce(ok({ projects: [{ id: 'last' }], hasMore: false }));+ const result = await niftyClient.listAll({ auth: testAuth(), path: 'projects', key: 'projects' });+ expect(result.items).toHaveLength(1001);+ expect(result.truncated).toBe(false);+ expect(sendRequest.mock.calls[0][0].queryParams).toEqual({ limit: '1000', offset: '0' });+ expect(sendRequest.mock.calls[1][0].queryParams).toEqual({ limit: '1000', offset: '1000' });+ });++ it('stops at the page cap and reports truncated', async () => {+ const full = Array.from({ length: 1000 }, (_, i) => ({ id: `p${i}` }));+ sendRequest.mockResolvedValue(ok({ projects: full, hasMore: true }));+ const result = await niftyClient.listAll({ auth: testAuth(), path: 'projects', key: 'projects', maxPages: 2 });+ expect(sendRequest).toHaveBeenCalledTimes(2);+ expect(result.truncated).toBe(true);+ });++ it('throws on an unexpected list shape instead of returning nothing', async () => {+ sendRequest.mockResolvedValueOnce(ok({ message: 'weird' }));+ await expect(niftyClient.listAll({ auth: testAuth(), path: 'projects', key: 'projects' })).rejects.toThrow('unexpected list response');+ });+});++describe('validators', () => {+ it('accepts Nifty IDs with ! and _ and rejects slashes and blanks', () => {+ expect(niftyClient.requireId({ value: ' jiA!cEfY03 ', label: 'Status ID' })).toBe('jiA!cEfY03');+ expect(niftyClient.segment('tk_O!179Q6')).toBe('tk_O!179Q6');+ expect(() => niftyClient.requireId({ value: 'a/b', label: 'Task ID' })).toThrow('not a valid Nifty ID');+ expect(() => niftyClient.requireId({ value: ' ', label: 'Task ID' })).toThrow('Task ID is required');+ });++ it('dedupes ID lists and splits comma text', () => {+ expect(niftyClient.idList({ value: ['a', 'b,a', ' c '], label: 'Member ID' })).toEqual(['a', 'b', 'c']);+ expect(niftyClient.idList({ value: undefined, label: 'Member ID' })).toEqual([]);+ });++ it('normalises dates to ISO and rejects junk', () => {+ expect(niftyClient.optionalIsoDate({ value: '2026-10-20', label: 'Due' })).toBe('2026-10-20T00:00:00.000Z');+ expect(() => niftyClient.optionalIsoDate({ value: 'next week', label: 'Due' })).toThrow('not a valid date');+ });++ it('validates number ranges', () => {+ expect(niftyClient.optionalNumber({ value: '5', label: 'Limit', min: 1, max: 1000, integer: true })).toBe(5);+ expect(() => niftyClient.optionalNumber({ value: 1.5, label: 'Limit', min: 1, max: 1000, integer: true })).toThrow('whole number');+ expect(() => niftyClient.optionalNumber({ value: 0, label: 'Limit', min: 1, max: 1000, integer: true })).toThrow('from 1 to 1000');+ });++ it('removes meeting passwords from projects', () => {+ expect(niftyClient.cleanProject({ id: 'p', zoom_password: 'x', webex_password: 'y', name: 'P' })).toEqual({ id: 'p', name: 'P' });+ });+});++describe('dropdowns', () => {+ it('portfolio dropdown explains a 403 instead of failing', async () => {+ sendRequest.mockRejectedValueOnce(httpError({ status: 403, body: { message: 'Forbidden resource' } }));+ const prop = niftyProps.portfolio({ required: false });+ const state = await prop.options({ auth: testAuth() }, { searchValue: undefined, server: { apiUrl: '', publicUrl: '', token: '' } });+ expect(state).toEqual({ disabled: true, placeholder: expect.stringContaining('Leave this empty'), options: [] });+ });++ it('project dropdown lists every page and filters by portfolio server-side', async () => {+ sendRequest.mockResolvedValueOnce(ok({ projects: [{ id: 'p1', name: 'One', subteam: 'pf' }, { id: 'p2', name: 'Two', subteam: 'other' }] }));+ const prop = niftyProps.project({ required: true });+ const state = await prop.options({ auth: testAuth(), portfolio: 'pf' }, { searchValue: undefined, server: { apiUrl: '', publicUrl: '', token: '' } });+ expect(sendRequest.mock.calls[0][0].queryParams).toEqual({ subteam_id: 'pf', limit: '1000', offset: '0' });+ expect(state.options).toEqual([{ label: 'One', value: 'p1' }]);+ });++ it('status dropdown asks for a project first', async () => {+ const prop = niftyProps.status({ required: true });+ const state = await prop.options({ auth: testAuth() }, { searchValue: undefined, server: { apiUrl: '', publicUrl: '', token: '' } });+ expect(state).toEqual({ disabled: true, placeholder: 'Select a project first', options: [] });+ });++ it('milestone dropdown keeps is_list=true and labels lists', async () => {+ sendRequest.mockResolvedValueOnce(+ ok({ items: [{ id: 'm1', name: 'Launch', is_list: false }, { id: 'l1', name: 'Backlog', is_list: true }], hasMore: false })+ );+ const prop = niftyProps.milestone({ required: false });+ const state = await prop.options({ auth: testAuth(), project: 'p1' }, { searchValue: undefined, server: { apiUrl: '', publicUrl: '', token: '' } });+ expect(sendRequest.mock.calls[0][0].queryParams).toMatchObject({ project_id: 'p1', is_list: 'true' });+ expect(state.options).toEqual([+ { label: 'Launch', value: 'm1' },+ { label: 'Backlog (list)', value: 'l1' },+ ]);+ });++ it('a failing dropdown shows the reason', async () => {+ sendRequest.mockRejectedValueOnce(httpError({ status: 401, body: { message: 'Unauthorized' } }));+ const prop = niftyProps.task({ required: true });+ const state = await prop.options({ auth: testAuth(), project: 'p1' }, { searchValue: undefined, server: { apiUrl: '', publicUrl: '', token: '' } });+ expect(state.disabled).toBe(true);+ expect(state.placeholder).toContain('Could not load tasks: Nifty did not accept the connection (401)');+ });+});diff --git a/packages/pieces/community/nifty/test/helpers.ts b/packages/pieces/community/nifty/test/helpers.tsnew file mode 100644index 00000000000..445c9fdf866--- /dev/null+++ b/packages/pieces/community/nifty/test/helpers.ts@@ -0,0 +1,84 @@+import { AppConnectionType, InputPropertyMap, StaticPropsValue } from '@activepieces/pieces-framework';+import { createMockActionContext, createMockPollingTriggerContext } from '../../../framework/src/lib/test';++export function testAuth() {+ return {+ type: AppConnectionType.OAUTH2 as const,+ access_token: 'tok_test',+ client_id: 'client',+ client_secret: 'secret',+ redirect_url: 'https://example.com/redirect',+ token_type: 'Bearer',+ claimed_at: 0,+ refresh_token: 'refresh',+ scope: 'task project',+ token_url: 'https://openapi.niftypm.com/oauth/token',+ data: {},+ };+}++export function runAction<Props extends InputPropertyMap>({+ action,+ propsValue,+}: {+ action: { run: (context: never) => Promise<unknown> };+ propsValue: StaticPropsValue<Props> | Record<string, unknown>;+}): Promise<unknown> {+ const context = { ...createMockActionContext({ propsValue: {} }), propsValue, auth: testAuth() };+ return Reflect.apply(action.run, action, [context]);+}++export function triggerContext({+ propsValue,+ store,+ isRepublish = false,+}: {+ propsValue: Record<string, unknown>;+ store: Map<string, string>;+ isRepublish?: boolean;+}) {+ return {+ ...createMockPollingTriggerContext({ propsValue: {} }),+ propsValue,+ isRepublish,+ auth: testAuth(),+ store: {+ put: async <T>(key: string, value: T) => {+ store.set(key, JSON.stringify(value));+ return value;+ },+ get: async <T>(key: string): Promise<T | null> => {+ const raw = store.get(key);+ return raw === undefined ? null : JSON.parse(raw);+ },+ delete: async (key: string) => {+ store.delete(key);+ },+ },+ };+}++export function ok(body: unknown) {+ return { status: 200, headers: {}, body };+}++export function created(body: unknown) {+ return { status: 201, headers: {}, body };+}++export function httpError({ status, body }: { status: number; body: unknown }) {+ return Object.assign(new Error(`HTTP ${status}`), { response: { status, body } });+}++export function task(overrides: Record<string, unknown>) {+ return {+ id: 't1',+ nice_id: 'ANP-1',+ name: 'Task',+ created_at: '2026-10-05T10:00:00.000Z',+ completed: false,+ project: 'p1',+ task_group: 's1',+ ...overrides,+ };+}diff --git a/packages/pieces/community/nifty/test/polling.test.ts b/packages/pieces/community/nifty/test/polling.test.tsnew file mode 100644index 00000000000..23eb480255c--- /dev/null+++ b/packages/pieces/community/nifty/test/polling.test.ts@@ -0,0 +1,223 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { newTask } from '../src/lib/triggers/new-task';+import { taskCompleted } from '../src/lib/triggers/task-completed';+import { newProject } from '../src/lib/triggers/new-project';+import { niftyPolling } from '../src/lib/common/polling';+import { ok, task, triggerContext } from './helpers';++const sendRequest = vi.fn();++vi.mock('@activepieces/pieces-common', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@activepieces/pieces-common')>();+ return { ...actual, httpClient: { sendRequest: (...args: unknown[]) => sendRequest(...args) } };+});++beforeEach(() => {+ sendRequest.mockReset();+});++function hook({ fn, ctx }: { fn: unknown; ctx: unknown }): Promise<unknown> {+ if (typeof fn !== 'function') {+ throw new Error('missing hook');+ }+ return Promise.resolve(Reflect.apply(fn, undefined, [ctx]));+}++const T0 = '2026-10-05T10:00:00.000Z';+const T1 = '2026-10-05T11:00:00.000Z';+const T2 = '2026-10-05T12:00:00.000Z';++describe('advanceTimeCursor', () => {+ const timeOf = (r: Record<string, unknown>) => String(r['created_at']);+ const keyOf = (r: Record<string, unknown>) => String(r['id']);++ it('emits ties at the checkpoint that were not seen, oldest first, and skips the seen ones', () => {+ const { emit, cursor } = niftyPolling.advanceTimeCursor({+ cursor: { cp: T0, seen: ['a'] },+ items: [task({ id: 'c', created_at: T1 }), task({ id: 'a', created_at: T0 }), task({ id: 'b', created_at: T0 })],+ timeOf,+ keyOf,+ });+ expect(emit.map((t) => t['id'])).toEqual(['b', 'c']);+ expect(cursor).toEqual({ cp: T1, seen: ['c'] });+ });++ it('keeps earlier seen keys when the checkpoint does not move', () => {+ const { cursor } = niftyPolling.advanceTimeCursor({ cursor: { cp: T0, seen: ['a'] }, items: [task({ id: 'b', created_at: T0 })], timeOf, keyOf });+ expect(cursor).toEqual({ cp: T0, seen: ['a', 'b'] });+ });++ it('bounds the seen list', () => {+ const items = Array.from({ length: 450 }, (_, i) => task({ id: `t${i}`, created_at: T1 }));+ const { cursor } = niftyPolling.advanceTimeCursor({ cursor: { cp: T0, seen: [] }, items, timeOf, keyOf });+ expect(cursor.seen).toHaveLength(200);+ });++ it('seeds from the newest item, or now when empty', () => {+ expect(niftyPolling.seedTimeCursor({ items: [], timeOf, keyOf, now: T1 })).toEqual({ cp: T1, seen: [] });+ expect(+ niftyPolling.seedTimeCursor({ items: [task({ id: 'x', created_at: T0 }), task({ id: 'y', created_at: T1 })], timeOf, keyOf, now: T0 })+ ).toEqual({ cp: T1, seen: ['y'] });+ });+});++describe('New Task trigger', () => {+ it('does not replay existing tasks, emits a new one once, then nothing', async () => {+ const store = new Map<string, string>();+ const ctx = triggerContext({ propsValue: { project: 'p1', include_subtasks: true }, store });+ sendRequest.mockResolvedValueOnce(ok({ tasks: [task({ id: 'old', created_at: T0 })], hasMore: false }));+ await hook({ fn: newTask.onEnable, ctx });+ expect(sendRequest.mock.calls[0][0].queryParams).toMatchObject({ project_id: 'p1', include_subtasks: 'true' });++ sendRequest.mockResolvedValueOnce(ok({ tasks: [task({ id: 'old', created_at: T0 }), task({ id: 'new', created_at: T1 })] }));+ const first = await hook({ fn: newTask.run, ctx });+ expect(first).toEqual([task({ id: 'new', created_at: T1 })]);++ sendRequest.mockResolvedValueOnce(ok({ tasks: [task({ id: 'old', created_at: T0 }), task({ id: 'new', created_at: T1 })] }));+ expect(await hook({ fn: newTask.run, ctx })).toEqual([]);+ });++ it('skips subtasks when include subtasks is off', async () => {+ const store = new Map<string, string>([['nifty_new_task_cursor', JSON.stringify({ cp: T0, seen: [], fp: '["p1",false]' })]]);+ const ctx = triggerContext({ propsValue: { project: 'p1', include_subtasks: false }, store });+ sendRequest.mockResolvedValueOnce(ok({ tasks: [task({ id: 'sub', task: 'parent', created_at: T1 }), task({ id: 'top', created_at: T1 })] }));+ const out = await hook({ fn: newTask.run, ctx });+ expect(out).toEqual([task({ id: 'top', created_at: T1 })]);+ expect(sendRequest.mock.calls[0][0].queryParams).not.toHaveProperty('include_subtasks');+ });++ it('keeps the cursor across a republish with the same inputs, so a task created in between still fires', async () => {+ const store = new Map<string, string>();+ const props = { project: 'p1', include_subtasks: true };+ sendRequest.mockResolvedValueOnce(ok({ tasks: [task({ id: 'old', created_at: T0 })] }));+ await hook({ fn: newTask.onEnable, ctx: triggerContext({ propsValue: props, store }) });+ await hook({ fn: newTask.onDisable, ctx: triggerContext({ propsValue: props, store }) });+ await hook({ fn: newTask.onEnable, ctx: triggerContext({ propsValue: props, store, isRepublish: true }) });+ expect(sendRequest).toHaveBeenCalledTimes(1);+ sendRequest.mockResolvedValueOnce(ok({ tasks: [task({ id: 'old', created_at: T0 }), task({ id: 'gap', created_at: T1 })] }));+ expect(await hook({ fn: newTask.run, ctx: triggerContext({ propsValue: props, store }) })).toEqual([task({ id: 'gap', created_at: T1 })]);+ });++ it('reseeds on republish when the inputs changed, and on a plain re-enable', async () => {+ const store = new Map<string, string>([['nifty_new_task_cursor', JSON.stringify({ cp: T0, seen: ['x'], fp: '["p1",true]' })]]);+ sendRequest.mockResolvedValueOnce(ok({ tasks: [task({ id: 'y', created_at: T1 })] }));+ await hook({ fn: newTask.onEnable, ctx: triggerContext({ propsValue: { project: 'p2' }, store, isRepublish: true }) });+ expect(JSON.parse(store.get('nifty_new_task_cursor') ?? '{}')).toEqual({ cp: T1, seen: ['y'], fp: '["p2",true]' });+ sendRequest.mockResolvedValueOnce(ok({ tasks: [task({ id: 'z', created_at: T1 }), task({ id: 'y', created_at: T1 })] }));+ await hook({ fn: newTask.onEnable, ctx: triggerContext({ propsValue: { project: 'p2' }, store }) });+ expect(JSON.parse(store.get('nifty_new_task_cursor') ?? '{}')).toEqual({ cp: T1, seen: ['z', 'y'], fp: '["p2",true]' });+ });++ it('throws on API errors instead of advancing', async () => {+ const store = new Map<string, string>([['nifty_new_task_cursor', JSON.stringify({ cp: T0, seen: [], fp: '[null,true]' })]]);+ sendRequest.mockRejectedValueOnce(Object.assign(new Error('x'), { response: { status: 500, body: 'down' } }));+ await expect(hook({ fn: newTask.run, ctx: triggerContext({ propsValue: {}, store }) })).rejects.toThrow('HTTP 500');+ expect(JSON.parse(store.get('nifty_new_task_cursor') ?? '{}')).toEqual({ cp: T0, seen: [], fp: '[null,true]' });+ });+});++describe('Task Completed trigger', () => {+ it('queries the completed window from the checkpoint and fires again after a re-completion', async () => {+ const store = new Map<string, string>([['nifty_task_completed_cursor', JSON.stringify({ cp: T0, seen: [`t1:${T0}`], fp: '[null,true]' })]]);+ const ctx = triggerContext({ propsValue: {}, store });+ sendRequest.mockResolvedValueOnce(+ ok({ tasks: [task({ id: 't1', completed: true, completed_on: T0 }), task({ id: 't1', completed: true, completed_on: T1 })] })+ );+ const out = await hook({ fn: taskCompleted.run, ctx });+ const query = sendRequest.mock.calls[0][0].queryParams;+ expect(query).toMatchObject({ completed: 'true', order: 'completedOn:DESC', completed_from: T0 });+ expect(Date.parse(query.completed_to)).toBeGreaterThan(Date.now());+ expect(out).toEqual([task({ id: 't1', completed: true, completed_on: T1 })]);+ });++ it('reads a smaller window instead of skipping completions when a scan is truncated, then catches up', async () => {+ const store = new Map<string, string>([['nifty_task_completed_cursor', JSON.stringify({ cp: T0, seen: [], fp: '[null,true]' })]]);+ const ctx = triggerContext({ propsValue: {}, store });+ const fullPage = Array.from({ length: 1000 }, (_, i) => task({ id: `n${i}`, completed: true, completed_on: T2 }));+ const early = task({ id: 'early', completed: true, completed_on: T1 });+ sendRequest.mockImplementation(async (request: { queryParams: Record<string, string> }) => {+ const to = Date.parse(request.queryParams['completed_to']);+ if (to > Date.parse(T2)) {+ return ok({ tasks: fullPage });+ }+ return ok({ tasks: Date.parse(T1) <= to ? [early] : [] });+ });+ const first = await hook({ fn: taskCompleted.run, ctx });+ expect(first).toEqual([early]);+ const cursor = JSON.parse(store.get('nifty_task_completed_cursor') ?? '{}');+ expect(Date.parse(cursor.cp)).toBeGreaterThanOrEqual(Date.parse(T1));+ expect(Date.parse(cursor.cp)).toBeLessThan(Date.parse(T2));+ const pages = sendRequest.mock.calls.filter((call) => Number(call[0].queryParams['offset'] ?? 0) === 0);+ expect(pages.length).toBeGreaterThan(1);+ });++ it('keeps the completion cursor across a republish with the same inputs', async () => {+ const stored = { cp: T0, seen: [`t1:${T0}`], fp: '["p1",true]' };+ const store = new Map<string, string>([['nifty_task_completed_cursor', JSON.stringify(stored)]]);+ await hook({ fn: taskCompleted.onDisable, ctx: triggerContext({ propsValue: { project: 'p1' }, store }) });+ await hook({ fn: taskCompleted.onEnable, ctx: triggerContext({ propsValue: { project: 'p1' }, store, isRepublish: true }) });+ expect(sendRequest).not.toHaveBeenCalled();+ expect(JSON.parse(store.get('nifty_task_completed_cursor') ?? '{}')).toEqual(stored);+ });++ it('does not advance when even the smallest window is truncated', async () => {+ const stored = { cp: T0, seen: [], fp: '[null,true]' };+ const store = new Map<string, string>([['nifty_task_completed_cursor', JSON.stringify(stored)]]);+ const fullPage = Array.from({ length: 1000 }, (_, i) => task({ id: `n${i}`, completed: true, completed_on: T0 }));+ sendRequest.mockResolvedValue(ok({ tasks: fullPage }));+ await expect(hook({ fn: taskCompleted.run, ctx: triggerContext({ propsValue: {}, store }) })).rejects.toThrow('cannot all be read');+ expect(JSON.parse(store.get('nifty_task_completed_cursor') ?? '{}')).toEqual(stored);+ });+});++describe('New Project trigger', () => {+ it('seeds known ids, emits only unseen projects, and strips meeting passwords', async () => {+ const store = new Map<string, string>();+ const ctx = triggerContext({ propsValue: {}, store });+ sendRequest.mockResolvedValueOnce(ok({ projects: [{ id: 'p1', name: 'A' }] }));+ await hook({ fn: newProject.onEnable, ctx });+ sendRequest.mockResolvedValueOnce(ok({ projects: [{ id: 'p1', name: 'A' }, { id: 'p2', name: 'B', zoom_password: 'z' }] }));+ expect(await hook({ fn: newProject.run, ctx })).toEqual([{ id: 'p2', name: 'B' }]);+ sendRequest.mockResolvedValueOnce(ok({ projects: [{ id: 'p1', name: 'A' }, { id: 'p2', name: 'B' }] }));+ expect(await hook({ fn: newProject.run, ctx })).toEqual([]);+ });++ it('does not re-emit a known project that drops out of one listing', () => {+ const first = niftyPolling.advanceIdSet({ known: ['a', 'b'], dropped: [], items: [{ id: 'a' }, { id: 'c' }], truncated: false });+ expect(first.emit).toEqual([{ id: 'c' }]);+ expect(first).toMatchObject({ known: ['a', 'c'], dropped: ['b'] });+ const second = niftyPolling.advanceIdSet({ known: first.known, dropped: first.dropped, items: [{ id: 'a' }, { id: 'b' }, { id: 'c' }], truncated: false });+ expect(second.emit).toEqual([]);+ });++ it('never re-fires a visible project after more than 10,000 projects have been seen', () => {+ const ids = ({ prefix, count }: { prefix: string; count: number }) => Array.from({ length: count }, (_, i) => `${prefix}${i}`);+ const oldest = { id: 'keep' };+ let state: { known: string[]; dropped: string[] } = { known: ['keep', ...ids({ prefix: 'a', count: 9000 })], dropped: [] };+ const rounds = [ids({ prefix: 'b', count: 9000 }), ids({ prefix: 'c', count: 9000 }), ids({ prefix: 'd', count: 9000 })];+ for (const round of rounds) {+ const result = niftyPolling.advanceIdSet({ ...state, items: [oldest, ...round.map((id) => ({ id }))], truncated: false });+ expect(result.emit).toHaveLength(9000);+ state = { known: result.known, dropped: result.dropped };+ }+ const last = niftyPolling.advanceIdSet({ ...state, items: [oldest, { id: 'd1' }], truncated: false });+ expect(last.emit).toEqual([]);+ expect(JSON.stringify(last).length).toBeLessThan(512 * 1024);+ });++ it('does not forget ids after a truncated listing', () => {+ const result = niftyPolling.advanceIdSet({ known: ['a', 'b'], dropped: [], items: [{ id: 'a' }, { id: 'n' }], truncated: true });+ expect(result).toEqual({ emit: [{ id: 'n' }], known: ['a', 'b', 'n'], dropped: [] });+ });++ it('keeps the known ids across a republish with the same portfolio', async () => {+ const store = new Map<string, string>();+ sendRequest.mockResolvedValueOnce(ok({ projects: [{ id: 'p1', name: 'A' }] }));+ await hook({ fn: newProject.onEnable, ctx: triggerContext({ propsValue: {}, store }) });+ await hook({ fn: newProject.onDisable, ctx: triggerContext({ propsValue: {}, store }) });+ await hook({ fn: newProject.onEnable, ctx: triggerContext({ propsValue: {}, store, isRepublish: true }) });+ sendRequest.mockResolvedValueOnce(ok({ projects: [{ id: 'p1', name: 'A' }, { id: 'p2', name: 'B' }] }));+ expect(await hook({ fn: newProject.run, ctx: triggerContext({ propsValue: {}, store }) })).toEqual([{ id: 'p2', name: 'B' }]);+ expect(sendRequest).toHaveBeenCalledTimes(2);+ });+});diff --git a/packages/pieces/community/nifty/vitest.config.ts b/packages/pieces/community/nifty/vitest.config.tsnew file mode 100644index 00000000000..79c97261904--- /dev/null+++ b/packages/pieces/community/nifty/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'),+ },+ },+})