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(linear): add issue lookup, search, labels, delete, links and project status updates (#15944)
Odai Ahmadf85c96fecc22
diff --git a/bun.lock b/bun.lockindex 0392709b0f3..90f0c33e431 100644--- a/bun.lock+++ b/bun.lock@@ -5163,7 +5163,7 @@},"packages/pieces/community/linear": {"name": "@activepieces/piece-linear",- "version": "0.6.1",+ "version": "0.7.0","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",diff --git a/packages/pieces/community/linear/package.json b/packages/pieces/community/linear/package.jsonindex 0a1fd78fa35..506c59dba76 100644--- a/packages/pieces/community/linear/package.json+++ b/packages/pieces/community/linear/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/piece-linear",- "version": "0.6.1",+ "version": "0.7.0","main": "./dist/src/index.js","types": "./dist/src/index.d.ts","dependencies": {diff --git a/packages/pieces/community/linear/src/i18n/translation.json b/packages/pieces/community/linear/src/i18n/translation.jsonindex 453b8893ee1..6dee03f3e72 100644--- a/packages/pieces/community/linear/src/i18n/translation.json+++ b/packages/pieces/community/linear/src/i18n/translation.json@@ -6,12 +6,26 @@"Create Project": "Create Project","Update Project": "Update Project","Create Comment": "Create Comment",+ "Get Issue": "Get Issue",+ "Search Issues": "Search Issues",+ "Add Label to Issue": "Add Label to Issue",+ "Remove Label from Issue": "Remove Label from Issue",+ "Delete Issue": "Delete Issue",+ "Attach Link to Issue": "Attach Link to Issue",+ "Post Project Status Update": "Post Project Status Update","Raw GraphQL query": "Raw GraphQL query","Create a new issue in Linear workspace": "Create a new issue in Linear workspace","Update a issue in Linear Workspace": "Update a issue in Linear Workspace","Create a new project in Linear workspace": "Create a new project in Linear workspace","Update a existing project in Linear workspace": "Update a existing project in Linear workspace","Create a new comment on an issue in Linear workspace": "Create a new comment on an issue in Linear workspace",+ "Get an issue by its ID or identifier (for example ENG-123)": "Get an issue by its ID or identifier (for example ENG-123)",+ "Search issues by text, optionally in one team": "Search issues by text, optionally in one team",+ "Add one label to an issue and keep its other labels": "Add one label to an issue and keep its other labels",+ "Remove one label from an issue and keep its other labels": "Remove one label from an issue and keep its other labels",+ "Move an issue to the trash. Linear keeps it for 30 days, so it can be restored.": "Move an issue to the trash. Linear keeps it for 30 days, so it can be restored.",+ "Link a URL (ticket, pull request, document) to an issue. Attaching the same URL again updates the existing link.": "Link a URL (ticket, pull request, document) to an issue. Attaching the same URL again updates the existing link.",+ "Post a status update (with health) on a project, like the weekly update in the project page": "Post a status update (with health) on a project, like the weekly update in the project page","Perform a raw GraphQL query": "Perform a raw GraphQL query","Team": "Team","Title": "Title",@@ -21,6 +35,11 @@"Assignee": "Assignee","Priority": "Priority","Template": "Template",+ "Project": "Project",+ "Cycle": "Cycle",+ "Parent Issue": "Parent Issue",+ "Due Date": "Due Date",+ "Estimate": "Estimate","Issue": "Issue","Project Name": "Project Name","Icon": "Icon",@@ -28,8 +47,18 @@"Start Date": "Start Date","Target Date": "Target Date","Project Status": "Project Status",- "Project": "Project","Comment Body": "Comment Body",+ "Issue ID or Identifier": "Issue ID or Identifier",+ "Search Text": "Search Text",+ "Also Search Comments": "Also Search Comments",+ "Include Archived Issues": "Include Archived Issues",+ "Max Results": "Max Results",+ "Cursor": "Cursor",+ "Label": "Label",+ "URL": "URL",+ "Subtitle": "Subtitle",+ "Update": "Update",+ "Health": "Health","Query": "Query","Parameters": "Parameters","The team for which the issue, project or comment will be created": "The team for which the issue, project or comment will be created",@@ -38,16 +67,37 @@"Assignee of the Issue / Comment": "Assignee of the Issue / Comment","Priority of the Issue": "Priority of the Issue","ID of Template": "ID of Template",+ "ID of Linear Project": "ID of Linear Project",+ "The cycle of the selected team to put the issue in. The team must have cycles enabled.": "The cycle of the selected team to put the issue in. The team must have cycles enabled.",+ "Identifier (e.g. ENG-123), ID or exact title of the parent issue.": "Identifier (e.g. ENG-123), ID or exact title of the parent issue.",+ "Only the date part is used, for example 2026-10-15.": "Only the date part is used, for example 2026-10-15.",+ "Estimate in the team's estimation points, for example 3. The team must have estimates enabled.": "Estimate in the team's estimation points, for example 3. The team must have estimates enabled.","ID of Linear Issue": "ID of Linear Issue","The status of the project": "The status of the project",- "ID of Linear Project": "ID of Linear Project",+ "Leave empty to keep the current name.": "Leave empty to keep the current name.",+ "Not used (kept for compatibility). The comment is always posted as the owner of the API key.": "Not used (kept for compatibility). The comment is always posted as the owner of the API key.","The content of the comment": "The content of the comment",+ "The issue identifier shown in Linear (for example ENG-123) or the issue UUID.": "The issue identifier shown in Linear (for example ENG-123) or the issue UUID.",+ "Words to look for, for example \"login timeout\".": "Words to look for, for example \"login timeout\".",+ "Only return issues from this team. Leave empty to search every team you can access.": "Only return issues from this team. Leave empty to search every team you can access.",+ "How many issues to return, 1 to 100. Default 25.": "How many issues to return, 1 to 100. Default 25.",+ "End Cursor from a previous search. Empty for the first page.": "End Cursor from a previous search. Empty for the first page.",+ "Team whose labels are listed. Pick the issue's team; workspace labels work on any issue.": "Team whose labels are listed. Pick the issue's team; workspace labels work on any issue.",+ "The label to add or remove. Team labels are listed first, then workspace labels.": "The label to add or remove. Team labels are listed first, then workspace labels.",+ "The full link, for example https://github.com/acme/app/pull/42.": "The full link, for example https://github.com/acme/app/pull/42.",+ "Text shown for the link, for example \"PR #42: Fix login timeout\".": "Text shown for the link, for example \"PR #42: Fix login timeout\".",+ "Optional second line, for example \"Open · 2 approvals\".": "Optional second line, for example \"Open · 2 approvals\".",+ "The update text. Markdown is supported.": "The update text. Markdown is supported.",+ "Leave empty to post without a health rating.": "Leave empty to post without a health rating.","Backlog": "Backlog","Planned": "Planned","In Progress": "In Progress","Paused": "Paused","Completed": "Completed","Canceled": "Canceled",+ "On track": "On track",+ "At risk": "At risk",+ "Off track": "Off track","New Comment": "New Comment","New Issue": "New Issue","Updated Issue": "Updated Issue",@@ -55,22 +105,23 @@"New Project": "New Project","Project Status Updated": "Project Status Updated","Removed Project": "Removed Project",- "Triggers when a new comment is created on a Linear issue": "Triggers when a new comment is created on a Linear issue",+ "New Project Status Update": "New Project Status Update",+ "Triggers when a new comment is created on a Linear issue. Only issues in public teams are covered.": "Triggers when a new comment is created on a Linear issue. Only issues in public teams are covered.","Triggers when Linear receives a new issue": "Triggers when Linear receives a new issue",- "Triggers when an existing Linear issue is updated": "Triggers when an existing Linear issue is updated",+ "Triggers when an existing Linear issue is updated. Without a team selected, only public teams are covered.": "Triggers when an existing Linear issue is updated. Without a team selected, only public teams are covered.","Triggers when an existing Linear issue is removed": "Triggers when an existing Linear issue is removed",- "Triggers when a new project is created in Linear": "Triggers when a new project is created in Linear",- "Triggers when the status of an Linear project is updated": "Triggers when the status of an Linear project is updated",- "Triggers when an existing Linear project is removed": "Triggers when an existing Linear project is removed",+ "Triggers when a new project is created in Linear. Only projects in public teams are covered.": "Triggers when a new project is created in Linear. Only projects in public teams are covered.",+ "Triggers when the status of an Linear project is updated. Only projects in public teams are covered.": "Triggers when the status of an Linear project is updated. Only projects in public teams are covered.",+ "Triggers when an existing Linear project is removed. Only projects in public teams are covered.": "Triggers when an existing Linear project is removed. Only projects in public teams are covered.",+ "Triggers when a status update is posted on a project. Only projects in public teams are covered.": "Triggers when a status update is posted on a project. Only projects in public teams are covered.","Teams": "Teams","Authors": "Authors",+ "Only when these fields change": "Only when these fields change","Filter by teams": "Filter by teams","Filter by authors": "Filter by authors",+ "Trigger only when at least one of the selected fields changed. Leave empty to trigger on every update.": "Trigger only when at least one of the selected fields changed. Leave empty to trigger on every update.","Filter by project status (leave empty to include all)": "Filter by project status (leave empty to include all)",- "Estimate": "Estimate",+ "Only fire for status updates posted on this project. Leave empty for every project.": "Only fire for status updates posted on this project. Leave empty for every project.","Due date": "Due date",- "Cycle": "Cycle",- "Parent": "Parent",- "Only when these fields change": "Only when these fields change",- "Trigger only when at least one of the selected fields changed. Leave empty to trigger on every update.": "Trigger only when at least one of the selected fields changed. Leave empty to trigger on every update."+ "Parent": "Parent"}\ No newline at end of filediff --git a/packages/pieces/community/linear/src/index.ts b/packages/pieces/community/linear/src/index.tsindex b0bc619a1a0..88b2298e674 100644--- a/packages/pieces/community/linear/src/index.ts+++ b/packages/pieces/community/linear/src/index.ts@@ -14,6 +14,14 @@ import { linearRemovedIssue } from './lib/triggers/removed-issue';import { linearNewProject } from './lib/triggers/new-project';import { linearUpdatedProject } from './lib/triggers/updated-project';import { linearRemovedProject } from './lib/triggers/removed-project';+import { linearGetIssue } from './lib/actions/issues/get-issue';+import { linearSearchIssues } from './lib/actions/issues/search-issues';+import { linearAddLabelToIssue } from './lib/actions/issues/add-label-to-issue';+import { linearRemoveLabelFromIssue } from './lib/actions/issues/remove-label-from-issue';+import { linearDeleteIssue } from './lib/actions/issues/delete-issue';+import { linearAttachLink } from './lib/actions/attachments/attach-link';+import { linearCreateProjectStatusUpdate } from './lib/actions/projects/create-project-status-update';+import { linearNewProjectStatusUpdate } from './lib/triggers/new-project-status-update';const markdown = `To obtain your API key, follow these steps:@@ -66,6 +74,13 @@ export const linear = createPiece({linearCreateProject,linearUpdateProject,linearCreateComment,+ linearGetIssue,+ linearSearchIssues,+ linearAddLabelToIssue,+ linearRemoveLabelFromIssue,+ linearDeleteIssue,+ linearAttachLink,+ linearCreateProjectStatusUpdate,linearRawGraphqlQuery,],triggers: [@@ -76,6 +91,7 @@ export const linear = createPiece({linearNewProject,linearUpdatedProject,linearRemovedProject,+ linearNewProjectStatusUpdate,],});diff --git a/packages/pieces/community/linear/src/lib/actions/attachments/attach-link.ts b/packages/pieces/community/linear/src/lib/actions/attachments/attach-link.tsnew file mode 100644index 00000000000..ab87c9bfd68--- /dev/null+++ b/packages/pieces/community/linear/src/lib/actions/attachments/attach-link.ts@@ -0,0 +1,63 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { linearAuth } from '../../..';+import { props } from '../../common/props';+import { linearGraphql } from '../../common/graphql';+import { LinearAttachmentNode, linearMappers } from '../../common/mappers';+import { ATTACHMENT_CREATE_MUTATION } from '../../common/queries';+import { attachmentOutputSchema } from '../../output-schemas';++export const linearAttachLink = createAction({+ auth: linearAuth,+ name: 'linear_attach_link',+ classification: 'WRITE',+ displayName: 'Attach Link to Issue',+ description: 'Link a URL (ticket, pull request, document) to an issue. Attaching the same URL again updates the existing link.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Attaches an external link (support ticket, pull request, document, dashboard) to a Linear issue, shown in the issue sidebar with a title and optional subtitle. Use to connect records in other tools to an issue; use Create Comment to post text instead. Idempotent: Linear updates the existing attachment when the same URL is attached to the same issue again.',+ idempotent: true,+ },+ props: {+ issue_id: props.issue_reference(),+ url: Property.ShortText({+ displayName: 'URL',+ description: 'The full link, for example https://github.com/acme/app/pull/42.',+ required: true,+ }),+ title: Property.ShortText({+ displayName: 'Title',+ description: 'Text shown for the link, for example "PR #42: Fix login timeout".',+ required: true,+ }),+ subtitle: Property.ShortText({+ displayName: 'Subtitle',+ description: 'Optional second line, for example "Open · 2 approvals".',+ required: false,+ }),+ },+ outputSchema: attachmentOutputSchema,+ async run({ auth, propsValue }) {+ const url = propsValue.url.trim();+ if (!/^https?:\/\//i.test(url)) {+ throw new Error('URL must start with http:// or https://.');+ }+ const issueId = await linearGraphql.resolveIssueId({ auth, value: propsValue.issue_id });+ const data = await linearGraphql.request<{+ attachmentCreate: { success: boolean; attachment: LinearAttachmentNode };+ }>({+ auth,+ query: ATTACHMENT_CREATE_MUTATION,+ variables: {+ input: linearGraphql.definedOnly({+ issueId,+ url,+ title: propsValue.title,+ subtitle: propsValue.subtitle,+ }),+ },+ });+ const payload = linearGraphql.requireSuccess({ payload: data.attachmentCreate, what: 'attachment' });+ return linearMappers.flattenAttachment(payload.attachment);+ },+});diff --git a/packages/pieces/community/linear/src/lib/actions/comments/create-comment.ts b/packages/pieces/community/linear/src/lib/actions/comments/create-comment.tsindex aa9fddc93a5..10e782180e1 100644--- a/packages/pieces/community/linear/src/lib/actions/comments/create-comment.ts+++ b/packages/pieces/community/linear/src/lib/actions/comments/create-comment.ts@@ -3,6 +3,7 @@ import { linearAuth } from '../../..';import { props } from '../../common/props';import { makeClient } from '../../common/client';import { LinearDocument } from '@linear/sdk';+import { commentMutationOutputSchema } from '../../output-schemas';export const linearCreateComment = createAction({auth: linearAuth,@@ -17,7 +18,10 @@ export const linearCreateComment = createAction({},props: {team_id: props.team_id(),- user_id: props.assignee_id(),+ user_id: {+ ...props.assignee_id(),+ description: 'Not used (kept for compatibility). The comment is always posted as the owner of the API key.',+ },issue_id: props.issue_id(),body: Property.LongText({displayName: 'Comment Body',@@ -25,6 +29,7 @@ export const linearCreateComment = createAction({required: true,}),},+ outputSchema: commentMutationOutputSchema,async run({ auth, propsValue }) {const comment: LinearDocument.CommentCreateInput = {issueId: propsValue.issue_id!,diff --git a/packages/pieces/community/linear/src/lib/actions/issues/add-label-to-issue.ts b/packages/pieces/community/linear/src/lib/actions/issues/add-label-to-issue.tsnew file mode 100644index 00000000000..5502cabfd92--- /dev/null+++ b/packages/pieces/community/linear/src/lib/actions/issues/add-label-to-issue.ts@@ -0,0 +1,42 @@+import { createAction } from '@activepieces/pieces-framework';+import { linearAuth } from '../../..';+import { props } from '../../common/props';+import { linearGraphql } from '../../common/graphql';+import { LinearIssueNode, linearMappers } from '../../common/mappers';+import { ISSUE_ADD_LABEL_MUTATION } from '../../common/queries';+import { issueOutputSchema } from '../../output-schemas';++export const linearAddLabelToIssue = createAction({+ auth: linearAuth,+ name: 'linear_add_label_to_issue',+ classification: 'WRITE',+ displayName: 'Add Label to Issue',+ description: 'Add one label to an issue and keep its other labels',+ audience: 'both',+ aiMetadata: {+ description:+ 'Adds one label to a Linear issue and keeps every label it already has. Use instead of Update Issue, whose Labels field replaces the whole label set. Needs the issue and the label ID (team or workspace label). Idempotent: adding a label the issue already has changes nothing. labels_complete is false when Linear did not return every label page; label_ids and label_names then hold only the labels read.',+ idempotent: true,+ },+ props: {+ team_id: props.team_id(true, "Team whose labels are listed. Pick the issue's team; workspace labels work on any issue."),+ issue_id: props.issue_reference(),+ label_id: props.label_id(),+ },+ outputSchema: issueOutputSchema,+ async run({ auth, propsValue }) {+ const labelId = propsValue.label_id;+ if (!labelId) {+ throw new Error('Select a label.');+ }+ const id = await linearGraphql.resolveIssueId({ auth, value: propsValue.issue_id });+ const data = await linearGraphql.request<{+ issueAddLabel: { success: boolean; issue: LinearIssueNode | null };+ }>({ auth, query: ISSUE_ADD_LABEL_MUTATION, variables: { id, labelId } });+ const payload = linearGraphql.requireSuccess({ payload: data.issueAddLabel, what: 'label change' });+ if (!payload.issue) {+ throw new Error('Linear did not return the updated issue.');+ }+ return linearMappers.flattenIssue(await linearGraphql.withAllIssueLabels({ auth, issue: payload.issue }));+ },+});diff --git a/packages/pieces/community/linear/src/lib/actions/issues/create-issue.ts b/packages/pieces/community/linear/src/lib/actions/issues/create-issue.tsindex 1b4c2ac47d0..d3228922817 100644--- a/packages/pieces/community/linear/src/lib/actions/issues/create-issue.ts+++ b/packages/pieces/community/linear/src/lib/actions/issues/create-issue.ts@@ -3,6 +3,8 @@ import { linearAuth } from '../../..';import { props } from '../../common/props';import { makeClient } from '../../common/client';import { LinearDocument } from '@linear/sdk';+import { linearGraphql } from '../../common/graphql';+import { issueMutationOutputSchema } from '../../output-schemas';export const linearCreateIssue = createAction({auth: linearAuth,@@ -12,7 +14,7 @@ export const linearCreateIssue = createAction({description: 'Create a new issue in Linear workspace',audience: 'both',aiMetadata: {- description: 'Creates a new issue in a Linear team, with optional assignee, status, labels, priority, and template. Use to file a task, bug, or work item. Requires a team ID and title; not idempotent, each call creates a distinct issue.',+ description: 'Creates a new issue in a Linear team, with optional assignee, status, labels, priority, template, project, cycle, parent issue (its identifier such as ENG-123, its ID, or its exact title), due date (YYYY-MM-DD) and estimate (points). Use to file a task, bug, or work item. Requires a team ID and title; not idempotent, each call creates a distinct issue.',idempotent: false,},props: {@@ -29,9 +31,26 @@ export const linearCreateIssue = createAction({labels: props.labels(),assignee_id: props.assignee_id(),priority_id: props.priority_id(),- template_id: props.template_id()+ template_id: props.template_id(),+ project_id: props.project_id(false),+ cycle_id: props.cycle_id(false),+ parent_id: props.parent_issue_id(),+ due_date: Property.DateTime({+ displayName: 'Due Date',+ description: 'Only the date part is used, for example 2026-10-15.',+ required: false,+ }),+ estimate: Property.Number({+ displayName: 'Estimate',+ description: "Estimate in the team's estimation points, for example 3. The team must have estimates enabled.",+ required: false,+ }),},+ outputSchema: issueMutationOutputSchema,async run({ auth, propsValue }) {+ const parentId = propsValue.parent_id?.trim()+ ? await linearGraphql.resolveParentIssueId({ auth, value: propsValue.parent_id, teamId: propsValue.team_id })+ : undefined;const issue: LinearDocument.IssueCreateInput = {teamId: propsValue.team_id!,title: propsValue.title,@@ -40,7 +59,9 @@ export const linearCreateIssue = createAction({stateId: propsValue.state_id,priority: propsValue.priority_id,labelIds: propsValue.labels?.length ? propsValue.labels : undefined,- templateId: propsValue.template_id+ templateId: propsValue.template_id,+ ...optionalIssueFields(propsValue),+ ...(parentId ? { parentId } : {}),};const client = makeClient(auth);const result = await client.createIssue(issue);@@ -56,3 +77,17 @@ export const linearCreateIssue = createAction({}},});++function optionalIssueFields(values: {+ project_id?: string;+ cycle_id?: string;+ due_date?: string;+ estimate?: number;+}) {+ return linearGraphql.definedOnly({+ projectId: values.project_id,+ cycleId: values.cycle_id,+ dueDate: linearGraphql.toTimelessDate({ value: values.due_date, fieldName: 'Due Date' }),+ estimate: linearGraphql.toOptionalInteger({ value: values.estimate, fieldName: 'Estimate' }),+ });+}diff --git a/packages/pieces/community/linear/src/lib/actions/issues/delete-issue.ts b/packages/pieces/community/linear/src/lib/actions/issues/delete-issue.tsnew file mode 100644index 00000000000..25a364b1d7c--- /dev/null+++ b/packages/pieces/community/linear/src/lib/actions/issues/delete-issue.ts@@ -0,0 +1,33 @@+import { createAction } from '@activepieces/pieces-framework';+import { linearAuth } from '../../..';+import { props } from '../../common/props';+import { linearGraphql } from '../../common/graphql';+import { LinearArchivedIssueNode, linearMappers } from '../../common/mappers';+import { ISSUE_DELETE_MUTATION } from '../../common/queries';+import { archivedIssueOutputSchema } from '../../output-schemas';++export const linearDeleteIssue = createAction({+ auth: linearAuth,+ name: 'linear_delete_issue',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete Issue',+ description: 'Move an issue to the trash. Linear keeps it for 30 days, so it can be restored.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Moves a Linear issue to the trash, where Linear keeps it for 30 days before deleting it for good; it is never deleted permanently by this action. Use for cleanup or de-duplication flows; to hide a finished issue without deleting it, archive it instead. Not idempotent: a second call on the same issue may fail because it is already in the trash.',+ idempotent: false,+ },+ props: {+ issue_id: props.issue_reference(),+ },+ outputSchema: archivedIssueOutputSchema,+ async run({ auth, propsValue }) {+ const id = await linearGraphql.resolveIssueId({ auth, value: propsValue.issue_id });+ const data = await linearGraphql.request<{+ issueDelete: { success: boolean; entity: LinearArchivedIssueNode | null };+ }>({ auth, query: ISSUE_DELETE_MUTATION, variables: { id } });+ const payload = linearGraphql.requireSuccess({ payload: data.issueDelete, what: 'issue deletion' });+ return linearMappers.flattenArchivedIssue(payload.entity);+ },+});diff --git a/packages/pieces/community/linear/src/lib/actions/issues/get-issue.ts b/packages/pieces/community/linear/src/lib/actions/issues/get-issue.tsnew file mode 100644index 00000000000..92c2261261b--- /dev/null+++ b/packages/pieces/community/linear/src/lib/actions/issues/get-issue.ts@@ -0,0 +1,43 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { linearAuth } from '../../..';+import { linearGraphql } from '../../common/graphql';+import { LinearIssueNode, linearMappers } from '../../common/mappers';+import { GET_ISSUE_QUERY } from '../../common/queries';+import { issueOutputSchema } from '../../output-schemas';++export const linearGetIssue = createAction({+ auth: linearAuth,+ name: 'linear_get_issue',+ classification: 'READ',+ displayName: 'Get Issue',+ description: 'Get an issue by its ID or identifier (for example ENG-123)',+ audience: 'both',+ aiMetadata: {+ description:+ 'Fetches one Linear issue by its UUID or its human identifier such as ENG-123, returning status, team, assignee, project, cycle, parent and labels. Use when a flow already holds an issue reference (from Slack, email or GitHub) and needs its current details; use Search Issues to find issues by text. Read-only and idempotent. labels_complete is false when Linear did not return every label page; label_ids and label_names then hold only the labels read.',+ idempotent: true,+ },+ props: {+ issue_id: Property.ShortText({+ displayName: 'Issue ID or Identifier',+ description: 'The issue identifier shown in Linear (for example ENG-123) or the issue UUID.',+ required: true,+ }),+ },+ outputSchema: issueOutputSchema,+ async run({ auth, propsValue }) {+ const id = propsValue.issue_id.trim();+ if (!linearGraphql.isUuid(id) && !linearGraphql.isIssueIdentifier(id)) {+ throw new Error(`"${id}" is not an issue UUID or an identifier like ENG-123.`);+ }+ const data = await linearGraphql.request<{ issue: LinearIssueNode | null }>({+ auth,+ query: GET_ISSUE_QUERY,+ variables: { id: linearGraphql.isUuid(id) ? id : id.toUpperCase() },+ });+ if (!data.issue) {+ throw new Error(`No Linear issue found for ${id}.`);+ }+ return linearMappers.flattenIssue(await linearGraphql.withAllIssueLabels({ auth, issue: data.issue }));+ },+});diff --git a/packages/pieces/community/linear/src/lib/actions/issues/issue-optional-props.test.ts b/packages/pieces/community/linear/src/lib/actions/issues/issue-optional-props.test.tsnew file mode 100644index 00000000000..b7b20011c1c--- /dev/null+++ b/packages/pieces/community/linear/src/lib/actions/issues/issue-optional-props.test.ts@@ -0,0 +1,168 @@+/// <reference types="vitest/globals" />++import { vi } from 'vitest';+import { createMockActionContext } from '@activepieces/pieces-framework';++const createIssue = vi.fn();+const updateIssue = vi.fn();+const rawRequest = vi.fn();++vi.mock('@linear/sdk', () => ({+ LinearClient: class {+ createIssue = createIssue;+ updateIssue = updateIssue;+ client = { rawRequest };+ },+ LinearDocument: {},+}));++import '../../../index';+import { linearCreateIssue } from './create-issue';+import { linearUpdateIssue } from './update-issue';++const auth = { type: 'SECRET_TEXT', secret_text: 'lin_api_test' };+const ok = { success: true, lastSyncId: 1, issue: Promise.resolve({ id: 'i1' }) };++function context(propsValue: Record<string, unknown>) {+ return { ...createMockActionContext({ propsValue }), auth };+}++describe('new optional issue props', () => {+ beforeEach(() => {+ createIssue.mockReset().mockResolvedValue(ok);+ updateIssue.mockReset().mockResolvedValue(ok);+ rawRequest.mockReset();+ });++ test('create sends project, cycle, parent, due date and estimate when given', async () => {+ await linearCreateIssue.run(+ context({ team_id: 't1', title: 'T', project_id: 'p1', cycle_id: 'c1', parent_id: '3f1a2b4c-5d6e-4f70-8a9b-0c1d2e3f4a5b', due_date: '2026-10-15T00:00:00.000Z', estimate: 3 }),+ );+ expect(createIssue.mock.calls[0][0]).toMatchObject({ projectId: 'p1', cycleId: 'c1', parentId: '3f1a2b4c-5d6e-4f70-8a9b-0c1d2e3f4a5b', dueDate: '2026-10-15', estimate: 3 });+ });++ test('update without the new props sends none of them (today\'s behaviour)', async () => {+ await linearUpdateIssue.run(context({ team_id: 't1', issue_id: 'i1', title: 'New' }));+ const input = JSON.parse(JSON.stringify(updateIssue.mock.calls[0][1]));+ expect(input).toEqual({ title: 'New' });+ });++ test('parent issue accepts an identifier and resolves it to the issue id', async () => {+ linearRoutes({ identifiers: { 'ENG-7': 'parent-uuid' } });+ await linearCreateIssue.run(context({ team_id: 't1', title: 'Child', parent_id: ' eng-7 ' }));+ expect(variablesOf('LinearIssueIdLookup')).toMatchObject({ id: 'ENG-7' });+ expect(createIssue.mock.calls[0][0]).toMatchObject({ parentId: 'parent-uuid' });+ });++ test('parent issue passes a UUID through without a lookup, on create and update', async () => {+ const uuid = '0b6d0a4c-2f0e-4a51-9d8e-4a2b1d1c9f00';+ await linearCreateIssue.run(context({ team_id: 't1', title: 'Child', parent_id: uuid }));+ await linearUpdateIssue.run(context({ team_id: 't1', issue_id: 'i1', parent_id: uuid }));+ expect(rawRequest).not.toHaveBeenCalled();+ expect(createIssue.mock.calls[0][0]).toMatchObject({ parentId: uuid });+ expect(updateIssue.mock.calls[0][1]).toMatchObject({ parentId: uuid });+ });++ test('an unknown parent fails before the issue is created', async () => {+ linearRoutes({});+ await expect(linearCreateIssue.run(context({ team_id: 't1', title: 'Child', parent_id: 'ENG-404' }))).rejects.toThrow(+ 'No issue with the identifier or exact title "ENG-404" was found in this team. Use its identifier (for example ENG-123) or ID.',+ );+ expect(createIssue).not.toHaveBeenCalled();+ });++ test('parent issue also accepts the exact title, looked up with an exact filter in the team', async () => {+ linearRoutes({+ titles: [+ { id: 'other', identifier: 'ENG-2', title: 'Checkout redesign v2' },+ { id: 'wanted', identifier: 'ENG-1', title: 'Checkout redesign' },+ ],+ });+ await linearCreateIssue.run(context({ team_id: 't1', title: 'Child', parent_id: ' checkout REDESIGN ' }));+ expect(callsOf('LinearParentTitleLookup')).toHaveLength(1);+ expect(variablesOf('LinearParentTitleLookup')).toEqual({+ first: 2,+ filter: { title: { eqIgnoreCase: 'checkout REDESIGN' }, team: { id: { eq: 't1' } } },+ });+ expect(createIssue.mock.calls[0][0]).toMatchObject({ parentId: 'wanted' });+ });++ test('two issues with the same title are refused as ambiguous', async () => {+ linearRoutes({ titles: [{ id: 'a', identifier: 'ENG-4', title: 'Bug' }, { id: 'b', identifier: 'ENG-5', title: 'bug' }, { id: 'c', identifier: 'ENG-6', title: 'BUG' }] });+ await expect(linearUpdateIssue.run(context({ team_id: 't1', issue_id: 'i1', parent_id: 'Bug' }))).rejects.toThrow(+ '"Bug" matches more than one issue: ENG-4 (title), ENG-5 (title). Use the ID of the one you mean.',+ );+ expect(updateIssue).not.toHaveBeenCalled();+ });++ test('an identifier-shaped title is found by title when no issue has that identifier', async () => {+ linearRoutes({ titles: [{ id: 'titled', identifier: 'OPS-3', title: 'ENG-12' }] });+ await linearCreateIssue.run(context({ team_id: 't1', title: 'Child', parent_id: 'ENG-12' }));+ expect(createIssue.mock.calls[0][0]).toMatchObject({ parentId: 'titled' });+ });++ test('an identifier that is also another issue title is refused instead of guessed', async () => {+ linearRoutes({ identifiers: { 'ENG-12': 'by-identifier' }, titles: [{ id: 'titled', identifier: 'OPS-3', title: 'ENG-12' }] });+ await expect(linearCreateIssue.run(context({ team_id: 't1', title: 'Child', parent_id: 'ENG-12' }))).rejects.toThrow(+ '"ENG-12" matches more than one issue: ENG-12 (identifier), OPS-3 (title). Use the ID of the one you mean.',+ );+ expect(createIssue).not.toHaveBeenCalled();+ });++ test('the same issue matching by identifier and by title is not ambiguous', async () => {+ linearRoutes({ identifiers: { 'ENG-12': 'same' }, titles: [{ id: 'same', identifier: 'ENG-12', title: 'ENG-12' }] });+ await linearCreateIssue.run(context({ team_id: 't1', title: 'Child', parent_id: 'ENG-12' }));+ expect(createIssue.mock.calls[0][0]).toMatchObject({ parentId: 'same' });+ });++ test('a valid identifier still works when the title lookup fails', async () => {+ linearRoutes({ identifiers: { 'ENG-7': 'by-identifier' }, titleError: new Error('Rate limit exceeded') });+ await linearCreateIssue.run(context({ team_id: 't1', title: 'Child', parent_id: 'ENG-7' }));+ expect(createIssue.mock.calls[0][0]).toMatchObject({ parentId: 'by-identifier' });+ });++ test('a failed title lookup is reported when there is no identifier match', async () => {+ linearRoutes({ titleError: new Error('Rate limit exceeded') });+ await expect(linearCreateIssue.run(context({ team_id: 't1', title: 'Child', parent_id: 'Checkout redesign' }))).rejects.toThrow(+ 'Rate limit exceeded',+ );+ expect(createIssue).not.toHaveBeenCalled();+ });+});++function linearRoutes({ identifiers = {}, titles = [], titleError }: LinearRoutes) {+ rawRequest.mockImplementation(async (query: string, variables: Record<string, unknown>) => {+ if (query.includes('LinearIssueIdLookup')) {+ const id = identifiers[String(variables['id'])];+ return { data: { issue: id ? { id } : null } };+ }+ if (query.includes('LinearParentTitleLookup')) {+ if (titleError) {+ throw titleError;+ }+ const filter = variables['filter'];+ const wanted = isRecord(filter) && isRecord(filter['title']) ? String(filter['title']['eqIgnoreCase']).toLowerCase() : '';+ const nodes = titles.filter((issue) => issue.title.toLowerCase() === wanted).slice(0, Number(variables['first']));+ return { data: { issues: { nodes } } };+ }+ throw new Error(`unexpected query ${query}`);+ });+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+}++function callsOf(name: string): Record<string, unknown>[] {+ return rawRequest.mock.calls.filter((call) => String(call[0]).includes(name)).map((call) => call[1]);+}++function variablesOf(name: string): Record<string, unknown> {+ return callsOf(name)[0];+}++type LinearRoutes = {+ identifiers?: Record<string, string>;+ titles?: Array<{ id: string; identifier: string; title: string }>;+ titleError?: Error;+};diff --git a/packages/pieces/community/linear/src/lib/actions/issues/remove-label-from-issue.ts b/packages/pieces/community/linear/src/lib/actions/issues/remove-label-from-issue.tsnew file mode 100644index 00000000000..6a0f2b0ea1a--- /dev/null+++ b/packages/pieces/community/linear/src/lib/actions/issues/remove-label-from-issue.ts@@ -0,0 +1,35 @@+import { createAction } from '@activepieces/pieces-framework';+import { linearAuth } from '../../..';+import { props } from '../../common/props';+import { linearGraphql } from '../../common/graphql';+import { linearMappers } from '../../common/mappers';+import { issueOutputSchema } from '../../output-schemas';++export const linearRemoveLabelFromIssue = createAction({+ auth: linearAuth,+ name: 'linear_remove_label_from_issue',+ classification: 'WRITE',+ displayName: 'Remove Label from Issue',+ description: 'Remove one label from an issue and keep its other labels',+ audience: 'both',+ aiMetadata: {+ description:+ 'Removes one label from a Linear issue and keeps its other labels; the label itself is not deleted. Use instead of Update Issue, whose Labels field replaces the whole label set. Needs the issue and the label ID. Idempotent: removing a label the issue does not have changes nothing. labels_complete is false when Linear did not return every label page; label_ids and label_names then hold only the labels read.',+ idempotent: true,+ },+ props: {+ team_id: props.team_id(true, "Team whose labels are listed. Pick the issue's team; workspace labels work on any issue."),+ issue_id: props.issue_reference(),+ label_id: props.label_id(),+ },+ outputSchema: issueOutputSchema,+ async run({ auth, propsValue }) {+ const labelId = propsValue.label_id;+ if (!labelId) {+ throw new Error('Select a label.');+ }+ const id = await linearGraphql.resolveIssueId({ auth, value: propsValue.issue_id });+ const issue = await linearGraphql.removeIssueLabel({ auth, id, labelId });+ return linearMappers.flattenIssue(issue);+ },+});diff --git a/packages/pieces/community/linear/src/lib/actions/issues/search-issues.ts b/packages/pieces/community/linear/src/lib/actions/issues/search-issues.tsnew file mode 100644index 00000000000..7f48cd8d494--- /dev/null+++ b/packages/pieces/community/linear/src/lib/actions/issues/search-issues.ts@@ -0,0 +1,79 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { linearAuth } from '../../..';+import { props } from '../../common/props';+import { linearGraphql } from '../../common/graphql';+import { LinearConnection, LinearIssueNode, linearMappers } from '../../common/mappers';+import { SEARCH_ISSUES_QUERY } from '../../common/queries';+import { issueSearchOutputSchema } from '../../output-schemas';++export const linearSearchIssues = createAction({+ auth: linearAuth,+ name: 'linear_search_issues',+ classification: 'SEARCH',+ displayName: 'Search Issues',+ description: 'Search issues by text, optionally in one team',+ audience: 'both',+ aiMetadata: {+ description:+ 'Runs a Linear full-text and semantic search over issue titles and descriptions (optionally comments), optionally limited to one team, and returns the best matches first. When has_next_page is true, pass end_cursor as cursor to get the next page. Use to find an existing issue before creating a duplicate; use Get Issue when the identifier is already known. Linear limits search to 30 requests per minute, and a just-created issue can take a moment to appear. Read-only and idempotent. labels_complete is false when Linear did not return every label page; label_ids and label_names then hold only the labels read.',+ idempotent: true,+ },+ props: {+ term: Property.ShortText({+ displayName: 'Search Text',+ description: 'Words to look for, for example "login timeout".',+ required: true,+ }),+ team_id: {+ ...props.team_id(false),+ description: 'Only return issues from this team. Leave empty to search every team you can access.',+ },+ include_comments: Property.Checkbox({+ displayName: 'Also Search Comments',+ required: false,+ defaultValue: false,+ }),+ include_archived: Property.Checkbox({+ displayName: 'Include Archived Issues',+ required: false,+ defaultValue: false,+ }),+ limit: Property.Number({+ displayName: 'Max Results',+ description: 'How many issues to return, 1 to 100. Default 25.',+ required: false,+ defaultValue: 25,+ }),+ cursor: Property.ShortText({+ displayName: 'Cursor',+ description: 'End Cursor from a previous search. Empty for the first page.',+ required: false,+ }),+ },+ outputSchema: issueSearchOutputSchema,+ async run({ auth, propsValue }) {+ const term = propsValue.term.trim();+ if (term.length === 0) {+ throw new Error('Search Text cannot be empty.');+ }+ const data = await linearGraphql.request<{+ searchIssues: LinearConnection<LinearIssueNode> & { totalCount: number };+ }>({+ auth,+ query: SEARCH_ISSUES_QUERY,+ variables: {+ term,+ first: linearGraphql.clampLimit({ value: propsValue.limit, fallback: 25, max: 100 }),+ after: propsValue.cursor?.trim() || undefined,+ includeComments: propsValue.include_comments === true,+ includeArchived: propsValue.include_archived === true,+ filter: propsValue.team_id ? { team: { id: { eq: propsValue.team_id } } } : undefined,+ },+ });+ const nodes = await linearGraphql.withAllIssuesLabels({ auth, issues: data.searchIssues.nodes });+ return {+ ...linearMappers.toPage({ connection: { ...data.searchIssues, nodes }, map: linearMappers.flattenIssue }),+ total_count: data.searchIssues.totalCount,+ };+ },+});diff --git a/packages/pieces/community/linear/src/lib/actions/issues/update-issue.ts b/packages/pieces/community/linear/src/lib/actions/issues/update-issue.tsindex a42fd91fabc..c00cce65131 100644--- a/packages/pieces/community/linear/src/lib/actions/issues/update-issue.ts+++ b/packages/pieces/community/linear/src/lib/actions/issues/update-issue.ts@@ -3,6 +3,8 @@ import { linearAuth } from '../../..';import { props } from '../../common/props';import { makeClient } from '../../common/client';import { LinearDocument } from '@linear/sdk';+import { linearGraphql } from '../../common/graphql';+import { issueMutationOutputSchema } from '../../output-schemas';export const linearUpdateIssue = createAction({auth: linearAuth,@@ -12,7 +14,7 @@ export const linearUpdateIssue = createAction({description: 'Update a issue in Linear Workspace',audience: 'both',aiMetadata: {- description: 'Updates an existing Linear issue identified by its issue ID, changing fields such as title, description, assignee, status, labels, or priority. Use to modify an issue already created. Only the provided fields are changed; repeating the same update is idempotent.',+ description: 'Updates an existing Linear issue identified by its issue ID, changing fields such as title, description, assignee, status, labels, priority, project, cycle, parent issue (its identifier such as ENG-123, its ID, or its exact title), due date (YYYY-MM-DD) or estimate (points). Use to modify an issue already created. Only the provided fields are changed; repeating the same update is idempotent.',idempotent: true,},props: {@@ -30,8 +32,25 @@ export const linearUpdateIssue = createAction({labels: props.labels(),assignee_id: props.assignee_id(),priority_id: props.priority_id(),+ project_id: props.project_id(false),+ cycle_id: props.cycle_id(false),+ parent_id: props.parent_issue_id(),+ due_date: Property.DateTime({+ displayName: 'Due Date',+ description: 'Only the date part is used, for example 2026-10-15.',+ required: false,+ }),+ estimate: Property.Number({+ displayName: 'Estimate',+ description: "Estimate in the team's estimation points, for example 3. The team must have estimates enabled.",+ required: false,+ }),},+ outputSchema: issueMutationOutputSchema,async run({ auth, propsValue }) {+ const parentId = propsValue.parent_id?.trim()+ ? await linearGraphql.resolveParentIssueId({ auth, value: propsValue.parent_id, teamId: propsValue.team_id })+ : undefined;const issueId = propsValue.issue_id!;const issue: LinearDocument.IssueUpdateInput = {title: propsValue.title,@@ -40,6 +59,8 @@ export const linearUpdateIssue = createAction({stateId: propsValue.state_id,priority: propsValue.priority_id,labelIds: propsValue.labels?.length ? propsValue.labels : undefined,+ ...optionalIssueFields(propsValue),+ ...(parentId ? { parentId } : {}),};const client = makeClient(auth);const result = await client.updateIssue(issueId, issue);@@ -55,3 +76,17 @@ export const linearUpdateIssue = createAction({}},});++function optionalIssueFields(values: {+ project_id?: string;+ cycle_id?: string;+ due_date?: string;+ estimate?: number;+}) {+ return linearGraphql.definedOnly({+ projectId: values.project_id,+ cycleId: values.cycle_id,+ dueDate: linearGraphql.toTimelessDate({ value: values.due_date, fieldName: 'Due Date' }),+ estimate: linearGraphql.toOptionalInteger({ value: values.estimate, fieldName: 'Estimate' }),+ });+}diff --git a/packages/pieces/community/linear/src/lib/actions/new-actions.test.ts b/packages/pieces/community/linear/src/lib/actions/new-actions.test.tsnew file mode 100644index 00000000000..e1363255458--- /dev/null+++ b/packages/pieces/community/linear/src/lib/actions/new-actions.test.ts@@ -0,0 +1,442 @@+/// <reference types="vitest/globals" />++import { vi } from 'vitest';+import { createMockActionContext } from '@activepieces/pieces-framework';++const rawRequest = vi.fn();+const issues = vi.fn();+const issueLabels = vi.fn();++vi.mock('@linear/sdk', () => ({+ LinearClient: class {+ client = { rawRequest };+ issues = issues;+ issueLabels = issueLabels;+ },+ LinearDocument: { PaginationOrderBy: { UpdatedAt: 'updatedAt' } },+}));++import '../../index';+import { linearGetIssue } from './issues/get-issue';+import { linearSearchIssues } from './issues/search-issues';+import { linearAddLabelToIssue } from './issues/add-label-to-issue';+import { linearRemoveLabelFromIssue } from './issues/remove-label-from-issue';+import { linearDeleteIssue } from './issues/delete-issue';+import { linearAttachLink } from './attachments/attach-link';+import { linearCreateProjectStatusUpdate } from './projects/create-project-status-update';+import { linearCreateIssue } from './issues/create-issue';+import { linearUpdateIssue } from './issues/update-issue';+import { props as linearProps } from '../common/props';++const auth = { type: 'SECRET_TEXT', secret_text: 'lin_api_test' };+const UUID = '0b6d0a4c-2f0e-4a51-9d8e-4a2b1d1c9f00';++function context(propsValue: Record<string, unknown>) {+ return { ...createMockActionContext({ propsValue }), auth };+}++function toRecord(value: unknown): Record<string, unknown> {+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {+ throw new Error('expected an object');+ }+ return Object.fromEntries(Object.entries(value));+}++function populated(): unknown {+ const base: Record<string, unknown> = { success: true, id: UUID, totalCount: 1, pageInfo: { hasNextPage: false, endCursor: null } };+ const proxy: unknown = new Proxy(base, {+ get(target, prop) {+ if (typeof prop === 'symbol' || prop === 'then' || prop === 'toJSON') return undefined;+ if (prop === 'nodes') return [proxy];+ if (prop in target) return target[prop];+ return proxy;+ },+ });+ return proxy;+}++function keys(fields: Array<{ key: string; value?: string }>): string[] {+ return fields.map((field) => field.value ?? field.key).sort();+}++const cases = [+ { action: linearGetIssue, props: { issue_id: 'ENG-1' } },+ { action: linearSearchIssues, props: { term: 'login', team_id: UUID, limit: 5 } },+ { action: linearAddLabelToIssue, props: { team_id: UUID, issue_id: UUID, label_id: UUID } },+ { action: linearRemoveLabelFromIssue, props: { team_id: UUID, issue_id: UUID, label_id: UUID } },+ { action: linearDeleteIssue, props: { team_id: UUID, issue_id: UUID } },+ { action: linearAttachLink, props: { team_id: UUID, issue_id: UUID, url: 'https://github.com/a/b/pull/1', title: 'PR 1' } },+ { action: linearCreateProjectStatusUpdate, props: { team_id: UUID, project_id: UUID, body: 'On track', health: 'onTrack' } },+];++describe('PR-A actions', () => {+ beforeEach(() => {+ rawRequest.mockReset();+ rawRequest.mockImplementation(async () => ({ data: populated() }));+ });++ test.each(cases)('$action.name output matches its outputSchema', async ({ action, props }) => {+ const result = toRecord(await action.run(context(props)));+ const fields = action.outputSchema?.fields ?? [];+ expect(Object.keys(result).sort()).toEqual(keys(fields));+ const itemsField = fields.find((field) => field.key === 'items');+ const items = result['items'];+ if (itemsField?.listItems && Array.isArray(items)) {+ expect(Object.keys(items[0]).sort()).toEqual(keys(itemsField.listItems));+ }+ });++ test('search filters by team through filter, and delete never sends permanentlyDelete', async () => {+ await linearSearchIssues.run(context({ term: 'x', team_id: UUID }));+ expect(rawRequest.mock.calls[0][1]).toMatchObject({ filter: { team: { id: { eq: UUID } } } });+ expect(rawRequest.mock.calls[0][1]).not.toHaveProperty('teamId');+ rawRequest.mockClear();+ await linearDeleteIssue.run(context({ team_id: UUID, issue_id: UUID }));+ expect(rawRequest.mock.calls[0][0]).not.toContain('permanentlyDelete');+ });++ test('search passes the cursor as after, and sends no after when it is empty', async () => {+ await linearSearchIssues.run(context({ term: 'x', cursor: ' cursor-1 ' }));+ expect(rawRequest.mock.calls[0][1]).toMatchObject({ after: 'cursor-1' });+ rawRequest.mockClear();+ await linearSearchIssues.run(context({ term: 'x' }));+ expect(rawRequest.mock.calls[0][1].after).toBeUndefined();+ rawRequest.mockClear();+ await linearSearchIssues.run(context({ term: 'x', cursor: '' }));+ expect(rawRequest.mock.calls[0][1].after).toBeUndefined();+ });++ test('attach link refuses a non-http url before any request', async () => {+ await expect(+ linearAttachLink.run(context({ team_id: UUID, issue_id: UUID, url: 'javascript:alert(1)', title: 'x' })),+ ).rejects.toThrow('http');+ expect(rawRequest).not.toHaveBeenCalled();+ });+});++describe('Parent Issue', () => {+ beforeEach(() => {+ rawRequest.mockReset();+ });++ test('is a text field, so the saved value is always shown and nothing is fetched while typing', () => {+ expect(linearCreateIssue.props['parent_id']).toMatchObject({ type: 'SHORT_TEXT', required: false });+ expect(linearUpdateIssue.props['parent_id']).toMatchObject({ type: 'SHORT_TEXT', required: false });+ });+});++function labelNodes({ from, count }: { from: number; count: number }) {+ return Array.from({ length: count }, (_, index) => ({ id: `label-${from + index}`, name: `L${from + index}` }));+}++function labelIds({ count }: { count: number }): string[] {+ return labelNodes({ from: 0, count }).map((label) => label.id);+}++function issueWithLabels({ id = UUID, count }: { id?: string; count: number }) {+ const nodes = labelNodes({ from: 0, count: Math.min(count, 20) });+ return {+ id,+ identifier: 'ENG-1',+ title: 'T',+ labels: { pageInfo: { hasNextPage: count > 20, endCursor: nodes.length > 0 ? nodes[nodes.length - 1].id : null }, nodes },+ };+}++function linearIssueLabels({ total, variables }: { total: number; variables: Record<string, unknown> }) {+ const all = labelNodes({ from: 0, count: total });+ const first = typeof variables['first'] === 'number' ? variables['first'] : 50;+ const after = variables['after'];+ const filter = variables['filter'];+ const idFilter = typeof filter === 'object' && filter !== null && 'id' in filter ? filter.id : undefined;+ const excluded = typeof idFilter === 'object' && idFilter !== null && 'nin' in idFilter && Array.isArray(idFilter.nin) ? idFilter.nin : [];+ const connection = ({ nodes, hasNextPage }: { nodes: typeof all; hasNextPage: boolean }) => ({+ data: { issue: { labels: { pageInfo: { hasNextPage, endCursor: nodes.length > 0 ? nodes[nodes.length - 1].id : null }, nodes } } },+ });+ if (typeof after === 'string') {+ return connection({ nodes: all.slice(0, Math.max(all.findIndex((label) => label.id === after), 0)).reverse().slice(0, first), hasNextPage: false });+ }+ if (filter !== undefined) {+ const remaining = all.filter((label) => !excluded.includes(label.id)).reverse();+ return connection({ nodes: remaining.slice(0, first), hasNextPage: remaining.length > first });+ }+ return connection({ nodes: all.slice(0, first), hasNextPage: all.length > first });+}++function labelPageCalls(): Array<Record<string, unknown>> {+ return rawRequest.mock.calls.filter(([query]) => String(query).includes('LinearIssueLabelsPage')).map(([, variables]) => variables);+}++describe('issue labels beyond the first 20', () => {+ beforeEach(() => {+ rawRequest.mockReset();+ });++ test('the fake pages labels the way Linear does: after walks backwards, first and an id filter walk forward', () => {+ expect(linearIssueLabels({ total: 22, variables: { first: 250, after: 'label-19' } }).data.issue.labels.nodes.map((label) => label.id)).toEqual(+ labelIds({ count: 19 }).reverse(),+ );+ expect(linearIssueLabels({ total: 22, variables: { first: 250 } }).data.issue.labels.nodes).toHaveLength(22);+ });++ test.each([22, 305])('Get Issue returns all %i labels once each, with labels_complete true', async (total) => {+ rawRequest.mockImplementation(async (query: string, variables: Record<string, unknown>) =>+ query.includes('LinearIssueLabelsPage') ? linearIssueLabels({ total, variables }) : { data: { issue: issueWithLabels({ count: total }) } },+ );+ const result = toRecord(await linearGetIssue.run(context({ issue_id: 'ENG-1' })));+ const ids = Array.isArray(result['label_ids']) ? result['label_ids'] : [];+ expect([...ids].sort()).toEqual(labelIds({ count: total }).sort());+ expect(new Set(ids).size).toBe(total);+ expect(result['labels_complete']).toBe(true);+ expect(rawRequest.mock.calls[0][0]).toContain('labels(first: 20)');+ const pages = labelPageCalls();+ expect(pages[0]).toEqual({ id: UUID, first: 250 });+ expect(pages.every((variables) => !('after' in variables))).toBe(true);+ expect(pages).toHaveLength(total > 250 ? 2 : 1);+ });++ test('Get Issue makes no extra request when every label fits in the first page', async () => {+ rawRequest.mockResolvedValueOnce({ data: { issue: issueWithLabels({ count: 3 }) } });+ const result = toRecord(await linearGetIssue.run(context({ issue_id: 'ENG-1' })));+ expect(result['label_ids']).toHaveLength(3);+ expect(result['labels_complete']).toBe(true);+ expect(rawRequest).toHaveBeenCalledTimes(1);+ });++ test.each([+ { page: 'repeats labels already read', repeat: labelNodes({ from: 0, count: 250 }), hasNextPage: true },+ { page: 'walks backwards over labels already read', repeat: labelNodes({ from: 230, count: 20 }).reverse(), hasNextPage: false },+ { page: 'brings nothing new but claims more', repeat: [], hasNextPage: true },+ ])('a follow-up page that $page is detected, so labels_complete is false and no label is duplicated', async ({ repeat, hasNextPage }) => {+ rawRequest.mockImplementation(async (query: string, variables: Record<string, unknown>) => {+ if (!query.includes('LinearIssueLabelsPage')) {+ return { data: { issue: issueWithLabels({ count: 305 }) } };+ }+ if (variables['filter'] === undefined) {+ return linearIssueLabels({ total: 305, variables });+ }+ return { data: { issue: { labels: { pageInfo: { hasNextPage, endCursor: null }, nodes: repeat } } } };+ });+ const result = toRecord(await linearGetIssue.run(context({ issue_id: 'ENG-1' })));+ const ids = Array.isArray(result['label_ids']) ? result['label_ids'] : [];+ expect(ids).toEqual(labelIds({ count: 250 }));+ expect(result['labels_complete']).toBe(false);+ });++ test('a follow-up page that fails keeps every label already read, with labels_complete false', async () => {+ rawRequest.mockImplementation(async (query: string, variables: Record<string, unknown>) => {+ if (!query.includes('LinearIssueLabelsPage')) {+ return { data: { issue: issueWithLabels({ count: 305 }) } };+ }+ if (variables['filter'] !== undefined) {+ throw new Error('network down');+ }+ return linearIssueLabels({ total: 305, variables });+ });+ const result = toRecord(await linearGetIssue.run(context({ issue_id: 'ENG-1' })));+ expect(result['label_ids']).toEqual(labelIds({ count: 250 }));+ expect(result['labels_complete']).toBe(false);+ expect(labelPageCalls()).toHaveLength(2);+ });++ test('a first page with a repeated label is de-duplicated when the re-read fails', async () => {+ const issue = issueWithLabels({ count: 25 });+ rawRequest+ .mockResolvedValueOnce({ data: { issue: { ...issue, labels: { ...issue.labels, nodes: [...issue.labels.nodes, issue.labels.nodes[0]] } } } })+ .mockRejectedValueOnce(new Error('network down'));+ const result = toRecord(await linearGetIssue.run(context({ issue_id: 'ENG-1' })));+ expect(result['label_ids']).toEqual(labelIds({ count: 20 }));+ expect(result['labels_complete']).toBe(false);+ });++ test('Search Issues completes the labels of each issue that has more than 20', async () => {+ rawRequest.mockImplementation(async (query: string, variables: Record<string, unknown>) => {+ if (query.includes('LinearIssueLabelsPage')) {+ return linearIssueLabels({ total: 30, variables });+ }+ return {+ data: {+ searchIssues: {+ totalCount: 2,+ pageInfo: { hasNextPage: false, endCursor: null },+ nodes: [issueWithLabels({ id: 'issue-a', count: 30 }), issueWithLabels({ id: 'issue-b', count: 2 })],+ },+ },+ };+ });+ const result = toRecord(await linearSearchIssues.run(context({ term: 'x' })));+ const items = Array.isArray(result['items']) ? result['items'].map((item) => toRecord(item)) : [];+ expect(items.map((item) => item['label_ids'])).toEqual([labelIds({ count: 30 }), ['label-0', 'label-1']]);+ expect(items.map((item) => item['labels_complete'])).toEqual([true, true]);+ expect(labelPageCalls()).toEqual([{ id: 'issue-a', first: 250 }]);+ });++ test('Add Label and Remove Label return every label of the issue', async () => {+ rawRequest.mockImplementation(async (query: string, variables: Record<string, unknown>) => {+ if (query.includes('LinearIssueLabelsPage')) {+ return linearIssueLabels({ total: 21, variables });+ }+ const payload = { success: true, issue: issueWithLabels({ count: 21 }) };+ return { data: query.includes('issueAddLabel') ? { issueAddLabel: payload } : { issueRemoveLabel: payload } };+ });+ const added = toRecord(await linearAddLabelToIssue.run(context({ team_id: UUID, issue_id: UUID, label_id: 'label-20' })));+ expect(added['label_ids']).toEqual(labelIds({ count: 21 }));+ expect(added['labels_complete']).toBe(true);+ const removed = toRecord(await linearRemoveLabelFromIssue.run(context({ team_id: UUID, issue_id: UUID, label_id: 'label-99' })));+ expect(removed['label_ids']).toEqual(labelIds({ count: 21 }));+ expect(removed['labels_complete']).toBe(true);+ });++ test('Add Label succeeds with labels_complete false when the follow-up label read fails', async () => {+ rawRequest+ .mockResolvedValueOnce({ data: { issueAddLabel: { success: true, issue: issueWithLabels({ count: 22 }) } } })+ .mockRejectedValueOnce(new Error('network down'));+ const added = toRecord(await linearAddLabelToIssue.run(context({ team_id: UUID, issue_id: UUID, label_id: 'label-20' })));+ expect(added['label_ids']).toEqual(labelIds({ count: 20 }));+ expect(added['labels_complete']).toBe(false);+ });++ test('Search Issues reads the label pages of several issues at once and marks only the failed one incomplete', async () => {+ let inFlight = 0;+ let maxInFlight = 0;+ rawRequest.mockImplementation(async (query: string, variables: Record<string, unknown>) => {+ if (!query.includes('LinearIssueLabelsPage')) {+ return {+ data: {+ searchIssues: {+ totalCount: 3,+ pageInfo: { hasNextPage: false, endCursor: null },+ nodes: ['issue-a', 'issue-b', 'issue-c'].map((id) => issueWithLabels({ id, count: 25 })),+ },+ },+ };+ }+ inFlight += 1;+ maxInFlight = Math.max(maxInFlight, inFlight);+ await new Promise((resolve) => setTimeout(resolve, 10));+ inFlight -= 1;+ if (variables['id'] === 'issue-b') {+ throw new Error('network down');+ }+ return linearIssueLabels({ total: 25, variables });+ });+ const result = toRecord(await linearSearchIssues.run(context({ term: 'x' })));+ const items = Array.isArray(result['items']) ? result['items'].map((item) => toRecord(item)) : [];+ expect(maxInFlight).toBe(3);+ expect(items.map((item) => item['labels_complete'])).toEqual([true, false, true]);+ expect(items.map((item) => Array.isArray(item['label_ids']) ? item['label_ids'].length : 0)).toEqual([25, 20, 25]);+ });+});++describe('issue field of Add Label, Remove Label, Delete Issue and Attach Link', () => {+ beforeEach(() => {+ rawRequest.mockReset();+ });++ const actions = [+ { action: linearAddLabelToIssue, props: { team_id: UUID, label_id: 'label-1' }, mutation: 'issueAddLabel' },+ { action: linearRemoveLabelFromIssue, props: { team_id: UUID, label_id: 'label-1' }, mutation: 'issueRemoveLabel' },+ { action: linearDeleteIssue, props: {}, mutation: 'issueDelete' },+ { action: linearAttachLink, props: { url: 'https://github.com/a/b/pull/1', title: 'PR 1' }, mutation: 'attachmentCreate' },+ ];++ test.each(actions)('$action.name takes any issue as text under the issue_id key', ({ action }) => {+ expect(action.props['issue_id']).toMatchObject({ type: 'SHORT_TEXT', required: true });+ });++ test.each(actions)('$action.name resolves an identifier like eng-7 to the issue UUID', async ({ action, props, mutation }) => {+ rawRequest.mockImplementation(async (query: string) => {+ if (query.includes('LinearIssueIdLookup')) return { data: { issue: { id: UUID } } };+ return { data: populated() };+ });+ await action.run(context({ ...props, issue_id: ' eng-7 ' }));+ expect(rawRequest.mock.calls[0][1]).toEqual({ id: 'ENG-7' });+ const mutationCall = rawRequest.mock.calls.find(([query]) => String(query).includes(mutation));+ expect(JSON.stringify(mutationCall?.[1])).toContain(UUID);+ });++ test.each(actions)('$action.name reports an unknown identifier', async ({ action, props }) => {+ rawRequest.mockResolvedValue({ data: { issue: null } });+ await expect(action.run(context({ ...props, issue_id: 'ENG-404' }))).rejects.toThrow('No Linear issue found for ENG-404');+ expect(rawRequest).toHaveBeenCalledTimes(1);+ });++ test('Delete Issue and Attach Link no longer ask for a team', () => {+ expect(linearDeleteIssue.props).not.toHaveProperty('team_id');+ expect(linearAttachLink.props).not.toHaveProperty('team_id');+ });+});++describe('Label and Cycle dropdowns', () => {+ beforeEach(() => {+ rawRequest.mockReset();+ issueLabels.mockReset();+ });++ test('Label dropdown lists team labels, then workspace labels', async () => {+ issueLabels+ .mockResolvedValueOnce({ nodes: [{ id: 'l2', name: 'Bug' }], pageInfo: { hasNextPage: false } })+ .mockResolvedValueOnce({ nodes: [{ id: 'l1', name: 'Security' }], pageInfo: { hasNextPage: false } });+ const result = await linearProps.label_id().options({ auth, team_id: UUID }, createMockActionContext({}));+ expect(result).toEqual({+ disabled: false,+ options: [+ { label: 'Bug', value: 'l2' },+ { label: '[Workspace] Security', value: 'l1' },+ ],+ });+ });++ test('Label dropdown shows why it could not load instead of throwing', async () => {+ issueLabels.mockRejectedValue(new Error('network down'));+ const result = await linearProps.label_id().options({ auth, team_id: UUID }, createMockActionContext({}));+ expect(result).toEqual({ disabled: true, placeholder: 'Could not load labels: network down', options: [] });+ });++ test('Cycle dropdown asks Linear only for current and upcoming cycles', async () => {+ rawRequest.mockResolvedValue({+ data: {+ cycles: {+ pageInfo: { hasNextPage: false, endCursor: null },+ nodes: [+ { id: 'c1', number: 4, name: null, startsAt: '2026-09-27T00:00:00.000Z', isActive: true, isNext: false, isPast: false },+ { id: 'c2', number: 5, name: 'Polish', startsAt: '2026-10-04T00:00:00.000Z', isActive: false, isNext: true, isPast: false },+ ],+ },+ },+ });+ const result = await linearProps.cycle_id().options({ auth, team_id: UUID }, createMockActionContext({}));+ expect(rawRequest.mock.calls[0][1]).toMatchObject({ filter: { team: { id: { eq: UUID } }, isPast: { eq: false } } });+ expect(result).toMatchObject({+ disabled: false,+ options: [+ { label: 'Cycle 4 · starts 2026-09-27 (current)', value: 'c1' },+ { label: 'Cycle 5 Polish · starts 2026-10-04 (next)', value: 'c2' },+ ],+ });+ });+});++describe('Team and Label fields of Add Label and Remove Label', () => {+ beforeEach(() => {+ rawRequest.mockReset();+ });++ const labelActions = [linearAddLabelToIssue, linearRemoveLabelFromIssue];++ test.each(labelActions)('$name explains which team to pick', (action) => {+ expect(action.props['team_id']).toMatchObject({+ required: true,+ description: "Team whose labels are listed. Pick the issue's team; workspace labels work on any issue.",+ });+ });++ test('other actions keep the shared Team description', () => {+ expect(linearCreateIssue.props['team_id']).toMatchObject({ description: 'The team for which the issue, project or comment will be created' });+ });++ test.each(labelActions)('$name asks for a label before looking up the issue', async (action) => {+ await expect(action.run(context({ team_id: UUID, issue_id: 'ENG-7', label_id: '' }))).rejects.toThrow('Select a label.');+ expect(rawRequest).not.toHaveBeenCalled();+ });+});diff --git a/packages/pieces/community/linear/src/lib/actions/projects/create-project-status-update.ts b/packages/pieces/community/linear/src/lib/actions/projects/create-project-status-update.tsnew file mode 100644index 00000000000..b8c77bc8de5--- /dev/null+++ b/packages/pieces/community/linear/src/lib/actions/projects/create-project-status-update.ts@@ -0,0 +1,53 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { linearAuth } from '../../..';+import { props } from '../../common/props';+import { linearGraphql } from '../../common/graphql';+import { LinearProjectStatusUpdateNode, linearMappers } from '../../common/mappers';+import { PROJECT_STATUS_UPDATE_CREATE_MUTATION } from '../../common/queries';+import { projectStatusUpdateOutputSchema } from '../../output-schemas';++export const linearCreateProjectStatusUpdate = createAction({+ auth: linearAuth,+ name: 'linear_create_project_status_update',+ classification: 'WRITE',+ displayName: 'Post Project Status Update',+ description: 'Post a status update (with health) on a project, like the weekly update in the project page',+ audience: 'both',+ aiMetadata: {+ description:+ 'Posts a status update on a Linear project: a markdown body plus an optional health of on track, at risk or off track, shown in the project Updates tab. This does not change the project itself; use Update Project to edit its name, dates or status. Not idempotent: each call posts a new update.',+ idempotent: false,+ },+ props: {+ team_id: props.team_id(),+ project_id: props.project_id(),+ body: Property.LongText({+ displayName: 'Update',+ description: 'The update text. Markdown is supported.',+ required: true,+ }),+ health: props.project_health(false),+ },+ outputSchema: projectStatusUpdateOutputSchema,+ async run({ auth, propsValue }) {+ const projectId = propsValue.project_id;+ if (!projectId) {+ throw new Error('Select a project.');+ }+ const data = await linearGraphql.request<{+ projectUpdateCreate: { success: boolean; projectUpdate: LinearProjectStatusUpdateNode };+ }>({+ auth,+ query: PROJECT_STATUS_UPDATE_CREATE_MUTATION,+ variables: {+ input: linearGraphql.definedOnly({+ projectId,+ body: propsValue.body,+ health: propsValue.health,+ }),+ },+ });+ const payload = linearGraphql.requireSuccess({ payload: data.projectUpdateCreate, what: 'project status update' });+ return linearMappers.flattenProjectStatusUpdate(payload.projectUpdate);+ },+});diff --git a/packages/pieces/community/linear/src/lib/actions/projects/create-project.ts b/packages/pieces/community/linear/src/lib/actions/projects/create-project.tsindex f261c8ee058..e7f0951e947 100644--- a/packages/pieces/community/linear/src/lib/actions/projects/create-project.ts+++ b/packages/pieces/community/linear/src/lib/actions/projects/create-project.ts@@ -2,6 +2,7 @@ import { createAction, Property } from '@activepieces/pieces-framework';import { linearAuth } from '../../..';import { props } from '../../common/props';import { makeClient } from '../../common/client';+import { projectMutationOutputSchema } from '../../output-schemas';export const linearCreateProject = createAction({auth: linearAuth,@@ -42,6 +43,7 @@ export const linearCreateProject = createAction({}),state: props.project_status(false),},+ outputSchema: projectMutationOutputSchema,async run({ auth, propsValue }) {const client = makeClient(auth);const input: Record<string, unknown> = {diff --git a/packages/pieces/community/linear/src/lib/actions/projects/update-project.test.ts b/packages/pieces/community/linear/src/lib/actions/projects/update-project.test.tsnew file mode 100644index 00000000000..96a5b4c61e9--- /dev/null+++ b/packages/pieces/community/linear/src/lib/actions/projects/update-project.test.ts@@ -0,0 +1,104 @@+/// <reference types="vitest/globals" />++import { vi } from 'vitest';+import { createMockActionContext } from '@activepieces/pieces-framework';++const rawRequest = vi.fn();++vi.mock('@linear/sdk', () => ({+ LinearClient: class {+ client = { rawRequest };+ },+ LinearDocument: {},+}));++import '../../../index';+import { linearUpdateProject } from './update-project';++const auth = { type: 'SECRET_TEXT', secret_text: 'lin_api_test' };++function run(propsValue: Record<string, unknown>) {+ return linearUpdateProject.run({ ...createMockActionContext({ propsValue }), auth });+}++describe('linear_update_project team handling (F1)', () => {+ beforeEach(() => {+ rawRequest.mockReset();+ rawRequest.mockImplementation(async (query: string) => {+ if (query.includes('LinearProjectTeamIds')) {+ return {+ data: {+ project: {+ id: 'p1',+ teams: { pageInfo: { hasNextPage: false, endCursor: null }, nodes: [{ id: 'team-a' }, { id: 'team-b' }] },+ },+ },+ };+ }+ return { data: { projectUpdate: { success: true, lastSyncId: 1, project: { id: 'p1' } } } };+ });+ });++ function sentInput() {+ const mutation = rawRequest.mock.calls.find(([query]) => String(query).includes('UpdateProject('));+ return mutation?.[1]?.input;+ }++ test('keeps the current teams and adds the selected one', async () => {+ await run({ team_id: 'team-c', project_id: 'p1', name: 'Renamed' });+ expect(sentInput().teamIds).toEqual(['team-a', 'team-b', 'team-c']);+ });++ test('does not send teamIds when the selected team is already on the project', async () => {+ await run({ team_id: 'team-b', project_id: 'p1', name: 'Renamed' });+ const input = sentInput();+ expect(input.teamIds).toBeUndefined();+ expect(JSON.parse(JSON.stringify(input))).not.toHaveProperty('teamIds');+ expect(input.name).toBe('Renamed');+ });++ test('reads every page of teams before adding a new one', async () => {+ const firstPage = Array.from({ length: 250 }, (_, index) => ({ id: `team-${index}` }));+ rawRequest.mockImplementation(async (query: string, variables?: Record<string, unknown>) => {+ if (query.includes('LinearProjectTeamIds')) {+ const after = variables?.['after'];+ if (after === undefined) {+ return { data: { project: { id: 'p1', teams: { pageInfo: { hasNextPage: true, endCursor: 'c1' }, nodes: firstPage } } } };+ }+ if (after === 'c1') {+ return { data: { project: { id: 'p1', teams: { pageInfo: { hasNextPage: true, endCursor: 'c2' }, nodes: [{ id: 'team-250' }] } } } };+ }+ return { data: { project: { id: 'p1', teams: { pageInfo: { hasNextPage: false, endCursor: null }, nodes: [{ id: 'team-251' }] } } } };+ }+ return { data: { projectUpdate: { success: true, lastSyncId: 1, project: { id: 'p1' } } } };+ });+ await run({ team_id: 'team-new', project_id: 'p1' });+ const teamQueries = rawRequest.mock.calls.filter(([query]) => String(query).includes('LinearProjectTeamIds'));+ expect(teamQueries.map(([, variables]) => variables.after)).toEqual([undefined, 'c1', 'c2']);+ const teamIds = sentInput().teamIds;+ expect(teamIds).toHaveLength(253);+ expect(teamIds.slice(-3)).toEqual(['team-250', 'team-251', 'team-new']);+ });++ test('does not send teamIds when the selected team is on a later page', async () => {+ rawRequest.mockImplementation(async (query: string, variables?: Record<string, unknown>) => {+ if (query.includes('LinearProjectTeamIds')) {+ if (variables?.['after'] === undefined) {+ return { data: { project: { id: 'p1', teams: { pageInfo: { hasNextPage: true, endCursor: 'c1' }, nodes: [{ id: 'team-a' }] } } } };+ }+ return { data: { project: { id: 'p1', teams: { pageInfo: { hasNextPage: false, endCursor: null }, nodes: [{ id: 'team-z' }] } } } };+ }+ return { data: { projectUpdate: { success: true, lastSyncId: 1, project: { id: 'p1' } } } };+ });+ await run({ team_id: 'team-z', project_id: 'p1', name: 'Renamed' });+ expect(sentInput().teamIds).toBeUndefined();+ });++ test('name is optional and not sent when left empty', async () => {+ await run({ team_id: 'team-a', project_id: 'p1', description: 'New summary' });+ const input = sentInput();+ expect(input.name).toBeUndefined();+ expect(JSON.parse(JSON.stringify(input))).not.toHaveProperty('name');+ expect(input.description).toBe('New summary');+ });+});diff --git a/packages/pieces/community/linear/src/lib/actions/projects/update-project.ts b/packages/pieces/community/linear/src/lib/actions/projects/update-project.tsindex 6409a509287..6b3c1172361 100644--- a/packages/pieces/community/linear/src/lib/actions/projects/update-project.ts+++ b/packages/pieces/community/linear/src/lib/actions/projects/update-project.ts@@ -2,6 +2,9 @@ import { createAction, Property } from '@activepieces/pieces-framework';import { linearAuth } from '../../..';import { props } from '../../common/props';import { makeClient } from '../../common/client';+import { LinearAuth, linearGraphql } from '../../common/graphql';+import { PROJECT_TEAM_IDS_QUERY } from '../../common/queries';+import { projectMutationOutputSchema } from '../../output-schemas';export const linearUpdateProject = createAction({auth: linearAuth,@@ -11,7 +14,7 @@ export const linearUpdateProject = createAction({description: 'Update a existing project in Linear workspace',audience: 'both',aiMetadata: {- description: 'Updates an existing Linear project identified by its project ID, changing fields such as name, description, icon, color, start/target dates, or status. Use to modify a project already created. Repeating the same update is idempotent.',+ description: 'Updates an existing Linear project identified by its project ID, changing fields such as name, description, icon, color, start/target dates, or status, and adds the selected team to the project without removing its other teams. Use to modify a project already created. Repeating the same update is idempotent.',idempotent: true,},props: {@@ -19,7 +22,8 @@ export const linearUpdateProject = createAction({project_id: props.project_id(),name: Property.ShortText({displayName: 'Project Name',- required: true,+ description: 'Leave empty to keep the current name.',+ required: false,}),description: Property.LongText({displayName: 'Description',@@ -43,10 +47,16 @@ export const linearUpdateProject = createAction({}),state: props.project_status(false),},+ outputSchema: projectMutationOutputSchema,async run({ auth, propsValue }) {const client = makeClient(auth);+ const currentTeamIds = await listProjectTeamIds({+ auth,+ projectId: propsValue.project_id!,+ });+ const teamId = propsValue.team_id!;const input: Record<string, unknown> = {- teamIds: [propsValue.team_id!],+ teamIds: currentTeamIds.includes(teamId) ? undefined : [...currentTeamIds, teamId],name: propsValue.name,description: propsValue.description,icon: propsValue.icon,@@ -101,3 +111,31 @@ export const linearUpdateProject = createAction({}},});++async function listProjectTeamIds({+ auth,+ projectId,+}: {+ auth: LinearAuth;+ projectId: string;+}): Promise<string[]> {+ const teamIds: string[] = [];+ let after: string | undefined;+ let hasNextPage = false;+ do {+ const data = await linearGraphql.request<{+ project: {+ id: string;+ teams: {+ pageInfo: { hasNextPage: boolean; endCursor?: string | null };+ nodes: Array<{ id: string }>;+ };+ } | null;+ }>({ auth, query: PROJECT_TEAM_IDS_QUERY, variables: { id: projectId, after } });+ const teams = data.project?.teams;+ teamIds.push(...(teams?.nodes.map((team) => team.id) ?? []));+ hasNextPage = teams?.pageInfo.hasNextPage === true && typeof teams.pageInfo.endCursor === 'string';+ after = teams?.pageInfo.endCursor ?? undefined;+ } while (hasNextPage);+ return teamIds;+}diff --git a/packages/pieces/community/linear/src/lib/common/client.ts b/packages/pieces/community/linear/src/lib/common/client.tsindex fd62da9fd8e..f12d842a83d 100644--- a/packages/pieces/community/linear/src/lib/common/client.ts+++ b/packages/pieces/community/linear/src/lib/common/client.ts@@ -91,6 +91,9 @@ export class LinearClientWrapper {async rawRequest(query: string, variables?: Record<string, unknown>) {return this.client.client.rawRequest(query, variables);}+ async typedRequest<Data>(query: string, variables?: Record<string, unknown>) {+ return this.client.client.rawRequest<Data, Record<string, unknown>>(query, variables);+ }}export function makeClient(auth: AppConnectionValueForAuthProperty<typeof linearAuth>): LinearClientWrapper {diff --git a/packages/pieces/community/linear/src/lib/common/graphql.test.ts b/packages/pieces/community/linear/src/lib/common/graphql.test.tsnew file mode 100644index 00000000000..208226a2733--- /dev/null+++ b/packages/pieces/community/linear/src/lib/common/graphql.test.ts@@ -0,0 +1,109 @@+/// <reference types="vitest/globals" />++import { vi } from 'vitest';++const rawRequest = vi.fn();++vi.mock('@linear/sdk', () => ({+ LinearClient: class {+ client = { rawRequest };+ },+ LinearDocument: {},+}));++import '../../index';+import { linearGraphql } from './graphql';++const auth = { type: 'SECRET_TEXT', secret_text: 'lin_api_test' };++describe('linearGraphql helpers', () => {+ beforeEach(() => rawRequest.mockReset());++ test('definedOnly drops undefined, null and blank strings but keeps false, 0 and arrays', () => {+ expect(+ linearGraphql.definedOnly({ a: undefined, b: null, c: '', d: ' ', e: false, f: 0, g: [], h: 'x' }),+ ).toEqual({ e: false, f: 0, g: [], h: 'x' });+ });++ test('toTimelessDate keeps the date part and rejects anything else', () => {+ expect(linearGraphql.toTimelessDate({ value: '2026-10-15', fieldName: 'Due' })).toBe('2026-10-15');+ expect(linearGraphql.toTimelessDate({ value: '2026-10-15T00:00:00.000Z', fieldName: 'Due' })).toBe('2026-10-15');+ expect(linearGraphql.toTimelessDate({ value: undefined, fieldName: 'Due' })).toBeUndefined();+ expect(() => linearGraphql.toTimelessDate({ value: '15/10/2026', fieldName: 'Due' })).toThrow('YYYY-MM-DD');+ });++ test('toStringArray trims, drops blanks and returns undefined for an empty list', () => {+ expect(linearGraphql.toStringArray([' a ', '', 3])).toEqual(['a', '3']);+ expect(linearGraphql.toStringArray([])).toBeUndefined();+ expect(linearGraphql.toStringArray(undefined)).toBeUndefined();+ });++ test('clampLimit bounds the page size', () => {+ expect(linearGraphql.clampLimit({ value: undefined, fallback: 50, max: 250 })).toBe(50);+ expect(linearGraphql.clampLimit({ value: 1000, fallback: 50, max: 250 })).toBe(250);+ expect(linearGraphql.clampLimit({ value: '0', fallback: 50, max: 250 })).toBe(1);+ });++ test('resolveIssueId passes a UUID through without a request', async () => {+ const id = '0b6d0a4c-2f0e-4a51-9d8e-4a2b1d1c9f00';+ expect(await linearGraphql.resolveIssueId({ auth, value: id })).toBe(id);+ expect(rawRequest).not.toHaveBeenCalled();+ });++ test('resolveIssueId looks up an identifier once and returns the UUID', async () => {+ rawRequest.mockResolvedValue({ data: { issue: { id: 'uuid-1' } } });+ expect(await linearGraphql.resolveIssueId({ auth, value: 'eng-12' })).toBe('uuid-1');+ expect(rawRequest).toHaveBeenCalledTimes(1);+ expect(rawRequest.mock.calls[0][1]).toEqual({ id: 'ENG-12' });+ });++ test('resolveIssueId rejects values that are neither', async () => {+ await expect(linearGraphql.resolveIssueId({ auth, value: 'not an id' })).rejects.toThrow('not an issue UUID');+ await expect(linearGraphql.resolveIssueId({ auth, value: '' })).rejects.toThrow('required');+ });++ test('request maps Linear error types to actionable messages', async () => {+ rawRequest.mockRejectedValueOnce(Object.assign(new Error('x'), { type: 'Forbidden', errors: [{ message: 'no access' }] }));+ await expect(linearGraphql.request({ auth, query: 'query { viewer { id } }' })).rejects.toThrow('Write or Admin permission');+ rawRequest.mockRejectedValueOnce(Object.assign(new Error('x'), { type: 'Ratelimited' }));+ await expect(linearGraphql.request({ auth, query: 'query { viewer { id } }' })).rejects.toThrow('rate limit');+ rawRequest.mockRejectedValueOnce(Object.assign(new Error('x'), { type: 'InvalidInput', errors: [{ message: 'bad teamId' }] }));+ await expect(linearGraphql.request({ auth, query: 'query { viewer { id } }' })).rejects.toThrow('bad teamId');+ });++ test('not-found and plan-limit errors read cleanly', async () => {+ rawRequest.mockRejectedValueOnce(Object.assign(new Error('x'), { type: 'InvalidInput', errors: [{ message: 'Could not find referenced Issue.' }] }));+ await expect(linearGraphql.resolveIssueId({ auth, value: 'ENG-99999' })).rejects.toThrow('No Linear issue found for ENG-99999.');+ rawRequest.mockRejectedValueOnce(Object.assign(new Error('x'), { type: 'InvalidInput', errors: [{ message: 'Could not find referenced ProjectUpdate.' }] }));+ await expect(linearGraphql.request({ auth, query: 'query { viewer { id } }' })).rejects.toThrow('No Linear project status update found');+ rawRequest.mockRejectedValueOnce(+ Object.assign(new Error('x'), { type: 'Forbidden', errors: [{ message: 'You have reached the limit of teams allowed in your current plan. Please upgrade to create more teams.' }] }),+ );+ await expect(linearGraphql.request({ auth, query: 'query { viewer { id } }' })).rejects.toMatchObject({+ message:+ 'Linear refused this request: You have reached the limit of teams allowed in your current plan. Please upgrade to create more teams.',+ });+ });++ test('requireSuccess refuses a payload without success', () => {+ expect(() => linearGraphql.requireSuccess({ payload: { success: false }, what: 'thing' })).toThrow('did not confirm the thing');+ });++ test('mapWithConcurrency runs at most the limit at once and keeps the input order', async () => {+ let inFlight = 0;+ let maxInFlight = 0;+ const results = await linearGraphql.mapWithConcurrency({+ items: Array.from({ length: 12 }, (_, index) => index),+ limit: linearGraphql.FOLLOW_UP_CONCURRENCY,+ map: async (item) => {+ inFlight += 1;+ maxInFlight = Math.max(maxInFlight, inFlight);+ await new Promise((resolve) => setTimeout(resolve, 5));+ inFlight -= 1;+ return item * 2;+ },+ });+ expect(maxInFlight).toBe(5);+ expect(results).toEqual(Array.from({ length: 12 }, (_, index) => index * 2));+ });+});diff --git a/packages/pieces/community/linear/src/lib/common/graphql.ts b/packages/pieces/community/linear/src/lib/common/graphql.tsnew file mode 100644index 00000000000..0cc70aad9d6--- /dev/null+++ b/packages/pieces/community/linear/src/lib/common/graphql.ts@@ -0,0 +1,412 @@+import { AppConnectionValueForAuthProperty } from '@activepieces/pieces-framework';+import { linearAuth } from '../..';+import { makeClient } from './client';+import { LinearIssueLabel, LinearIssueLabelConnection, LinearIssueNode } from './mappers';+import {+ GET_ISSUE_QUERY,+ ISSUE_ID_LOOKUP_QUERY,+ ISSUE_LABELS_PAGE_QUERY,+ ISSUE_REMOVE_LABEL_MUTATION,+ PARENT_TITLE_LOOKUP_QUERY,+} from './queries';++async function request<T>({ auth, query, variables }: RequestParams): Promise<T> {+ try {+ const result = await makeClient(auth).typedRequest<T>(query, variables);+ if (result.data === undefined || result.data === null) {+ throw new Error('Linear returned an empty response.');+ }+ return result.data;+ } catch (error) {+ throw toActionError(error);+ }+}++function toActionError(error: unknown): Error {+ if (!isLinearError(error)) {+ return error instanceof Error ? error : new Error(String(error));+ }+ const detail = (firstGraphqlMessage(error) ?? error.message).trim().replace(/\.+$/, '');+ const notFound = NOT_FOUND_PATTERN.exec(detail);+ if (notFound) {+ return new Error(`No Linear ${describeEntity(notFound[1])} found with that ID. Check the ID and that this API key can see it.`);+ }+ switch (error.type) {+ case 'AuthenticationError':+ return new Error(+ 'Linear did not accept the API key of this connection. Create a new personal API key in Linear (Settings, Security & access) and update the connection.',+ );+ case 'Forbidden':+ if (PLAN_LIMIT_PATTERN.test(detail)) {+ return new Error(`Linear refused this request: ${detail}.`);+ }+ return new Error(+ `Linear refused this request: ${detail}. The API key may be missing the Write or Admin permission, or may not have access to this team.`,+ );+ case 'Ratelimited':+ return new Error('Linear rate limit reached. Wait a minute and try again.');+ case 'InvalidInput':+ return new Error(`Linear rejected the input: ${detail}.`);+ case 'FeatureNotAccessible':+ return new Error(`This Linear feature is not available on the workspace plan: ${detail}`);+ default:+ return new Error(`Linear API error: ${detail}`);+ }+}++function isNotFoundError(error: unknown): boolean {+ if (!(error instanceof Error)) return false;+ return error.message.startsWith('No Linear ') || NOT_FOUND_PATTERN.test(error.message);+}++function describeEntity(typeName: string): string {+ if (typeName === 'ProjectUpdate') return 'project status update';+ return typeName.replace(/([a-z])([A-Z])/g, '$1 $2').toLowerCase();+}++async function removeIssueLabel({ auth, id, labelId }: { auth: LinearAuth; id: string; labelId: string }): Promise<LinearIssueNode> {+ try {+ const data = await request<{ issueRemoveLabel: { success: boolean; issue: LinearIssueNode | null } }>({+ auth,+ query: ISSUE_REMOVE_LABEL_MUTATION,+ variables: { id, labelId },+ });+ const payload = requireSuccess({ payload: data.issueRemoveLabel, what: 'label change' });+ if (!payload.issue) {+ throw new Error('Linear did not return the updated issue.');+ }+ return await withAllIssueLabels({ auth, issue: payload.issue });+ } catch (error) {+ if (!(error instanceof Error) || !LABEL_NOT_ON_ISSUE_PATTERN.test(error.message)) {+ throw error;+ }+ const current = await request<{ issue: LinearIssueNode | null }>({ auth, query: GET_ISSUE_QUERY, variables: { id } });+ if (!current.issue) {+ throw error;+ }+ return withAllIssueLabels({ auth, issue: current.issue });+ }+}++async function withAllIssueLabels({ auth, issue }: { auth: LinearAuth; issue: LinearIssueNode }): Promise<LinearIssueNode> {+ if (issue.labels?.pageInfo?.hasNextPage !== true) {+ return issue;+ }+ const firstPage = uniqueLabels({ labels: issue.labels.nodes });+ return { ...issue, labels: await readAllIssueLabels({ auth, issueId: issue.id, known: firstPage }) };+}++async function readAllIssueLabels({+ auth,+ issueId,+ known,+}: {+ auth: LinearAuth;+ issueId: string;+ known: LinearIssueLabel[];+}): Promise<LinearIssueLabelConnection> {+ const read = new Map<string, LinearIssueLabel>();+ for (let page = 0; page < MAX_LABEL_PAGES; page += 1) {+ const readIds = [...read.keys()];+ const data: IssueLabelsPage | undefined = await request<IssueLabelsPage>({+ auth,+ query: ISSUE_LABELS_PAGE_QUERY,+ variables: { id: issueId, first: LABEL_PAGE_SIZE, ...(readIds.length > 0 ? { filter: { id: { nin: readIds } } } : {}) },+ }).catch(() => undefined);+ const connection = data?.issue?.labels;+ if (!connection) {+ break;+ }+ const fresh = uniqueLabels({ labels: connection.nodes }).filter((label) => !read.has(label.id));+ fresh.forEach((label) => read.set(label.id, label));+ if (fresh.length < connection.nodes.length) {+ break;+ }+ if (connection.pageInfo?.hasNextPage !== true) {+ return { nodes: [...read.values()], pageInfo: { hasNextPage: false, endCursor: null } };+ }+ if (fresh.length === 0) {+ break;+ }+ }+ return { nodes: uniqueLabels({ labels: [...read.values(), ...known] }), pageInfo: { hasNextPage: true, endCursor: null } };+}++function uniqueLabels({ labels }: { labels: LinearIssueLabel[] }): LinearIssueLabel[] {+ const seen = new Set<string>();+ return labels.filter((label) => {+ if (seen.has(label.id)) {+ return false;+ }+ seen.add(label.id);+ return true;+ });+}++async function withAllIssuesLabels({ auth, issues }: { auth: LinearAuth; issues: LinearIssueNode[] }): Promise<LinearIssueNode[]> {+ return mapWithConcurrency({ items: issues, limit: FOLLOW_UP_CONCURRENCY, map: (issue) => withAllIssueLabels({ auth, issue }) });+}++async function mapWithConcurrency<TItem, TResult>({+ items,+ limit,+ map,+}: {+ items: TItem[];+ limit: number;+ map: (item: TItem) => Promise<TResult>;+}): Promise<TResult[]> {+ const results: TResult[] = new Array(items.length);+ let next = 0;+ const worker = async (): Promise<void> => {+ while (next < items.length) {+ const index = next;+ next += 1;+ results[index] = await map(items[index]);+ }+ };+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, () => worker()));+ return results;+}++function isUuid(value: string): boolean {+ return UUID_PATTERN.test(value);+}++function isIssueIdentifier(value: string): boolean {+ return ISSUE_IDENTIFIER_PATTERN.test(value);+}++async function resolveIssueId({ auth, value }: { auth: LinearAuth; value: unknown }): Promise<string> {+ const trimmed = typeof value === 'string' ? value.trim() : '';+ if (trimmed.length === 0) {+ throw new Error('An issue ID or identifier (for example ENG-123) is required.');+ }+ if (isUuid(trimmed)) {+ return trimmed;+ }+ if (!isIssueIdentifier(trimmed)) {+ throw new Error(`"${trimmed}" is not an issue UUID or an identifier like ENG-123.`);+ }+ const data = await request<{ issue: { id: string } | null }>({+ auth,+ query: ISSUE_ID_LOOKUP_QUERY,+ variables: { id: trimmed.toUpperCase() },+ }).catch((error: unknown) => {+ if (isNotFoundError(error)) {+ throw new Error(`No Linear issue found for ${trimmed}.`);+ }+ throw error;+ });+ if (!data.issue?.id) {+ throw new Error(`No Linear issue found for ${trimmed}.`);+ }+ return data.issue.id;+}++async function resolveParentIssueId({+ auth,+ value,+ teamId,+}: {+ auth: LinearAuth;+ value: string;+ teamId: string | undefined;+}): Promise<string> {+ const trimmed = value.trim();+ if (isUuid(trimmed)) {+ return trimmed;+ }+ const [identifierResult, titleResult] = await Promise.allSettled([+ isIssueIdentifier(trimmed) ? findIssueIdByIdentifier({ auth, identifier: trimmed }) : Promise.resolve(undefined),+ findIssuesByExactTitle({ auth, title: trimmed, teamId }),+ ]);+ if (identifierResult.status === 'rejected') {+ throw identifierResult.reason;+ }+ const byIdentifier = identifierResult.value;+ if (titleResult.status === 'rejected') {+ if (byIdentifier) {+ return byIdentifier;+ }+ throw titleResult.reason;+ }+ const byTitle = titleResult.value;+ const candidates = [+ ...(byIdentifier ? [{ id: byIdentifier, label: `${trimmed.toUpperCase()} (identifier)` }] : []),+ ...byTitle.filter((issue) => issue.id !== byIdentifier).map((issue) => ({ id: issue.id, label: `${issue.identifier} (title)` })),+ ];+ if (candidates.length === 1) {+ return candidates[0].id;+ }+ if (candidates.length === 0) {+ throw new Error(+ `No issue with the identifier or exact title "${trimmed}" was found${teamId ? ' in this team' : ''}. Use its identifier (for example ENG-123) or ID.`,+ );+ }+ throw new Error(+ `"${trimmed}" matches more than one issue: ${candidates.map((candidate) => candidate.label).join(', ')}. Use the ID of the one you mean.`,+ );+}++async function findIssueIdByIdentifier({ auth, identifier }: { auth: LinearAuth; identifier: string }): Promise<string | undefined> {+ const data = await request<{ issue: { id: string } | null }>({+ auth,+ query: ISSUE_ID_LOOKUP_QUERY,+ variables: { id: identifier.toUpperCase() },+ }).catch((error: unknown) => {+ if (isNotFoundError(error)) {+ return { issue: null };+ }+ throw error;+ });+ return data.issue?.id ?? undefined;+}++async function findIssuesByExactTitle({+ auth,+ title,+ teamId,+}: {+ auth: LinearAuth;+ title: string;+ teamId: string | undefined;+}): Promise<Array<{ id: string; identifier: string }>> {+ const data = await request<{ issues: { nodes: Array<{ id: string; identifier: string; title: string }> } }>({+ auth,+ query: PARENT_TITLE_LOOKUP_QUERY,+ variables: {+ first: PARENT_TITLE_MATCH_LIMIT,+ filter: {+ title: { eqIgnoreCase: title },+ ...(teamId ? { team: { id: { eq: teamId } } } : {}),+ },+ },+ });+ return data.issues.nodes;+}++function toTimelessDate({ value, fieldName }: { value: unknown; fieldName: string }): string | undefined {+ if (value === undefined || value === null || value === '') {+ return undefined;+ }+ if (typeof value !== 'string') {+ throw new Error(`${fieldName} must be a date in YYYY-MM-DD format.`);+ }+ const match = /^(\d{4}-\d{2}-\d{2})(?:$|T)/.exec(value.trim());+ if (!match || Number.isNaN(Date.parse(match[1]))) {+ throw new Error(`${fieldName} must be a date in YYYY-MM-DD format, got "${value}".`);+ }+ return match[1];+}++function definedOnly(input: Record<string, unknown>): Record<string, unknown> {+ return Object.fromEntries(+ Object.entries(input).filter(([, value]) => {+ if (value === undefined || value === null) return false;+ if (typeof value === 'string' && value.trim() === '') return false;+ return true;+ }),+ );+}++function toStringArray(value: unknown): string[] | undefined {+ if (value === undefined || value === null) return undefined;+ const items = (Array.isArray(value) ? value : [value])+ .filter((item): item is string | number => typeof item === 'string' || typeof item === 'number')+ .map((item) => String(item).trim())+ .filter((item) => item.length > 0);+ return items.length > 0 ? items : undefined;+}++function toOptionalNumber({ value, fieldName }: { value: unknown; fieldName: string }): number | undefined {+ if (value === undefined || value === null || value === '') return undefined;+ const parsed = typeof value === 'number' ? value : Number(value);+ if (!Number.isFinite(parsed)) {+ throw new Error(`${fieldName} must be a number.`);+ }+ return parsed;+}++function toOptionalInteger({ value, fieldName }: { value: unknown; fieldName: string }): number | undefined {+ const parsed = toOptionalNumber({ value, fieldName });+ if (parsed !== undefined && !Number.isInteger(parsed)) {+ throw new Error(`${fieldName} must be a whole number.`);+ }+ return parsed;+}++function clampLimit({ value, fallback, max }: { value: unknown; fallback: number; max: number }): number {+ const parsed = toOptionalNumber({ value, fieldName: 'Limit' });+ if (parsed === undefined) return fallback;+ if (parsed < 1) return 1;+ return Math.min(Math.floor(parsed), max);+}++function requireSuccess<T extends { success: boolean }>({ payload, what }: { payload: T | null | undefined; what: string }): T {+ if (!payload || payload.success !== true) {+ throw new Error(`Linear did not confirm the ${what}.`);+ }+ return payload;+}++function isLinearError(error: unknown): error is LinearErrorLike {+ return (+ typeof error === 'object' &&+ error !== null &&+ 'message' in error &&+ ('type' in error || 'errors' in error)+ );+}++function firstGraphqlMessage(error: LinearErrorLike): string | undefined {+ return error.errors?.find((e) => typeof e.message === 'string' && e.message.length > 0)?.message;+}++const PARENT_TITLE_MATCH_LIMIT = 2;+const FOLLOW_UP_CONCURRENCY = 5;+const LABEL_PAGE_SIZE = 250;+const MAX_LABEL_PAGES = 20;+const NOT_FOUND_PATTERN = /Could not find referenced (\w+)/i;+const PLAN_LIMIT_PATTERN = /\b(plan|upgrade)\b/i;+const LABEL_NOT_ON_ISSUE_PATTERN = /is not on issue/i;+const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;+const ISSUE_IDENTIFIER_PATTERN = /^[A-Za-z][A-Za-z0-9_]*-\d+$/;++export const linearGraphql = {+ request,+ toActionError,+ resolveIssueId,+ resolveParentIssueId,+ isUuid,+ isIssueIdentifier,+ toTimelessDate,+ definedOnly,+ toStringArray,+ toOptionalNumber,+ toOptionalInteger,+ clampLimit,+ requireSuccess,+ removeIssueLabel,+ isNotFoundError,+ withAllIssueLabels,+ withAllIssuesLabels,+ mapWithConcurrency,+ FOLLOW_UP_CONCURRENCY,+};++export type LinearAuth = AppConnectionValueForAuthProperty<typeof linearAuth>;++type RequestParams = {+ auth: LinearAuth;+ query: string;+ variables?: Record<string, unknown>;+};++type IssueLabelsPage = { issue: { labels: LinearIssueLabelConnection | null } | null };++type LinearErrorLike = {+ type?: string;+ message: string;+ errors?: Array<{ message?: string }>;+};diff --git a/packages/pieces/community/linear/src/lib/common/mappers.ts b/packages/pieces/community/linear/src/lib/common/mappers.tsnew file mode 100644index 00000000000..e92b5617f30--- /dev/null+++ b/packages/pieces/community/linear/src/lib/common/mappers.ts@@ -0,0 +1,292 @@+function flattenIssue(issue: LinearIssueNode): FlatIssue {+ const labels = issue.labels?.nodes ?? [];+ return {+ id: issue.id,+ identifier: issue.identifier,+ number: issue.number,+ title: issue.title,+ description: issue.description ?? null,+ url: issue.url,+ priority: issue.priority,+ priority_label: issue.priorityLabel,+ estimate: issue.estimate ?? null,+ due_date: issue.dueDate ?? null,+ branch_name: issue.branchName,+ state_id: issue.state?.id ?? null,+ state_name: issue.state?.name ?? null,+ state_type: issue.state?.type ?? null,+ team_id: issue.team?.id ?? null,+ team_key: issue.team?.key ?? null,+ team_name: issue.team?.name ?? null,+ assignee_id: issue.assignee?.id ?? null,+ assignee_name: issue.assignee?.name ?? null,+ assignee_email: issue.assignee?.email ?? null,+ creator_id: issue.creator?.id ?? null,+ creator_name: issue.creator?.name ?? null,+ creator_email: issue.creator?.email ?? null,+ project_id: issue.project?.id ?? null,+ project_name: issue.project?.name ?? null,+ project_milestone_id: issue.projectMilestone?.id ?? null,+ project_milestone_name: issue.projectMilestone?.name ?? null,+ cycle_id: issue.cycle?.id ?? null,+ cycle_number: issue.cycle?.number ?? null,+ cycle_name: issue.cycle?.name ?? null,+ parent_id: issue.parent?.id ?? null,+ parent_identifier: issue.parent?.identifier ?? null,+ parent_title: issue.parent?.title ?? null,+ label_ids: labels.map((label) => label.id),+ label_names: labels.map((label) => label.name).join(', '),+ labels_complete: issue.labels?.pageInfo?.hasNextPage !== true,+ created_at: issue.createdAt,+ updated_at: issue.updatedAt,+ started_at: issue.startedAt ?? null,+ completed_at: issue.completedAt ?? null,+ canceled_at: issue.canceledAt ?? null,+ archived_at: issue.archivedAt ?? null,+ trashed: issue.trashed ?? false,+ };+}++function flattenAttachment(attachment: LinearAttachmentNode): FlatAttachment {+ return {+ id: attachment.id,+ title: attachment.title,+ subtitle: attachment.subtitle ?? null,+ url: attachment.url,+ source_type: attachment.sourceType ?? null,+ issue_id: attachment.issue?.id ?? null,+ issue_identifier: attachment.issue?.identifier ?? null,+ issue_title: attachment.issue?.title ?? null,+ creator_id: attachment.creator?.id ?? null,+ creator_name: attachment.creator?.name ?? null,+ created_at: attachment.createdAt,+ updated_at: attachment.updatedAt,+ };+}++function flattenProjectStatusUpdate(update: LinearProjectStatusUpdateNode): FlatProjectStatusUpdate {+ return {+ id: update.id,+ body: update.body,+ health: update.health ?? null,+ url: update.url,+ is_diff_hidden: update.isDiffHidden,+ user_id: update.user?.id ?? null,+ user_name: update.user?.name ?? null,+ user_email: update.user?.email ?? null,+ project_id: update.project?.id ?? null,+ project_name: update.project?.name ?? null,+ created_at: update.createdAt,+ updated_at: update.updatedAt,+ edited_at: update.editedAt ?? null,+ archived_at: update.archivedAt ?? null,+ };+}++function flattenArchivedIssue(entity: LinearArchivedIssueNode | null | undefined): FlatArchivedIssue {+ return {+ success: true,+ id: entity?.id ?? null,+ identifier: entity?.identifier ?? null,+ title: entity?.title ?? null,+ url: entity?.url ?? null,+ trashed: entity?.trashed ?? null,+ archived_at: entity?.archivedAt ?? null,+ };+}++function toPage<TNode, TFlat>({+ connection,+ map,+}: {+ connection: LinearConnection<TNode>;+ map: (node: TNode) => TFlat;+}): FlatPage<TFlat> {+ const items = connection.nodes.map(map);+ return {+ items,+ count: items.length,+ has_next_page: connection.pageInfo.hasNextPage,+ end_cursor: connection.pageInfo.endCursor ?? null,+ };+}++export const linearMappers = {+ flattenIssue,+ flattenAttachment,+ flattenProjectStatusUpdate,+ flattenArchivedIssue,+ toPage,+};++export type LinearConnection<TNode> = {+ nodes: TNode[];+ pageInfo: { hasNextPage: boolean; endCursor?: string | null };+};++export type LinearIssueNode = {+ id: string;+ identifier: string;+ number: number;+ title: string;+ description?: string | null;+ url: string;+ priority: number;+ priorityLabel: string;+ estimate?: number | null;+ dueDate?: string | null;+ branchName: string;+ createdAt: string;+ updatedAt: string;+ startedAt?: string | null;+ completedAt?: string | null;+ canceledAt?: string | null;+ archivedAt?: string | null;+ trashed?: boolean | null;+ state?: { id: string; name: string; type: string } | null;+ team?: { id: string; key: string; name: string } | null;+ assignee?: { id: string; name: string; email: string } | null;+ creator?: { id: string; name: string; email: string } | null;+ project?: { id: string; name: string } | null;+ projectMilestone?: { id: string; name: string } | null;+ cycle?: { id: string; number: number; name?: string | null } | null;+ parent?: { id: string; identifier: string; title: string } | null;+ labels?: LinearIssueLabelConnection | null;+};++export type LinearIssueLabelConnection = {+ pageInfo?: { hasNextPage: boolean; endCursor?: string | null };+ nodes: LinearIssueLabel[];+};++export type LinearIssueLabel = { id: string; name: string };++export type LinearAttachmentNode = {+ id: string;+ title: string;+ subtitle?: string | null;+ url: string;+ sourceType?: string | null;+ createdAt: string;+ updatedAt: string;+ issue?: { id: string; identifier: string; title: string } | null;+ creator?: { id: string; name: string } | null;+};++export type LinearProjectStatusUpdateNode = {+ id: string;+ body: string;+ health?: string | null;+ url: string;+ isDiffHidden: boolean;+ createdAt: string;+ updatedAt: string;+ editedAt?: string | null;+ archivedAt?: string | null;+ user?: { id: string; name: string; email: string } | null;+ project?: { id: string; name: string } | null;+};++export type LinearArchivedIssueNode = {+ id: string;+ identifier: string;+ title: string;+ url: string;+ trashed?: boolean | null;+ archivedAt?: string | null;+};++export type FlatIssue = {+ id: string;+ identifier: string;+ number: number;+ title: string;+ description: string | null;+ url: string;+ priority: number;+ priority_label: string;+ estimate: number | null;+ due_date: string | null;+ branch_name: string;+ state_id: string | null;+ state_name: string | null;+ state_type: string | null;+ team_id: string | null;+ team_key: string | null;+ team_name: string | null;+ assignee_id: string | null;+ assignee_name: string | null;+ assignee_email: string | null;+ creator_id: string | null;+ creator_name: string | null;+ creator_email: string | null;+ project_id: string | null;+ project_name: string | null;+ project_milestone_id: string | null;+ project_milestone_name: string | null;+ cycle_id: string | null;+ cycle_number: number | null;+ cycle_name: string | null;+ parent_id: string | null;+ parent_identifier: string | null;+ parent_title: string | null;+ label_ids: string[];+ label_names: string;+ labels_complete: boolean;+ created_at: string;+ updated_at: string;+ started_at: string | null;+ completed_at: string | null;+ canceled_at: string | null;+ archived_at: string | null;+ trashed: boolean;+};++export type FlatAttachment = {+ id: string;+ title: string;+ subtitle: string | null;+ url: string;+ source_type: string | null;+ issue_id: string | null;+ issue_identifier: string | null;+ issue_title: string | null;+ creator_id: string | null;+ creator_name: string | null;+ created_at: string;+ updated_at: string;+};++export type FlatProjectStatusUpdate = {+ id: string;+ body: string;+ health: string | null;+ url: string;+ is_diff_hidden: boolean;+ user_id: string | null;+ user_name: string | null;+ user_email: string | null;+ project_id: string | null;+ project_name: string | null;+ created_at: string;+ updated_at: string;+ edited_at: string | null;+ archived_at: string | null;+};++export type FlatArchivedIssue = {+ success: true;+ id: string | null;+ identifier: string | null;+ title: string | null;+ url: string | null;+ trashed: boolean | null;+ archived_at: string | null;+};++export type FlatPage<TFlat> = {+ items: TFlat[];+ count: number;+ has_next_page: boolean;+ end_cursor: string | null;+};diff --git a/packages/pieces/community/linear/src/lib/common/props.ts b/packages/pieces/community/linear/src/lib/common/props.tsindex 7a0b6d49376..095e435c20a 100644--- a/packages/pieces/community/linear/src/lib/common/props.ts+++ b/packages/pieces/community/linear/src/lib/common/props.ts@@ -1,14 +1,15 @@-import { DropdownOption, Property } from '@activepieces/pieces-framework';+import { DropdownOption, Property, tryCatch } from '@activepieces/pieces-framework';import { makeClient } from './client';import { LinearDocument } from '@linear/sdk';import { linearAuth } from '../..';+import { LinearAuth, linearGraphql } from './graphql';+import { ALL_PROJECTS_QUERY, TEAM_CYCLES_QUERY } from './queries';export const props = {- team_id: (required = true) =>+ team_id: (required = true, description = 'The team for which the issue, project or comment will be created') =>Property.Dropdown({auth: linearAuth,- description:- 'The team for which the issue, project or comment will be created',+ description,displayName: 'Team',required,refreshers: ['auth'],@@ -342,12 +343,12 @@ auth: linearAuth,};},}),- issue_id: (required = true) =>+ issue_id: (required = true, displayName = 'Issue', description = 'ID of Linear Issue') =>Property.Dropdown({auth: linearAuth,- displayName: 'Issue',+ displayName,required,- description: 'ID of Linear Issue',+ description,refreshers: ['team_id'],options: async ({ auth, team_id }) => {if (!auth || !team_id) {@@ -372,9 +373,9 @@ auth: linearAuth,const issues = await client.listIssues(filter);return {disabled: false,- options: issues.nodes.map((issue: { title: any; id: any }) => {+ options: issues.nodes.map((issue: { identifier: string; title: string; id: string }) => {return {- label: issue.title,+ label: `${issue.identifier} · ${issue.title}`,value: issue.id,};}),@@ -382,6 +383,20 @@ auth: linearAuth,},}),+ issue_reference: () =>+ Property.ShortText({+ displayName: 'Issue ID or Identifier',+ description: 'The issue identifier shown in Linear (for example ENG-123) or the issue UUID.',+ required: true,+ }),++ parent_issue_id: () =>+ Property.ShortText({+ displayName: 'Parent Issue',+ description: 'Identifier (e.g. ENG-123), ID or exact title of the parent issue.',+ required: false,+ }),+project_id: (required = true) =>Property.Dropdown({auth: linearAuth,@@ -521,4 +536,194 @@ auth: linearAuth,};},}),+ project_health: (required = false) =>+ Property.StaticDropdown({+ displayName: 'Health',+ description: 'Leave empty to post without a health rating.',+ required,+ options: {+ options: [+ { label: 'On track', value: 'onTrack' },+ { label: 'At risk', value: 'atRisk' },+ { label: 'Off track', value: 'offTrack' },+ ],+ },+ }),+ label_id: (required = true) =>+ Property.Dropdown({+ auth: linearAuth,+ displayName: 'Label',+ description: 'The label to add or remove. Team labels are listed first, then workspace labels.',+ required,+ refreshers: ['auth', 'team_id'],+ options: async ({ auth, team_id }) => {+ if (!auth) {+ return {+ disabled: true,+ placeholder: 'connect your account first',+ options: [],+ };+ }+ if (!team_id) {+ return {+ disabled: true,+ placeholder: 'select a team to load labels',+ options: [],+ };+ }+ const { data: options, error } = await tryCatch(() => loadLabelOptions({ auth, teamId: String(team_id) }));+ if (error) {+ return { disabled: true, placeholder: `Could not load labels: ${error.message}`, options: [] };+ }+ return { disabled: false, options };+ },+ }),+ cycle_id: (required = false) =>+ Property.Dropdown({+ auth: linearAuth,+ displayName: 'Cycle',+ description: 'The cycle of the selected team to put the issue in. The team must have cycles enabled.',+ required,+ refreshers: ['auth', 'team_id'],+ options: async ({ auth, team_id }) => {+ if (!auth || !team_id) {+ return {+ disabled: true,+ placeholder: 'connect your account first and select team',+ options: [],+ };+ }+ const { data: options, error } = await tryCatch(() => loadCycleOptions({ auth, teamId: String(team_id) }));+ if (error) {+ return { disabled: true, placeholder: `Could not load cycles: ${error.message}`, options: [] };+ }+ return {+ disabled: false,+ options,+ placeholder: options.length === 0 ? 'this team has no current or upcoming cycles' : undefined,+ };+ },+ }),+ any_project_id: (required = false) =>+ Property.Dropdown({+ auth: linearAuth,+ displayName: 'Project',+ description: 'Only fire for status updates posted on this project. Leave empty for every project.',+ required,+ refreshers: ['auth'],+ options: async ({ auth }) => {+ if (!auth) {+ return {+ disabled: true,+ placeholder: 'connect your account first',+ options: [],+ };+ }+ const { data: options, error } = await tryCatch(() => loadProjectOptions({ auth }));+ if (error) {+ return { disabled: true, placeholder: `Could not load projects: ${error.message}`, options: [] };+ }+ return { disabled: false, options };+ },+ }),};++async function loadLabelOptions({ auth, teamId }: { auth: LinearAuth; teamId: string }): Promise<DropdownOption<string>[]> {+ const client = makeClient(auth);+ const teamLabels = await collectLabels({+ load: (after) =>+ client.listIssueLabels({+ filter: { team: { id: { eq: teamId } } },+ first: 100,+ after,+ }),+ prefix: '',+ });+ const workspaceLabels = await collectLabels({+ load: (after) =>+ client.listIssueLabels({+ filter: { team: { null: true } },+ first: 100,+ after,+ }),+ prefix: '[Workspace] ',+ });+ return [...teamLabels, ...workspaceLabels];+}++async function collectLabels({+ load,+ prefix,+}: {+ load: (after: string | undefined) => Promise<{+ nodes: Array<{ id: string; name: string }>;+ pageInfo: { hasNextPage: boolean; endCursor?: string };+ }>;+ prefix: string;+}): Promise<DropdownOption<string>[]> {+ const options: DropdownOption<string>[] = [];+ let after: string | undefined;+ let hasNextPage = false;+ do {+ const page = await load(after);+ for (const label of page.nodes) {+ options.push({ label: `${prefix}${label.name}`, value: label.id });+ }+ hasNextPage = page.pageInfo.hasNextPage;+ after = page.pageInfo.endCursor;+ } while (hasNextPage);+ return options.sort((a, b) => a.label.localeCompare(b.label));+}++async function loadCycleOptions({ auth, teamId }: { auth: LinearAuth; teamId: string }): Promise<DropdownOption<string>[]> {+ const options: DropdownOption<string>[] = [];+ let after: string | undefined;+ let hasNextPage = false;+ do {+ const data = await linearGraphql.request<{+ cycles: {+ pageInfo: { hasNextPage: boolean; endCursor?: string | null };+ nodes: Array<{ id: string; number: number; name?: string | null; startsAt: string; isActive: boolean; isNext: boolean; isPast: boolean }>;+ };+ }>({+ auth,+ query: TEAM_CYCLES_QUERY,+ variables: {+ filter: { team: { id: { eq: teamId } }, isPast: { eq: false } },+ first: 100,+ after,+ },+ });+ for (const cycle of data.cycles.nodes) {+ const status = cycle.isActive ? ' (current)' : cycle.isNext ? ' (next)' : '';+ const name = cycle.name ? ` ${cycle.name}` : '';+ options.push({+ label: `Cycle ${cycle.number}${name} · starts ${cycle.startsAt.slice(0, 10)}${status}`,+ value: cycle.id,+ });+ }+ hasNextPage = data.cycles.pageInfo.hasNextPage;+ after = data.cycles.pageInfo.endCursor ?? undefined;+ } while (hasNextPage);+ return options;+}++async function loadProjectOptions({ auth }: { auth: LinearAuth }): Promise<DropdownOption<string>[]> {+ const options: DropdownOption<string>[] = [];+ let after: string | undefined;+ let hasNextPage = false;+ do {+ const data = await linearGraphql.request<{+ projects: {+ pageInfo: { hasNextPage: boolean; endCursor?: string | null };+ nodes: Array<{ id: string; name: string }>;+ };+ }>({ auth, query: ALL_PROJECTS_QUERY, variables: { first: 100, after } });+ for (const project of data.projects.nodes) {+ options.push({ label: project.name, value: project.id });+ }+ hasNextPage = data.projects.pageInfo.hasNextPage;+ after = data.projects.pageInfo.endCursor ?? undefined;+ } while (hasNextPage);+ return options;+}diff --git a/packages/pieces/community/linear/src/lib/common/queries.ts b/packages/pieces/community/linear/src/lib/common/queries.tsnew file mode 100644index 00000000000..19a7dcb97d5--- /dev/null+++ b/packages/pieces/community/linear/src/lib/common/queries.ts@@ -0,0 +1,183 @@+export const ISSUE_SELECTION = `+ id+ identifier+ number+ title+ description+ url+ priority+ priorityLabel+ estimate+ dueDate+ branchName+ createdAt+ updatedAt+ startedAt+ completedAt+ canceledAt+ archivedAt+ trashed+ state { id name type }+ team { id key name }+ assignee { id name email }+ creator { id name email }+ project { id name }+ projectMilestone { id name }+ cycle { id number name }+ parent { id identifier title }+ labels(first: 20) {+ pageInfo { hasNextPage endCursor }+ nodes { id name }+ }+`;++export const ATTACHMENT_SELECTION = `+ id+ title+ subtitle+ url+ sourceType+ createdAt+ updatedAt+ issue { id identifier title }+ creator { id name }+`;++export const PROJECT_STATUS_UPDATE_SELECTION = `+ id+ body+ health+ url+ isDiffHidden+ createdAt+ updatedAt+ editedAt+ archivedAt+ user { id name email }+ project { id name }+`;++export const PARENT_TITLE_LOOKUP_QUERY = `+ query LinearParentTitleLookup($filter: IssueFilter!, $first: Int) {+ issues(filter: $filter, first: $first) {+ nodes { id identifier title }+ }+ }+`;++export const ISSUE_ID_LOOKUP_QUERY = `+ query LinearIssueIdLookup($id: String!) {+ issue(id: $id) { id }+ }+`;++export const ISSUE_LABELS_PAGE_QUERY = `+ query LinearIssueLabelsPage($id: String!, $first: Int!, $filter: IssueLabelFilter) {+ issue(id: $id) {+ labels(first: $first, filter: $filter) {+ pageInfo { hasNextPage endCursor }+ nodes { id name }+ }+ }+ }+`;++export const GET_ISSUE_QUERY = `+ query LinearGetIssue($id: String!) {+ issue(id: $id) { ${ISSUE_SELECTION} }+ }+`;++export const SEARCH_ISSUES_QUERY = `+ query LinearSearchIssues($term: String!, $filter: IssueFilter, $first: Int, $after: String, $includeArchived: Boolean, $includeComments: Boolean) {+ searchIssues(term: $term, filter: $filter, first: $first, after: $after, includeArchived: $includeArchived, includeComments: $includeComments) {+ totalCount+ pageInfo { hasNextPage endCursor }+ nodes { ${ISSUE_SELECTION} }+ }+ }+`;++export const ISSUE_ADD_LABEL_MUTATION = `+ mutation LinearIssueAddLabel($id: String!, $labelId: String!) {+ issueAddLabel(id: $id, labelId: $labelId) {+ success+ issue { ${ISSUE_SELECTION} }+ }+ }+`;++export const ISSUE_REMOVE_LABEL_MUTATION = `+ mutation LinearIssueRemoveLabel($id: String!, $labelId: String!) {+ issueRemoveLabel(id: $id, labelId: $labelId) {+ success+ issue { ${ISSUE_SELECTION} }+ }+ }+`;++export const ISSUE_DELETE_MUTATION = `+ mutation LinearIssueDelete($id: String!) {+ issueDelete(id: $id) {+ success+ entity { id identifier title url trashed archivedAt }+ }+ }+`;++export const ATTACHMENT_CREATE_MUTATION = `+ mutation LinearAttachmentCreate($input: AttachmentCreateInput!) {+ attachmentCreate(input: $input) {+ success+ attachment { ${ATTACHMENT_SELECTION} }+ }+ }+`;++export const PROJECT_STATUS_UPDATE_CREATE_MUTATION = `+ mutation LinearProjectStatusUpdateCreate($input: ProjectUpdateCreateInput!) {+ projectUpdateCreate(input: $input) {+ success+ projectUpdate { ${PROJECT_STATUS_UPDATE_SELECTION} }+ }+ }+`;++export const WEBHOOK_CREATE_MUTATION = `+ mutation LinearWebhookCreate($input: WebhookCreateInput!) {+ webhookCreate(input: $input) {+ success+ webhook { id }+ }+ }+`;++export const PROJECT_TEAM_IDS_QUERY = `+ query LinearProjectTeamIds($id: String!, $after: String) {+ project(id: $id) {+ id+ teams(first: 250, after: $after) {+ pageInfo { hasNextPage endCursor }+ nodes { id }+ }+ }+ }+`;++export const TEAM_CYCLES_QUERY = `+ query LinearTeamCycles($filter: CycleFilter, $first: Int, $after: String) {+ cycles(filter: $filter, first: $first, after: $after) {+ pageInfo { hasNextPage endCursor }+ nodes { id number name startsAt endsAt isActive isNext isPast }+ }+ }+`;++export const ALL_PROJECTS_QUERY = `+ query LinearAllProjects($first: Int, $after: String) {+ projects(first: $first, after: $after) {+ pageInfo { hasNextPage endCursor }+ nodes { id name }+ }+ }+`;diff --git a/packages/pieces/community/linear/src/lib/common/webhook-samples.ts b/packages/pieces/community/linear/src/lib/common/webhook-samples.tsnew file mode 100644index 00000000000..d4c616ac907--- /dev/null+++ b/packages/pieces/community/linear/src/lib/common/webhook-samples.ts@@ -0,0 +1,463 @@+const newIssueSample = {+ action: 'create',+ type: 'Issue',+ url: 'https://linear.app/acme/issue/ENG-16/fix-checkout-button-on-mobile',+ createdAt: '2026-09-29T11:40:04.426Z',+ actor: {+ id: '0d756b70-49e3-4c06-abeb-667df5d00e4a',+ name: 'Jane Doe',+ email: '[email protected]',+ avatarUrl: 'https://public.linear.app/avatar.png',+ url: 'https://linear.app/acme/profiles/jane',+ type: 'user',+ },+ data: {+ id: 'a276f64a-bbf4-4ab4-8cdb-9ff558d42ed8',+ identifier: 'ENG-16',+ number: 16,+ title: 'Fix checkout button on mobile',+ url: 'https://linear.app/acme/issue/ENG-16/fix-checkout-button-on-mobile',+ priority: 3,+ priorityLabel: 'Medium',+ dueDate: '2026-10-15',+ stateId: '5cb9e604-45e4-43da-b2b1-06ec0a940cba',+ state: {+ id: '5cb9e604-45e4-43da-b2b1-06ec0a940cba',+ name: 'Backlog',+ type: 'backlog',+ color: '#bec2c8',+ },+ teamId: '25a6a33a-fc39-44fa-a441-4383a09ab4ec',+ team: {+ id: '25a6a33a-fc39-44fa-a441-4383a09ab4ec',+ key: 'ENG',+ name: 'Engineering',+ },+ assigneeId: '0d756b70-49e3-4c06-abeb-667df5d00e4a',+ assignee: {+ id: '0d756b70-49e3-4c06-abeb-667df5d00e4a',+ name: 'Jane Doe',+ email: '[email protected]',+ avatarUrl: 'https://public.linear.app/avatar.png',+ url: 'https://linear.app/acme/profiles/jane',+ },+ creatorId: '0d756b70-49e3-4c06-abeb-667df5d00e4a',+ projectId: '88657020-ff26-4832-8183-26f5d943a70d',+ project: {+ id: '88657020-ff26-4832-8183-26f5d943a70d',+ name: 'Website Relaunch',+ url: 'https://linear.app/acme/project/website-relaunch-e25bc5c7ddbb',+ },+ parentId: '50c94733-81f5-419c-a370-d35b7405643c',+ labelIds: [+ '4cc5da39-f988-4290-ada2-6f5e3ab73d06',+ ],+ labels: [+ {+ id: '4cc5da39-f988-4290-ada2-6f5e3ab73d06',+ name: 'bug',+ color: '#ff0000',+ },+ ],+ subscriberIds: [+ '0d756b70-49e3-4c06-abeb-667df5d00e4a',+ ],+ createdAt: '2026-09-29T11:40:04.426Z',+ updatedAt: '2026-09-29T11:40:04.426Z',+ },+ organizationId: 'b274213f-4064-4760-bcba-decd45c8d9be',+ webhookId: '8bbfc2ef-b432-439b-bd16-2a217af0e8f9',+ webhookTimestamp: 1790682004728,+};++const updatedIssueSample = {+ action: 'update',+ type: 'Issue',+ url: 'https://linear.app/acme/issue/ENG-16/fix-checkout-button-on-mobile',+ createdAt: '2026-09-29T11:40:15.016Z',+ actor: {+ id: '0d756b70-49e3-4c06-abeb-667df5d00e4a',+ name: 'Jane Doe',+ email: '[email protected]',+ avatarUrl: 'https://public.linear.app/avatar.png',+ url: 'https://linear.app/acme/profiles/jane',+ type: 'user',+ },+ data: {+ id: 'a276f64a-bbf4-4ab4-8cdb-9ff558d42ed8',+ identifier: 'ENG-16',+ number: 16,+ title: 'Fix checkout button on mobile',+ url: 'https://linear.app/acme/issue/ENG-16/fix-checkout-button-on-mobile',+ priority: 3,+ priorityLabel: 'Medium',+ dueDate: '2026-10-15',+ stateId: 'd1675f0a-50bf-45eb-96f2-1a479f7e2db8',+ state: {+ id: 'd1675f0a-50bf-45eb-96f2-1a479f7e2db8',+ name: 'Done',+ type: 'completed',+ color: '#5e6ad2',+ },+ teamId: '25a6a33a-fc39-44fa-a441-4383a09ab4ec',+ team: {+ id: '25a6a33a-fc39-44fa-a441-4383a09ab4ec',+ key: 'ENG',+ name: 'Engineering',+ },+ assigneeId: '0d756b70-49e3-4c06-abeb-667df5d00e4a',+ assignee: {+ id: '0d756b70-49e3-4c06-abeb-667df5d00e4a',+ name: 'Jane Doe',+ email: '[email protected]',+ avatarUrl: 'https://public.linear.app/avatar.png',+ url: 'https://linear.app/acme/profiles/jane',+ },+ creatorId: '0d756b70-49e3-4c06-abeb-667df5d00e4a',+ projectId: '88657020-ff26-4832-8183-26f5d943a70d',+ project: {+ id: '88657020-ff26-4832-8183-26f5d943a70d',+ name: 'Website Relaunch',+ url: 'https://linear.app/acme/project/website-relaunch-e25bc5c7ddbb',+ },+ parentId: '50c94733-81f5-419c-a370-d35b7405643c',+ labelIds: [+ '4cc5da39-f988-4290-ada2-6f5e3ab73d06',+ ],+ labels: [+ {+ id: '4cc5da39-f988-4290-ada2-6f5e3ab73d06',+ name: 'bug',+ color: '#ff0000',+ },+ ],+ subscriberIds: [+ '0d756b70-49e3-4c06-abeb-667df5d00e4a',+ ],+ createdAt: '2026-09-29T11:40:04.426Z',+ updatedAt: '2026-09-29T11:40:15.015Z',+ completedAt: '2026-09-29T11:40:14.954Z',+ },+ updatedFrom: {+ updatedAt: '2026-09-29T11:40:04.426Z',+ sortOrder: -4084,+ completedAt: null,+ stateId: '5cb9e604-45e4-43da-b2b1-06ec0a940cba',+ },+ organizationId: 'b274213f-4064-4760-bcba-decd45c8d9be',+ webhookId: '6a1a2412-b590-4b48-8025-28c7a7769080',+ webhookTimestamp: 1790682015236,+};++const removedIssueSample = {+ action: 'remove',+ type: 'Issue',+ url: 'https://linear.app/acme/issue/ENG-14/fix-checkout-button-on-mobile-title-only',+ createdAt: '2026-09-29T11:37:05.098Z',+ actor: {+ id: '0d756b70-49e3-4c06-abeb-667df5d00e4a',+ name: 'Jane Doe',+ email: '[email protected]',+ avatarUrl: 'https://public.linear.app/avatar.png',+ url: 'https://linear.app/acme/profiles/jane',+ type: 'user',+ },+ data: {+ id: 'dc65d8cc-5637-4f7f-bfc8-1462b930ab2f',+ identifier: 'ENG-14',+ number: 14,+ title: 'Fix checkout button on mobile (title only)',+ description: 'The button does not respond on small screens.',+ url: 'https://linear.app/acme/issue/ENG-14/fix-checkout-button-on-mobile-title-only',+ priority: 2,+ priorityLabel: 'High',+ stateId: '0329c834-8f90-44d5-9929-cdf3e9ba482f',+ state: {+ id: '0329c834-8f90-44d5-9929-cdf3e9ba482f',+ name: 'In Progress',+ type: 'started',+ color: '#f2c94c',+ },+ teamId: '25a6a33a-fc39-44fa-a441-4383a09ab4ec',+ team: {+ id: '25a6a33a-fc39-44fa-a441-4383a09ab4ec',+ key: 'ENG',+ name: 'Engineering',+ },+ assigneeId: '0d756b70-49e3-4c06-abeb-667df5d00e4a',+ assignee: {+ id: '0d756b70-49e3-4c06-abeb-667df5d00e4a',+ name: 'Jane Doe',+ email: '[email protected]',+ avatarUrl: 'https://public.linear.app/avatar.png',+ url: 'https://linear.app/acme/profiles/jane',+ },+ creatorId: '0d756b70-49e3-4c06-abeb-667df5d00e4a',+ labelIds: [],+ labels: [],+ subscriberIds: [+ '0d756b70-49e3-4c06-abeb-667df5d00e4a',+ ],+ createdAt: '2026-09-29T11:36:08.752Z',+ updatedAt: '2026-09-29T11:36:48.430Z',+ startedAt: '2026-09-29T11:36:38.982Z',+ trashed: true,+ },+ organizationId: 'b274213f-4064-4760-bcba-decd45c8d9be',+ webhookId: '0898e887-e7aa-4761-bab0-b67525091d33',+ webhookTimestamp: 1790681825897,+};++const newCommentSample = {+ action: 'create',+ type: 'Comment',+ url: 'https://linear.app/acme/issue/ENG-15/checkout-improvements#comment-7d9994f5',+ createdAt: '2026-09-29T11:40:14.853Z',+ actor: {+ id: '0d756b70-49e3-4c06-abeb-667df5d00e4a',+ name: 'Jane Doe',+ email: '[email protected]',+ avatarUrl: 'https://public.linear.app/avatar.png',+ url: 'https://linear.app/acme/profiles/jane',+ type: 'user',+ },+ data: {+ id: '7d9994f5-daa2-4289-9403-62cd9523cf34',+ body: 'I can reproduce this on iOS 18.',+ issueId: '50c94733-81f5-419c-a370-d35b7405643c',+ parentId: '45b94028-bd90-4198-bc16-7175e2f25b8d',+ userId: '0d756b70-49e3-4c06-abeb-667df5d00e4a',+ user: {+ id: '0d756b70-49e3-4c06-abeb-667df5d00e4a',+ name: 'Jane Doe',+ email: '[email protected]',+ avatarUrl: 'https://public.linear.app/avatar.png',+ url: 'https://linear.app/acme/profiles/jane',+ },+ issue: {+ id: '50c94733-81f5-419c-a370-d35b7405643c',+ identifier: 'ENG-15',+ title: 'Checkout improvements',+ url: 'https://linear.app/acme/issue/ENG-15/checkout-improvements',+ teamId: '25a6a33a-fc39-44fa-a441-4383a09ab4ec',+ team: {+ id: '25a6a33a-fc39-44fa-a441-4383a09ab4ec',+ key: 'ENG',+ name: 'Engineering',+ },+ },+ createdAt: '2026-09-29T11:40:14.853Z',+ updatedAt: '2026-09-29T11:40:14.819Z',+ },+ organizationId: 'b274213f-4064-4760-bcba-decd45c8d9be',+ webhookId: 'aedb526f-21e7-4430-b0e6-6ba22cb8c317',+ webhookTimestamp: 1790682015236,+};++const newProjectSample = {+ action: 'create',+ type: 'Project',+ url: 'https://linear.app/acme/project/website-relaunch-e25bc5c7ddbb',+ createdAt: '2026-09-29T11:39:53.443Z',+ actor: {+ id: '0d756b70-49e3-4c06-abeb-667df5d00e4a',+ name: 'Jane Doe',+ email: '[email protected]',+ avatarUrl: 'https://public.linear.app/avatar.png',+ url: 'https://linear.app/acme/profiles/jane',+ type: 'user',+ },+ data: {+ id: '88657020-ff26-4832-8183-26f5d943a70d',+ identifier: 'P-ENG-5',+ name: 'Website Relaunch',+ description: '',+ url: 'https://linear.app/acme/project/website-relaunch-e25bc5c7ddbb',+ slugId: 'e25bc5c7ddbb',+ color: '#bec2c8',+ icon: 'Rocket',+ priority: 0,+ statusId: 'f6ec040e-2e2d-4fe9-997d-931359a280ca',+ status: {+ id: 'f6ec040e-2e2d-4fe9-997d-931359a280ca',+ name: 'Backlog',+ type: 'backlog',+ color: '#F2994A',+ },+ teamIds: [+ '25a6a33a-fc39-44fa-a441-4383a09ab4ec',+ ],+ leadId: '0d756b70-49e3-4c06-abeb-667df5d00e4a',+ lead: {+ id: '0d756b70-49e3-4c06-abeb-667df5d00e4a',+ name: 'Jane Doe',+ email: '[email protected]',+ avatarUrl: 'https://public.linear.app/avatar.png',+ url: 'https://linear.app/acme/profiles/jane',+ },+ memberIds: [+ '0d756b70-49e3-4c06-abeb-667df5d00e4a',+ ],+ labelIds: [],+ creatorId: '0d756b70-49e3-4c06-abeb-667df5d00e4a',+ startDate: '2026-09-29',+ targetDate: '2026-10-31',+ createdAt: '2026-09-29T11:39:53.443Z',+ updatedAt: '2026-09-29T11:39:53.443Z',+ },+ organizationId: 'b274213f-4064-4760-bcba-decd45c8d9be',+ webhookId: 'fbc579fb-5023-4761-ac79-f3dde5a84c13',+ webhookTimestamp: 1790681993971,+};++const updatedProjectSample = {+ action: 'update',+ type: 'Project',+ url: 'https://linear.app/acme/project/website-relaunch-cb2d4f61101b',+ createdAt: '2026-09-29T11:36:48.465Z',+ actor: {+ id: '0d756b70-49e3-4c06-abeb-667df5d00e4a',+ name: 'Jane Doe',+ email: '[email protected]',+ avatarUrl: 'https://public.linear.app/avatar.png',+ url: 'https://linear.app/acme/profiles/jane',+ type: 'user',+ },+ data: {+ id: '789d88a5-6c49-4615-a2c5-d08c78c6d84c',+ identifier: 'P-ENG-4',+ name: 'Website Relaunch',+ description: 'Relaunch of the marketing site.',+ url: 'https://linear.app/acme/project/website-relaunch-cb2d4f61101b',+ slugId: 'cb2d4f61101b',+ color: '#26b5ce',+ priority: 0,+ statusId: '53b1cca7-2c88-4790-a857-e3006c040b1e',+ status: {+ id: '53b1cca7-2c88-4790-a857-e3006c040b1e',+ name: 'In Progress',+ type: 'started',+ color: '#F2C94C',+ },+ teamIds: [+ '25a6a33a-fc39-44fa-a441-4383a09ab4ec',+ ],+ memberIds: [],+ labelIds: [],+ creatorId: '0d756b70-49e3-4c06-abeb-667df5d00e4a',+ startDate: '2026-09-29',+ targetDate: null,+ createdAt: '2026-09-29T11:36:38.932Z',+ updatedAt: '2026-09-29T11:36:48.463Z',+ startedAt: '2026-09-29T11:36:48.462Z',+ },+ updatedFrom: {+ updatedAt: '2026-09-29T11:36:38.932Z',+ statusId: 'f6ec040e-2e2d-4fe9-997d-931359a280ca',+ startDate: null,+ startedAt: null,+ },+ organizationId: 'b274213f-4064-4760-bcba-decd45c8d9be',+ webhookId: '1c049afa-f601-4914-8a2f-f247856c8858',+ webhookTimestamp: 1790681808726,+};++const removedProjectSample = {+ action: 'remove',+ type: 'Project',+ url: 'https://linear.app/acme/project/website-relaunch-cb2d4f61101b',+ createdAt: '2026-09-29T11:37:05.533Z',+ actor: {+ id: '0d756b70-49e3-4c06-abeb-667df5d00e4a',+ name: 'Jane Doe',+ email: '[email protected]',+ avatarUrl: 'https://public.linear.app/avatar.png',+ url: 'https://linear.app/acme/profiles/jane',+ type: 'user',+ },+ data: {+ id: '789d88a5-6c49-4615-a2c5-d08c78c6d84c',+ identifier: 'P-ENG-4',+ name: 'Website Relaunch',+ description: 'Relaunch of the marketing site.',+ url: 'https://linear.app/acme/project/website-relaunch-cb2d4f61101b',+ slugId: 'cb2d4f61101b',+ color: '#26b5ce',+ priority: 0,+ statusId: '53b1cca7-2c88-4790-a857-e3006c040b1e',+ status: {+ id: '53b1cca7-2c88-4790-a857-e3006c040b1e',+ name: 'In Progress',+ type: 'started',+ color: '#F2C94C',+ },+ health: 'onTrack',+ teamIds: [+ '25a6a33a-fc39-44fa-a441-4383a09ab4ec',+ ],+ memberIds: [],+ labelIds: [],+ creatorId: '0d756b70-49e3-4c06-abeb-667df5d00e4a',+ startDate: '2026-09-29',+ targetDate: null,+ createdAt: '2026-09-29T11:36:38.932Z',+ updatedAt: '2026-09-29T11:36:48.463Z',+ startedAt: '2026-09-29T11:36:48.462Z',+ trashed: true,+ },+ organizationId: 'b274213f-4064-4760-bcba-decd45c8d9be',+ webhookId: '595fe5d9-5f09-41e9-b398-de458c86fe50',+ webhookTimestamp: 1790681826388,+};++const newProjectStatusUpdateSample = {+ action: 'create',+ type: 'ProjectUpdate',+ url: 'https://linear.app/acme/project/website-relaunch-cb2d4f61101b/activity#project-update-06c926c2',+ createdAt: '2026-09-29T11:36:48.413Z',+ actor: {+ id: '0d756b70-49e3-4c06-abeb-667df5d00e4a',+ name: 'Jane Doe',+ email: '[email protected]',+ avatarUrl: 'https://public.linear.app/avatar.png',+ url: 'https://linear.app/acme/profiles/jane',+ type: 'user',+ },+ data: {+ id: '06c926c2-140c-432c-b618-ae0d595ff59d',+ body: 'On track for the October launch.',+ health: 'onTrack',+ diffMarkdown: '**Status**: In Progress\n**Start date** set to Sep 29th',+ slugId: '06c926c2',+ projectId: '789d88a5-6c49-4615-a2c5-d08c78c6d84c',+ project: {+ id: '789d88a5-6c49-4615-a2c5-d08c78c6d84c',+ name: 'Website Relaunch',+ url: 'https://linear.app/acme/project/website-relaunch-cb2d4f61101b',+ },+ userId: '0d756b70-49e3-4c06-abeb-667df5d00e4a',+ user: {+ id: '0d756b70-49e3-4c06-abeb-667df5d00e4a',+ name: 'Jane Doe',+ email: '[email protected]',+ avatarUrl: 'https://public.linear.app/avatar.png',+ url: 'https://linear.app/acme/profiles/jane',+ },+ createdAt: '2026-09-29T11:36:48.413Z',+ updatedAt: '2026-09-29T11:36:48.413Z',+ },+ organizationId: 'b274213f-4064-4760-bcba-decd45c8d9be',+ webhookId: 'a3800b1a-0896-49ac-a389-c713c08c9595',+ webhookTimestamp: 1790681808718,+};++export const linearWebhookSamples = {+ newIssueSample,+ updatedIssueSample,+ removedIssueSample,+ newCommentSample,+ newProjectSample,+ updatedProjectSample,+ removedProjectSample,+ newProjectStatusUpdateSample,+};diff --git a/packages/pieces/community/linear/src/lib/common/webhook-signature.ts b/packages/pieces/community/linear/src/lib/common/webhook-signature.tsnew file mode 100644index 00000000000..14359c1888f--- /dev/null+++ b/packages/pieces/community/linear/src/lib/common/webhook-signature.ts@@ -0,0 +1,65 @@+import crypto from 'crypto';++function verify({+ secret,+ signatureHeader,+ rawBody,+}: {+ secret: string | undefined;+ signatureHeader: string | undefined;+ rawBody: unknown;+}): boolean {+ if (!secret || !signatureHeader || !HEX.test(signatureHeader)) {+ return false;+ }+ const payload = bytesOf(rawBody);+ if (payload === undefined) {+ return false;+ }+ const expected = crypto.createHmac('sha256', secret).update(payload).digest();+ const provided = Buffer.from(signatureHeader, 'hex');+ return provided.length === expected.length && crypto.timingSafeEqual(provided, expected);+}++function headerOf({+ headers,+ name,+}: {+ headers: Record<string, string> | undefined;+ name: string;+}): string | undefined {+ if (!headers) {+ return undefined;+ }+ const key = Object.keys(headers).find((header) => header.toLowerCase() === name);+ return key === undefined ? undefined : headers[key];+}++function isFreshTimestamp({ timestamp, now }: { timestamp: unknown; now: number }): boolean {+ if (typeof timestamp !== 'number' || !Number.isFinite(timestamp)) {+ return false;+ }+ return Math.abs(now - timestamp) <= MAX_DELIVERY_AGE_MS;+}++function newSecret(): string {+ return crypto.randomBytes(32).toString('hex');+}++function bytesOf(rawBody: unknown): Buffer | undefined {+ if (Buffer.isBuffer(rawBody)) {+ return rawBody;+ }+ if (typeof rawBody === 'string') {+ return Buffer.from(rawBody, 'utf8');+ }+ return undefined;+}++const HEX = /^[0-9a-fA-F]+$/;+const MAX_DELIVERY_AGE_MS = 7 * 60 * 60 * 1000;++export const LINEAR_SIGNATURE_HEADER = 'linear-signature';+export const LINEAR_DELIVERY_HEADER = 'linear-delivery';++export const linearWebhookSignature = { verify, headerOf, isFreshTimestamp, newSecret };diff --git a/packages/pieces/community/linear/src/lib/common/webhook.test.ts b/packages/pieces/community/linear/src/lib/common/webhook.test.tsnew file mode 100644index 00000000000..633cd931b1f--- /dev/null+++ b/packages/pieces/community/linear/src/lib/common/webhook.test.ts@@ -0,0 +1,103 @@+/// <reference types="vitest/globals" />++import { vi } from 'vitest';++const rawRequest = vi.fn();+const deleteWebhook = vi.fn();++vi.mock('@linear/sdk', () => ({+ LinearClient: class {+ client = { rawRequest };+ deleteWebhook = deleteWebhook;+ },+ LinearDocument: {},+}));++import '../../index';+import { linearNewIssue } from '../triggers/new-issue';++function buildContext(store: { put: ReturnType<typeof vi.fn> }) {+ return {+ auth: { type: 'SECRET_TEXT', secret_text: 'lin_api_test' },+ webhookUrl: 'https://example.com/hook',+ propsValue: { team_id: 'team-1' },+ store: { ...store, get: vi.fn(), delete: vi.fn() },+ };+}++describe('trigger onEnable (F2)', () => {+ beforeEach(() => {+ rawRequest.mockReset();+ deleteWebhook.mockReset();+ });++ test('stores the webhook id when Linear creates the webhook', async () => {+ rawRequest.mockResolvedValue({ data: { webhookCreate: { success: true, webhook: { id: 'wh-1' } } } });+ const put = vi.fn().mockResolvedValue(undefined);+ await linearNewIssue.onEnable(buildContext({ put }));+ expect(put).toHaveBeenCalledWith('_new_issue_trigger', { webhookId: 'wh-1' });+ expect(rawRequest).toHaveBeenCalledTimes(1);+ expect(rawRequest.mock.calls[0][0]).toContain('webhookCreate');+ expect(rawRequest.mock.calls[0][1]).toMatchObject({ input: { teamId: 'team-1', resourceTypes: ['Issue'] } });+ });++ test('throws a clear admin-key message when Linear refuses', async () => {+ rawRequest.mockRejectedValue(Object.assign(new Error('Forbidden'), { type: 'Forbidden' }));+ await expect(linearNewIssue.onEnable(buildContext({ put: vi.fn() }))).rejects.toThrow('workspace admin');+ });++ test('throws instead of silently continuing when success is false', async () => {+ rawRequest.mockResolvedValue({ data: { webhookCreate: { success: false, webhook: null } } });+ const put = vi.fn();+ await expect(linearNewIssue.onEnable(buildContext({ put }))).rejects.toThrow('refused to create the webhook');+ expect(put).not.toHaveBeenCalled();+ });++ test('deletes the created webhook when storing its id fails', async () => {+ rawRequest.mockResolvedValue({ data: { webhookCreate: { success: true, webhook: { id: 'wh-2' } } } });+ deleteWebhook.mockResolvedValue({ success: true });+ const put = vi.fn().mockRejectedValue(new Error('store down'));+ await expect(linearNewIssue.onEnable(buildContext({ put }))).rejects.toThrow('store down');+ expect(deleteWebhook).toHaveBeenCalledWith('wh-2');+ });+});++describe('trigger onDisable', () => {+ beforeEach(() => {+ deleteWebhook.mockReset();+ });++ function disableContext() {+ const values = new Map<string, unknown>([['_new_issue_trigger', { webhookId: 'wh-9' }]]);+ return {+ values,+ context: {+ auth: { type: 'SECRET_TEXT', secret_text: 'lin_api_test' },+ webhookUrl: 'https://example.com/hook',+ propsValue: {},+ store: {+ put: vi.fn(),+ get: vi.fn(async (key: string) => values.get(key)),+ delete: vi.fn(async (key: string) => {+ values.delete(key);+ }),+ },+ },+ };+ }++ test('treats a webhook Linear already deleted as gone and clears the store', async () => {+ deleteWebhook.mockRejectedValue(new Error('Entity not found: Webhook - Could not find referenced Webhook.'));+ const { values, context } = disableContext();+ await linearNewIssue.onDisable(context);+ expect(deleteWebhook).toHaveBeenCalledWith('wh-9');+ expect(values.has('_new_issue_trigger')).toBe(false);+ });++ test('rethrows any other error and keeps the stored webhook', async () => {+ deleteWebhook.mockRejectedValue(new Error('Linear rate limit reached.'));+ const { values, context } = disableContext();+ await expect(linearNewIssue.onDisable(context)).rejects.toThrow('rate limit');+ expect(values.get('_new_issue_trigger')).toEqual({ webhookId: 'wh-9' });+ });+});diff --git a/packages/pieces/community/linear/src/lib/common/webhook.ts b/packages/pieces/community/linear/src/lib/common/webhook.tsnew file mode 100644index 00000000000..5ac10427db2--- /dev/null+++ b/packages/pieces/community/linear/src/lib/common/webhook.ts@@ -0,0 +1,98 @@+import { Store } from '@activepieces/pieces-framework';+import { LinearDocument } from '@linear/sdk';+import { makeClient } from './client';+import { LinearAuth, linearGraphql } from './graphql';+import { WEBHOOK_CREATE_MUTATION } from './queries';++async function register({ auth, store, storeKey, input }: RegisterParams): Promise<string> {+ const client = makeClient(auth);+ const webhookId = await createWebhook({ client, input });+ try {+ await store.put<WebhookInformation>(storeKey, { webhookId, ...(input.secret ? { secret: input.secret } : {}) });+ } catch (error) {+ await client.deleteWebhook(webhookId).catch(() => undefined);+ throw error;+ }+ return webhookId;+}++async function unregister({ auth, store, storeKey }: UnregisterParams): Promise<void> {+ const stored = await store.get<WebhookInformation>(storeKey);+ if (stored?.webhookId) {+ await deleteWebhookIfPresent({ client: makeClient(auth), webhookId: stored.webhookId });+ }+ await store.delete(storeKey);+}++async function createWebhook({+ client,+ input,+}: {+ client: ReturnType<typeof makeClient>;+ input: LinearDocument.WebhookCreateInput;+}): Promise<string> {+ const result = await client.typedRequest<WebhookCreateData>(WEBHOOK_CREATE_MUTATION, { input }).catch((error: unknown) => {+ throw toEnableError(error);+ });+ const payload = result.data?.webhookCreate;+ const webhook = payload?.success === true ? payload.webhook : undefined;+ if (!webhook?.id) {+ throw new Error(REFUSED_MESSAGE);+ }+ return webhook.id;+}++function toEnableError(error: unknown): Error {+ const type = typeof error === 'object' && error !== null && 'type' in error ? error.type : undefined;+ if (type === 'Forbidden' || type === 'AuthenticationError') {+ return new Error(REFUSED_MESSAGE);+ }+ const message = error instanceof Error ? error.message : String(error);+ return new Error(`Linear could not create the webhook: ${message}`);+}++async function deleteWebhookIfPresent({+ client,+ webhookId,+}: {+ client: ReturnType<typeof makeClient>;+ webhookId: string;+}): Promise<void> {+ try {+ await client.deleteWebhook(webhookId);+ } catch (error) {+ if (!linearGraphql.isNotFoundError(error)) {+ throw error;+ }+ }+}++const REFUSED_MESSAGE =+ 'Linear refused to create the webhook. Webhooks need a personal API key created by a workspace admin, with the Admin permission (or Full access).';++export const linearWebhook = {+ register,+ unregister,+};++type RegisterParams = {+ auth: LinearAuth;+ store: Store;+ storeKey: string;+ input: LinearDocument.WebhookCreateInput;+};++type UnregisterParams = {+ auth: LinearAuth;+ store: Store;+ storeKey: string;+};++type WebhookCreateData = {+ webhookCreate: { success: boolean; webhook: { id: string } | null } | null;+};++type WebhookInformation = {+ webhookId: string;+ secret?: string;+};diff --git a/packages/pieces/community/linear/src/lib/output-schemas.ts b/packages/pieces/community/linear/src/lib/output-schemas.tsnew file mode 100644index 00000000000..4583870e23c--- /dev/null+++ b/packages/pieces/community/linear/src/lib/output-schemas.ts@@ -0,0 +1,384 @@+import { OutputSchema } from '@activepieces/pieces-framework';++const idOnly: OutputSchema['fields'] = [{ key: 'id', label: 'ID' }];++const issueFlatFields: OutputSchema['fields'] = [+ { key: 'id', label: 'Issue ID' },+ { key: 'identifier', label: 'Identifier' },+ { key: 'number', label: 'Number', format: 'number' },+ { key: 'title', label: 'Title' },+ { key: 'description', label: 'Description' },+ { key: 'url', label: 'URL', format: 'url' },+ { key: 'priority', label: 'Priority', format: 'number', description: '0 none, 1 urgent, 2 high, 3 medium, 4 low' },+ { key: 'priority_label', label: 'Priority Label' },+ { key: 'estimate', label: 'Estimate', format: 'number' },+ { key: 'due_date', label: 'Due Date', format: 'date' },+ { key: 'branch_name', label: 'Git Branch Name' },+ { key: 'state_id', label: 'Status ID' },+ { key: 'state_name', label: 'Status' },+ { key: 'state_type', label: 'Status Type' },+ { key: 'team_id', label: 'Team ID' },+ { key: 'team_key', label: 'Team Key' },+ { key: 'team_name', label: 'Team Name' },+ { key: 'assignee_id', label: 'Assignee ID' },+ { key: 'assignee_name', label: 'Assignee Name' },+ { key: 'assignee_email', label: 'Assignee Email', format: 'email' },+ { key: 'creator_id', label: 'Creator ID' },+ { key: 'creator_name', label: 'Creator Name' },+ { key: 'creator_email', label: 'Creator Email', format: 'email' },+ { key: 'project_id', label: 'Project ID' },+ { key: 'project_name', label: 'Project Name' },+ { key: 'project_milestone_id', label: 'Milestone ID' },+ { key: 'project_milestone_name', label: 'Milestone Name' },+ { key: 'cycle_id', label: 'Cycle ID' },+ { key: 'cycle_number', label: 'Cycle Number', format: 'number' },+ { key: 'cycle_name', label: 'Cycle Name' },+ { key: 'parent_id', label: 'Parent Issue ID' },+ { key: 'parent_identifier', label: 'Parent Identifier' },+ { key: 'parent_title', label: 'Parent Title' },+ { key: 'label_ids', label: 'Label IDs' },+ { key: 'label_names', label: 'Labels' },+ {+ key: 'labels_complete',+ label: 'All Labels Loaded',+ format: 'boolean',+ description: 'False when Linear did not return every label page; Label IDs and Labels then hold only the labels read',+ },+ { key: 'created_at', label: 'Created At', format: 'datetime' },+ { key: 'updated_at', label: 'Updated At', format: 'datetime' },+ { key: 'started_at', label: 'Started At', format: 'datetime' },+ { key: 'completed_at', label: 'Completed At', format: 'datetime' },+ { key: 'canceled_at', label: 'Canceled At', format: 'datetime' },+ { key: 'archived_at', label: 'Archived At', format: 'datetime' },+ { key: 'trashed', label: 'In Trash', format: 'boolean' },+];++const attachmentFlatFields: OutputSchema['fields'] = [+ { key: 'id', label: 'Attachment ID' },+ { key: 'title', label: 'Title' },+ { key: 'subtitle', label: 'Subtitle' },+ { key: 'url', label: 'URL', format: 'url' },+ { key: 'source_type', label: 'Source Type' },+ { key: 'issue_id', label: 'Issue ID' },+ { key: 'issue_identifier', label: 'Issue Identifier' },+ { key: 'issue_title', label: 'Issue Title' },+ { key: 'creator_id', label: 'Creator ID' },+ { key: 'creator_name', label: 'Creator Name' },+ { key: 'created_at', label: 'Created At', format: 'datetime' },+ { key: 'updated_at', label: 'Updated At', format: 'datetime' },+];++const projectStatusUpdateFlatFields: OutputSchema['fields'] = [+ { key: 'id', label: 'Status Update ID' },+ { key: 'body', label: 'Body (Markdown)' },+ { key: 'health', label: 'Health' },+ { key: 'url', label: 'URL', format: 'url' },+ { key: 'is_diff_hidden', label: 'Diff Hidden', format: 'boolean' },+ { key: 'user_id', label: 'Author ID' },+ { key: 'user_name', label: 'Author Name' },+ { key: 'user_email', label: 'Author Email', format: 'email' },+ { key: 'project_id', label: 'Project ID' },+ { key: 'project_name', label: 'Project Name' },+ { key: 'created_at', label: 'Created At', format: 'datetime' },+ { key: 'updated_at', label: 'Updated At', format: 'datetime' },+ { key: 'edited_at', label: 'Edited At', format: 'datetime' },+ { key: 'archived_at', label: 'Archived At', format: 'datetime' },+];++const archivedIssueFields: OutputSchema['fields'] = [+ { key: 'success', label: 'Success', format: 'boolean' },+ { key: 'id', label: 'Issue ID' },+ { key: 'identifier', label: 'Identifier' },+ { key: 'title', label: 'Title' },+ { key: 'url', label: 'URL', format: 'url' },+ { key: 'trashed', label: 'In Trash', format: 'boolean' },+ { key: 'archived_at', label: 'Archived At', format: 'datetime' },+];++const pageFields = ({ itemsLabel, items, labelKey }: { itemsLabel: string; items: OutputSchema['fields']; labelKey: string }): OutputSchema['fields'] => [+ { key: 'items', label: itemsLabel, labelKey, listItems: items },+ { key: 'count', label: 'Returned Count', format: 'number' },+ { key: 'has_next_page', label: 'Has More', format: 'boolean' },+ { key: 'end_cursor', label: 'Next Page Cursor' },+];++const sdkIssueModelFields: OutputSchema['fields'] = [+ { key: 'id', label: 'Issue ID' },+ { key: 'identifier', label: 'Identifier' },+ { key: 'number', label: 'Number', format: 'number' },+ { key: 'title', label: 'Title' },+ { key: 'description', label: 'Description' },+ { key: 'url', label: 'URL', format: 'url' },+ { key: 'priority', label: 'Priority', format: 'number' },+ { key: 'priorityLabel', label: 'Priority Label' },+ { key: 'estimate', label: 'Estimate', format: 'number' },+ { key: 'dueDate', label: 'Due Date', format: 'date' },+ { key: 'branchName', label: 'Git Branch Name' },+ { key: 'createdAt', label: 'Created At', format: 'datetime' },+ { key: 'updatedAt', label: 'Updated At', format: 'datetime' },+ { key: 'startedAt', label: 'Started At', format: 'datetime' },+ { key: 'completedAt', label: 'Completed At', format: 'datetime' },+ { key: 'canceledAt', label: 'Canceled At', format: 'datetime' },+ { key: '_team', label: 'Team', children: idOnly },+ { key: '_state', label: 'Status', children: idOnly },+ { key: '_assignee', label: 'Assignee', children: idOnly },+ { key: '_creator', label: 'Creator', children: idOnly },+ { key: '_project', label: 'Project', children: idOnly },+ { key: '_projectMilestone', label: 'Milestone', children: idOnly },+ { key: '_cycle', label: 'Cycle', children: idOnly },+ { key: '_parent', label: 'Parent Issue', children: idOnly },+];++const legacyProjectFields: OutputSchema['fields'] = [+ { key: 'id', label: 'Project ID' },+ { key: 'name', label: 'Name' },+ { key: 'description', label: 'Description' },+ { key: 'color', label: 'Color' },+ { key: 'icon', label: 'Icon' },+ { key: 'state', label: 'State' },+ { key: 'startDate', label: 'Start Date', format: 'date' },+ { key: 'targetDate', label: 'Target Date', format: 'date' },+ { key: 'progress', label: 'Progress', format: 'number' },+ { key: 'url', label: 'URL', format: 'url' },+ { key: 'createdAt', label: 'Created At', format: 'datetime' },+ { key: 'updatedAt', label: 'Updated At', format: 'datetime' },+];++const sdkCommentModelFields: OutputSchema['fields'] = [+ { key: 'id', label: 'Comment ID' },+ { key: 'body', label: 'Body (Markdown)' },+ { key: 'url', label: 'URL', format: 'url' },+ { key: 'createdAt', label: 'Created At', format: 'datetime' },+ { key: 'updatedAt', label: 'Updated At', format: 'datetime' },+ { key: '_issue', label: 'Issue', children: idOnly },+ { key: '_user', label: 'Author', children: idOnly },+];++const mutationEnvelope = ({ key, label, children }: { key: string; label: string; children: OutputSchema['fields'] }): OutputSchema => ({+ fields: [+ { key: 'success', label: 'Success', format: 'boolean' },+ { key: 'lastSyncId', label: 'Last Sync ID', format: 'number' },+ { key, label, children },+ ],+});++const webhookUserFields = ({ prefix }: { prefix: string }): OutputSchema['fields'] => [+ { key: 'id', label: `${prefix} ID` },+ { key: 'name', label: `${prefix} Name` },+ { key: 'email', label: `${prefix} Email`, format: 'email' },+ { key: 'avatarUrl', label: `${prefix} Avatar`, format: 'image' },+ { key: 'url', label: `${prefix} Profile URL`, format: 'url' },+];++const webhookEnvelope = ({ data, extra }: { data: OutputSchema['fields']; extra?: OutputSchema['fields'] }): OutputSchema => ({+ fields: [+ { key: 'action', label: 'Action', description: 'create, update or remove' },+ { key: 'type', label: 'Resource Type' },+ { key: 'url', label: 'URL', format: 'url' },+ { key: 'createdAt', label: 'Event Time', format: 'datetime' },+ {+ key: 'actor',+ label: 'Actor',+ children: [...webhookUserFields({ prefix: 'Actor' }), { key: 'type', label: 'Actor Type' }],+ },+ { key: 'data', label: 'Data', children: data },+ ...(extra ?? []),+ { key: 'organizationId', label: 'Workspace ID' },+ { key: 'webhookId', label: 'Webhook ID' },+ { key: 'webhookTimestamp', label: 'Webhook Timestamp', format: 'number', description: 'Unix time in milliseconds' },+ ],+});++const issueWebhookDataFields: OutputSchema['fields'] = [+ { key: 'id', label: 'Issue ID' },+ { key: 'identifier', label: 'Identifier' },+ { key: 'number', label: 'Number', format: 'number' },+ { key: 'title', label: 'Title' },+ { key: 'description', label: 'Description', description: 'Markdown. Missing when the issue has no description' },+ { key: 'url', label: 'URL', format: 'url' },+ { key: 'priority', label: 'Priority', format: 'number', description: '0 none, 1 urgent, 2 high, 3 medium, 4 low' },+ { key: 'priorityLabel', label: 'Priority Label' },+ { key: 'dueDate', label: 'Due Date', format: 'date' },+ { key: 'stateId', label: 'Status ID' },+ {+ key: 'state',+ label: 'Status',+ children: [+ { key: 'id', label: 'Status ID' },+ { key: 'name', label: 'Status Name' },+ { key: 'type', label: 'Status Type' },+ { key: 'color', label: 'Color' },+ ],+ },+ { key: 'teamId', label: 'Team ID' },+ {+ key: 'team',+ label: 'Team',+ children: [+ { key: 'id', label: 'Team ID' },+ { key: 'key', label: 'Team Key' },+ { key: 'name', label: 'Team Name' },+ ],+ },+ { key: 'assigneeId', label: 'Assignee ID', description: 'Missing when the issue is unassigned' },+ { key: 'assignee', label: 'Assignee', children: webhookUserFields({ prefix: 'Assignee' }) },+ { key: 'creatorId', label: 'Creator ID' },+ { key: 'projectId', label: 'Project ID' },+ {+ key: 'project',+ label: 'Project',+ children: [+ { key: 'id', label: 'Project ID' },+ { key: 'name', label: 'Project Name' },+ { key: 'url', label: 'Project URL', format: 'url' },+ ],+ },+ { key: 'parentId', label: 'Parent Issue ID' },+ { key: 'labelIds', label: 'Label IDs' },+ {+ key: 'labels',+ label: 'Labels',+ labelKey: 'name',+ listItems: [+ { key: 'id', label: 'Label ID' },+ { key: 'name', label: 'Label Name' },+ { key: 'color', label: 'Color' },+ ],+ },+ { key: 'subscriberIds', label: 'Subscriber IDs' },+ { key: 'createdAt', label: 'Created At', format: 'datetime' },+ { key: 'updatedAt', label: 'Updated At', format: 'datetime' },+ { key: 'startedAt', label: 'Started At', format: 'datetime' },+ { key: 'completedAt', label: 'Completed At', format: 'datetime' },+ { key: 'canceledAt', label: 'Canceled At', format: 'datetime' },+ { key: 'trashed', label: 'In Trash', format: 'boolean', description: 'Set on Removed Issue events' },+];++const projectWebhookDataFields: OutputSchema['fields'] = [+ { key: 'id', label: 'Project ID' },+ { key: 'identifier', label: 'Identifier' },+ { key: 'name', label: 'Name' },+ { key: 'description', label: 'Description' },+ { key: 'url', label: 'URL', format: 'url' },+ { key: 'slugId', label: 'Slug ID' },+ { key: 'color', label: 'Color' },+ { key: 'icon', label: 'Icon' },+ { key: 'priority', label: 'Priority', format: 'number', description: '0 none, 1 urgent, 2 high, 3 medium, 4 low' },+ { key: 'statusId', label: 'Status ID' },+ {+ key: 'status',+ label: 'Status',+ children: [+ { key: 'id', label: 'Status ID' },+ { key: 'name', label: 'Status Name' },+ { key: 'type', label: 'Status Type' },+ { key: 'color', label: 'Color' },+ ],+ },+ { key: 'health', label: 'Health', description: 'onTrack, atRisk or offTrack, from the latest status update' },+ { key: 'teamIds', label: 'Team IDs' },+ { key: 'leadId', label: 'Lead ID' },+ { key: 'lead', label: 'Lead', children: webhookUserFields({ prefix: 'Lead' }) },+ { key: 'memberIds', label: 'Member IDs' },+ { key: 'labelIds', label: 'Label IDs' },+ { key: 'creatorId', label: 'Creator ID' },+ { key: 'startDate', label: 'Start Date', format: 'date' },+ { key: 'targetDate', label: 'Target Date', format: 'date' },+ { key: 'createdAt', label: 'Created At', format: 'datetime' },+ { key: 'updatedAt', label: 'Updated At', format: 'datetime' },+ { key: 'startedAt', label: 'Started At', format: 'datetime' },+ { key: 'trashed', label: 'In Trash', format: 'boolean', description: 'Set on Removed Project events' },+];++const commentWebhookDataFields: OutputSchema['fields'] = [+ { key: 'id', label: 'Comment ID' },+ { key: 'body', label: 'Body (Markdown)' },+ { key: 'issueId', label: 'Issue ID' },+ { key: 'parentId', label: 'Parent Comment ID', description: 'Only on replies' },+ { key: 'userId', label: 'Author ID' },+ { key: 'user', label: 'Author', children: webhookUserFields({ prefix: 'Author' }) },+ {+ key: 'issue',+ label: 'Issue',+ children: [+ { key: 'id', label: 'Issue ID' },+ { key: 'identifier', label: 'Identifier' },+ { key: 'title', label: 'Title' },+ { key: 'url', label: 'Issue URL', format: 'url' },+ { key: 'teamId', label: 'Team ID' },+ {+ key: 'team',+ label: 'Team',+ children: [+ { key: 'id', label: 'Team ID' },+ { key: 'key', label: 'Team Key' },+ { key: 'name', label: 'Team Name' },+ ],+ },+ ],+ },+ { key: 'createdAt', label: 'Created At', format: 'datetime' },+ { key: 'updatedAt', label: 'Updated At', format: 'datetime' },+];++const projectStatusUpdateWebhookDataFields: OutputSchema['fields'] = [+ { key: 'id', label: 'Status Update ID' },+ { key: 'body', label: 'Body (Markdown)' },+ { key: 'health', label: 'Health', description: 'onTrack, atRisk or offTrack' },+ { key: 'diffMarkdown', label: 'Changes Since Last Update', description: 'Markdown summary Linear adds of what changed in the project' },+ { key: 'slugId', label: 'Slug ID' },+ { key: 'projectId', label: 'Project ID' },+ {+ key: 'project',+ label: 'Project',+ children: [+ { key: 'id', label: 'Project ID' },+ { key: 'name', label: 'Project Name' },+ { key: 'url', label: 'Project URL', format: 'url' },+ ],+ },+ { key: 'userId', label: 'Author ID' },+ { key: 'user', label: 'Author', children: webhookUserFields({ prefix: 'Author' }) },+ { key: 'createdAt', label: 'Created At', format: 'datetime' },+ { key: 'updatedAt', label: 'Updated At', format: 'datetime' },+];++const updatedFromField: OutputSchema['fields'] = [+ {+ key: 'updatedFrom',+ label: 'Previous Values',+ dynamicKey: true,+ description: 'Only the fields that changed, with their value before the update',+ },+];++export const linearFieldSets = {+ idOnly,+ issueFlatFields,+ attachmentFlatFields,+ projectStatusUpdateFlatFields,+ archivedIssueFields,+ pageFields,+};++export const issueMutationOutputSchema: OutputSchema = mutationEnvelope({ key: 'issue', label: 'Issue', children: sdkIssueModelFields });+export const projectMutationOutputSchema: OutputSchema = mutationEnvelope({ key: 'project', label: 'Project', children: legacyProjectFields });+export const commentMutationOutputSchema: OutputSchema = mutationEnvelope({ key: 'comment', label: 'Comment', children: sdkCommentModelFields });++export const issueOutputSchema: OutputSchema = { fields: issueFlatFields };+export const issueSearchOutputSchema: OutputSchema = {+ fields: [+ ...pageFields({ itemsLabel: 'Issues', items: issueFlatFields, labelKey: 'identifier' }),+ { key: 'total_count', label: 'Total Matches', format: 'number' },+ ],+};+export const archivedIssueOutputSchema: OutputSchema = { fields: archivedIssueFields };+export const attachmentOutputSchema: OutputSchema = { fields: attachmentFlatFields };+export const projectStatusUpdateOutputSchema: OutputSchema = { fields: projectStatusUpdateFlatFields };++export const issueWebhookOutputSchema: OutputSchema = webhookEnvelope({ data: issueWebhookDataFields });+export const updatedIssueWebhookOutputSchema: OutputSchema = webhookEnvelope({ data: issueWebhookDataFields, extra: updatedFromField });+export const projectWebhookOutputSchema: OutputSchema = webhookEnvelope({ data: projectWebhookDataFields });+export const updatedProjectWebhookOutputSchema: OutputSchema = webhookEnvelope({ data: projectWebhookDataFields, extra: updatedFromField });+export const commentWebhookOutputSchema: OutputSchema = webhookEnvelope({ data: commentWebhookDataFields });+export const projectStatusUpdateWebhookOutputSchema: OutputSchema = webhookEnvelope({ data: projectStatusUpdateWebhookDataFields });diff --git a/packages/pieces/community/linear/src/lib/triggers/new-comment.ts b/packages/pieces/community/linear/src/lib/triggers/new-comment.tsindex 9d08be8dd14..9c3242445b6 100644--- a/packages/pieces/community/linear/src/lib/triggers/new-comment.ts+++ b/packages/pieces/community/linear/src/lib/triggers/new-comment.ts@@ -1,6 +1,8 @@import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';import { linearAuth } from '../..';-import { makeClient } from '../common/client';+import { linearWebhook } from '../common/webhook';+import { commentWebhookOutputSchema } from '../output-schemas';+import { linearWebhookSamples } from '../common/webhook-samples';import { props } from '../common/props';export const linearNewComment = createTrigger({@@ -8,74 +10,36 @@ export const linearNewComment = createTrigger({name: 'new_comment',classification: 'READ',displayName: 'New Comment',- description: 'Triggers when a new comment is created on a Linear issue',+ description: 'Triggers when a new comment is created on a Linear issue. Only issues in public teams are covered.',aiMetadata: {- description: 'Fires when a new comment is posted on a Linear issue, optionally filtered to specific teams or comment authors. Represents the created comment and its parent issue.',+ description: 'Fires when a new comment is posted on a Linear issue, optionally filtered to specific teams or comment authors. Represents the created comment and its parent issue. Only public teams are covered: events in private teams do not fire it.',},props: {team_ids: props.team_ids(false),author_ids: props.author_ids(false),},- sampleData: {- action: 'create',- data: {- id: 'c1a2b3c4-d5e6-7890-abcd-ef1234567890',- body: 'This is a test comment',- issueId: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890',- parentId: null,- userId: 'u1a2b3c4-d5e6-7890-abcd-ef1234567890',- reactionData: [],- createdAt: '2023-09-05T12:00:00.000Z',- updatedAt: '2023-09-05T12:00:00.000Z',- user: {- id: 'u1a2b3c4-d5e6-7890-abcd-ef1234567890',- name: 'Test user',- },- issue: {- id: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890',- title: 'Test issue',- identifier: 'TEST-1',- team: {- id: 't1a2b3c4-d5e6-7890-abcd-ef1234567890',- key: 'TEST',- name: 'Test team',- },- },- },- type: 'Comment',- actor: { id: 'u1a2b3c4-d5e6-7890-abcd-ef1234567890', name: 'Test user', type: 'user' },- createdAt: '2023-09-05T12:00:00.000Z',- url: 'https://linear.app/test-team/issue/TEST-1#comment-c1a2b3c4',- organizationId: 'org_1',- webhookTimestamp: 1693915200000,- webhookId: 'webhook_1',- },+ sampleData: linearWebhookSamples.newCommentSample,+ outputSchema: commentWebhookOutputSchema,type: TriggerStrategy.WEBHOOK,async onEnable(context) {- const client = makeClient(context.auth);-- const webhook = await client.createWebhook({- label: 'ActivePieces New Comment',- url: context.webhookUrl,- resourceTypes: ['Comment'],- allPublicTeams: true,+ await linearWebhook.register({+ auth: context.auth,+ store: context.store,+ storeKey: '_new_comment_trigger',+ input: {+ label: 'ActivePieces New Comment',+ url: context.webhookUrl,+ resourceTypes: ['Comment'],+ allPublicTeams: true,+ },});-- if (webhook.success && webhook.webhook) {- await context.store?.put<WebhookInformation>('_new_comment_trigger', {- webhookId: (await webhook.webhook).id,- });- } else {- console.error('Failed to create the webhook');- }},async onDisable(context) {- const client = makeClient(context.auth);- const response =- await context.store?.get<WebhookInformation>('_new_comment_trigger');- if (response && response.webhookId) {- await client.deleteWebhook(response.webhookId);- }+ await linearWebhook.unregister({+ auth: context.auth,+ store: context.store,+ storeKey: '_new_comment_trigger',+ });},async run(context) {const body = context.payload.body as {@@ -110,7 +74,3 @@ export const linearNewComment = createTrigger({return [body];},});--interface WebhookInformation {- webhookId: string;-}diff --git a/packages/pieces/community/linear/src/lib/triggers/new-issue.ts b/packages/pieces/community/linear/src/lib/triggers/new-issue.tsindex a55c1e13bf9..f8bddb568c6 100644--- a/packages/pieces/community/linear/src/lib/triggers/new-issue.ts+++ b/packages/pieces/community/linear/src/lib/triggers/new-issue.ts@@ -1,6 +1,8 @@import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';import { linearAuth } from '../..';-import { makeClient } from '../common/client';+import { linearWebhook } from '../common/webhook';+import { issueWebhookOutputSchema } from '../output-schemas';+import { linearWebhookSamples } from '../common/webhook-samples';import { props } from '../common/props';export const linearNewIssue = createTrigger({@@ -15,88 +17,28 @@ export const linearNewIssue = createTrigger({props: {team_id: props.team_id(),},- sampleData: {- // Sample data structure based on Linear's webhook payload for issues- action: 'create',- data: {- id: 'issue_1',- identifier: '1',- title: 'Test issue',- description: 'This is a test issue',- priority: 'priority_1',- priorityLabel: 'High',- state: 'state_1',- stateLabel: 'In Progress',- team: {- id: 'team_1',- name: 'Test team',- key: 'test-team',- description: 'This is a test team',- archived: false,- createdAt: '2023-09-05T12:00:00.000Z',- updatedAt: '2023-09-05T12:00:00.000Z',- },- creator: {- id: 'user_1',- name: 'Test user',- email: '[email protected]',- avatarUrl: 'https://avatars.githubusercontent.com/u/1?v=4',- createdAt: '2023-09-05T12:00:00.000Z',- updatedAt: '2023-09-05T12:00:00.000Z',- },- assignee: {- id: 'user_1',- name: 'Test user',- email: '[email protected]',- avatarUrl: 'https://avatars.githubusercontent.com/u/1?v=4',- createdAt: '2023-09-05T12:00:00.000Z',- updatedAt: '2023-09-05T12:00:00.000Z',- },- labels: [- {- id: 'label_1',- name: 'Test label',- color: '#000000',- createdAt: '2023-09-05T12:00:00.000Z',- updatedAt: '2023-09-05T12:00:00.000Z',- },- ],- createdAt: '2023-09-05T12:00:00.000Z',- updatedAt: '2023-09-05T12:00:00.000Z',- },- type: 'Issue',- actor: { id: 'user_1', name: 'Test user', type: 'user' },- createdAt: '2023-09-05T12:00:00.000Z',- url: 'https://linear.app/test-team/issue/1',- organizationId: 'org_1',- webhookTimestamp: 1693915200000,- webhookId: 'webhook_1',- },+ sampleData: linearWebhookSamples.newIssueSample,+ outputSchema: issueWebhookOutputSchema,type: TriggerStrategy.WEBHOOK,async onEnable(context) {- const client = makeClient(context.auth);- const webhook = await client.createWebhook({- label: 'ActivePieces New Issue',- url: context.webhookUrl,- teamId: context.propsValue['team_id'],- resourceTypes: ['Issue'],+ await linearWebhook.register({+ auth: context.auth,+ store: context.store,+ storeKey: '_new_issue_trigger',+ input: {+ label: 'ActivePieces New Issue',+ url: context.webhookUrl,+ teamId: context.propsValue['team_id'],+ resourceTypes: ['Issue'],+ },});- if (webhook.success && webhook.webhook) {- await context.store?.put<WebhookInformation>('_new_issue_trigger', {- webhookId: (await webhook.webhook).id,- });- } else {- console.error('Failed to create the webhook');- }},async onDisable(context) {- const client = makeClient(context.auth);- const response = await context.store?.get<WebhookInformation>(- '_new_issue_trigger'- );- if (response && response.webhookId) {- await client.deleteWebhook(response.webhookId);- }+ await linearWebhook.unregister({+ auth: context.auth,+ store: context.store,+ storeKey: '_new_issue_trigger',+ });},async run(context) {const body = context.payload.body as { action: string; data: unknown };@@ -106,7 +48,3 @@ export const linearNewIssue = createTrigger({return [];},});--interface WebhookInformation {- webhookId: string;-}diff --git a/packages/pieces/community/linear/src/lib/triggers/new-project-status-update.test.ts b/packages/pieces/community/linear/src/lib/triggers/new-project-status-update.test.tsnew file mode 100644index 00000000000..96667b013f6--- /dev/null+++ b/packages/pieces/community/linear/src/lib/triggers/new-project-status-update.test.ts@@ -0,0 +1,189 @@+/// <reference types="vitest/globals" />++import crypto from 'crypto';+import { vi } from 'vitest';++const rawRequest = vi.fn();+const deleteWebhook = vi.fn();++vi.mock('@linear/sdk', () => ({+ LinearClient: class {+ client = { rawRequest };+ deleteWebhook = deleteWebhook;+ },+ LinearDocument: {},+}));++import '../../index';+import { linearNewProjectStatusUpdate } from './new-project-status-update';++const SECRET = 'a'.repeat(64);+const HOUR = 60 * 60 * 1000;+const BODY = bodyAt(Date.now());++function bodyAt(webhookTimestamp: number | undefined): string {+ return JSON.stringify({ action: 'create', type: 'ProjectUpdate', data: { id: 'pu-1', projectId: 'p-1' }, webhookTimestamp });+}++function sign({ body, secret = SECRET }: { body: string; secret?: string }): string {+ return crypto.createHmac('sha256', secret).update(body).digest('hex');+}++function memoryStore(initial: Record<string, unknown>) {+ const values = new Map<string, unknown>(Object.entries(initial));+ return {+ values,+ get: vi.fn(async (key: string) => values.get(key) ?? null),+ put: vi.fn(async (key: string, value: unknown) => {+ values.set(key, value);+ return value;+ }),+ delete: vi.fn(async (key: string) => {+ values.delete(key);+ }),+ };+}++function runContext({+ headers,+ rawBody = BODY,+ stored = { webhookId: 'wh-1', secret: SECRET },+ store = memoryStore({ _new_project_status_update_trigger: stored }),+}: RunContextParams) {+ return {+ auth: { type: 'SECRET_TEXT', secret_text: 'lin_api_test' },+ propsValue: { project_id: undefined },+ store,+ payload: { body: JSON.parse(rawBody), headers, rawBody },+ };+}++describe('new_project_status_update signature', () => {+ test('onEnable sends a random secret to Linear and stores it with the webhook id', async () => {+ rawRequest.mockResolvedValue({ data: { webhookCreate: { success: true, webhook: { id: 'wh-1' } } } });+ const put = vi.fn().mockResolvedValue(undefined);+ await linearNewProjectStatusUpdate.onEnable({+ auth: { type: 'SECRET_TEXT', secret_text: 'lin_api_test' },+ webhookUrl: 'https://example.com/hook',+ propsValue: {},+ store: { put, get: vi.fn(), delete: vi.fn() },+ });+ const secret = rawRequest.mock.calls[0][1].input.secret;+ expect(secret).toMatch(/^[0-9a-f]{64}$/);+ expect(put).toHaveBeenCalledWith('_new_project_status_update_trigger', { webhookId: 'wh-1', secret });+ });++ test('accepts a delivery signed with the stored secret', async () => {+ const out = await linearNewProjectStatusUpdate.run(runContext({ headers: { 'Linear-Signature': sign({ body: BODY }) } }));+ expect(out).toHaveLength(1);+ });++ test('drops unsigned, wrongly signed and tampered deliveries', async () => {+ expect(await linearNewProjectStatusUpdate.run(runContext({ headers: {} }))).toEqual([]);+ expect(+ await linearNewProjectStatusUpdate.run(runContext({ headers: { 'linear-signature': sign({ body: BODY, secret: 'b'.repeat(64) }) } })),+ ).toEqual([]);+ expect(+ await linearNewProjectStatusUpdate.run(+ runContext({ headers: { 'linear-signature': sign({ body: BODY }) }, rawBody: BODY.replace('pu-1', 'pu-2') }),+ ),+ ).toEqual([]);+ expect(await linearNewProjectStatusUpdate.run(runContext({ headers: { 'linear-signature': 'zz' } }))).toEqual([]);+ });++ test('drops deliveries when no secret was stored', async () => {+ const out = await linearNewProjectStatusUpdate.run(+ runContext({ headers: { 'linear-signature': sign({ body: BODY }) }, stored: { webhookId: 'wh-1', secret: undefined } }),+ );+ expect(out).toEqual([]);+ });+});++describe('new_project_status_update replay protection', () => {+ test('drops a signed delivery whose webhookTimestamp is more than 7 hours old or ahead, or missing', async () => {+ for (const timestamp of [Date.now() - 7 * HOUR - 60 * 1000, Date.now() + 7 * HOUR + 60 * 1000, undefined]) {+ const body = bodyAt(timestamp);+ const out = await linearNewProjectStatusUpdate.run(runContext({ headers: { 'linear-signature': sign({ body }) }, rawBody: body }));+ expect(out).toEqual([]);+ }+ });++ test.each([+ { retry: 'first retry after about a minute', age: 60 * 1000 },+ { retry: 'second retry after about an hour', age: HOUR },+ { retry: 'last retry after about six hours', age: 6 * HOUR + 10 * 60 * 1000 },+ ])('accepts a signed delivery on the $retry', async ({ age }) => {+ const body = bodyAt(Date.now() - age);+ const out = await linearNewProjectStatusUpdate.run(runContext({ headers: { 'linear-signature': sign({ body }) }, rawBody: body }));+ expect(out).toHaveLength(1);+ });++ test('returns a repeated Linear-Delivery id only once', async () => {+ const store = memoryStore({ _new_project_status_update_trigger: { webhookId: 'wh-1', secret: SECRET } });+ const headers = { 'Linear-Signature': sign({ body: BODY }), 'Linear-Delivery': 'delivery-1' };+ expect(await linearNewProjectStatusUpdate.run(runContext({ headers, store }))).toHaveLength(1);+ expect(await linearNewProjectStatusUpdate.run(runContext({ headers: { 'linear-signature': sign({ body: BODY }), 'linear-delivery': 'delivery-1' }, store }))).toEqual([]);+ expect(+ await linearNewProjectStatusUpdate.run(runContext({ headers: { ...headers, 'Linear-Delivery': 'delivery-2' }, store })),+ ).toHaveLength(1);+ expect(store.values.get('_new_project_status_update_deliveries')).toEqual(['delivery-1', 'delivery-2']);+ });++ test('keeps only the last 200 delivery ids', async () => {+ const earlier = Array.from({ length: 200 }, (_, index) => `old-${index}`);+ const store = memoryStore({+ _new_project_status_update_trigger: { webhookId: 'wh-1', secret: SECRET },+ _new_project_status_update_deliveries: earlier,+ });+ const headers = { 'linear-signature': sign({ body: BODY }), 'linear-delivery': 'new-1' };+ expect(await linearNewProjectStatusUpdate.run(runContext({ headers, store }))).toHaveLength(1);+ const kept = store.values.get('_new_project_status_update_deliveries');+ expect(kept).toHaveLength(200);+ expect(kept).toEqual([...earlier.slice(1), 'new-1']);+ });+});++describe('new_project_status_update onDisable', () => {+ beforeEach(() => {+ deleteWebhook.mockReset();+ });++ test('deletes the webhook and clears the store', async () => {+ deleteWebhook.mockResolvedValue({ success: true });+ const store = memoryStore({ _new_project_status_update_trigger: { webhookId: 'wh-1', secret: SECRET } });+ await linearNewProjectStatusUpdate.onDisable(disableContext(store));+ expect(deleteWebhook).toHaveBeenCalledWith('wh-1');+ expect(store.delete).toHaveBeenCalledWith('_new_project_status_update_trigger');+ });++ test('treats a webhook Linear no longer has as already deleted', async () => {+ deleteWebhook.mockRejectedValue(new Error('Entity not found: Webhook - Could not find referenced Webhook.'));+ const store = memoryStore({ _new_project_status_update_trigger: { webhookId: 'wh-1', secret: SECRET } });+ await linearNewProjectStatusUpdate.onDisable(disableContext(store));+ expect(store.delete).toHaveBeenCalledWith('_new_project_status_update_trigger');+ expect(store.values.has('_new_project_status_update_trigger')).toBe(false);+ });++ test('keeps the stored webhook when Linear fails for another reason', async () => {+ deleteWebhook.mockRejectedValue(new Error('Linear rate limit reached.'));+ const store = memoryStore({ _new_project_status_update_trigger: { webhookId: 'wh-1', secret: SECRET } });+ await expect(linearNewProjectStatusUpdate.onDisable(disableContext(store))).rejects.toThrow('rate limit');+ expect(store.values.has('_new_project_status_update_trigger')).toBe(true);+ });+});++function disableContext(store: ReturnType<typeof memoryStore>) {+ return {+ auth: { type: 'SECRET_TEXT', secret_text: 'lin_api_test' },+ webhookUrl: 'https://example.com/hook',+ propsValue: {},+ store,+ };+}++type RunContextParams = {+ headers: Record<string, string>;+ rawBody?: string;+ stored?: { webhookId: string; secret: string | undefined };+ store?: ReturnType<typeof memoryStore>;+};diff --git a/packages/pieces/community/linear/src/lib/triggers/new-project-status-update.ts b/packages/pieces/community/linear/src/lib/triggers/new-project-status-update.tsnew file mode 100644index 00000000000..f29f361c89a--- /dev/null+++ b/packages/pieces/community/linear/src/lib/triggers/new-project-status-update.ts@@ -0,0 +1,111 @@+import { createTrigger, Store, TriggerStrategy } from '@activepieces/pieces-framework';+import { linearAuth } from '../..';+import { props } from '../common/props';+import { linearWebhook } from '../common/webhook';+import { projectStatusUpdateWebhookOutputSchema } from '../output-schemas';+import { linearWebhookSamples } from '../common/webhook-samples';+import { LINEAR_DELIVERY_HEADER, LINEAR_SIGNATURE_HEADER, linearWebhookSignature } from '../common/webhook-signature';++export const linearNewProjectStatusUpdate = createTrigger({+ auth: linearAuth,+ name: 'new_project_status_update',+ classification: 'READ',+ displayName: 'New Project Status Update',+ description: 'Triggers when a status update is posted on a project. Only projects in public teams are covered.',+ aiMetadata: {+ description:+ 'Fires once each time someone posts a status update (body plus on track / at risk / off track health) on a Linear project, optionally only for one project. Does not fire when the project itself is edited. Only public teams are covered: updates on projects of private teams do not fire it.',+ },+ props: {+ project_id: props.any_project_id(false),+ },+ sampleData: linearWebhookSamples.newProjectStatusUpdateSample,+ outputSchema: projectStatusUpdateWebhookOutputSchema,+ type: TriggerStrategy.WEBHOOK,+ async onEnable(context) {+ await linearWebhook.register({+ auth: context.auth,+ store: context.store,+ storeKey: STORE_KEY,+ input: {+ label: 'ActivePieces New Project Status Update',+ url: context.webhookUrl,+ resourceTypes: ['ProjectUpdate'],+ allPublicTeams: true,+ secret: linearWebhookSignature.newSecret(),+ },+ });+ },+ async onDisable(context) {+ await linearWebhook.unregister({ auth: context.auth, store: context.store, storeKey: STORE_KEY });+ await context.store.delete(DELIVERIES_STORE_KEY);+ },+ async run(context) {+ const stored = await context.store.get<StoredWebhook>(STORE_KEY);+ const verified = linearWebhookSignature.verify({+ secret: stored?.secret,+ signatureHeader: linearWebhookSignature.headerOf({+ headers: context.payload.headers,+ name: LINEAR_SIGNATURE_HEADER,+ }),+ rawBody: context.payload.rawBody,+ });+ if (!verified) {+ return [];+ }+ const body = context.payload.body;+ if (!isProjectUpdatePayload(body) || !linearWebhookSignature.isFreshTimestamp({ timestamp: body.webhookTimestamp, now: Date.now() })) {+ return [];+ }+ const deliveryId = linearWebhookSignature.headerOf({ headers: context.payload.headers, name: LINEAR_DELIVERY_HEADER });+ if (deliveryId && !(await rememberDelivery({ store: context.store, deliveryId }))) {+ return [];+ }+ if (body.action !== 'create') {+ return [];+ }+ const projectId = context.propsValue.project_id;+ if (projectId && (body.data.projectId ?? body.data.project?.id) !== projectId) {+ return [];+ }+ return [body];+ },+});++async function rememberDelivery({ store, deliveryId }: { store: Store; deliveryId: string }): Promise<boolean> {+ const seen = (await store.get<string[]>(DELIVERIES_STORE_KEY)) ?? [];+ if (seen.includes(deliveryId)) {+ return false;+ }+ await store.put<string[]>(DELIVERIES_STORE_KEY, [...seen, deliveryId].slice(-MAX_REMEMBERED_DELIVERIES));+ return true;+}++function isProjectUpdatePayload(value: unknown): value is ProjectUpdatePayload {+ return (+ typeof value === 'object' &&+ value !== null &&+ 'action' in value &&+ 'data' in value &&+ typeof value.data === 'object' &&+ value.data !== null+ );+}++const STORE_KEY = '_new_project_status_update_trigger';+const DELIVERIES_STORE_KEY = '_new_project_status_update_deliveries';+const MAX_REMEMBERED_DELIVERIES = 200;++type StoredWebhook = {+ webhookId: string;+ secret?: string;+};++type ProjectUpdatePayload = {+ action: string;+ webhookTimestamp?: number;+ data: {+ projectId?: string;+ project?: { id?: string };+ };+};diff --git a/packages/pieces/community/linear/src/lib/triggers/new-project.ts b/packages/pieces/community/linear/src/lib/triggers/new-project.tsindex 4a808e9dd97..5041103b529 100644--- a/packages/pieces/community/linear/src/lib/triggers/new-project.ts+++ b/packages/pieces/community/linear/src/lib/triggers/new-project.ts@@ -1,76 +1,41 @@import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';import { linearAuth } from '../..';-import { makeClient } from '../common/client';+import { linearWebhook } from '../common/webhook';+import { projectWebhookOutputSchema } from '../output-schemas';+import { linearWebhookSamples } from '../common/webhook-samples';export const linearNewProject = createTrigger({auth: linearAuth,name: 'new_project',classification: 'READ',displayName: 'New Project',- description: 'Triggers when a new project is created in Linear',+ description: 'Triggers when a new project is created in Linear. Only projects in public teams are covered.',aiMetadata: {- description: 'Fires when a new project is created anywhere in the Linear workspace. Represents the newly created project with its details such as name, state, dates, and teams.',+ description: 'Fires when a new project is created anywhere in the Linear workspace. Represents the newly created project with its details such as name, state, dates, and teams. Only public teams are covered: events in private teams do not fire it.',},props: {},- sampleData: {- action: 'create',- data: {- id: 'project_1',- name: 'Test project',- description: 'This is a test project',- state: 'planned',- color: '#000000',- icon: null,- startDate: '2023-09-05',- targetDate: '2023-12-05',- creator: {- id: 'user_1',- name: 'Test user',- email: '[email protected]',- },- teams: [- {- id: 'team_1',- name: 'Test team',- key: 'test-team',- },- ],- createdAt: '2023-09-05T12:00:00.000Z',- updatedAt: '2023-09-05T12:00:00.000Z',- },- type: 'Project',- actor: { id: 'user_1', name: 'Test user', type: 'user' },- createdAt: '2023-09-05T12:00:00.000Z',- url: 'https://linear.app/test-team/project/project_1',- organizationId: 'org_1',- webhookTimestamp: 1693915200000,- webhookId: 'webhook_1',- },+ sampleData: linearWebhookSamples.newProjectSample,+ outputSchema: projectWebhookOutputSchema,type: TriggerStrategy.WEBHOOK,async onEnable(context) {- const client = makeClient(context.auth);- const webhook = await client.createWebhook({- label: 'ActivePieces New Project',- url: context.webhookUrl,- resourceTypes: ['Project'],- allPublicTeams: true,+ await linearWebhook.register({+ auth: context.auth,+ store: context.store,+ storeKey: '_new_project_trigger',+ input: {+ label: 'ActivePieces New Project',+ url: context.webhookUrl,+ resourceTypes: ['Project'],+ allPublicTeams: true,+ },});- if (webhook.success && webhook.webhook) {- await context.store?.put<WebhookInformation>('_new_project_trigger', {- webhookId: (await webhook.webhook).id,- });- } else {- console.error('Failed to create the webhook');- }},async onDisable(context) {- const client = makeClient(context.auth);- const response = await context.store?.get<WebhookInformation>(- '_new_project_trigger'- );- if (response && response.webhookId) {- await client.deleteWebhook(response.webhookId);- }+ await linearWebhook.unregister({+ auth: context.auth,+ store: context.store,+ storeKey: '_new_project_trigger',+ });},async run(context) {const body = context.payload.body as { action: string; data: unknown };@@ -80,7 +45,3 @@ export const linearNewProject = createTrigger({return [];},});--interface WebhookInformation {- webhookId: string;-}diff --git a/packages/pieces/community/linear/src/lib/triggers/removed-issue.ts b/packages/pieces/community/linear/src/lib/triggers/removed-issue.tsindex 52a4ed703ea..b9b1f8d2a01 100644--- a/packages/pieces/community/linear/src/lib/triggers/removed-issue.ts+++ b/packages/pieces/community/linear/src/lib/triggers/removed-issue.ts@@ -1,6 +1,8 @@import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';import { linearAuth } from '../..';-import { makeClient } from '../common/client';+import { linearWebhook } from '../common/webhook';+import { issueWebhookOutputSchema } from '../output-schemas';+import { linearWebhookSamples } from '../common/webhook-samples';import { props } from '../common/props';export const linearRemovedIssue = createTrigger({@@ -15,88 +17,28 @@ export const linearRemovedIssue = createTrigger({props: {team_id: props.team_id()},- sampleData: {- // Sample data structure based on Linear's webhook payload for issues- action: 'remove',- data: {- id: 'issue_1',- identifier: '1',- title: 'Test issue',- description: 'This is a test issue',- priority: 'priority_1',- priorityLabel: 'High',- state: 'state_1',- stateLabel: 'In Progress',- team: {- id: 'team_1',- name: 'Test team',- key: 'test-team',- description: 'This is a test team',- archived: false,- createdAt: '2023-09-05T12:00:00.000Z',- updatedAt: '2023-09-05T12:00:00.000Z',- },- creator: {- id: 'user_1',- name: 'Test user',- email: '[email protected]',- avatarUrl: 'https://avatars.githubusercontent.com/u/1?v=4',- createdAt: '2023-09-05T12:00:00.000Z',- updatedAt: '2023-09-05T12:00:00.000Z',- },- assignee: {- id: 'user_1',- name: 'Test user',- email: '[email protected]',- avatarUrl: 'https://avatars.githubusercontent.com/u/1?v=4',- createdAt: '2023-09-05T12:00:00.000Z',- updatedAt: '2023-09-05T12:00:00.000Z',- },- labels: [- {- id: 'label_1',- name: 'Test label',- color: '#000000',- createdAt: '2023-09-05T12:00:00.000Z',- updatedAt: '2023-09-05T12:00:00.000Z',- },- ],- createdAt: '2023-09-05T12:00:00.000Z',- updatedAt: '2023-09-05T12:00:00.000Z',- },- type: 'Issue',- actor: { id: 'user_1', name: 'Test user', type: 'user' },- createdAt: '2023-09-05T12:00:00.000Z',- url: 'https://linear.app/test-team/issue/1',- organizationId: 'org_1',- webhookTimestamp: 1693915200000,- webhookId: 'webhook_1',- },+ sampleData: linearWebhookSamples.removedIssueSample,+ outputSchema: issueWebhookOutputSchema,type: TriggerStrategy.WEBHOOK,async onEnable(context) {- const client = makeClient(context.auth);- const webhook = await client.createWebhook({- label: 'ActivePieces Updated Issue',- url: context.webhookUrl,- teamId: context.propsValue['team_id'],- resourceTypes: ['Issue']+ await linearWebhook.register({+ auth: context.auth,+ store: context.store,+ storeKey: '_removed_issue_trigger',+ input: {+ label: 'ActivePieces Removed Issue',+ url: context.webhookUrl,+ teamId: context.propsValue['team_id'],+ resourceTypes: ['Issue'],+ },});- if (webhook.success && webhook.webhook) {- await context.store?.put<WebhookInformation>('_removed_issue_trigger', {- webhookId: (await webhook.webhook).id- });- } else {- console.error('Failed to create the webhook');- }},async onDisable(context) {- const client = makeClient(context.auth);- const response = await context.store?.get<WebhookInformation>(- '_removed_issue_trigger'- );- if (response && response.webhookId) {- await client.deleteWebhook(response.webhookId);- }+ await linearWebhook.unregister({+ auth: context.auth,+ store: context.store,+ storeKey: '_removed_issue_trigger',+ });},async run(context) {const body = context.payload.body as { action: string; data: unknown};@@ -106,7 +48,3 @@ export const linearRemovedIssue = createTrigger({return [];}});--interface WebhookInformation {- webhookId: string;-}diff --git a/packages/pieces/community/linear/src/lib/triggers/removed-project.ts b/packages/pieces/community/linear/src/lib/triggers/removed-project.tsindex 048c0d192c7..9ad28ea2f75 100644--- a/packages/pieces/community/linear/src/lib/triggers/removed-project.ts+++ b/packages/pieces/community/linear/src/lib/triggers/removed-project.ts@@ -1,79 +1,41 @@import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';import { linearAuth } from '../..';-import { makeClient } from '../common/client';+import { linearWebhook } from '../common/webhook';+import { projectWebhookOutputSchema } from '../output-schemas';+import { linearWebhookSamples } from '../common/webhook-samples';export const linearRemovedProject = createTrigger({auth: linearAuth,name: 'removed_project',classification: 'READ',displayName: 'Removed Project',- description: 'Triggers when an existing Linear project is removed',+ description: 'Triggers when an existing Linear project is removed. Only projects in public teams are covered.',aiMetadata: {- description: 'Fires when an existing project is deleted anywhere in the Linear workspace. Represents the project as it was at the time of removal.',+ description: 'Fires when an existing project is deleted anywhere in the Linear workspace. Represents the project as it was at the time of removal. Only public teams are covered: events in private teams do not fire it.',},props: {},- sampleData: {- action: 'remove',- data: {- id: 'project_1',- name: 'Test project',- description: 'This is a test project',- state: 'planned',- color: '#000000',- icon: null,- startDate: '2023-09-05',- targetDate: '2023-12-05',- creator: {- id: 'user_1',- name: 'Test user',- email: '[email protected]',- },- teams: [- {- id: 'team_1',- name: 'Test team',- key: 'test-team',- },- ],- createdAt: '2023-09-05T12:00:00.000Z',- updatedAt: '2023-09-05T12:00:00.000Z',- },- type: 'Project',- actor: { id: 'user_1', name: 'Test user', type: 'user' },- createdAt: '2023-09-05T12:00:00.000Z',- url: 'https://linear.app/test-team/project/project_1',- organizationId: 'org_1',- webhookTimestamp: 1693915200000,- webhookId: 'webhook_1',- },+ sampleData: linearWebhookSamples.removedProjectSample,+ outputSchema: projectWebhookOutputSchema,type: TriggerStrategy.WEBHOOK,async onEnable(context) {- const client = makeClient(context.auth);- const webhook = await client.createWebhook({- label: 'ActivePieces Removed Project',- url: context.webhookUrl,- resourceTypes: ['Project'],- allPublicTeams: true,+ await linearWebhook.register({+ auth: context.auth,+ store: context.store,+ storeKey: '_removed_project_trigger',+ input: {+ label: 'ActivePieces Removed Project',+ url: context.webhookUrl,+ resourceTypes: ['Project'],+ allPublicTeams: true,+ },});- if (webhook.success && webhook.webhook) {- await context.store?.put<WebhookInformation>(- '_removed_project_trigger',- {- webhookId: (await webhook.webhook).id,- }- );- } else {- console.error('Failed to create the webhook');- }},async onDisable(context) {- const client = makeClient(context.auth);- const response = await context.store?.get<WebhookInformation>(- '_removed_project_trigger'- );- if (response && response.webhookId) {- await client.deleteWebhook(response.webhookId);- }+ await linearWebhook.unregister({+ auth: context.auth,+ store: context.store,+ storeKey: '_removed_project_trigger',+ });},async run(context) {const body = context.payload.body as { action: string; data: unknown };@@ -83,7 +45,3 @@ export const linearRemovedProject = createTrigger({return [];},});--interface WebhookInformation {- webhookId: string;-}diff --git a/packages/pieces/community/linear/src/lib/triggers/updated-issue.ts b/packages/pieces/community/linear/src/lib/triggers/updated-issue.tsindex 751b34b961e..b15b6973c66 100644--- a/packages/pieces/community/linear/src/lib/triggers/updated-issue.ts+++ b/packages/pieces/community/linear/src/lib/triggers/updated-issue.ts@@ -4,7 +4,9 @@ import {TriggerStrategy,} from '@activepieces/pieces-framework';import { linearAuth } from '../..';-import { makeClient } from '../common/client';+import { linearWebhook } from '../common/webhook';+import { updatedIssueWebhookOutputSchema } from '../output-schemas';+import { linearWebhookSamples } from '../common/webhook-samples';import { props } from '../common/props';export const linearUpdatedIssue = createTrigger({@@ -12,10 +14,10 @@ export const linearUpdatedIssue = createTrigger({name: 'updated_issue',classification: 'READ',displayName: 'Updated Issue',- description: 'Triggers when an existing Linear issue is updated',+ description: 'Triggers when an existing Linear issue is updated. Without a team selected, only public teams are covered.',aiMetadata: {description:- 'Fires when an existing Linear issue is modified, optionally scoped to a specific team. Represents the updated issue along with the fields that changed.',+ 'Fires when an existing Linear issue is modified, optionally scoped to a specific team. Represents the updated issue along with the fields that changed. Without a team selected only public teams are covered; pick the team to include a private one.',},props: {team_id: props.team_id(false),@@ -42,112 +44,29 @@ export const linearUpdatedIssue = createTrigger({},}),},- sampleData: {- // Sample data structure based on Linear's webhook payload for issues- action: 'update',- data: {- id: 'issue_1',- identifier: '1',- title: 'Test issue updated',- description: 'This is a test issue (updated)',- priority: 'priority_1',- priorityLabel: 'High',- state: 'state_2',- stateLabel: 'In Review',- team: {- id: 'team_2',- name: 'Test team',- key: 'test-team',- description: 'This is another test team',- archived: false,- createdAt: '2023-09-05T12:00:00.000Z',- updatedAt: '2023-09-06T12:00:00.000Z',- },- creator: {- id: 'user_1',- name: 'Test user',- email: '[email protected]',- avatarUrl: 'https://avatars.githubusercontent.com/u/1?v=4',- createdAt: '2023-09-05T12:00:00.000Z',- updatedAt: '2023-09-06T12:00:00.000Z',- },- assignee: {- id: 'user_1',- name: 'Test user',- email: '[email protected]',- avatarUrl: 'https://avatars.githubusercontent.com/u/1?v=4',- createdAt: '2023-09-05T12:00:00.000Z',- updatedAt: '2023-09-05T12:00:00.000Z',- },- labels: [- {- id: 'label_1',- name: 'Test label',- color: '#000000',- createdAt: '2023-09-05T12:00:00.000Z',- updatedAt: '2023-09-05T12:00:00.000Z',- },- {- id: 'label_1',- name: 'Test label 2',- color: '#000000',- createdAt: '2023-09-05T12:00:00.000Z',- updatedAt: '2023-09-06T12:00:00.000Z',- },- ],- createdAt: '2023-09-05T12:00:00.000Z',- updatedAt: '2023-09-06T12:00:00.000Z',- },- updatedFrom: {- updatedAt: '2023-09-06T12:00:00.000Z',- sortOrder: -14.61,- startedAt: null,- stateId: 'state_1',- },- type: 'Issue',- actor: { id: 'user_1', name: 'Test user', type: 'user' },- createdAt: '2023-09-06T12:00:00.000Z',- url: 'https://linear.app/test-team/issue/1',- organizationId: 'org_1',- webhookTimestamp: 1694001600000,- webhookId: 'webhook_1',- },+ sampleData: linearWebhookSamples.updatedIssueSample,+ outputSchema: updatedIssueWebhookOutputSchema,type: TriggerStrategy.WEBHOOK,async onEnable(context) {- const client = makeClient(context.auth);-- // Create webhook configuration- const webhookConfig: any = {- label: 'ActivePieces Updated Issue',- url: context.webhookUrl,- resourceTypes: ['Issue'],- };-- // Only add teamId if it's provided- if (context.propsValue['team_id']) {- webhookConfig.teamId = context.propsValue['team_id'];- } else {- webhookConfig.allPublicTeams = true;- }-- const webhook = await client.createWebhook(webhookConfig);-- if (webhook.success && webhook.webhook) {- await context.store?.put<WebhookInformation>('_updated_issue_trigger', {- webhookId: (await webhook.webhook).id,- });- } else {- console.error('Failed to create the webhook');- }+ const teamId = context.propsValue['team_id'];+ await linearWebhook.register({+ auth: context.auth,+ store: context.store,+ storeKey: '_updated_issue_trigger',+ input: {+ label: 'ActivePieces Updated Issue',+ url: context.webhookUrl,+ resourceTypes: ['Issue'],+ ...(teamId ? { teamId } : { allPublicTeams: true }),+ },+ });},async onDisable(context) {- const client = makeClient(context.auth);- const response = await context.store?.get<WebhookInformation>(- '_updated_issue_trigger'- );- if (response && response.webhookId) {- await client.deleteWebhook(response.webhookId);- }+ await linearWebhook.unregister({+ auth: context.auth,+ store: context.store,+ storeKey: '_updated_issue_trigger',+ });},async run(context) {const body = context.payload.body as {@@ -168,7 +87,3 @@ export const linearUpdatedIssue = createTrigger({return [body];},});--interface WebhookInformation {- webhookId: string;-}diff --git a/packages/pieces/community/linear/src/lib/triggers/updated-project.ts b/packages/pieces/community/linear/src/lib/triggers/updated-project.tsindex 57dd7c76cc9..38892f53bb1 100644--- a/packages/pieces/community/linear/src/lib/triggers/updated-project.ts+++ b/packages/pieces/community/linear/src/lib/triggers/updated-project.ts@@ -1,6 +1,8 @@import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';import { linearAuth } from '../..';-import { makeClient } from '../common/client';+import { linearWebhook } from '../common/webhook';+import { updatedProjectWebhookOutputSchema } from '../output-schemas';+import { linearWebhookSamples } from '../common/webhook-samples';import { props } from '../common/props';export const linearUpdatedProject = createTrigger({@@ -8,82 +10,36 @@ export const linearUpdatedProject = createTrigger({name: 'updated_project',classification: 'READ',displayName: 'Project Status Updated',- description: 'Triggers when the status of an Linear project is updated',+ description: 'Triggers when the status of an Linear project is updated. Only projects in public teams are covered.',aiMetadata: {- description: 'Fires when a Linear project status changes, optionally filtered to specific teams or a target status. Represents the project after the status change.',+ description: 'Fires when a Linear project status changes, optionally filtered to specific teams or a target status. Represents the project after the status change. Only public teams are covered: events in private teams do not fire it.',},props: {team_ids: props.team_ids(false),project_status: props.project_statuses(false),},- sampleData: {- action: 'update',- data: {- id: 'project_1',- name: 'Test project updated',- description: 'This is a test project (updated)',- state: 'started',- statusName: 'In Progress',- color: '#000000',- icon: null,- startDate: '2023-09-05',- targetDate: '2023-12-05',- creator: {- id: 'user_1',- name: 'Test user',- email: '[email protected]',- },- teams: [- {- id: 'team_1',- name: 'Test team',- key: 'test-team',- },- ],- createdAt: '2023-09-05T12:00:00.000Z',- updatedAt: '2023-09-06T12:00:00.000Z',- },- updatedFrom: {- updatedAt: '2023-09-06T12:00:00.000Z',- state: 'planned',- statusId: 'status_1',- },- type: 'Project',- actor: { id: 'user_1', name: 'Test user', type: 'user' },- createdAt: '2023-09-06T12:00:00.000Z',- url: 'https://linear.app/test-team/project/project_1',- organizationId: 'org_1',- webhookTimestamp: 1694001600000,- webhookId: 'webhook_1',- },+ sampleData: linearWebhookSamples.updatedProjectSample,+ outputSchema: updatedProjectWebhookOutputSchema,type: TriggerStrategy.WEBHOOK,async onEnable(context) {- const client = makeClient(context.auth);- const webhook = await client.createWebhook({- label: 'ActivePieces Updated Project',- url: context.webhookUrl,- resourceTypes: ['Project'],- allPublicTeams: true,+ await linearWebhook.register({+ auth: context.auth,+ store: context.store,+ storeKey: '_updated_project_trigger',+ input: {+ label: 'ActivePieces Updated Project',+ url: context.webhookUrl,+ resourceTypes: ['Project'],+ allPublicTeams: true,+ },});- if (webhook.success && webhook.webhook) {- await context.store?.put<WebhookInformation>(- '_updated_project_trigger',- {- webhookId: (await webhook.webhook).id,- }- );- } else {- console.error('Failed to create the webhook');- }},async onDisable(context) {- const client = makeClient(context.auth);- const response = await context.store?.get<WebhookInformation>(- '_updated_project_trigger'- );- if (response && response.webhookId) {- await client.deleteWebhook(response.webhookId);- }+ await linearWebhook.unregister({+ auth: context.auth,+ store: context.store,+ storeKey: '_updated_project_trigger',+ });},async run(context) {const body = context.payload.body as ProjectUpdatePayload;@@ -110,9 +66,6 @@ export const linearUpdatedProject = createTrigger({},});-interface WebhookInformation {- webhookId: string;-}interface ProjectUpdatePayload {action: string;