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(jumpcloud): add JumpCloud piece to manage users, devices, groups and apps (#16292)
Eliseu Kadesh9da81d83af02
diff --git a/bun.lock b/bun.lockindex ed461a685ec..4234401cd95 100644--- a/bun.lock+++ b/bun.lock@@ -4812,6 +4812,18 @@"tslib": "2.6.2",},},+ "packages/pieces/community/jumpcloud": {+ "name": "@activepieces/piece-jumpcloud",+ "version": "0.0.1",+ "dependencies": {+ "@activepieces/pieces-common": "workspace:*",+ "@activepieces/pieces-framework": "workspace:*",+ },+ "devDependencies": {+ "tslib": "2.6.2",+ "vitest": "3.2.6",+ },+ },"packages/pieces/community/jungle-grid": {"name": "@activepieces/piece-jungle-grid","version": "0.2.1",@@ -11996,6 +12008,8 @@"@activepieces/piece-json": ["@activepieces/piece-json@workspace:packages/pieces/community/json"],+ "@activepieces/piece-jumpcloud": ["@activepieces/piece-jumpcloud@workspace:packages/pieces/community/jumpcloud"],+"@activepieces/piece-jungle-grid": ["@activepieces/piece-jungle-grid@workspace:packages/pieces/community/jungle-grid"],"@activepieces/piece-just-invoice": ["@activepieces/piece-just-invoice@workspace:packages/pieces/community/just-invoice"],diff --git a/packages/pieces/community/jumpcloud/.eslintrc.json b/packages/pieces/community/jumpcloud/.eslintrc.jsonnew file mode 100644index 00000000000..9ee1a0770e8--- /dev/null+++ b/packages/pieces/community/jumpcloud/.eslintrc.json@@ -0,0 +1,26 @@+{+ "extends": ["../../../../.eslintrc.json"],+ "ignorePatterns": ["!**/*"],+ "overrides": [+ { "files": ["*.ts", "*.tsx", "*.js", "*.jsx"], "rules": {} },+ {+ "files": ["*.ts", "*.tsx"],+ "rules": {+ "no-restricted-imports": [+ "error",+ {+ "patterns": [+ "lodash",+ "lodash/*",+ "@activepieces/core-*",+ "@activepieces/server*",+ "@activepieces/engine",+ "@activepieces/shared"+ ]+ }+ ]+ }+ },+ { "files": ["*.js", "*.jsx"], "rules": {} }+ ]+}diff --git a/packages/pieces/community/jumpcloud/jumpcloud.png b/packages/pieces/community/jumpcloud/jumpcloud.pngnew file mode 100644index 00000000000..6b5d4321fdcBinary files /dev/null and b/packages/pieces/community/jumpcloud/jumpcloud.png differdiff --git a/packages/pieces/community/jumpcloud/package.json b/packages/pieces/community/jumpcloud/package.jsonnew file mode 100644index 00000000000..96dbde92531--- /dev/null+++ b/packages/pieces/community/jumpcloud/package.json@@ -0,0 +1,20 @@+{+ "name": "@activepieces/piece-jumpcloud",+ "version": "0.0.1",+ "main": "./dist/src/index.js",+ "types": "./dist/src/index.d.ts",+ "scripts": {+ "build": "tsc -p tsconfig.lib.json && cp package.json dist/",+ "bundle": "node ../../../../dist/packages/cli/src/index.js pieces bundle",+ "lint": "eslint 'src/**/*.ts'",+ "test": "vitest run"+ },+ "dependencies": {+ "@activepieces/pieces-common": "workspace:*",+ "@activepieces/pieces-framework": "workspace:*"+ },+ "devDependencies": {+ "tslib": "2.6.2",+ "vitest": "3.2.6"+ }+}diff --git a/packages/pieces/community/jumpcloud/src/i18n/translation.json b/packages/pieces/community/jumpcloud/src/i18n/translation.jsonnew file mode 100644index 00000000000..4e1f3c124f9--- /dev/null+++ b/packages/pieces/community/jumpcloud/src/i18n/translation.json@@ -0,0 +1,137 @@+{+ "Manage JumpCloud users, devices, groups and applications.": "Manage JumpCloud users, devices, groups and applications.",+ "API Key": "API Key",+ "Region": "Region",+ "Organization ID": "Organization ID",+ "The administrator API key from My API Key in the Admin Portal.": "The administrator API key from My API Key in the Admin Portal.",+ "The data center your JumpCloud organization lives in.": "The data center your JumpCloud organization lives in.",+ "Only needed if you manage several organizations (multi-tenant admin). Find it in the Admin Portal under Settings > Organization Profile. Leave empty otherwise.": "Only needed if you manage several organizations (multi-tenant admin). Find it in the Admin Portal under Settings > Organization Profile. Leave empty otherwise.",+ "United States (console.jumpcloud.com)": "United States (console.jumpcloud.com)",+ "European Union (console.eu.jumpcloud.com)": "European Union (console.eu.jumpcloud.com)",+ "India (console.in.jumpcloud.com)": "India (console.in.jumpcloud.com)",+ "Connect with a JumpCloud administrator API key.\n\n1. Sign in to the [JumpCloud Admin Portal](https://console.jumpcloud.com).\n2. Click your account initials in the top-right corner and choose **My API Key**.\n3. Generate a key if you have none, copy it and paste it below.\n4. Pick the region your organization lives in. Use **EU** if you sign in at console.eu.jumpcloud.com, **India** for console.in.jumpcloud.com.\n\nThe key acts with the permissions of the admin who owns it.": "Connect with a JumpCloud administrator API key.\n\n1. Sign in to the [JumpCloud Admin Portal](https://console.jumpcloud.com).\n2. Click your account initials in the top-right corner and choose **My API Key**.\n3. Generate a key if you have none, copy it and paste it below.\n4. Pick the region your organization lives in. Use **EU** if you sign in at console.eu.jumpcloud.com, **India** for console.in.jumpcloud.com.\n\nThe key acts with the permissions of the admin who owns it.",+ "Create Object": "Create Object",+ "Update Object": "Update Object",+ "Delete Object": "Delete Object",+ "Get Object by ID": "Get Object by ID",+ "List Objects (Batch)": "List Objects (Batch)",+ "List Objects by ID (Batch)": "List Objects by ID (Batch)",+ "Search Objects (Batch)": "Search Objects (Batch)",+ "Create Association": "Create Association",+ "Delete Association": "Delete Association",+ "Search User by Employee ID": "Search User by Employee ID",+ "Lock User": "Lock User",+ "Unlock User": "Unlock User",+ "Reset User MFA": "Reset User MFA",+ "Update User on System": "Update User on System",+ "Run Trigger Command": "Run Trigger Command",+ "Custom API Call": "Custom API Call",+ "Create a user, group or application. Devices join JumpCloud by installing the agent, so they cannot be created here.": "Create a user, group or application. Devices join JumpCloud by installing the agent, so they cannot be created here.",+ "Change fields on a user, device, group or application. Fields you leave empty keep their current value.": "Change fields on a user, device, group or application. Fields you leave empty keep their current value.",+ "Permanently delete a user, device, group or application.": "Permanently delete a user, device, group or application.",+ "Get a user, device, group or application, with its main fields and the full JumpCloud record.": "Get a user, device, group or application, with its main fields and the full JumpCloud record.",+ "List users, devices, groups or applications, one page at a time or all pages at once.": "List users, devices, groups or applications, one page at a time or all pages at once.",+ "Get many users, devices, groups or applications at once from a list of IDs.": "Get many users, devices, groups or applications at once from a list of IDs.",+ "Find users, devices, groups or applications by text or by a field value.": "Find users, devices, groups or applications by text or by a field value.",+ "Link two JumpCloud objects, such as adding a user to a group or giving a user group access to an application or device.": "Link two JumpCloud objects, such as adding a user to a group or giving a user group access to an application or device.",+ "Unlink two JumpCloud objects, such as removing a user from a group or revoking a user group's access to an application or device.": "Unlink two JumpCloud objects, such as removing a user from a group or revoking a user group's access to an application or device.",+ "Find the JumpCloud user with an exact employee ID, for example one sent by your HR system.": "Find the JumpCloud user with an exact employee ID, for example one sent by your HR system.",+ "Lock a user so they cannot sign in to JumpCloud, their devices or connected applications until unlocked.": "Lock a user so they cannot sign in to JumpCloud, their devices or connected applications until unlocked.",+ "Unlock a user who was locked by an admin or by too many failed sign-in attempts.": "Unlock a user who was locked by an admin or by too many failed sign-in attempts.",+ "Clear the multi-factor authentication enrollment of a user so they set it up again, for example after losing their phone.": "Clear the multi-factor authentication enrollment of a user so they set it up again, for example after losing their phone.",+ "Set a user's administrator (sudo) rights on a device, binding the user to the device first if you choose.": "Set a user's administrator (sudo) rights on a device, binding the user to the device first if you choose.",+ "Run the JumpCloud commands launched by a trigger name, and optionally wait for their results.": "Run the JumpCloud commands launched by a trigger name, and optionally wait for their results.",+ "Call any JumpCloud API endpoint with this connection. Use a path such as /systemusers for the v1 API or /v2/usergroups for the v2 API.": "Call any JumpCloud API endpoint with this connection. Use a path such as /systemusers for the v1 API or /v2/usergroups for the v2 API.",+ "Object Type": "Object Type",+ "Fields": "Fields",+ "Additional Fields": "Additional Fields",+ "Object": "Object",+ "Fields to Change": "Fields to Change",+ "Max Results": "Max Results",+ "Skip": "Skip",+ "Fetch All Pages": "Fetch All Pages",+ "Max Objects": "Max Objects",+ "Object IDs": "Object IDs",+ "Search Text": "Search Text",+ "Filter Field": "Filter Field",+ "Filter Operator": "Filter Operator",+ "Filter Value": "Filter Value",+ "Associate With": "Associate With",+ "Associated Object": "Associated Object",+ "Remove Association With": "Remove Association With",+ "Employee ID": "Employee ID",+ "User": "User",+ "Allow Sign-in Without MFA for a While": "Allow Sign-in Without MFA for a While",+ "Grace Period (days)": "Grace Period (days)",+ "System (device)": "System (device)",+ "Administrator (sudo) Rights": "Administrator (sudo) Rights",+ "Sudo Without Password": "Sudo Without Password",+ "Bind If Needed": "Bind If Needed",+ "Markdown": "Markdown",+ "Trigger Name": "Trigger Name",+ "Variables": "Variables",+ "Wait For Results": "Wait For Results",+ "Max Wait (seconds)": "Max Wait (seconds)",+ "Method": "Method",+ "Headers": "Headers",+ "Query Parameters": "Query Parameters",+ "Body Type": "Body Type",+ "Body": "Body",+ "Response is Binary": "Response is Binary",+ "Return Error as Output": "Return Error as Output",+ "Timeout": "Timeout",+ "Follow redirects": "Follow redirects",+ "The kind of JumpCloud object to work with.": "The kind of JumpCloud object to work with.",+ "Any other JumpCloud fields for this object, as a JSON object, for example {\"phoneNumbers\": [{\"type\": \"work\", \"number\": \"+1 555 0100\"}]}. Fields above take precedence. See the JumpCloud API reference for the field names.": "Any other JumpCloud fields for this object, as a JSON object, for example {\"phoneNumbers\": [{\"type\": \"work\", \"number\": \"+1 555 0100\"}]}. Fields above take precedence. See the JumpCloud API reference for the field names.",+ "Pick the object, or type to search by name. You can also map an ID from an earlier step.": "Pick the object, or type to search by name. You can also map an ID from an earlier step.",+ "Only filled-in fields are changed. Empty fields keep their current value.": "Only filled-in fields are changed. Empty fields keep their current value.",+ "The object to delete. This cannot be undone.": "The object to delete. This cannot be undone.",+ "How many objects to return per run, from 1 to 100. Ignored when Fetch All Pages is on.": "How many objects to return per run, from 1 to 100. Ignored when Fetch All Pages is on.",+ "How many objects to skip before the first result. Use the Next Skip value from a previous run to get the next page.": "How many objects to skip before the first result. Use the Next Skip value from a previous run to get the next page.",+ "Keep requesting pages until every object is returned, up to Max Objects.": "Keep requesting pages until every object is returned, up to Max Objects.",+ "Safety cap when fetching all pages, up to 10000.": "Safety cap when fetching all pages, up to 10000.",+ "The IDs to fetch. Map a list from an earlier step or add them one by one. Duplicates are ignored.": "The IDs to fetch. Map a list from an earlier step or add them one by one. Duplicates are ignored.",+ "Matches names, usernames, emails or hostnames. Leave empty to filter by a field instead.": "Matches names, usernames, emails or hostnames. Leave empty to filter by a field instead.",+ "A JumpCloud field name, for example department, jobTitle, email or name. Leave empty to search by text.": "A JumpCloud field name, for example department, jobTitle, email or name. Leave empty to search by text.",+ "The value to compare with. Matching is case-sensitive.": "The value to compare with. Matching is case-sensitive.",+ "The kind of the first object.": "The kind of the first object.",+ "The kind of object to link it to.": "The kind of object to link it to.",+ "The kind of object to unlink it from.": "The kind of object to unlink it from.",+ "The exact employee ID stored on the user in JumpCloud. Matching is case-sensitive.": "The exact employee ID stored on the user in JumpCloud. Matching is case-sensitive.",+ "Lets the user sign in without MFA until they enroll again, for the number of days below.": "Lets the user sign in without MFA until they enroll again, for the number of days below.",+ "How many days the user can sign in without MFA, from 1 to 365.": "How many days the user can sign in without MFA, from 1 to 365.",+ "Gives the user administrator rights on this device.": "Gives the user administrator rights on this device.",+ "Lets the user run administrator commands without typing their password. Only applies with administrator rights.": "Lets the user run administrator commands without typing their password. Only applies with administrator rights.",+ "Binds the user to the device when they are not bound yet. Leave off to only change an existing binding.": "Binds the user to the device when they are not bound yet. Leave off to only change an existing binding.",+ "In the JumpCloud Admin Portal, open **Device Management > Commands**, edit the command, set **Launch Event** to **Run on Trigger (webhook)** and enter a **Trigger Name**. Use that name below.": "In the JumpCloud Admin Portal, open **Device Management > Commands**, edit the command, set **Launch Event** to **Run on Trigger (webhook)** and enter a **Trigger Name**. Use that name below.",+ "The Trigger Name set on the command in JumpCloud. Every command with this name runs.": "The Trigger Name set on the command in JumpCloud. Every command with this name runs.",+ "Optional JSON object passed to the command. JumpCloud exposes each key to the script as an environment variable.": "Optional JSON object passed to the command. JumpCloud exposes each key to the script as an environment variable.",+ "Wait until each command reports a result, up to the time below.": "Wait until each command reports a result, up to the time below.",+ "How long to wait for results, from 5 to 300 seconds. Devices that are offline report later.": "How long to wait for results, from 5 to 300 seconds. Devices that are offline report later.",+ "Authorization headers are injected automatically from your connection.": "Authorization headers are injected automatically from your connection.",+ "Appended to the URL as ?key=value.": "Appended to the URL as ?key=value.",+ "Enable for files like PDFs, images, etc.": "Enable for files like PDFs, images, etc.",+ "On a failed request, output the error instead of failing the step.": "On a failed request, output the error instead of failing the step.",+ "Seconds to wait for a response. Empty: up to the flow limit (10 min).": "Seconds to wait for a response. Empty: up to the flow limit (10 min).",+ "Follow 3xx redirects instead of returning them as the response.": "Follow 3xx redirects instead of returning them as the response.",+ "User Group": "User Group",+ "Device Group": "Device Group",+ "Application (SSO)": "Application (SSO)",+ "Equals": "Equals",+ "Does not equal": "Does not equal",+ "Starts with (contains for groups)": "Starts with (contains for groups)",+ "Is one of (separate values with |)": "Is one of (separate values with |)",+ "Greater than": "Greater than",+ "Greater than or equal": "Greater than or equal",+ "Less than": "Less than",+ "Less than or equal": "Less than or equal",+ "GET": "GET",+ "POST": "POST",+ "PATCH": "PATCH",+ "PUT": "PUT",+ "DELETE": "DELETE",+ "HEAD": "HEAD",+ "New Object": "New Object",+ "Triggers when a new user, device, group or application appears in JumpCloud.": "Triggers when a new user, device, group or application appears in JumpCloud.",+ "The kind of new object to watch for.": "The kind of new object to watch for."+}\ No newline at end of filediff --git a/packages/pieces/community/jumpcloud/src/index.ts b/packages/pieces/community/jumpcloud/src/index.tsnew file mode 100644index 00000000000..544897840df--- /dev/null+++ b/packages/pieces/community/jumpcloud/src/index.ts@@ -0,0 +1,73 @@+import { createCustomApiCallAction } from '@activepieces/pieces-common';+import { createPiece, PieceCategory } from '@activepieces/pieces-framework';+import { createAssociationAction } from './lib/actions/create-association';+import { createObjectAction } from './lib/actions/create-object';+import { deleteAssociationAction } from './lib/actions/delete-association';+import { deleteObjectAction } from './lib/actions/delete-object';+import { findUserByEmployeeIdAction } from './lib/actions/find-user-by-employee-id';+import { getObjectAction } from './lib/actions/get-object';+import { listObjectsAction } from './lib/actions/list-objects';+import { listObjectsByIdAction } from './lib/actions/list-objects-by-id';+import { lockUserAction } from './lib/actions/lock-user';+import { resetUserMfaAction } from './lib/actions/reset-user-mfa';+import { runTriggerCommandAction } from './lib/actions/run-trigger-command';+import { searchObjectsAction } from './lib/actions/search-objects';+import { unlockUserAction } from './lib/actions/unlock-user';+import { updateObjectAction } from './lib/actions/update-object';+import { updateUserOnSystemAction } from './lib/actions/update-user-on-system';+import { jumpcloudAuth } from './lib/auth';+import { jumpcloudApi } from './lib/common/client';+import { newObjectTrigger } from './lib/triggers/new-object';++export const jumpcloud = createPiece({+ displayName: 'JumpCloud',+ description: 'Manage JumpCloud users, devices, groups and applications.',+ minimumSupportedRelease: '0.88.2',+ logoUrl: 'https://cdn.activepieces.com/pieces/jumpcloud.png',+ categories: [PieceCategory.DEVELOPER_TOOLS],+ auth: jumpcloudAuth,+ authors: ['eliseukadesh67'],+ actions: [+ createObjectAction,+ updateObjectAction,+ deleteObjectAction,+ getObjectAction,+ listObjectsAction,+ listObjectsByIdAction,+ searchObjectsAction,+ createAssociationAction,+ deleteAssociationAction,+ findUserByEmployeeIdAction,+ lockUserAction,+ unlockUserAction,+ resetUserMfaAction,+ updateUserOnSystemAction,+ runTriggerCommandAction,+ createCustomApiCallAction({+ auth: jumpcloudAuth,+ description: 'Call any JumpCloud API endpoint with this connection. Use a path such as /systemusers for the v1 API or /v2/usergroups for the v2 API.',+ baseUrl: (auth) => (auth === undefined ? '' : jumpcloudApi.resolveBaseUrl(auth.props)),+ authMapping: async (auth, propsValue) => {+ assertJumpcloudUrl({ baseUrl: jumpcloudApi.resolveBaseUrl(auth.props), url: readUrl(propsValue) });+ return jumpcloudApi.authHeaders(auth.props);+ },+ }),+ ],+ triggers: [newObjectTrigger],+});++// The admin key must only reach the connection's JumpCloud host, never a full URL pointing elsewhere.+function assertJumpcloudUrl({ baseUrl, url }: { baseUrl: string; url: string }): void {+ const isAbsolute = url.startsWith('http://') || url.startsWith('https://');+ if (isAbsolute && new URL(url).origin !== new URL(baseUrl).origin) {+ throw new Error(`Custom API Call only sends this connection to ${new URL(baseUrl).origin}. Use a path such as /systemusers.`);+ }+}++function readUrl(propsValue: Record<string, unknown>): string {+ const url = propsValue['url'];+ if (url !== null && typeof url === 'object' && 'url' in url && typeof url.url === 'string') {+ return url.url;+ }+ return '';+}diff --git a/packages/pieces/community/jumpcloud/src/lib/actions/create-association.ts b/packages/pieces/community/jumpcloud/src/lib/actions/create-association.tsnew file mode 100644index 00000000000..ea735099f8b--- /dev/null+++ b/packages/pieces/community/jumpcloud/src/lib/actions/create-association.ts@@ -0,0 +1,31 @@+import { createAction } from '@activepieces/pieces-framework';+import { jumpcloudAuth } from '../auth';+import { jumpcloudAssociations } from '../common/associations';+import { jumpcloudProps } from '../common/props';+import { associationOutputSchema } from '../output-schemas';++export const createAssociationAction = createAction({+ auth: jumpcloudAuth,+ name: 'create_association',+ classification: 'WRITE',+ displayName: 'Create Association',+ description: 'Link two JumpCloud objects, such as adding a user to a group or giving a user group access to an application or device.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Associates two JumpCloud objects: user group or device group membership, or access between users/user groups and devices, device groups and SSO applications. Errors when the pair cannot be associated and lists the valid targets. Re-adding an existing association may fail with a conflict, so check before retrying.',+ idempotent: false,+ },+ props: {+ objectType: jumpcloudProps.objectType({ description: 'The kind of the first object.' }),+ objectId: jumpcloudProps.objectId({ displayName: 'Object' }),+ targetType: jumpcloudProps.objectType({ displayName: 'Associate With', description: 'The kind of object to link it to.' }),+ targetId: jumpcloudProps.objectId({ displayName: 'Associated Object', typeProp: 'targetType' }),+ },+ outputSchema: associationOutputSchema,+ async run(context) {+ const ends = jumpcloudAssociations.parseEnds(context.propsValue);+ await jumpcloudAssociations.change({ auth: context.auth.props, op: 'add', ends });+ return jumpcloudAssociations.toOutput({ ends, associated: true });+ },+});diff --git a/packages/pieces/community/jumpcloud/src/lib/actions/create-object.ts b/packages/pieces/community/jumpcloud/src/lib/actions/create-object.tsnew file mode 100644index 00000000000..9e09a090828--- /dev/null+++ b/packages/pieces/community/jumpcloud/src/lib/actions/create-object.ts@@ -0,0 +1,58 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { jumpcloudAuth } from '../auth';+import { jumpcloudApi } from '../common/client';+import { jumpcloudFields } from '../common/fields';+import { jumpcloudObjects } from '../common/objects';+import { jumpcloudOutput } from '../common/output';+import { jumpcloudProps } from '../common/props';+import { ApiRecord, ObjectTypeKey } from '../common/types';++export const createObjectAction = createAction({+ auth: jumpcloudAuth,+ name: 'create_object',+ classification: 'WRITE',+ displayName: 'Create Object',+ description: 'Create a user, group or application. Devices join JumpCloud by installing the agent, so they cannot be created here.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Creates a JumpCloud user, user group, device group or SSO/bookmark application and returns it with its new ID. Users need a unique username and email; groups a unique name; applications a display label and URL. Systems (devices) cannot be created through the API. Each call creates a new object, so retries fail on the duplicate name or create duplicates.',+ idempotent: false,+ },+ props: {+ objectType: jumpcloudProps.objectType({ creatableOnly: true }),+ fields: jumpcloudFields.fieldsProp({ mode: 'create' }),+ additionalFields: jumpcloudFields.additionalFieldsProp(),+ },+ async run(context) {+ const type = jumpcloudObjects.parseType(context.propsValue.objectType);+ const config = jumpcloudObjects.config(type);+ if (!config.canCreate) {+ throw new Error(`${config.label} objects cannot be created through the JumpCloud API.`);+ }+ const changes = jumpcloudFields.buildChanges({+ type,+ fields: context.propsValue.fields,+ additionalFields: context.propsValue.additionalFields,+ });+ const created = await jumpcloudApi.send<unknown>({+ auth: context.auth.props,+ method: HttpMethod.POST,+ path: config.path,+ version: config.version,+ body: withCreateDefaults({ type, body: changes }),+ });+ if (!jumpcloudApi.isRecord(created)) {+ throw new Error(`JumpCloud did not return the new ${config.label}.`);+ }+ return jumpcloudOutput.flatten({ type, record: created });+ },+});++function withCreateDefaults({ type, body }: { type: ObjectTypeKey; body: ApiRecord }): ApiRecord {+ if (type !== 'application') {+ return body;+ }+ return { config: {}, ...body, name: typeof body['name'] === 'string' ? body['name'] : 'bookmark' };+}diff --git a/packages/pieces/community/jumpcloud/src/lib/actions/delete-association.ts b/packages/pieces/community/jumpcloud/src/lib/actions/delete-association.tsnew file mode 100644index 00000000000..e9c439a555a--- /dev/null+++ b/packages/pieces/community/jumpcloud/src/lib/actions/delete-association.ts@@ -0,0 +1,31 @@+import { createAction } from '@activepieces/pieces-framework';+import { jumpcloudAuth } from '../auth';+import { jumpcloudAssociations } from '../common/associations';+import { jumpcloudProps } from '../common/props';+import { associationOutputSchema } from '../output-schemas';++export const deleteAssociationAction = createAction({+ auth: jumpcloudAuth,+ name: 'delete_association',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete Association',+ description: "Unlink two JumpCloud objects, such as removing a user from a group or revoking a user group's access to an application or device.",+ audience: 'both',+ aiMetadata: {+ description:+ 'Removes the association between two JumpCloud objects: group membership, or access between users/user groups and devices, device groups and SSO applications. Access is revoked at the next agent check-in or sign-in. Not safe to retry blindly: a second call may fail because the association is already gone.',+ idempotent: false,+ },+ props: {+ objectType: jumpcloudProps.objectType({ description: 'The kind of the first object.' }),+ objectId: jumpcloudProps.objectId({ displayName: 'Object' }),+ targetType: jumpcloudProps.objectType({ displayName: 'Remove Association With', description: 'The kind of object to unlink it from.' }),+ targetId: jumpcloudProps.objectId({ displayName: 'Associated Object', typeProp: 'targetType' }),+ },+ outputSchema: associationOutputSchema,+ async run(context) {+ const ends = jumpcloudAssociations.parseEnds(context.propsValue);+ await jumpcloudAssociations.change({ auth: context.auth.props, op: 'remove', ends });+ return jumpcloudAssociations.toOutput({ ends, associated: false });+ },+});diff --git a/packages/pieces/community/jumpcloud/src/lib/actions/delete-object.ts b/packages/pieces/community/jumpcloud/src/lib/actions/delete-object.tsnew file mode 100644index 00000000000..6a8be79da03--- /dev/null+++ b/packages/pieces/community/jumpcloud/src/lib/actions/delete-object.ts@@ -0,0 +1,35 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { jumpcloudAuth } from '../auth';+import { jumpcloudApi } from '../common/client';+import { jumpcloudObjects } from '../common/objects';+import { jumpcloudProps } from '../common/props';++export const deleteObjectAction = createAction({+ auth: jumpcloudAuth,+ name: 'delete_object',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete Object',+ description: 'Permanently delete a user, device, group or application.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Permanently deletes one JumpCloud user, system (device), user group, device group or SSO application by ID. Deleting a system removes it from management; deleting a user removes their access everywhere JumpCloud provisions it. Prefer Lock User to suspend access reversibly. Not safe to retry: a second call fails with not found.',+ idempotent: false,+ },+ props: {+ objectType: jumpcloudProps.objectType(),+ objectId: jumpcloudProps.objectId({ description: 'The object to delete. This cannot be undone.' }),+ },+ async run(context) {+ const type = jumpcloudObjects.parseType(context.propsValue.objectType);+ const id = context.propsValue.objectId.trim();+ await jumpcloudApi.send<unknown>({+ auth: context.auth.props,+ method: HttpMethod.DELETE,+ path: jumpcloudObjects.itemPath({ type, id }),+ version: jumpcloudObjects.config(type).version,+ });+ return { id, object_type: type, deleted: true };+ },+});diff --git a/packages/pieces/community/jumpcloud/src/lib/actions/find-user-by-employee-id.ts b/packages/pieces/community/jumpcloud/src/lib/actions/find-user-by-employee-id.tsnew file mode 100644index 00000000000..8b998f9b938--- /dev/null+++ b/packages/pieces/community/jumpcloud/src/lib/actions/find-user-by-employee-id.ts@@ -0,0 +1,41 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { jumpcloudAuth } from '../auth';+import { jumpcloudObjects } from '../common/objects';+import { jumpcloudOutput } from '../common/output';+import { findUserOutputSchema } from '../output-schemas';++export const findUserByEmployeeIdAction = createAction({+ auth: jumpcloudAuth,+ name: 'find_user_by_employee_id',+ classification: 'SEARCH',+ displayName: 'Search User by Employee ID',+ description: 'Find the JumpCloud user with an exact employee ID, for example one sent by your HR system.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Looks up the JumpCloud user whose employeeIdentifier exactly matches the given value (case-sensitive) and returns found plus the user fields, or found=false with empty fields. Use Search Objects for partial or other-field matches. Safe to retry.',+ idempotent: true,+ },+ props: {+ employeeId: Property.ShortText({+ displayName: 'Employee ID',+ description: 'The exact employee ID stored on the user in JumpCloud. Matching is case-sensitive.',+ required: true,+ }),+ },+ outputSchema: findUserOutputSchema,+ async run(context) {+ const employeeId = context.propsValue.employeeId.trim();+ if (employeeId.length === 0) {+ throw new Error('Enter the Employee ID to search for.');+ }+ const page = await jumpcloudObjects.listPage({+ auth: context.auth.props,+ type: 'user',+ page: { limit: 2, skip: 0 },+ filter: `employeeIdentifier:$eq:${employeeId}`,+ });+ const [user] = page.items;+ return { found: user !== undefined, ...jumpcloudOutput.flatten({ type: 'user', record: user ?? {} }) };+ },+});diff --git a/packages/pieces/community/jumpcloud/src/lib/actions/get-object.ts b/packages/pieces/community/jumpcloud/src/lib/actions/get-object.tsnew file mode 100644index 00000000000..0fec5919fe4--- /dev/null+++ b/packages/pieces/community/jumpcloud/src/lib/actions/get-object.ts@@ -0,0 +1,28 @@+import { createAction } from '@activepieces/pieces-framework';+import { jumpcloudAuth } from '../auth';+import { jumpcloudObjects } from '../common/objects';+import { jumpcloudOutput } from '../common/output';+import { jumpcloudProps } from '../common/props';++export const getObjectAction = createAction({+ auth: jumpcloudAuth,+ name: 'get_object',+ classification: 'READ',+ displayName: 'Get Object by ID',+ description: 'Get a user, device, group or application, with its main fields and the full JumpCloud record.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Fetches one JumpCloud user, system (device), user group, device group or SSO application by its ID and returns its main fields plus the complete JumpCloud record under raw. Use List Objects by ID for several IDs at once, or Search Objects when you only know a name or attribute. Safe to retry.',+ idempotent: true,+ },+ props: {+ objectType: jumpcloudProps.objectType(),+ objectId: jumpcloudProps.objectId(),+ },+ async run(context) {+ const type = jumpcloudObjects.parseType(context.propsValue.objectType);+ const record = await jumpcloudObjects.getRecord({ auth: context.auth.props, type, id: context.propsValue.objectId });+ return { ...jumpcloudOutput.flatten({ type, record }), raw: record };+ },+});diff --git a/packages/pieces/community/jumpcloud/src/lib/actions/list-objects-by-id.ts b/packages/pieces/community/jumpcloud/src/lib/actions/list-objects-by-id.tsnew file mode 100644index 00000000000..b36bd8d1ff0--- /dev/null+++ b/packages/pieces/community/jumpcloud/src/lib/actions/list-objects-by-id.ts@@ -0,0 +1,74 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { jumpcloudAuth } from '../auth';+import { jumpcloudApi, MAX_PAGE_SIZE } from '../common/client';+import { jumpcloudObjects } from '../common/objects';+import { jumpcloudOutput } from '../common/output';+import { jumpcloudProps } from '../common/props';+import { ApiRecord, ConnectionProps, ObjectTypeKey } from '../common/types';++export const listObjectsByIdAction = createAction({+ auth: jumpcloudAuth,+ name: 'list_objects_by_id',+ classification: 'READ',+ displayName: 'List Objects by ID (Batch)',+ description: 'Get many users, devices, groups or applications at once from a list of IDs.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Fetches JumpCloud objects of one type for a list of IDs and returns them in the order given, plus missing_ids for IDs that were not found. Pages over the ID list with Max Results / Skip. Use Get Object by ID for a single object. Safe to retry.',+ idempotent: true,+ },+ props: {+ objectType: jumpcloudProps.objectType(),+ ids: Property.Array({+ displayName: 'Object IDs',+ description: 'The IDs to fetch. Map a list from an earlier step or add them one by one. Duplicates are ignored.',+ required: true,+ }),+ ...jumpcloudProps.pagination(),+ },+ async run(context) {+ const auth = context.auth.props;+ const { limit, skip, fetchAll, maxItems } = context.propsValue;+ const type = jumpcloudObjects.parseType(context.propsValue.objectType);+ const ids = normalizeIds(context.propsValue.ids);+ if (ids.length === 0) {+ throw new Error('Add at least one Object ID.');+ }+ const { start, count } = jumpcloudApi.pageWindow({ limit, skip, fetchAll, maxItems });+ const requested = ids.slice(start, start + count);+ const records = await fetchInChunks({ auth, type, ids: requested });+ const byId = new Map(+ records.flatMap((record): [string, ApiRecord][] => {+ const id = jumpcloudObjects.readId({ type, record });+ return id === null ? [] : [[id, record]];+ }),+ );+ const end = start + requested.length;+ return {+ items: requested.flatMap((id) => {+ const record = byId.get(id);+ return record === undefined ? [] : [jumpcloudOutput.flatten({ type, record })];+ }),+ missing_ids: requested.filter((id) => !byId.has(id)),+ total_count: ids.length,+ next_skip: end < ids.length ? end : null,+ };+ },+});++function normalizeIds(value: unknown): string[] {+ const list = Array.isArray(value) ? value : [value];+ const ids = list.flatMap((item) => (typeof item === 'string' || typeof item === 'number' ? [String(item).trim()] : []));+ return [...new Set(ids.filter((id) => id.length > 0))];+}++async function fetchInChunks({ auth, type, ids }: { auth: ConnectionProps; type: ObjectTypeKey; ids: string[] }): Promise<ApiRecord[]> {+ const chunks = Array.from({ length: Math.ceil(ids.length / MAX_PAGE_SIZE) }, (_, index) =>+ ids.slice(index * MAX_PAGE_SIZE, (index + 1) * MAX_PAGE_SIZE),+ );+ return chunks.reduce<Promise<ApiRecord[]>>(async (previous, chunk) => {+ const collected = await previous;+ return [...collected, ...(await jumpcloudObjects.listByIds({ auth, type, ids: chunk }))];+ }, Promise.resolve([]));+}diff --git a/packages/pieces/community/jumpcloud/src/lib/actions/list-objects.ts b/packages/pieces/community/jumpcloud/src/lib/actions/list-objects.tsnew file mode 100644index 00000000000..51c43eda5a3--- /dev/null+++ b/packages/pieces/community/jumpcloud/src/lib/actions/list-objects.ts@@ -0,0 +1,37 @@+import { createAction } from '@activepieces/pieces-framework';+import { jumpcloudAuth } from '../auth';+import { jumpcloudApi } from '../common/client';+import { jumpcloudObjects } from '../common/objects';+import { jumpcloudOutput } from '../common/output';+import { jumpcloudProps } from '../common/props';++export const listObjectsAction = createAction({+ auth: jumpcloudAuth,+ name: 'list_objects',+ classification: 'SEARCH',+ displayName: 'List Objects (Batch)',+ description: 'List users, devices, groups or applications, one page at a time or all pages at once.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Lists JumpCloud objects of one type (users, systems/devices, user groups, device groups or SSO applications) in a stable order, with paging. Returns items plus total_count and next_skip; pass next_skip back as Skip to continue. Use Search Objects to filter by name or field. Safe to retry.',+ idempotent: true,+ },+ props: {+ objectType: jumpcloudProps.objectType(),+ ...jumpcloudProps.pagination(),+ },+ async run(context) {+ const auth = context.auth.props;+ const { limit, skip, fetchAll, maxItems } = context.propsValue;+ const type = jumpcloudObjects.parseType(context.propsValue.objectType);+ const result = await jumpcloudApi.collectPages({+ fetchPage: (page) => jumpcloudObjects.listPage({ auth, type, page }),+ limit,+ skip,+ fetchAll,+ maxItems,+ });+ return { ...result, items: result.items.map((record) => jumpcloudOutput.flatten({ type, record })) };+ },+});diff --git a/packages/pieces/community/jumpcloud/src/lib/actions/lock-user.ts b/packages/pieces/community/jumpcloud/src/lib/actions/lock-user.tsnew file mode 100644index 00000000000..fd6539f1268--- /dev/null+++ b/packages/pieces/community/jumpcloud/src/lib/actions/lock-user.ts@@ -0,0 +1,38 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { jumpcloudAuth } from '../auth';+import { jumpcloudApi } from '../common/client';+import { jumpcloudObjects } from '../common/objects';+import { jumpcloudOutput } from '../common/output';+import { jumpcloudProps } from '../common/props';+import { userOutputSchema } from '../output-schemas';++export const lockUserAction = createAction({+ auth: jumpcloudAuth,+ name: 'lock_user',+ classification: 'WRITE',+ displayName: 'Lock User',+ description: 'Lock a user so they cannot sign in to JumpCloud, their devices or connected applications until unlocked.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Locks a JumpCloud user account (account_locked=true), blocking sign-in everywhere JumpCloud authenticates them, and returns the user. Reversible with Unlock User; prefer it over Delete Object to cut access temporarily. Safe to retry.',+ idempotent: true,+ },+ props: {+ userId: jumpcloudProps.objectId({ displayName: 'User', fixedType: 'user' }),+ },+ outputSchema: userOutputSchema,+ async run(context) {+ const user = await jumpcloudApi.send<unknown>({+ auth: context.auth.props,+ method: HttpMethod.PUT,+ path: jumpcloudObjects.itemPath({ type: 'user', id: context.propsValue.userId }),+ body: { account_locked: true },+ });+ if (!jumpcloudApi.isRecord(user)) {+ throw new Error('JumpCloud did not return the locked user.');+ }+ return jumpcloudOutput.flatten({ type: 'user', record: user });+ },+});diff --git a/packages/pieces/community/jumpcloud/src/lib/actions/reset-user-mfa.ts b/packages/pieces/community/jumpcloud/src/lib/actions/reset-user-mfa.tsnew file mode 100644index 00000000000..b62ec7bcbbb--- /dev/null+++ b/packages/pieces/community/jumpcloud/src/lib/actions/reset-user-mfa.ts@@ -0,0 +1,57 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { jumpcloudAuth } from '../auth';+import { jumpcloudApi } from '../common/client';+import { jumpcloudObjects } from '../common/objects';+import { jumpcloudProps } from '../common/props';+import { resetMfaOutputSchema } from '../output-schemas';++export const resetUserMfaAction = createAction({+ auth: jumpcloudAuth,+ name: 'reset_user_mfa',+ classification: 'WRITE',+ displayName: 'Reset User MFA',+ description: 'Clear the multi-factor authentication enrollment of a user so they set it up again, for example after losing their phone.',+ audience: 'both',+ aiMetadata: {+ description:+ "Resets a JumpCloud user's MFA (TOTP) enrollment so they must enroll again, optionally with a grace period of days during which they can sign in without MFA. Each call resets again, which forces the user to re-enroll if they already did.",+ idempotent: false,+ },+ props: {+ userId: jumpcloudProps.objectId({ displayName: 'User', fixedType: 'user' }),+ allowGracePeriod: Property.Checkbox({+ displayName: 'Allow Sign-in Without MFA for a While',+ description: 'Lets the user sign in without MFA until they enroll again, for the number of days below.',+ required: false,+ defaultValue: false,+ reveals: ['gracePeriodDays'],+ }),+ gracePeriodDays: Property.Number({+ displayName: 'Grace Period (days)',+ description: 'How many days the user can sign in without MFA, from 1 to 365.',+ required: false,+ defaultValue: 7,+ }),+ },+ outputSchema: resetMfaOutputSchema,+ async run(context) {+ const { allowGracePeriod, gracePeriodDays } = context.propsValue;+ const userId = context.propsValue.userId.trim();+ const days = allowGracePeriod === true ? validateDays(gracePeriodDays) : null;+ await jumpcloudApi.send<unknown>({+ auth: context.auth.props,+ method: HttpMethod.POST,+ path: `${jumpcloudObjects.itemPath({ type: 'user', id: userId })}/resetmfa`,+ body: days === null ? { exclusion: false } : { exclusion: true, exclusionDays: days },+ });+ return { user_id: userId, mfa_reset: true, grace_period_days: days };+ },+});++function validateDays(value: number | undefined): number {+ if (value === undefined || !Number.isInteger(value) || value < 1 || value > 365) {+ throw new Error('Grace Period must be a whole number of days from 1 to 365.');+ }+ return value;+}diff --git a/packages/pieces/community/jumpcloud/src/lib/actions/run-trigger-command.ts b/packages/pieces/community/jumpcloud/src/lib/actions/run-trigger-command.tsnew file mode 100644index 00000000000..48ba806c296--- /dev/null+++ b/packages/pieces/community/jumpcloud/src/lib/actions/run-trigger-command.ts@@ -0,0 +1,210 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { jumpcloudAuth } from '../auth';+import { COMMAND_MAX_WAIT_SECONDS, COMMAND_POLL_SECONDS, jumpcloudApi } from '../common/client';+import { jumpcloudOutput } from '../common/output';+import { ApiRecord, ConnectionProps, FlatObject } from '../common/types';+import { runCommandOutputSchema } from '../output-schemas';++export const runTriggerCommandAction = createAction({+ auth: jumpcloudAuth,+ name: 'run_trigger_command',+ classification: 'WRITE',+ displayName: 'Run Trigger Command',+ description: 'Run the JumpCloud commands launched by a trigger name, and optionally wait for their results.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Launches every JumpCloud command whose launch event is "Run on Trigger" with the given trigger name, passing optional JSON variables, and returns the launched command IDs; with Wait For Results it also returns each device result (exit code, output) reported within the wait time. Each call runs the commands again on their devices.',+ idempotent: false,+ },+ props: {+ instructions: Property.MarkDown({+ value: `In the JumpCloud Admin Portal, open **Device Management > Commands**, edit the command, set **Launch Event** to **Run on Trigger (webhook)** and enter a **Trigger Name**. Use that name below.`,+ }),+ triggerName: Property.ShortText({+ displayName: 'Trigger Name',+ description: 'The Trigger Name set on the command in JumpCloud. Every command with this name runs.',+ required: true,+ }),+ variables: Property.Json({+ displayName: 'Variables',+ description: 'Optional JSON object passed to the command. JumpCloud exposes each key to the script as an environment variable.',+ required: false,+ }),+ waitForResults: Property.Checkbox({+ displayName: 'Wait For Results',+ description: 'Wait until each command reports a result, up to the time below.',+ required: false,+ defaultValue: false,+ reveals: ['waitSeconds'],+ }),+ waitSeconds: Property.Number({+ displayName: 'Max Wait (seconds)',+ description: `How long to wait for results, from ${COMMAND_POLL_SECONDS} to ${COMMAND_MAX_WAIT_SECONDS} seconds. Devices that are offline report later.`,+ required: false,+ defaultValue: 60,+ }),+ },+ outputSchema: runCommandOutputSchema,+ async run(context) {+ const auth = context.auth.props;+ const triggerName = context.propsValue.triggerName.trim();+ if (triggerName.length === 0) {+ throw new Error('Enter the Trigger Name of the command.');+ }+ const waitForResults = context.propsValue.waitForResults === true;+ const waitMs = waitForResults ? validateWait(context.propsValue.waitSeconds) * 1000 : 0;+ const commands = await fetchTriggerCommands({ auth, triggerName, skip: 0 });+ const earlier = waitForResults ? await snapshotResults({ auth, commandIds: commands.map((command) => command.id) }) : new Set<string>();+ const launchedAt = Date.now() - CLOCK_SKEW_MS;+ const response = await jumpcloudApi.send<unknown>({+ auth,+ method: HttpMethod.POST,+ path: `/command/trigger/${encodeURIComponent(triggerName)}`,+ body: context.propsValue.variables ?? {},+ });+ // JumpCloud answers with the names of the launched commands, not their IDs.+ const launchedNames = readTriggered(response);+ if (launchedNames.length === 0) {+ throw new Error(+ `No JumpCloud command uses the trigger name "${triggerName}". Set the command's Launch Event to Run on Trigger (webhook) with this Trigger Name.`,+ );+ }+ const commandIds = commands.filter((command) => launchedNames.includes(command.name)).map((command) => command.id);+ if (!waitForResults) {+ return { trigger_name: triggerName, command_ids: commandIds, waited: false, completed: false, results: [] };+ }+ const targets = await Promise.all(commandIds.map(async (commandId) => ({ commandId, systemIds: await fetchTargetSystems({ auth, commandId, skip: 0 }) })));+ const deadline = Date.now() + waitMs;+ const results = await pollResults({ auth, targets, launchedAt, earlier, deadline });+ return {+ trigger_name: triggerName,+ command_ids: commandIds,+ waited: true,+ completed: allReported({ targets, results }),+ results,+ };+ },+});++async function pollResults({ auth, targets, launchedAt, earlier, deadline }: WaitParams): Promise<FlatObject[]> {+ const lists = await Promise.all(targets.map(({ commandId }) => fetchResults({ auth, commandId, launchedAt, earlier })));+ const results = lists.flat();+ if (allReported({ targets, results }) || Date.now() + COMMAND_POLL_SECONDS * 1000 > deadline) {+ return results;+ }+ await sleep(COMMAND_POLL_SECONDS * 1000);+ return pollResults({ auth, targets, launchedAt, earlier, deadline });+}++function allReported({ targets, results }: { targets: CommandTargets[]; results: FlatObject[] }): boolean {+ return targets.every(({ commandId, systemIds }) => {+ const reported = new Set(results.filter((result) => result['command_id'] === commandId).map((result) => result['system_id']));+ return systemIds.length === 0 ? reported.size > 0 : systemIds.every((systemId) => reported.has(systemId));+ });+}++async function fetchTargetSystems({ auth, commandId, skip }: { auth: ConnectionProps; commandId: string; skip: number }): Promise<string[]> {+ const body = await jumpcloudApi.send<unknown>({+ auth,+ method: HttpMethod.GET,+ path: `/commands/${encodeURIComponent(commandId)}/systems`,+ version: 'v2',+ queryParams: { limit: String(TARGET_PAGE_SIZE), skip: String(skip) },+ });+ const page = Array.isArray(body) ? body.filter(jumpcloudApi.isRecord) : [];+ const ids = page.flatMap((record) => (typeof record['id'] === 'string' && record['id'].length > 0 ? [record['id']] : []));+ if (page.length < TARGET_PAGE_SIZE) {+ return ids;+ }+ return [...ids, ...(await fetchTargetSystems({ auth, commandId, skip: skip + page.length }))];+}++async function fetchRecords({ auth, commandId }: { auth: ConnectionProps; commandId: string }): Promise<ApiRecord[]> {+ const body = await jumpcloudApi.send<unknown>({+ auth,+ method: HttpMethod.GET,+ path: `/commands/${encodeURIComponent(commandId)}/results`,+ });+ return Array.isArray(body) ? body.filter(jumpcloudApi.isRecord) : [];+}++async function fetchResults({ auth, commandId, launchedAt, earlier }: { auth: ConnectionProps; commandId: string; launchedAt: number; earlier: Set<string> }): Promise<FlatObject[]> {+ const records = await fetchRecords({ auth, commandId });+ return records+ .filter((record) => {+ const requested = typeof record['requestTime'] === 'string' ? Date.parse(record['requestTime']) : Number.NaN;+ return Number.isFinite(requested) && requested >= launchedAt && !earlier.has(resultKey(record));+ })+ .map((record) => jumpcloudOutput.flattenCommandResult({ commandId, record }));+}++// Results listed before the launch belong to an earlier run, even inside the clock skew window.+async function snapshotResults({ auth, commandIds }: { auth: ConnectionProps; commandIds: string[] }): Promise<Set<string>> {+ const records = await Promise.all(commandIds.map((commandId) => fetchRecords({ auth, commandId })));+ return new Set(records.flat().map(resultKey));+}++async function fetchTriggerCommands({ auth, triggerName, skip }: { auth: ConnectionProps; triggerName: string; skip: number }): Promise<TriggerCommand[]> {+ const page = await jumpcloudApi.fetchListPage({+ auth,+ method: HttpMethod.GET,+ path: '/commands',+ queryParams: { filter: `trigger:eq:${triggerName}`, fields: 'name trigger', limit: String(TARGET_PAGE_SIZE), skip: String(skip) },+ });+ const commands = page.items.flatMap((record) => {+ const id = record['_id'] ?? record['id'];+ const name = record['name'];+ return record['trigger'] === triggerName && typeof id === 'string' && id.length > 0 && typeof name === 'string' ? [{ id, name }] : [];+ });+ if (page.items.length < TARGET_PAGE_SIZE) {+ return commands;+ }+ return [...commands, ...(await fetchTriggerCommands({ auth, triggerName, skip: skip + page.items.length }))];+}++function resultKey(record: ApiRecord): string {+ const id = record['_id'] ?? record['id'];+ return typeof id === 'string' && id.length > 0 ? id : `${String(record['systemId'])}|${String(record['requestTime'])}`;+}++function readTriggered(body: unknown): string[] {+ if (!jumpcloudApi.isRecord(body) || !Array.isArray(body['triggered'])) {+ return [];+ }+ return body['triggered'].filter((name): name is string => typeof name === 'string' && name.length > 0);+}++function validateWait(value: number | undefined): number {+ const seconds = value ?? 60;+ if (!Number.isFinite(seconds) || seconds < COMMAND_POLL_SECONDS || seconds > COMMAND_MAX_WAIT_SECONDS) {+ throw new Error(`Max Wait must be from ${COMMAND_POLL_SECONDS} to ${COMMAND_MAX_WAIT_SECONDS} seconds.`);+ }+ return seconds;+}++function sleep(ms: number): Promise<void> {+ return new Promise((resolve) => setTimeout(resolve, ms));+}++const CLOCK_SKEW_MS = 10_000;+const TARGET_PAGE_SIZE = 100;++type TriggerCommand = {+ id: string;+ name: string;+};++type CommandTargets = {+ commandId: string;+ systemIds: string[];+};++type WaitParams = {+ auth: ConnectionProps;+ targets: CommandTargets[];+ launchedAt: number;+ earlier: Set<string>;+ deadline: number;+};diff --git a/packages/pieces/community/jumpcloud/src/lib/actions/search-objects.ts b/packages/pieces/community/jumpcloud/src/lib/actions/search-objects.tsnew file mode 100644index 00000000000..b68363f24c5--- /dev/null+++ b/packages/pieces/community/jumpcloud/src/lib/actions/search-objects.ts@@ -0,0 +1,114 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { jumpcloudAuth } from '../auth';+import { jumpcloudApi } from '../common/client';+import { jumpcloudObjects } from '../common/objects';+import { jumpcloudOutput } from '../common/output';+import { jumpcloudProps } from '../common/props';+import { ApiVersion, ConnectionProps, ListPage, ObjectTypeKey, PageRequest } from '../common/types';++export const searchObjectsAction = createAction({+ auth: jumpcloudAuth,+ name: 'search_objects',+ classification: 'SEARCH',+ displayName: 'Search Objects (Batch)',+ description: 'Find users, devices, groups or applications by text or by a field value.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Searches JumpCloud objects of one type either by free text (names, usernames, emails, hostnames) or by one field condition such as department equals Finance, with paging. Returns items plus total_count and next_skip. Use Search User by Employee ID for that exact lookup. Safe to retry.',+ idempotent: true,+ },+ props: {+ objectType: jumpcloudProps.objectType(),+ searchText: Property.ShortText({+ displayName: 'Search Text',+ description: 'Matches names, usernames, emails or hostnames. Leave empty to filter by a field instead.',+ required: false,+ }),+ filterField: Property.ShortText({+ displayName: 'Filter Field',+ description: 'A JumpCloud field name, for example department, jobTitle, email or name. Leave empty to search by text.',+ required: false,+ }),+ filterOperator: Property.StaticDropdown({+ displayName: 'Filter Operator',+ required: false,+ defaultValue: 'equals',+ options: {+ disabled: false,+ options: [+ { label: 'Equals', value: 'equals' },+ { label: 'Does not equal', value: 'not_equals' },+ { label: 'Starts with (contains for groups)', value: 'starts_with' },+ { label: 'Is one of (separate values with |)', value: 'in' },+ { label: 'Greater than', value: 'greater_than' },+ { label: 'Greater than or equal', value: 'greater_or_equal' },+ { label: 'Less than', value: 'less_than' },+ { label: 'Less than or equal', value: 'less_or_equal' },+ ],+ },+ }),+ filterValue: Property.ShortText({+ displayName: 'Filter Value',+ description: 'The value to compare with. Matching is case-sensitive.',+ required: false,+ }),+ ...jumpcloudProps.pagination(),+ },+ async run(context) {+ const auth = context.auth.props;+ const { limit, skip, fetchAll, maxItems, searchText, filterField, filterOperator, filterValue } = context.propsValue;+ const type = jumpcloudObjects.parseType(context.propsValue.objectType);+ const fetchPage = pageFetcher({ auth, type, searchText, filterField, filterOperator, filterValue });+ const result = await jumpcloudApi.collectPages({ fetchPage, limit, skip, fetchAll, maxItems });+ return { ...result, items: result.items.map((record) => jumpcloudOutput.flatten({ type, record })) };+ },+});++function pageFetcher({ auth, type, searchText, filterField, filterOperator, filterValue }: SearchInput): (page: PageRequest) => Promise<ListPage> {+ const text = searchText?.trim() ?? '';+ const field = filterField?.trim() ?? '';+ if (text.length > 0 && field.length > 0) {+ throw new Error('Use either Search Text or a Filter Field, not both.');+ }+ if (field.length > 0) {+ const value = filterValue?.trim() ?? '';+ if (value.length === 0) {+ throw new Error('Enter a Filter Value for the Filter Field.');+ }+ const filter = `${field}:${resolveOperator({ operator: filterOperator, version: jumpcloudObjects.config(type).version })}:${value}`;+ return (page) => jumpcloudObjects.listPage({ auth, type, page, filter });+ }+ if (text.length === 0) {+ throw new Error('Enter Search Text, or a Filter Field and Filter Value.');+ }+ return jumpcloudObjects.searchPager({ auth, type, term: text });+}++function resolveOperator({ operator, version }: { operator: string | undefined; version: ApiVersion }): string {+ const mapped = OPERATORS[operator ?? 'equals'];+ if (mapped === undefined) {+ throw new Error(`Unknown Filter Operator "${operator}".`);+ }+ return mapped[version];+}++const OPERATORS: Record<string, Record<ApiVersion, string>> = {+ equals: { v1: '$eq', v2: 'eq' },+ not_equals: { v1: '$ne', v2: 'ne' },+ starts_with: { v1: '$sw', v2: 'search' },+ in: { v1: '$in', v2: 'in' },+ greater_than: { v1: '$gt', v2: 'gt' },+ greater_or_equal: { v1: '$gte', v2: 'ge' },+ less_than: { v1: '$lt', v2: 'lt' },+ less_or_equal: { v1: '$lte', v2: 'le' },+};++type SearchInput = {+ auth: ConnectionProps;+ type: ObjectTypeKey;+ searchText: string | undefined;+ filterField: string | undefined;+ filterOperator: string | undefined;+ filterValue: string | undefined;+};diff --git a/packages/pieces/community/jumpcloud/src/lib/actions/unlock-user.ts b/packages/pieces/community/jumpcloud/src/lib/actions/unlock-user.tsnew file mode 100644index 00000000000..698c6229522--- /dev/null+++ b/packages/pieces/community/jumpcloud/src/lib/actions/unlock-user.ts@@ -0,0 +1,33 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { jumpcloudAuth } from '../auth';+import { jumpcloudApi } from '../common/client';+import { jumpcloudObjects } from '../common/objects';+import { jumpcloudOutput } from '../common/output';+import { jumpcloudProps } from '../common/props';+import { userOutputSchema } from '../output-schemas';++export const unlockUserAction = createAction({+ auth: jumpcloudAuth,+ name: 'unlock_user',+ classification: 'WRITE',+ displayName: 'Unlock User',+ description: 'Unlock a user who was locked by an admin or by too many failed sign-in attempts.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Unlocks a JumpCloud user account, whether locked by an admin or by failed sign-ins, and returns the user as it is afterwards. Use Lock User to block access again. Safe to retry.',+ idempotent: true,+ },+ props: {+ userId: jumpcloudProps.objectId({ displayName: 'User', fixedType: 'user' }),+ },+ outputSchema: userOutputSchema,+ async run(context) {+ const auth = context.auth.props;+ const path = jumpcloudObjects.itemPath({ type: 'user', id: context.propsValue.userId });+ await jumpcloudApi.send<unknown>({ auth, method: HttpMethod.POST, path: `${path}/unlock` });+ const user = await jumpcloudObjects.getRecord({ auth, type: 'user', id: context.propsValue.userId });+ return jumpcloudOutput.flatten({ type: 'user', record: user });+ },+});diff --git a/packages/pieces/community/jumpcloud/src/lib/actions/update-object.ts b/packages/pieces/community/jumpcloud/src/lib/actions/update-object.tsnew file mode 100644index 00000000000..48438cad298--- /dev/null+++ b/packages/pieces/community/jumpcloud/src/lib/actions/update-object.ts@@ -0,0 +1,56 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { jumpcloudAuth } from '../auth';+import { jumpcloudApi } from '../common/client';+import { jumpcloudFields } from '../common/fields';+import { jumpcloudObjects } from '../common/objects';+import { jumpcloudOutput } from '../common/output';+import { jumpcloudProps } from '../common/props';++export const updateObjectAction = createAction({+ auth: jumpcloudAuth,+ name: 'update_object',+ classification: 'WRITE',+ displayName: 'Update Object',+ description: 'Change fields on a user, device, group or application. Fields you leave empty keep their current value.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Updates the given fields of one JumpCloud user, system (device), user group, device group or SSO application by ID and returns the updated object. Only provided fields change; to lock or unlock a user use Lock User / Unlock User. Safe to retry with the same values.',+ idempotent: true,+ },+ props: {+ objectType: jumpcloudProps.objectType(),+ objectId: jumpcloudProps.objectId(),+ fields: jumpcloudFields.fieldsProp({ mode: 'update' }),+ additionalFields: jumpcloudFields.additionalFieldsProp(),+ },+ async run(context) {+ const auth = context.auth.props;+ const type = jumpcloudObjects.parseType(context.propsValue.objectType);+ const config = jumpcloudObjects.config(type);+ const id = context.propsValue.objectId.trim();+ const changes = jumpcloudFields.buildChanges({+ type,+ fields: context.propsValue.fields,+ additionalFields: context.propsValue.additionalFields,+ });+ if (Object.keys(changes).length === 0) {+ throw new Error('Fill in at least one field to change, or set Additional Fields.');+ }+ const body = config.replaceOnUpdate+ ? jumpcloudFields.mergeForReplace({ type, current: await jumpcloudObjects.getRecord({ auth, type, id }), changes })+ : changes;+ const updated = await jumpcloudApi.send<unknown>({+ auth,+ method: HttpMethod.PUT,+ path: jumpcloudObjects.itemPath({ type, id }),+ version: config.version,+ body,+ });+ if (!jumpcloudApi.isRecord(updated)) {+ throw new Error(`JumpCloud did not return the updated ${config.label}.`);+ }+ return jumpcloudOutput.flatten({ type, record: updated });+ },+});diff --git a/packages/pieces/community/jumpcloud/src/lib/actions/update-user-on-system.ts b/packages/pieces/community/jumpcloud/src/lib/actions/update-user-on-system.tsnew file mode 100644index 00000000000..202c4cd33fa--- /dev/null+++ b/packages/pieces/community/jumpcloud/src/lib/actions/update-user-on-system.ts@@ -0,0 +1,66 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { jumpcloudAuth } from '../auth';+import { jumpcloudAssociations } from '../common/associations';+import { jumpcloudProps } from '../common/props';+import { userOnSystemOutputSchema } from '../output-schemas';++export const updateUserOnSystemAction = createAction({+ auth: jumpcloudAuth,+ name: 'update_user_on_system',+ classification: 'WRITE',+ displayName: 'Update User on System',+ description: "Set a user's administrator (sudo) rights on a device, binding the user to the device first if you choose.",+ audience: 'both',+ aiMetadata: {+ description:+ "Sets the binding between a JumpCloud user and a system (device): whether the user has administrator/sudo rights and whether sudo asks for a password. With Bind If Needed it also creates the binding; otherwise the user must already be bound. Use Create Association for a plain binding. Safe to retry with the same values.",+ idempotent: true,+ },+ props: {+ userId: jumpcloudProps.objectId({ displayName: 'User', fixedType: 'user' }),+ systemId: jumpcloudProps.objectId({ displayName: 'System (device)', fixedType: 'system' }),+ sudoEnabled: Property.Checkbox({+ displayName: 'Administrator (sudo) Rights',+ description: 'Gives the user administrator rights on this device.',+ required: false,+ defaultValue: false,+ }),+ sudoWithoutPassword: Property.Checkbox({+ displayName: 'Sudo Without Password',+ description: 'Lets the user run administrator commands without typing their password. Only applies with administrator rights.',+ required: false,+ defaultValue: false,+ }),+ bindIfNeeded: Property.Checkbox({+ displayName: 'Bind If Needed',+ description: 'Binds the user to the device when they are not bound yet. Leave off to only change an existing binding.',+ required: false,+ defaultValue: false,+ }),+ },+ outputSchema: userOnSystemOutputSchema,+ async run(context) {+ const { sudoEnabled, sudoWithoutPassword, bindIfNeeded } = context.propsValue;+ const enabled = sudoEnabled === true;+ const withoutPassword = enabled && sudoWithoutPassword === true;+ const ends = jumpcloudAssociations.parseEnds({+ objectType: 'user',+ objectId: context.propsValue.userId,+ targetType: 'system',+ targetId: context.propsValue.systemId,+ });+ const bound = bindIfNeeded === true ? await jumpcloudAssociations.exists({ auth: context.auth.props, ends }) : true;+ await jumpcloudAssociations.change({+ auth: context.auth.props,+ op: bound ? 'update' : 'add',+ ends,+ attributes: { sudo: { enabled, withoutPassword } },+ });+ return {+ user_id: ends.sourceId,+ system_id: ends.targetId,+ sudo_enabled: enabled,+ sudo_without_password: withoutPassword,+ };+ },+});diff --git a/packages/pieces/community/jumpcloud/src/lib/auth.ts b/packages/pieces/community/jumpcloud/src/lib/auth.tsnew file mode 100644index 00000000000..9a9f38e9b57--- /dev/null+++ b/packages/pieces/community/jumpcloud/src/lib/auth.ts@@ -0,0 +1,43 @@+import { PieceAuth, Property } from '@activepieces/pieces-framework';+import { JUMPCLOUD_REGION, jumpcloudApi } from './common/client';++export const jumpcloudAuth = PieceAuth.CustomAuth({+ displayName: 'JumpCloud Connection',+ description: `Connect with a JumpCloud administrator API key.++1. Sign in to the [JumpCloud Admin Portal](https://console.jumpcloud.com).+2. Click your account initials in the top-right corner and choose **My API Key**.+3. Generate a key if you have none, copy it and paste it below.+4. Pick the region your organization lives in. Use **EU** if you sign in at console.eu.jumpcloud.com, **India** for console.in.jumpcloud.com.++The key acts with the permissions of the admin who owns it.`,+ required: true,+ props: {+ apiKey: PieceAuth.SecretText({+ displayName: 'API Key',+ description: 'The administrator API key from My API Key in the Admin Portal.',+ required: true,+ }),+ region: Property.StaticDropdown({+ displayName: 'Region',+ description: 'The data center your JumpCloud organization lives in.',+ required: true,+ defaultValue: JUMPCLOUD_REGION.US,+ options: {+ disabled: false,+ options: [+ { label: 'United States (console.jumpcloud.com)', value: JUMPCLOUD_REGION.US },+ { label: 'European Union (console.eu.jumpcloud.com)', value: JUMPCLOUD_REGION.EU },+ { label: 'India (console.in.jumpcloud.com)', value: JUMPCLOUD_REGION.IN },+ ],+ },+ }),+ orgId: Property.ShortText({+ displayName: 'Organization ID',+ description:+ 'Only needed if you manage several organizations (multi-tenant admin). Find it in the Admin Portal under Settings > Organization Profile. Leave empty otherwise.',+ required: false,+ }),+ },+ validate: async ({ auth }) => jumpcloudApi.validateConnection(auth),+});diff --git a/packages/pieces/community/jumpcloud/src/lib/common/associations.ts b/packages/pieces/community/jumpcloud/src/lib/common/associations.tsnew file mode 100644index 00000000000..c5cdcee39b3--- /dev/null+++ b/packages/pieces/community/jumpcloud/src/lib/common/associations.ts@@ -0,0 +1,151 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { jumpcloudApi } from './client';+import { jumpcloudObjects } from './objects';+import { ApiRecord, ConnectionProps, ObjectTypeKey } from './types';++export const jumpcloudAssociations = {+ route,+ change,+ exists,+ parseEnds,+ toOutput,+};++function parseEnds({ objectType, objectId, targetType, targetId }: EndsInput): AssociationEnds {+ return {+ sourceType: jumpcloudObjects.parseType(objectType),+ sourceId: objectId.trim(),+ targetType: jumpcloudObjects.parseType(targetType),+ targetId: targetId.trim(),+ };+}++function toOutput({ ends, associated }: { ends: AssociationEnds; associated: boolean }): AssociationOutput {+ return {+ object_type: ends.sourceType,+ object_id: ends.sourceId,+ associated_type: ends.targetType,+ associated_id: ends.targetId,+ associated,+ };+}++function route({ sourceType, sourceId, targetType, targetId }: AssociationEnds): AssociationRoute {+ const membership = MEMBERSHIPS.find(+ (pair) => (pair.group === sourceType && pair.member === targetType) || (pair.group === targetType && pair.member === sourceType),+ );+ if (membership !== undefined) {+ const groupId = sourceType === membership.group ? sourceId : targetId;+ const memberId = sourceType === membership.group ? targetId : sourceId;+ return { path: `${GRAPH_PATHS[membership.group]}/${encodeURIComponent(groupId)}/members`, type: membership.member, id: memberId };+ }+ if (ASSOCIATION_TARGETS[sourceType].includes(targetType)) {+ return { path: `${GRAPH_PATHS[sourceType]}/${encodeURIComponent(sourceId)}/associations`, type: targetType, id: targetId };+ }+ const allowed = [...ASSOCIATION_TARGETS[sourceType], ...membershipPartners(sourceType)].map((type) => jumpcloudObjects.config(type).label);+ throw new Error(+ `JumpCloud cannot associate a ${jumpcloudObjects.config(sourceType).label} with a ${jumpcloudObjects.config(targetType).label}. Pick one of: ${allowed.join(', ')}.`,+ );+}++async function change({ auth, op, ends, attributes }: ChangeParams): Promise<void> {+ const sourceId = ends.sourceId.trim();+ const targetId = ends.targetId.trim();+ if (sourceId.length === 0 || targetId.length === 0) {+ throw new Error('Select both objects of the association.');+ }+ const target = route({ ...ends, sourceId, targetId });+ await jumpcloudApi.send<unknown>({+ auth,+ method: HttpMethod.POST,+ path: target.path,+ version: 'v2',+ body: { op, type: target.type, id: target.id, ...(attributes === undefined ? {} : { attributes }) },+ });+}++async function exists({ auth, ends }: { auth: ConnectionProps; ends: AssociationEnds }): Promise<boolean> {+ const target = route(ends);+ return findTarget({ auth, target, skip: 0 });+}++async function findTarget({ auth, target, skip }: { auth: ConnectionProps; target: AssociationRoute; skip: number }): Promise<boolean> {+ const body = await jumpcloudApi.send<unknown>({+ auth,+ method: HttpMethod.GET,+ path: target.path,+ version: 'v2',+ queryParams: { targets: target.type, limit: String(ASSOCIATION_PAGE_SIZE), skip: String(skip) },+ });+ const page = Array.isArray(body) ? body.filter(jumpcloudApi.isRecord) : [];+ const found = page.some((connection) => {+ const to = connection['to'];+ return jumpcloudApi.isRecord(to) && to['id'] === target.id;+ });+ if (found || page.length < ASSOCIATION_PAGE_SIZE) {+ return found;+ }+ return findTarget({ auth, target, skip: skip + page.length });+}++function membershipPartners(type: ObjectTypeKey): ObjectTypeKey[] {+ return MEMBERSHIPS.flatMap((pair) => (pair.group === type ? [pair.member] : pair.member === type ? [pair.group] : []));+}++const GRAPH_PATHS: Record<ObjectTypeKey, string> = {+ user: '/users',+ system: '/systems',+ user_group: '/usergroups',+ system_group: '/systemgroups',+ application: '/applications',+};++const ASSOCIATION_TARGETS: Record<ObjectTypeKey, ObjectTypeKey[]> = {+ user: ['system', 'system_group', 'application'],+ system: ['user', 'user_group'],+ user_group: ['system', 'system_group', 'application'],+ system_group: ['user', 'user_group'],+ application: ['user', 'user_group'],+};++const ASSOCIATION_PAGE_SIZE = 100;++const MEMBERSHIPS: { group: ObjectTypeKey; member: ObjectTypeKey }[] = [+ { group: 'user_group', member: 'user' },+ { group: 'system_group', member: 'system' },+];++type AssociationEnds = {+ sourceType: ObjectTypeKey;+ sourceId: string;+ targetType: ObjectTypeKey;+ targetId: string;+};++type EndsInput = {+ objectType: unknown;+ objectId: string;+ targetType: unknown;+ targetId: string;+};++type AssociationOutput = {+ object_type: ObjectTypeKey;+ object_id: string;+ associated_type: ObjectTypeKey;+ associated_id: string;+ associated: boolean;+};++type AssociationRoute = {+ path: string;+ type: ObjectTypeKey;+ id: string;+};++type ChangeParams = {+ auth: ConnectionProps;+ op: 'add' | 'remove' | 'update';+ ends: AssociationEnds;+ attributes?: ApiRecord;+};diff --git a/packages/pieces/community/jumpcloud/src/lib/common/client.ts b/packages/pieces/community/jumpcloud/src/lib/common/client.tsnew file mode 100644index 00000000000..7bbe6368c8c--- /dev/null+++ b/packages/pieces/community/jumpcloud/src/lib/common/client.ts@@ -0,0 +1,239 @@+import { httpClient, HttpError, HttpMethod, QueryParams } from '@activepieces/pieces-common';+import { ApiRecord, ApiVersion, CollectedPage, ConnectionProps, ListPage, PageRequest, PageWindow, PaginationInput } from './types';++export const jumpcloudApi = {+ resolveBaseUrl,+ authHeaders,+ describeError,+ validateConnection,+ send,+ fetchListPage,+ collectPages,+ pageWindow,+ isRecord,+ isNotFound,+};++function resolveBaseUrl({ region }: BaseUrlProps): string {+ return REGION_BASE_URLS[region ?? JUMPCLOUD_REGION.US] ?? REGION_BASE_URLS[JUMPCLOUD_REGION.US];+}++function authHeaders({ apiKey, orgId }: HeaderProps): Record<string, string> {+ const trimmedOrgId = orgId?.trim() ?? '';+ return {+ 'x-api-key': apiKey.trim(),+ Accept: 'application/json',+ ...(trimmedOrgId.length > 0 ? { 'x-org-id': trimmedOrgId } : {}),+ };+}++function describeError(error: unknown): string {+ if (!(error instanceof HttpError)) {+ return describeNonHttpError(error);+ }+ const status = error.response.status;+ const detail = readErrorMessage(error.response.body);+ const base = `JumpCloud API error (HTTP ${status})${detail.length > 0 ? `: ${detail}` : ''}`;+ const hint = STATUS_HINTS[status];+ return hint === undefined ? base : `${base}. ${hint}`;+}++async function validateConnection(props: ConnectionProps): Promise<ValidationResult> {+ try {+ const baseUrl = resolveBaseUrl(props);+ await httpClient.sendRequest({+ method: HttpMethod.GET,+ url: `${baseUrl}/systemusers`,+ headers: authHeaders(props),+ queryParams: { limit: '1' },+ });+ return { valid: true };+ } catch (error) {+ return { valid: false, error: describeError(error) };+ }+}++async function send<T>({ auth, method, path, version = 'v1', body, queryParams }: SendParams): Promise<T> {+ const url = `${resolveBaseUrl(auth)}${version === 'v2' ? '/v2' : ''}${path}`;+ try {+ const response = await httpClient.sendRequest<T>({+ method,+ url,+ headers: authHeaders(auth),+ ...(queryParams === undefined ? {} : { queryParams }),+ ...(body === undefined ? {} : { body }),+ });+ return response.body;+ } catch (error) {+ throw new Error(describeError(error), { cause: error });+ }+}++async function fetchListPage(params: SendParams): Promise<ListPage> {+ const body = await send<unknown>(params);+ return parseListBody(body);+}++function pageWindow({ skip, limit, fetchAll, maxItems }: PaginationInput): PageWindow {+ return {+ start: clampInt({ value: skip, min: 0, max: Number.MAX_SAFE_INTEGER, fallback: 0 }),+ count: fetchAll+ ? clampInt({ value: maxItems, min: 1, max: MAX_FETCH_ALL_ITEMS, fallback: DEFAULT_MAX_ITEMS })+ : clampInt({ value: limit, min: 1, max: MAX_PAGE_SIZE, fallback: DEFAULT_PAGE_SIZE }),+ };+}++async function collectPages({ fetchPage, ...pagination }: CollectParams): Promise<CollectedPage> {+ const { start, count: target } = pageWindow(pagination);+ let items: ApiRecord[] = [];+ let cursor = start;+ let totalCount: number | undefined;+ while (items.length < target) {+ const pageSize = Math.min(MAX_PAGE_SIZE, target - items.length);+ const page = await fetchPage({ limit: pageSize, skip: cursor });+ items = [...items, ...page.items];+ cursor += page.items.length;+ totalCount = page.totalCount ?? totalCount;+ const reachedEnd = page.items.length < pageSize || (totalCount !== undefined && cursor >= totalCount);+ if (reachedEnd) {+ return { items, total_count: totalCount ?? null, next_skip: null };+ }+ }+ return { items, total_count: totalCount ?? null, next_skip: cursor };+}++function isNotFound(error: unknown): boolean {+ const source = error instanceof Error && error.cause instanceof HttpError ? error.cause : error;+ return source instanceof HttpError && source.response.status === 404;+}++function isRecord(value: unknown): value is ApiRecord {+ return value !== null && typeof value === 'object' && !Array.isArray(value);+}++function parseListBody(body: unknown): ListPage {+ if (Array.isArray(body)) {+ return { items: body.filter(isRecord) };+ }+ if (isRecord(body) && Array.isArray(body['results'])) {+ const totalCount = body['totalCount'];+ return {+ items: body['results'].filter(isRecord),+ ...(typeof totalCount === 'number' && totalCount >= 0 ? { totalCount } : {}),+ };+ }+ throw new Error('JumpCloud returned an unexpected list response. Run the step again, or use Custom API Call to inspect the raw response.');+}++function clampInt({ value, min, max, fallback }: { value: number | undefined; min: number; max: number; fallback: number }): number {+ if (value === undefined || !Number.isFinite(value)) {+ return fallback;+ }+ return Math.min(max, Math.max(min, Math.trunc(value)));+}++function describeNonHttpError(error: unknown): string {+ if (!(error instanceof Error)) {+ return String(error);+ }+ const code = readCauseCode(error);+ if (error.message !== 'fetch failed' && code === undefined) {+ return error.message;+ }+ const reason = code === undefined ? error.message : code;+ return `Could not reach the JumpCloud API (${reason}). Check the connection region and your network.`;+}++function readCauseCode(error: Error): string | undefined {+ const cause = error.cause;+ if (cause !== null && typeof cause === 'object' && 'code' in cause && typeof cause.code === 'string') {+ return cause.code;+ }+ return undefined;+}++function readErrorMessage(body: unknown): string {+ const parsed = typeof body === 'string' ? parseJson(body) : body;+ if (typeof parsed === 'string') {+ const text = parsed.trim();+ if (text.startsWith('<')) {+ return '';+ }+ return text.length > 300 ? `${text.slice(0, 300)}…` : text;+ }+ if (parsed === null || typeof parsed !== 'object') {+ return '';+ }+ if ('message' in parsed && typeof parsed.message === 'string' && parsed.message.length > 0) {+ return parsed.message;+ }+ if ('error' in parsed) {+ const nested = parsed.error;+ if (typeof nested === 'string') {+ return nested;+ }+ if (nested !== null && typeof nested === 'object' && 'message' in nested && typeof nested.message === 'string') {+ return nested.message;+ }+ }+ return '';+}++function parseJson(text: string): unknown {+ try {+ return JSON.parse(text);+ } catch {+ return text;+ }+}++export const JUMPCLOUD_REGION = {+ US: 'us',+ EU: 'eu',+ IN: 'in',+} as const;++export const MAX_PAGE_SIZE = 100;+export const DEFAULT_PAGE_SIZE = 50;+export const DEFAULT_MAX_ITEMS = 1000;+export const MAX_FETCH_ALL_ITEMS = 10000;+export const COMMAND_POLL_SECONDS = 5;+export const COMMAND_MAX_WAIT_SECONDS = 300;++const REGION_BASE_URLS: Record<string, string> = {+ [JUMPCLOUD_REGION.US]: 'https://console.jumpcloud.com/api',+ [JUMPCLOUD_REGION.EU]: 'https://console.eu.jumpcloud.com/api',+ [JUMPCLOUD_REGION.IN]: 'https://console.in.jumpcloud.com/api',+};++const STATUS_HINTS: Record<number, string> = {+ 400: 'Check the values sent to JumpCloud. Multi-tenant admins must also set the Organization ID in the connection.',+ 401: 'Check the API key in the connection. In the JumpCloud Admin Portal, open your account menu and choose My API Key.',+ 403: 'The admin who owns this API key is not allowed to do this. Check the admin role, and set the Organization ID if you manage several organizations.',+ 404: 'Check that the object exists, and that the connection region is correct.',+ 429: 'JumpCloud is rate-limiting requests. Wait a minute and run the step again.',+};++type BaseUrlProps = {+ region?: string;+};++type HeaderProps = {+ apiKey: string;+ orgId?: string;+};++type SendParams = {+ auth: ConnectionProps;+ method: HttpMethod;+ path: string;+ version?: ApiVersion;+ body?: unknown;+ queryParams?: QueryParams;+};++type CollectParams = PaginationInput & {+ fetchPage: (page: PageRequest) => Promise<ListPage>;+};++type ValidationResult = { valid: true } | { valid: false; error: string };diff --git a/packages/pieces/community/jumpcloud/src/lib/common/fields.ts b/packages/pieces/community/jumpcloud/src/lib/common/fields.tsnew file mode 100644index 00000000000..e617b33497a--- /dev/null+++ b/packages/pieces/community/jumpcloud/src/lib/common/fields.ts@@ -0,0 +1,146 @@+import { DynamicPropsValue, InputPropertyMap, Property } from '@activepieces/pieces-framework';+import { jumpcloudAuth } from '../auth';+import { jumpcloudApi } from './client';+import { jumpcloudObjects } from './objects';+import { ApiRecord, ObjectTypeKey } from './types';++export const jumpcloudFields = {+ fieldsProp,+ additionalFieldsProp,+ buildChanges,+ mergeForReplace,+};++function fieldsProp({ mode }: { mode: FieldMode }) {+ return Property.DynamicProperties({+ auth: jumpcloudAuth,+ displayName: mode === 'create' ? 'Fields' : 'Fields to Change',+ description: mode === 'create' ? undefined : 'Only filled-in fields are changed. Empty fields keep their current value.',+ required: true,+ refreshers: ['objectType'],+ props: async ({ objectType }) => {+ if (!jumpcloudObjects.isObjectType(objectType)) {+ return {};+ }+ return FIELD_SPECS[objectType].reduce<InputPropertyMap>(+ (props, spec) => ({+ ...props,+ [spec.key]: Property.ShortText({+ displayName: spec.label,+ description: spec.description,+ required: mode === 'create' && spec.requiredOnCreate === true,+ ...(mode === 'create' && spec.createDefault !== undefined ? { defaultValue: spec.createDefault } : {}),+ }),+ }),+ {},+ );+ },+ });+}++function additionalFieldsProp() {+ return Property.Json({+ displayName: 'Additional Fields',+ description:+ 'Any other JumpCloud fields for this object, as a JSON object, for example {"phoneNumbers": [{"type": "work", "number": "+1 555 0100"}]}. Fields above take precedence. See the JumpCloud API reference for the field names.',+ required: false,+ advanced: true,+ });+}++function buildChanges({ type, fields, additionalFields }: BuildParams): ApiRecord {+ const extra = parseAdditionalFields(additionalFields);+ const typed = FIELD_SPECS[type].reduce<ApiRecord>((body, spec) => {+ const value = fields?.[spec.key];+ return typeof value === 'string' && value.trim().length > 0 ? { ...body, [spec.key]: value.trim() } : body;+ }, {});+ return { ...extra, ...typed };+}++function mergeForReplace({ type, current, changes }: { type: ObjectTypeKey; current: ApiRecord; changes: ApiRecord }): ApiRecord {+ const kept = Object.fromEntries(Object.entries(current).filter(([key]) => !READ_ONLY_KEYS[type].includes(key)));+ return { ...kept, ...changes };+}++function parseAdditionalFields(value: unknown): ApiRecord {+ if (value === undefined || value === null || value === '') {+ return {};+ }+ const parsed = typeof value === 'string' ? parseJsonObject(value) : value;+ if (!jumpcloudApi.isRecord(parsed)) {+ throw new Error('Additional Fields must be a JSON object, such as {"location": "Remote"}.');+ }+ return parsed;+}++function parseJsonObject(text: string): unknown {+ try {+ return JSON.parse(text);+ } catch {+ throw new Error('Additional Fields is not valid JSON. Use a JSON object, such as {"location": "Remote"}.');+ }+}++const USER_FIELDS: FieldSpec[] = [+ { key: 'username', label: 'Username', requiredOnCreate: true, description: 'Unique login name, for example jane.doe.' },+ { key: 'email', label: 'Email', requiredOnCreate: true, description: 'Unique email address. JumpCloud sends the activation email here.' },+ { key: 'firstname', label: 'First Name' },+ { key: 'lastname', label: 'Last Name' },+ { key: 'displayname', label: 'Display Name' },+ { key: 'employeeIdentifier', label: 'Employee ID', description: 'Must be unique across the organization.' },+ { key: 'employeeType', label: 'Employee Type', description: 'For example Full-time or Contractor.' },+ { key: 'jobTitle', label: 'Job Title' },+ { key: 'department', label: 'Department' },+ { key: 'company', label: 'Company' },+ { key: 'costCenter', label: 'Cost Center' },+ { key: 'location', label: 'Location' },+ { key: 'description', label: 'Description' },+];++const GROUP_FIELDS: FieldSpec[] = [+ { key: 'name', label: 'Name', requiredOnCreate: true, description: 'Group names must be unique.' },+ { key: 'description', label: 'Description' },+ { key: 'email', label: 'Email', description: 'Optional email address for the group.' },+];++const FIELD_SPECS: Record<ObjectTypeKey, FieldSpec[]> = {+ user: USER_FIELDS,+ system: [{ key: 'displayName', label: 'Display Name', description: 'The name shown for this device in JumpCloud.' }],+ user_group: GROUP_FIELDS,+ system_group: GROUP_FIELDS,+ application: [+ { key: 'displayLabel', label: 'Display Label', requiredOnCreate: true, description: 'The name users see in the JumpCloud User Portal.' },+ { key: 'ssoUrl', label: 'URL', requiredOnCreate: true, description: 'The address the application opens, for example https://app.example.com.' },+ {+ key: 'name',+ label: 'Application Template',+ createDefault: 'bookmark',+ description: 'The JumpCloud catalog template name. Keep "bookmark" for a simple link; SAML apps also need their config in Additional Fields.',+ },+ { key: 'description', label: 'Description' },+ ],+};++const READ_ONLY_KEYS: Record<ObjectTypeKey, string[]> = {+ user: ['_id', 'created'],+ system: ['_id', 'created'],+ user_group: ['id', 'type', 'memberQueryErrorFlags', 'suggestionCounts', 'organizationObjectId'],+ system_group: ['id', 'type', 'memberQueryErrorFlags', 'organizationObjectId'],+ application: ['_id', 'id', 'created', 'organization'],+};++type FieldMode = 'create' | 'update';++type FieldSpec = {+ key: string;+ label: string;+ description?: string;+ requiredOnCreate?: boolean;+ createDefault?: string;+};++type BuildParams = {+ type: ObjectTypeKey;+ fields: DynamicPropsValue | undefined;+ additionalFields: unknown;+};diff --git a/packages/pieces/community/jumpcloud/src/lib/common/objects.ts b/packages/pieces/community/jumpcloud/src/lib/common/objects.tsnew file mode 100644index 00000000000..0846c9110e3--- /dev/null+++ b/packages/pieces/community/jumpcloud/src/lib/common/objects.ts@@ -0,0 +1,335 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { jumpcloudApi, MAX_PAGE_SIZE } from './client';+import { ApiRecord, ConnectionProps, ListPage, ObjectTypeConfig, ObjectTypeKey, PageRequest } from './types';++export const jumpcloudObjects = {+ config,+ isObjectType,+ parseType,+ typeOptions,+ itemPath,+ readId,+ listPage,+ searchPage,+ searchPager,+ optionLabel,+ getRecord,+ listByIds,+ createdAt,+ sortsByCreated,+ listAll,+ listCreatedSince,+};++function config(type: ObjectTypeKey): ObjectTypeConfig {+ return OBJECT_TYPES[type];+}++function isObjectType(value: unknown): value is ObjectTypeKey {+ return typeof value === 'string' && Object.prototype.hasOwnProperty.call(OBJECT_TYPES, value);+}++function parseType(value: unknown): ObjectTypeKey {+ if (!isObjectType(value)) {+ throw new Error('Select a valid Object Type: User, System (device), User Group, Device Group or Application (SSO).');+ }+ return value;+}++function typeOptions({ creatableOnly }: { creatableOnly: boolean }): { label: string; value: ObjectTypeKey }[] {+ return OBJECT_TYPE_KEYS.filter((type) => !creatableOnly || OBJECT_TYPES[type].canCreate).map((type) => ({+ label: OBJECT_TYPES[type].label,+ value: type,+ }));+}++function itemPath({ type, id }: { type: ObjectTypeKey; id: string }): string {+ const trimmed = id.trim();+ if (trimmed.length === 0) {+ throw new Error(`Select or enter the ${OBJECT_TYPES[type].label} ID.`);+ }+ return `${OBJECT_TYPES[type].path}/${encodeURIComponent(trimmed)}`;+}++function readId({ type, record }: { type: ObjectTypeKey; record: ApiRecord }): string | null {+ const value = record[OBJECT_TYPES[type].idField];+ return typeof value === 'string' && value.length > 0 ? value : null;+}++async function listPage({ auth, type, page, filter, sort }: ListParams): Promise<ListPage> {+ const { path, version, defaultSort } = OBJECT_TYPES[type];+ return jumpcloudApi.fetchListPage({+ auth,+ method: HttpMethod.GET,+ path,+ version,+ queryParams: {+ limit: String(page.limit),+ skip: String(page.skip),+ sort: sort ?? defaultSort,+ ...(filter === undefined ? {} : { filter }),+ },+ });+}++async function searchPage({ auth, type, term, page }: SearchParams): Promise<ListPage> {+ return searchPager({ auth, type, term })(page);+}++function searchPager({ auth, type, term }: Omit<SearchParams, 'page'>): (page: PageRequest) => Promise<ListPage> {+ const search = OBJECT_TYPES[type].search;+ if (search.kind !== 'local' || term.trim().length === 0) {+ return (page) => remoteSearchPage({ auth, type, term, page });+ }+ const matches = localMatches({ auth, type, term: term.trim() });+ return async (page) => {+ const all = await matches;+ return { items: all.slice(page.skip, page.skip + page.limit), totalCount: all.length };+ };+}++async function localMatches({ auth, type, term }: Omit<SearchParams, 'page'>): Promise<ApiRecord[]> {+ const all = await listAll({ auth, type, sort: OBJECT_TYPES[type].pickerSort });+ const needle = term.toLowerCase();+ return all.filter((record) => optionLabel({ type, record }).toLowerCase().includes(needle));+}++async function remoteSearchPage({ auth, type, term, page }: SearchParams): Promise<ListPage> {+ const trimmed = term.trim();+ if (trimmed.length === 0) {+ return listPage({ auth, type, page, sort: OBJECT_TYPES[type].pickerSort });+ }+ const search = OBJECT_TYPES[type].search;+ switch (search.kind) {+ case 'endpoint':+ return jumpcloudApi.fetchListPage({+ auth,+ method: HttpMethod.POST,+ path: search.path,+ queryParams: { limit: String(page.limit), skip: String(page.skip) },+ body: { searchFilter: { searchTerm: trimmed, fields: search.fields } },+ });+ case 'filter':+ return listPage({ auth, type, page, filter: `${search.field}:${search.operator}:${trimmed}` });+ case 'local': {+ const matches = await localMatches({ auth, type, term: trimmed });+ return { items: matches.slice(page.skip, page.skip + page.limit), totalCount: matches.length };+ }+ }+}++async function getRecord({ auth, type, id }: { auth: ConnectionProps; type: ObjectTypeKey; id: string }): Promise<ApiRecord> {+ const body = await jumpcloudApi.send<unknown>({+ auth,+ method: HttpMethod.GET,+ path: itemPath({ type, id }),+ version: OBJECT_TYPES[type].version,+ });+ if (!jumpcloudApi.isRecord(body)) {+ throw new Error(`JumpCloud returned an unexpected response for ${OBJECT_TYPES[type].label} ${id}.`);+ }+ return body;+}++async function listByIds({ auth, type, ids }: { auth: ConnectionProps; type: ObjectTypeKey; ids: string[] }): Promise<ApiRecord[]> {+ if (ids.length === 0) {+ return [];+ }+ const { version, idField } = OBJECT_TYPES[type];+ if (version === 'v1') {+ const page = await listPage({ auth, type, page: { limit: ids.length, skip: 0 }, filter: `${idField}:$in:${ids.join('|')}` });+ return page.items;+ }+ const batches = Array.from({ length: Math.ceil(ids.length / PARALLEL_FETCHES) }, (_, index) =>+ ids.slice(index * PARALLEL_FETCHES, (index + 1) * PARALLEL_FETCHES),+ );+ const results = await batches.reduce<Promise<ApiRecord[]>>(async (previous, batch) => {+ const collected = await previous;+ const fetched = await Promise.all(batch.map((id) => getRecordOrNull({ auth, type, id })));+ return [...collected, ...fetched.filter((record): record is ApiRecord => record !== null)];+ }, Promise.resolve([]));+ return results;+}++async function getRecordOrNull({ auth, type, id }: { auth: ConnectionProps; type: ObjectTypeKey; id: string }): Promise<ApiRecord | null> {+ try {+ return await getRecord({ auth, type, id });+ } catch (error) {+ if (jumpcloudApi.isNotFound(error)) {+ return null;+ }+ throw error;+ }+}++function createdAt({ type, record }: { type: ObjectTypeKey; record: ApiRecord }): number | null {+ const created = record['created'];+ if (typeof created === 'string') {+ const parsed = Date.parse(created);+ if (Number.isFinite(parsed)) {+ return parsed;+ }+ }+ const id = readId({ type, record });+ return id !== null && OBJECT_ID_PATTERN.test(id) ? parseInt(id.slice(0, 8), 16) * 1000 : null;+}++function sortsByCreated(type: ObjectTypeKey): boolean {+ return OBJECT_TYPES[type].sortsByCreated;+}++async function listAll({ auth, type, sort }: { auth: ConnectionProps; type: ObjectTypeKey; sort?: string }): Promise<ApiRecord[]> {+ return collectUntil({ auth, type, sort: sort ?? OBJECT_TYPES[type].defaultSort, skip: 0, collected: [], done: () => false });+}++async function listCreatedSince({ auth, type, since, maxItems }: CreatedSinceParams): Promise<ApiRecord[]> {+ return collectUntil({+ auth,+ type,+ sort: '-created',+ skip: 0,+ collected: [],+ done: (page, collected) => {+ const oldest = page.length === 0 ? null : createdAt({ type, record: page[page.length - 1] });+ return (oldest !== null && oldest < since) || (maxItems !== undefined && collected.length >= maxItems);+ },+ });+}++async function collectUntil({ auth, type, sort, skip, collected, done }: CollectUntilParams): Promise<ApiRecord[]> {+ const page = await listPage({ auth, type, page: { limit: MAX_PAGE_SIZE, skip }, sort });+ const items = [...collected, ...page.items];+ if (page.items.length < MAX_PAGE_SIZE || done(page.items, items)) {+ return items;+ }+ return collectUntil({ auth, type, sort, skip: skip + page.items.length, collected: items, done });+}++function optionLabel({ type, record }: { type: ObjectTypeKey; record: ApiRecord }): string {+ const id = readId({ type, record }) ?? 'unknown ID';+ switch (type) {+ case 'user': {+ const fullName = [text(record['firstname']), text(record['lastname'])].filter((part) => part.length > 0).join(' ');+ const name = firstNonEmpty([text(record['displayname']), fullName, text(record['username'])]) ?? id;+ const email = text(record['email']);+ return email.length > 0 ? `${name} (${email})` : name;+ }+ case 'system': {+ const name = firstNonEmpty([text(record['displayName']), text(record['hostname'])]) ?? id;+ const os = text(record['os']);+ return os.length > 0 ? `${name} (${os})` : name;+ }+ case 'user_group':+ case 'system_group':+ return firstNonEmpty([text(record['name'])]) ?? id;+ case 'application':+ return firstNonEmpty([text(record['displayLabel']), text(record['displayName']), text(record['name'])]) ?? id;+ }+}++function text(value: unknown): string {+ return typeof value === 'string' ? value.trim() : '';+}++function firstNonEmpty(values: string[]): string | undefined {+ return values.find((value) => value.length > 0);+}++const OBJECT_TYPES: Record<ObjectTypeKey, ObjectTypeConfig & { pickerSort: string; sortsByCreated: boolean }> = {+ user: {+ label: 'User',+ version: 'v1',+ path: '/systemusers',+ idField: '_id',+ defaultSort: '_id',+ pickerSort: 'username',+ sortsByCreated: true,+ canCreate: true,+ replaceOnUpdate: false,+ search: { kind: 'endpoint', path: '/search/systemusers', fields: ['username', 'email', 'firstname', 'lastname', 'displayname'] },+ },+ system: {+ label: 'System (device)',+ version: 'v1',+ path: '/systems',+ idField: '_id',+ defaultSort: '_id',+ pickerSort: 'displayName',+ sortsByCreated: true,+ canCreate: false,+ replaceOnUpdate: false,+ search: { kind: 'endpoint', path: '/search/systems', fields: ['displayName', 'hostname', 'serialNumber'] },+ },+ user_group: {+ label: 'User Group',+ version: 'v2',+ path: '/usergroups',+ idField: 'id',+ defaultSort: 'name',+ pickerSort: 'name',+ sortsByCreated: false,+ canCreate: true,+ replaceOnUpdate: true,+ search: { kind: 'filter', field: 'name', operator: 'search' },+ },+ system_group: {+ label: 'Device Group',+ version: 'v2',+ path: '/systemgroups',+ idField: 'id',+ defaultSort: 'name',+ pickerSort: 'name',+ sortsByCreated: false,+ canCreate: true,+ replaceOnUpdate: true,+ search: { kind: 'filter', field: 'name', operator: 'search' },+ },+ application: {+ label: 'Application (SSO)',+ version: 'v1',+ path: '/applications',+ idField: '_id',+ defaultSort: '_id',+ pickerSort: 'displayLabel',+ sortsByCreated: true,+ canCreate: true,+ replaceOnUpdate: true,+ search: { kind: 'local' },+ },+};++const PARALLEL_FETCHES = 10;+const OBJECT_ID_PATTERN = /^[0-9a-f]{24}$/i;++const OBJECT_TYPE_KEYS: ObjectTypeKey[] = ['user', 'system', 'user_group', 'system_group', 'application'];++type ListParams = {+ auth: ConnectionProps;+ type: ObjectTypeKey;+ page: PageRequest;+ filter?: string;+ sort?: string;+};++type CreatedSinceParams = {+ auth: ConnectionProps;+ type: ObjectTypeKey;+ since: number;+ maxItems?: number;+};++type CollectUntilParams = {+ auth: ConnectionProps;+ type: ObjectTypeKey;+ sort: string;+ skip: number;+ collected: ApiRecord[];+ done: (page: ApiRecord[], collected: ApiRecord[]) => boolean;+};++type SearchParams = {+ auth: ConnectionProps;+ type: ObjectTypeKey;+ term: string;+ page: PageRequest;+};diff --git a/packages/pieces/community/jumpcloud/src/lib/common/output.ts b/packages/pieces/community/jumpcloud/src/lib/common/output.tsnew file mode 100644index 00000000000..d125307dc75--- /dev/null+++ b/packages/pieces/community/jumpcloud/src/lib/common/output.ts@@ -0,0 +1,115 @@+import { ApiRecord, FlatObject, ObjectTypeKey } from './types';++export const jumpcloudOutput = {+ flatten,+ flattenCommandResult,+};++function flatten({ type, record }: { type: ObjectTypeKey; record: ApiRecord }): FlatObject {+ switch (type) {+ case 'user':+ return flattenUser(record);+ case 'system':+ return flattenSystem(record);+ case 'user_group':+ case 'system_group':+ return flattenGroup(record);+ case 'application':+ return flattenApplication(record);+ }+}++function flattenUser(record: ApiRecord): FlatObject {+ const mfa = record['mfa'];+ return {+ id: str(record['_id']),+ username: str(record['username']),+ email: str(record['email']),+ first_name: str(record['firstname']),+ last_name: str(record['lastname']),+ display_name: str(record['displayname']),+ employee_id: str(record['employeeIdentifier']),+ employee_type: str(record['employeeType']),+ job_title: str(record['jobTitle']),+ department: str(record['department']),+ company: str(record['company']),+ cost_center: str(record['costCenter']),+ location: str(record['location']),+ manager_id: str(record['manager']),+ state: str(record['state']),+ activated: bool(record['activated']),+ account_locked: bool(record['account_locked']),+ suspended: bool(record['suspended']),+ password_expired: bool(record['password_expired']),+ mfa_configured: mfa !== null && typeof mfa === 'object' && 'configured' in mfa ? bool(mfa.configured) : null,+ totp_enabled: bool(record['totp_enabled']),+ created: str(record['created']),+ };+}++function flattenSystem(record: ApiRecord): FlatObject {+ return {+ id: str(record['_id']),+ display_name: str(record['displayName']),+ hostname: str(record['hostname']),+ os: str(record['os']),+ os_family: str(record['osFamily']),+ os_version: str(record['version']),+ architecture: str(record['arch']),+ serial_number: str(record['serialNumber']),+ agent_version: str(record['agentVersion']),+ active: bool(record['active']),+ last_contact: str(record['lastContact']),+ remote_ip: str(record['remoteIP']),+ created: str(record['created']),+ };+}++function flattenGroup(record: ApiRecord): FlatObject {+ return {+ id: str(record['id']),+ name: str(record['name']),+ description: str(record['description']),+ email: str(record['email']),+ type: str(record['type']),+ membership_method: str(record['membershipMethod']),+ };+}++function flattenApplication(record: ApiRecord): FlatObject {+ return {+ id: str(record['_id']),+ name: str(record['name']),+ display_label: str(record['displayLabel']),+ display_name: str(record['displayName']),+ description: str(record['description']),+ sso_url: str(record['ssoUrl']),+ active: bool(record['active']),+ created: str(record['created']),+ };+}++function flattenCommandResult({ commandId, record }: { commandId: string; record: ApiRecord }): FlatObject {+ const response = record['response'];+ const data = response !== null && typeof response === 'object' && 'data' in response ? response.data : undefined;+ return {+ command_id: commandId,+ command_name: str(record['name']),+ system_id: str(record['systemId']),+ system_name: str(record['system']),+ run_as_user: str(record['user']),+ exit_code: data !== null && typeof data === 'object' && 'exitCode' in data && typeof data.exitCode === 'number' ? data.exitCode : null,+ output: data !== null && typeof data === 'object' && 'output' in data ? str(data.output) : null,+ error: response !== null && typeof response === 'object' && 'error' in response ? str(response.error) : null,+ request_time: str(record['requestTime']),+ response_time: str(record['responseTime']),+ };+}++function str(value: unknown): string | null {+ return typeof value === 'string' && value.length > 0 ? value : null;+}++function bool(value: unknown): boolean | null {+ return typeof value === 'boolean' ? value : null;+}diff --git a/packages/pieces/community/jumpcloud/src/lib/common/props.ts b/packages/pieces/community/jumpcloud/src/lib/common/props.tsnew file mode 100644index 00000000000..ac8c5a3c779--- /dev/null+++ b/packages/pieces/community/jumpcloud/src/lib/common/props.ts@@ -0,0 +1,112 @@+import { Property } from '@activepieces/pieces-framework';+import { jumpcloudAuth } from '../auth';+import { DEFAULT_MAX_ITEMS, DEFAULT_PAGE_SIZE, jumpcloudApi, MAX_FETCH_ALL_ITEMS, MAX_PAGE_SIZE } from './client';+import { jumpcloudObjects } from './objects';+import { ObjectTypeKey } from './types';++export const jumpcloudProps = {+ objectType,+ objectId,+ pagination,+};++function objectType({+ creatableOnly = false,+ displayName = 'Object Type',+ description = 'The kind of JumpCloud object to work with.',+}: { creatableOnly?: boolean; displayName?: string; description?: string } = {}) {+ return Property.StaticDropdown({+ displayName,+ description,+ required: true,+ defaultValue: 'user',+ options: {+ disabled: false,+ options: jumpcloudObjects.typeOptions({ creatableOnly }),+ },+ });+}++function objectId({ displayName = 'Object', description, typeProp = 'objectType', fixedType }: ObjectIdParams = {}) {+ return Property.Dropdown({+ auth: jumpcloudAuth,+ displayName,+ description: description ?? 'Pick the object, or type to search by name. You can also map an ID from an earlier step.',+ required: true,+ refreshers: fixedType === undefined ? [typeProp] : [],+ refreshOnSearch: true,+ options: async (propsValue, { searchValue }) => {+ const { auth } = propsValue;+ const objectType = fixedType ?? propsValue[typeProp];+ if (auth === undefined) {+ return { disabled: true, options: [], placeholder: 'Connect your JumpCloud account first.' };+ }+ if (!jumpcloudObjects.isObjectType(objectType)) {+ return { disabled: true, options: [], placeholder: 'Select an object type first.' };+ }+ try {+ const page = await jumpcloudObjects.searchPage({+ auth: auth.props,+ type: objectType,+ term: searchValue ?? '',+ page: { limit: PICKER_PAGE_SIZE, skip: 0 },+ });+ const options = page.items.flatMap((record) => {+ const id = jumpcloudObjects.readId({ type: objectType, record });+ return id === null ? [] : [{ label: jumpcloudObjects.optionLabel({ type: objectType, record }), value: id }];+ });+ return {+ disabled: false,+ options,+ placeholder: options.length === 0 ? 'No matching objects found.' : undefined,+ };+ } catch (error) {+ return { disabled: true, options: [], placeholder: jumpcloudApi.describeError(error) };+ }+ },+ });+}++function pagination() {+ return {+ limit: Property.Number({+ displayName: 'Max Results',+ description: `How many objects to return per run, from 1 to ${MAX_PAGE_SIZE}. Ignored when Fetch All Pages is on.`,+ required: false,+ defaultValue: DEFAULT_PAGE_SIZE,+ display: 'stepper',+ min: 1,+ max: MAX_PAGE_SIZE,+ step: 1,+ }),+ skip: Property.Number({+ displayName: 'Skip',+ description: 'How many objects to skip before the first result. Use the Next Skip value from a previous run to get the next page.',+ required: false,+ defaultValue: 0,+ advanced: true,+ }),+ fetchAll: Property.Checkbox({+ displayName: 'Fetch All Pages',+ description: 'Keep requesting pages until every object is returned, up to Max Objects.',+ required: false,+ defaultValue: false,+ reveals: ['maxItems'],+ }),+ maxItems: Property.Number({+ displayName: 'Max Objects',+ description: `Safety cap when fetching all pages, up to ${MAX_FETCH_ALL_ITEMS}.`,+ required: false,+ defaultValue: DEFAULT_MAX_ITEMS,+ }),+ };+}++const PICKER_PAGE_SIZE = 50;++type ObjectIdParams = {+ displayName?: string;+ description?: string;+ typeProp?: string;+ fixedType?: ObjectTypeKey;+};diff --git a/packages/pieces/community/jumpcloud/src/lib/common/types.ts b/packages/pieces/community/jumpcloud/src/lib/common/types.tsnew file mode 100644index 00000000000..4378045dacb--- /dev/null+++ b/packages/pieces/community/jumpcloud/src/lib/common/types.ts@@ -0,0 +1,57 @@+export type ApiVersion = 'v1' | 'v2';++export type ConnectionProps = {+ apiKey: string;+ region?: string;+ orgId?: string;+};++export type ApiRecord = Record<string, unknown>;++export type ListPage = {+ items: ApiRecord[];+ totalCount?: number;+};++export type PageRequest = {+ limit: number;+ skip: number;+};++export type CollectedPage = {+ items: ApiRecord[];+ total_count: number | null;+ next_skip: number | null;+};++export type ObjectTypeKey = 'user' | 'system' | 'user_group' | 'system_group' | 'application';++export type ObjectSearch =+ | { kind: 'endpoint'; path: string; fields: string[] }+ | { kind: 'filter'; field: string; operator: string }+ | { kind: 'local' };++export type ObjectTypeConfig = {+ label: string;+ version: ApiVersion;+ path: string;+ idField: '_id' | 'id';+ defaultSort: string;+ canCreate: boolean;+ replaceOnUpdate: boolean;+ search: ObjectSearch;+};++export type PageWindow = {+ start: number;+ count: number;+};++export type PaginationInput = {+ skip?: number;+ limit?: number;+ fetchAll?: boolean;+ maxItems?: number;+};++export type FlatObject = Record<string, string | number | boolean | null>;diff --git a/packages/pieces/community/jumpcloud/src/lib/output-schemas.ts b/packages/pieces/community/jumpcloud/src/lib/output-schemas.tsnew file mode 100644index 00000000000..28b280575d5--- /dev/null+++ b/packages/pieces/community/jumpcloud/src/lib/output-schemas.ts@@ -0,0 +1,87 @@+import { OutputSchema } from '@activepieces/pieces-framework';++const userFields: OutputSchema['fields'] = [+ { key: 'id', label: 'User ID' },+ { key: 'username', label: 'Username' },+ { key: 'email', label: 'Email', format: 'email' },+ { key: 'first_name', label: 'First Name' },+ { key: 'last_name', label: 'Last Name' },+ { key: 'display_name', label: 'Display Name' },+ { key: 'employee_id', label: 'Employee ID' },+ { key: 'employee_type', label: 'Employee Type' },+ { key: 'job_title', label: 'Job Title' },+ { key: 'department', label: 'Department' },+ { key: 'company', label: 'Company' },+ { key: 'cost_center', label: 'Cost Center' },+ { key: 'location', label: 'Location' },+ { key: 'manager_id', label: 'Manager ID' },+ { key: 'state', label: 'State' },+ { key: 'activated', label: 'Activated', format: 'boolean' },+ { key: 'account_locked', label: 'Account Locked', format: 'boolean' },+ { key: 'suspended', label: 'Suspended', format: 'boolean' },+ { key: 'password_expired', label: 'Password Expired', format: 'boolean' },+ { key: 'mfa_configured', label: 'MFA Configured', format: 'boolean' },+ { key: 'totp_enabled', label: 'TOTP Enabled', format: 'boolean' },+ { key: 'created', label: 'Created', format: 'datetime' },+];++export const userOutputSchema: OutputSchema = {+ fields: userFields,+};++export const findUserOutputSchema: OutputSchema = {+ fields: [{ key: 'found', label: 'Found', format: 'boolean' }, ...userFields],+};++export const associationOutputSchema: OutputSchema = {+ fields: [+ { key: 'object_type', label: 'Object Type' },+ { key: 'object_id', label: 'Object ID' },+ { key: 'associated_type', label: 'Associated Type' },+ { key: 'associated_id', label: 'Associated Object ID' },+ { key: 'associated', label: 'Associated', format: 'boolean' },+ ],+};++export const resetMfaOutputSchema: OutputSchema = {+ fields: [+ { key: 'user_id', label: 'User ID' },+ { key: 'mfa_reset', label: 'MFA Reset', format: 'boolean' },+ { key: 'grace_period_days', label: 'Grace Period (days)', format: 'number' },+ ],+};++export const userOnSystemOutputSchema: OutputSchema = {+ fields: [+ { key: 'user_id', label: 'User ID' },+ { key: 'system_id', label: 'System ID' },+ { key: 'sudo_enabled', label: 'Administrator (sudo) Rights', format: 'boolean' },+ { key: 'sudo_without_password', label: 'Sudo Without Password', format: 'boolean' },+ ],+};++export const runCommandOutputSchema: OutputSchema = {+ fields: [+ { key: 'trigger_name', label: 'Trigger Name' },+ { key: 'command_ids', label: 'Launched Command IDs' },+ { key: 'waited', label: 'Waited For Results', format: 'boolean' },+ { key: 'completed', label: 'All Commands Reported', format: 'boolean' },+ {+ key: 'results',+ label: 'Results',+ labelKey: 'system_name',+ listItems: [+ { key: 'command_id', label: 'Command ID' },+ { key: 'command_name', label: 'Command Name' },+ { key: 'system_id', label: 'System ID' },+ { key: 'system_name', label: 'System Name' },+ { key: 'run_as_user', label: 'Run As User' },+ { key: 'exit_code', label: 'Exit Code', format: 'number' },+ { key: 'output', label: 'Output' },+ { key: 'error', label: 'Error' },+ { key: 'request_time', label: 'Requested At', format: 'datetime' },+ { key: 'response_time', label: 'Completed At', format: 'datetime' },+ ],+ },+ ],+};diff --git a/packages/pieces/community/jumpcloud/src/lib/triggers/new-object.ts b/packages/pieces/community/jumpcloud/src/lib/triggers/new-object.tsnew file mode 100644index 00000000000..ffe7f3edb64--- /dev/null+++ b/packages/pieces/community/jumpcloud/src/lib/triggers/new-object.ts@@ -0,0 +1,146 @@+import { createTrigger, Store, TriggerStrategy } from '@activepieces/pieces-framework';+import { jumpcloudAuth } from '../auth';+import { jumpcloudObjects } from '../common/objects';+import { jumpcloudOutput } from '../common/output';+import { jumpcloudProps } from '../common/props';+import { ApiRecord, ConnectionProps, ObjectTypeKey } from '../common/types';++export const newObjectTrigger = createTrigger({+ auth: jumpcloudAuth,+ name: 'new_object',+ classification: 'READ',+ displayName: 'New Object',+ description: 'Triggers when a new user, device, group or application appears in JumpCloud.',+ aiMetadata: {+ description:+ 'Fires once per new JumpCloud object of the selected type (user, system/device, user group, device group or SSO application), checked every few minutes. Each run carries one object with its fields and object_type.',+ },+ props: newObjectProps(),+ sampleData: {+ object_type: 'user',+ id: '5f8a1c2b3d4e5f6a7b8c9d0e',+ username: 'jane.doe',+ email: '[email protected]',+ first_name: 'Jane',+ last_name: 'Doe',+ display_name: 'Jane Doe',+ employee_id: 'E-1042',+ employee_type: 'Full-time',+ job_title: 'Software Engineer',+ department: 'Engineering',+ company: 'Example Inc.',+ cost_center: null,+ location: 'Remote',+ manager_id: null,+ state: 'ACTIVATED',+ activated: true,+ account_locked: false,+ suspended: false,+ password_expired: false,+ mfa_configured: false,+ totp_enabled: false,+ created: '2026-10-06T12:00:00.000Z',+ },+ type: TriggerStrategy.POLLING,+ async test(context) {+ const type = jumpcloudObjects.parseType(context.propsValue.objectType);+ const records = jumpcloudObjects.sortsByCreated(type)+ ? await jumpcloudObjects.listCreatedSince({ auth: context.auth.props, type, since: 0, maxItems: TEST_ITEMS })+ : await jumpcloudObjects.listAll({ auth: context.auth.props, type });+ return toOutputs({ type, records }).slice(0, TEST_ITEMS);+ },+ async onEnable(context) {+ const type = jumpcloudObjects.parseType(context.propsValue.objectType);+ const existing = await context.store.get<Checkpoint>(CHECKPOINT_KEY);+ if (context.isRepublish === true && existing !== null && existing.type === type) {+ return;+ }+ await context.store.put(CHECKPOINT_KEY, await initialCheckpoint({ auth: context.auth.props, type }));+ },+ async onDisable() {+ return;+ },+ async run(context) {+ const type = jumpcloudObjects.parseType(context.propsValue.objectType);+ const auth = context.auth.props;+ const checkpoint = await context.store.get<Checkpoint>(CHECKPOINT_KEY);+ if (checkpoint === null || checkpoint.type !== type) {+ await context.store.put(CHECKPOINT_KEY, await initialCheckpoint({ auth, type }));+ return [];+ }+ return poll({ auth, type, checkpoint, store: context.store });+ },+});++function newObjectProps() {+ return {+ objectType: jumpcloudProps.objectType({ description: 'The kind of new object to watch for.' }),+ };+}++async function initialCheckpoint({ auth, type }: { auth: ConnectionProps; type: ObjectTypeKey }): Promise<Checkpoint> {+ if (jumpcloudObjects.sortsByCreated(type)) {+ return { kind: 'created', type, since: Date.now(), boundaryIds: [] };+ }+ const records = await jumpcloudObjects.listAll({ auth, type });+ return { kind: 'ids', type, ids: readIds({ type, records }) };+}++async function poll({ auth, type, checkpoint, store }: PollParams): Promise<OutputItem[]> {+ if (checkpoint.kind === 'ids') {+ const records = await jumpcloudObjects.listAll({ auth, type });+ const known = new Set(checkpoint.ids);+ const created = records.filter((record) => {+ const id = jumpcloudObjects.readId({ type, record });+ return id !== null && !known.has(id);+ });+ await store.put(CHECKPOINT_KEY, { kind: 'ids', type, ids: readIds({ type, records }) });+ return toOutputs({ type, records: created });+ }+ const records = await jumpcloudObjects.listCreatedSince({ auth, type, since: checkpoint.since });+ const boundary = new Set(checkpoint.boundaryIds);+ const created = records.filter((record) => {+ const id = jumpcloudObjects.readId({ type, record });+ const at = jumpcloudObjects.createdAt({ type, record });+ return id !== null && at !== null && (at > checkpoint.since || (at === checkpoint.since && !boundary.has(id)));+ });+ await store.put(CHECKPOINT_KEY, advance({ type, checkpoint, created }));+ return toOutputs({ type, records: created });+}++function advance({ type, checkpoint, created }: { type: ObjectTypeKey; checkpoint: CreatedCheckpoint; created: ApiRecord[] }): CreatedCheckpoint {+ const since = created.reduce((latest, record) => Math.max(latest, jumpcloudObjects.createdAt({ type, record }) ?? latest), checkpoint.since);+ const atSince = readIds({ type, records: created.filter((record) => jumpcloudObjects.createdAt({ type, record }) === since) });+ const boundaryIds = since === checkpoint.since ? [...new Set([...checkpoint.boundaryIds, ...atSince])] : atSince;+ return { kind: 'created', type, since, boundaryIds };+}++function toOutputs({ type, records }: { type: ObjectTypeKey; records: ApiRecord[] }): OutputItem[] {+ return records+ .map((record) => ({ at: jumpcloudObjects.createdAt({ type, record }) ?? 0, data: { object_type: type, ...jumpcloudOutput.flatten({ type, record }) } }))+ .sort((a, b) => b.at - a.at)+ .map((item) => item.data);+}++function readIds({ type, records }: { type: ObjectTypeKey; records: ApiRecord[] }): string[] {+ return records.flatMap((record) => {+ const id = jumpcloudObjects.readId({ type, record });+ return id === null ? [] : [id];+ });+}++const CHECKPOINT_KEY = 'checkpoint';+const TEST_ITEMS = 5;++type CreatedCheckpoint = { kind: 'created'; type: ObjectTypeKey; since: number; boundaryIds: string[] };++type Checkpoint = CreatedCheckpoint | { kind: 'ids'; type: ObjectTypeKey; ids: string[] };++type OutputItem = { object_type: ObjectTypeKey } & ReturnType<typeof jumpcloudOutput.flatten>;++type PollParams = {+ auth: ConnectionProps;+ type: ObjectTypeKey;+ checkpoint: Checkpoint;+ store: Store;+};diff --git a/packages/pieces/community/jumpcloud/test/actions.test.ts b/packages/pieces/community/jumpcloud/test/actions.test.tsnew file mode 100644index 00000000000..9daf0301730--- /dev/null+++ b/packages/pieces/community/jumpcloud/test/actions.test.ts@@ -0,0 +1,376 @@+import { HttpError, httpClient, HttpMethod } from '@activepieces/pieces-common';+import {+ AppConnectionType,+ AppConnectionValueForAuthProperty,+ createMockActionContext,+ InputPropertyMap,+ StaticPropsValue,+} from '@activepieces/pieces-framework';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { jumpcloud } from '../src';+import { createObjectAction } from '../src/lib/actions/create-object';+import { deleteObjectAction } from '../src/lib/actions/delete-object';+import { getObjectAction } from '../src/lib/actions/get-object';+import { listObjectsAction } from '../src/lib/actions/list-objects';+import { listObjectsByIdAction } from '../src/lib/actions/list-objects-by-id';+import { searchObjectsAction } from '../src/lib/actions/search-objects';+import { updateObjectAction } from '../src/lib/actions/update-object';+import { jumpcloudAuth } from '../src/lib/auth';+import { ObjectTypeKey } from '../src/lib/common/types';++const sendRequest = vi.fn();++const V1 = 'https://console.jumpcloud.com/api';+const V2 = 'https://console.jumpcloud.com/api/v2';+const PAGING = { limit: 50, skip: 0, fetchAll: false, maxItems: 1000 };++beforeEach(() => {+ sendRequest.mockReset();+ vi.spyOn(httpClient, 'sendRequest').mockImplementation((request) => sendRequest(request));+});++afterEach(() => {+ vi.restoreAllMocks();+});++describe('piece definition', () => {+ it.each([+ ['https://evil.example.com/collect', true],+ ['https://console.jumpcloud.com.evil.example.com/x', true],+ ['https://console.jumpcloud.com/api/systemusers', false],+ ['/systemusers', false],+ ])('custom API call only sends the key to JumpCloud (%s)', async (url, rejected) => {+ sendRequest.mockResolvedValue({ status: 200, body: {} });+ const action = jumpcloud.actions()['custom_api_call'];+ const pending = action.run(context<InputPropertyMap>({ url: { url }, method: HttpMethod.GET, headers: {}, queryParams: {}, body_type: 'none', body: {} }));++ if (rejected) {+ await expect(pending).rejects.toThrow('Custom API Call only sends this connection to https://console.jumpcloud.com');+ expect(sendRequest).not.toHaveBeenCalled();+ } else {+ await pending;+ expect(sendRequest.mock.calls[0][0].headers['x-api-key']).toBeDefined();+ }+ });++ it('registers every action and the custom API call', () => {+ expect(Object.keys(jumpcloud.actions())).toEqual([+ 'create_object',+ 'update_object',+ 'delete_object',+ 'get_object',+ 'list_objects',+ 'list_objects_by_id',+ 'search_objects',+ 'create_association',+ 'delete_association',+ 'find_user_by_employee_id',+ 'lock_user',+ 'unlock_user',+ 'reset_user_mfa',+ 'update_user_on_system',+ 'run_trigger_command',+ 'custom_api_call',+ ]);+ });++ it('tags every hand-written action for agents', () => {+ const actions = Object.values(jumpcloud.actions()).filter((action) => action.name !== 'custom_api_call');+ actions.forEach((action) => {+ expect(action.audience).toBe('both');+ expect(action.aiMetadata?.description?.length ?? 0).toBeGreaterThan(40);+ expect(typeof action.aiMetadata?.idempotent).toBe('boolean');+ expect(action.classification).toBeDefined();+ });+ });+});++describe('Get Object by ID', () => {+ it('fetches the object and returns it flattened', async () => {+ respond({ 'GET /systemusers/u1': { _id: 'u1', username: 'jdoe', email: '[email protected]' } });++ const result = await getObjectAction.run(context<typeof getObjectAction.props>({ objectType: 'user', objectId: ' u1 ' }));++ expect(result).toMatchObject({ id: 'u1', username: 'jdoe', email: '[email protected]' });+ });++ it('returns the full JumpCloud record under raw', async () => {+ const record = { _id: 'u1', username: 'jdoe', phoneNumbers: [{ type: 'work', number: '555-0100' }] };+ respond({ 'GET /systemusers/u1': record });++ const result = await getObjectAction.run(context<typeof getObjectAction.props>({ objectType: 'user', objectId: 'u1' }));++ expect(result).toMatchObject({ id: 'u1', raw: record });+ });++ it('explains a missing object', async () => {+ sendRequest.mockRejectedValue(new HttpError({}, { status: 404, responseBody: { message: 'Not Found' } }));++ await expect(getObjectAction.run(context<typeof getObjectAction.props>({ objectType: 'system', objectId: 's9' }))).rejects.toThrow(+ 'JumpCloud API error (HTTP 404): Not Found',+ );+ });+});++describe('Delete Object', () => {+ it('deletes through the v2 path for groups', async () => {+ respond({ 'DELETE /v2/usergroups/g1': '' });++ const result = await deleteObjectAction.run(context<typeof deleteObjectAction.props>({ objectType: 'user_group', objectId: 'g1' }));++ expect(result).toEqual({ id: 'g1', object_type: 'user_group', deleted: true });+ expect(lastRequest()).toMatchObject({ method: HttpMethod.DELETE, url: `${V2}/usergroups/g1` });+ });+});++describe('Create Object', () => {+ it('creates a user from trimmed fields merged over additional fields', async () => {+ respond({ 'POST /systemusers': { _id: 'u1', username: 'jdoe', email: '[email protected]', location: 'Remote' } });++ const result = await createObjectAction.run(+ context<typeof createObjectAction.props>({+ objectType: 'user',+ fields: { username: ' jdoe ', email: '[email protected]', firstname: '', jobTitle: 'Engineer' },+ additionalFields: { location: 'Remote', username: 'ignored' },+ }),+ );++ expect(lastRequest().body).toEqual({ location: 'Remote', username: 'jdoe', email: '[email protected]', jobTitle: 'Engineer' });+ expect(result).toMatchObject({ id: 'u1', username: 'jdoe' });+ });++ it('creates a bookmark application with an empty config by default', async () => {+ respond({ 'POST /applications': { _id: 'a1', displayLabel: 'Wiki' } });++ await createObjectAction.run(+ context<typeof createObjectAction.props>({+ objectType: 'application',+ fields: { displayLabel: 'Wiki', ssoUrl: 'https://wiki.example.com' },+ additionalFields: undefined,+ }),+ );++ expect(lastRequest().body).toEqual({ config: {}, displayLabel: 'Wiki', ssoUrl: 'https://wiki.example.com', name: 'bookmark' });+ });++ it('refuses to create systems', async () => {+ await expect(+ createObjectAction.run(context<typeof createObjectAction.props>({ objectType: 'system', fields: {}, additionalFields: undefined })),+ ).rejects.toThrow('cannot be created');+ });+});++describe('Update Object', () => {+ it('sends only the changed fields for users', async () => {+ respond({ 'PUT /systemusers/u1': { _id: 'u1', department: 'Finance' } });++ const result = await updateObjectAction.run(+ context<typeof updateObjectAction.props>({ objectType: 'user', objectId: 'u1', fields: { department: 'Finance' }, additionalFields: undefined }),+ );++ expect(sendRequest).toHaveBeenCalledTimes(1);+ expect(lastRequest()).toMatchObject({ method: HttpMethod.PUT, url: `${V1}/systemusers/u1`, body: { department: 'Finance' } });+ expect(result).toMatchObject({ id: 'u1', department: 'Finance' });+ });++ it('merges changes into the current group because the API replaces it', async () => {+ respond({+ 'GET /v2/systemgroups/g1': { id: 'g1', name: 'Macs', description: 'old', type: 'system_group', membershipMethod: 'STATIC' },+ 'PUT /v2/systemgroups/g1': { id: 'g1', name: 'Macs', description: 'new' },+ });++ await updateObjectAction.run(+ context<typeof updateObjectAction.props>({+ objectType: 'system_group',+ objectId: 'g1',+ fields: { description: 'new' },+ additionalFields: undefined,+ }),+ );++ expect(lastRequest()).toMatchObject({+ method: HttpMethod.PUT,+ url: `${V2}/systemgroups/g1`,+ body: { name: 'Macs', description: 'new', membershipMethod: 'STATIC' },+ });+ expect(lastRequest().body).not.toHaveProperty('id');+ expect(lastRequest().body).not.toHaveProperty('type');+ });++ it('requires at least one change', async () => {+ await expect(+ updateObjectAction.run(+ context<typeof updateObjectAction.props>({ objectType: 'user', objectId: 'u1', fields: { email: ' ' }, additionalFields: undefined }),+ ),+ ).rejects.toThrow('Fill in at least one field');+ expect(sendRequest).not.toHaveBeenCalled();+ });+});++describe('List Objects (Batch)', () => {+ it('returns flattened items with paging info', async () => {+ respond({ 'GET /systemusers': { totalCount: 3, results: [{ _id: 'u1' }, { _id: 'u2' }] } });++ const result = await listObjectsAction.run(context<typeof listObjectsAction.props>({ objectType: 'user', ...PAGING, limit: 2 }));++ expect(lastRequest().queryParams).toEqual({ limit: '2', skip: '0', sort: '_id' });+ expect(result).toMatchObject({ items: [{ id: 'u1' }, { id: 'u2' }], total_count: 3, next_skip: 2 });+ });+});++describe('List Objects by ID (Batch)', () => {+ it('uses one $in filter for v1 types and keeps the requested order', async () => {+ respond({ 'GET /systems': { totalCount: 2, results: [{ _id: 's2', hostname: 'b' }, { _id: 's1', hostname: 'a' }] } });++ const result = await listObjectsByIdAction.run(+ context<typeof listObjectsByIdAction.props>({ objectType: 'system', ids: ['s1', 's2', 's1', ' ', 's3'], ...PAGING }),+ );++ expect(lastRequest().queryParams).toEqual({ limit: '3', skip: '0', sort: '_id', filter: '_id:$in:s1|s2|s3' });+ expect(result).toMatchObject({ items: [{ id: 's1' }, { id: 's2' }], missing_ids: ['s3'], total_count: 3, next_skip: null });+ });++ it('pages over the ID list', async () => {+ respond({ 'GET /systemusers': { totalCount: 1, results: [{ _id: 'b' }] } });++ const result = await listObjectsByIdAction.run(+ context<typeof listObjectsByIdAction.props>({ objectType: 'user', ids: ['a', 'b', 'c'], ...PAGING, limit: 1, skip: 1 }),+ );++ expect(lastRequest().queryParams).toMatchObject({ filter: '_id:$in:b' });+ expect(result).toMatchObject({ total_count: 3, next_skip: 2, missing_ids: [] });+ });++ it('fetches v2 groups one by one and reports the ones not found', async () => {+ sendRequest.mockImplementation(async (request: Request) => {+ if (request.url === `${V2}/usergroups/g1`) {+ return { status: 200, body: { id: 'g1', name: 'Eng' } };+ }+ throw new HttpError({}, { status: 404, responseBody: {} });+ });++ const result = await listObjectsByIdAction.run(+ context<typeof listObjectsByIdAction.props>({ objectType: 'user_group', ids: ['g1', 'g2'], ...PAGING }),+ );++ expect(result).toMatchObject({ items: [{ id: 'g1', name: 'Eng' }], missing_ids: ['g2'] });+ });++ it('does not hide errors other than not found', async () => {+ sendRequest.mockRejectedValue(new HttpError({}, { status: 403, responseBody: {} }));++ await expect(+ listObjectsByIdAction.run(context<typeof listObjectsByIdAction.props>({ objectType: 'system_group', ids: ['g1'], ...PAGING })),+ ).rejects.toThrow('HTTP 403');+ });++ it('requires at least one ID', async () => {+ await expect(+ listObjectsByIdAction.run(context<typeof listObjectsByIdAction.props>({ objectType: 'user', ids: [' '], ...PAGING })),+ ).rejects.toThrow('Add at least one Object ID.');+ });+});++describe('Search Objects (Batch)', () => {+ const base = { searchText: undefined, filterField: undefined, filterOperator: 'equals', filterValue: undefined, ...PAGING };++ it('searches users by text through the search endpoint', async () => {+ respond({ 'POST /search/systemusers': { totalCount: 1, results: [{ _id: 'u1', username: 'jdoe' }] } });++ const result = await searchObjectsAction.run(context<typeof searchObjectsAction.props>({ ...base, objectType: 'user', searchText: 'jdoe' }));++ expect(lastRequest().body).toEqual({ searchFilter: { searchTerm: 'jdoe', fields: ['username', 'email', 'firstname', 'lastname', 'displayname'] } });+ expect(result).toMatchObject({ total_count: 1, next_skip: null });+ });++ it.each(FILTER_CASES)('filters %s with the %s operator of its API version', async (objectType, filterOperator, url, filter) => {+ sendRequest.mockResolvedValue({ status: 200, body: [] });++ await searchObjectsAction.run(+ context<typeof searchObjectsAction.props>({ ...base, objectType, filterField: 'department', filterOperator, filterValue: ' Fin ' }),+ );++ expect(lastRequest()).toMatchObject({ url, queryParams: { filter } });+ });++ it('pages application text search locally', async () => {+ respond({+ 'GET /applications': {+ totalCount: 3,+ results: [{ _id: 'a1', displayLabel: 'Slack A' }, { _id: 'a2', displayLabel: 'Zoom' }, { _id: 'a3', displayLabel: 'Slack B' }],+ },+ });++ const result = await searchObjectsAction.run(+ context<typeof searchObjectsAction.props>({ ...base, objectType: 'application', searchText: 'slack', limit: 1, skip: 1 }),+ );++ expect(result).toMatchObject({ items: [{ id: 'a3' }], total_count: 2, next_skip: null });+ });++ it('downloads the application list once when fetching every page of matches', async () => {+ sendRequest.mockImplementation(async (request: { queryParams?: Record<string, string> }) => {+ const skip = Number(request.queryParams?.['skip']);+ const count = Math.max(0, Math.min(100, 250 - skip));+ const results = Array.from({ length: count }, (_, index) => ({ _id: `a${skip + index}`, displayLabel: `Slack ${skip + index}` }));+ return { status: 200, body: { totalCount: 250, results } };+ });++ const result = await searchObjectsAction.run(+ context<typeof searchObjectsAction.props>({ ...base, objectType: 'application', searchText: 'slack', fetchAll: true, maxItems: 1000 }),+ );++ expect(result.items).toHaveLength(250);+ expect(sendRequest).toHaveBeenCalledTimes(3);+ });++ it.each([+ [{ searchText: 'a', filterField: 'b', filterValue: 'c' }, 'not both'],+ [{ filterField: 'department' }, 'Enter a Filter Value'],+ [{}, 'Enter Search Text'],+ [{ filterField: 'department', filterValue: 'x', filterOperator: 'like' }, 'Unknown Filter Operator'],+ ])('validates the inputs %o', async (input, message) => {+ await expect(searchObjectsAction.run(context<typeof searchObjectsAction.props>({ ...base, objectType: 'user', ...input }))).rejects.toThrow(+ message,+ );+ expect(sendRequest).not.toHaveBeenCalled();+ });+});++function context<Props extends InputPropertyMap>(propsValue: StaticPropsValue<Props>) {+ return { ...createMockActionContext<Props>({ propsValue }), auth: CONNECTION };+}++function respond(routes: Record<string, unknown>): void {+ sendRequest.mockImplementation(async (request: Request) => {+ const path = request.url.replace(V1, '');+ const key = `${request.method} ${path}`;+ if (!(key in routes)) {+ throw new Error(`Unexpected request ${key}`);+ }+ return { status: 200, body: routes[key] };+ });+}++function lastRequest(): Request {+ return sendRequest.mock.calls[sendRequest.mock.calls.length - 1][0];+}++const FILTER_CASES: [ObjectTypeKey, string, string, string][] = [+ ['user', 'starts_with', `${V1}/systemusers`, 'department:$sw:Fin'],+ ['user_group', 'starts_with', `${V2}/usergroups`, 'department:search:Fin'],+ ['application', 'greater_or_equal', `${V1}/applications`, 'department:$gte:Fin'],+ ['system_group', 'in', `${V2}/systemgroups`, 'department:in:Fin'],+];++const CONNECTION: AppConnectionValueForAuthProperty<typeof jumpcloudAuth> = {+ type: AppConnectionType.CUSTOM_AUTH,+ props: { apiKey: 'key', region: 'us', orgId: undefined },+};++type Request = {+ method: string;+ url: string;+ body?: unknown;+ queryParams?: Record<string, string>;+};diff --git a/packages/pieces/community/jumpcloud/test/client.test.ts b/packages/pieces/community/jumpcloud/test/client.test.tsnew file mode 100644index 00000000000..85bae6aeff4--- /dev/null+++ b/packages/pieces/community/jumpcloud/test/client.test.ts@@ -0,0 +1,122 @@+import { HttpError, httpClient, HttpMethod } from '@activepieces/pieces-common';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { JUMPCLOUD_REGION, jumpcloudApi } from '../src/lib/common/client';++const sendRequest = vi.fn();++beforeEach(() => {+ sendRequest.mockReset();+ vi.spyOn(httpClient, 'sendRequest').mockImplementation((request) => sendRequest(request));+});++afterEach(() => {+ vi.restoreAllMocks();+});++describe('resolveBaseUrl', () => {+ it.each([+ [JUMPCLOUD_REGION.US, 'https://console.jumpcloud.com/api'],+ [JUMPCLOUD_REGION.EU, 'https://console.eu.jumpcloud.com/api'],+ [JUMPCLOUD_REGION.IN, 'https://console.in.jumpcloud.com/api'],+ [undefined, 'https://console.jumpcloud.com/api'],+ ['unknown', 'https://console.jumpcloud.com/api'],+ ])('maps region %s to %s', (region, expected) => {+ expect(jumpcloudApi.resolveBaseUrl({ region })).toBe(expected);+ });+});++describe('authHeaders', () => {+ it('sends the trimmed API key without an org header by default', () => {+ expect(jumpcloudApi.authHeaders({ apiKey: ' key ' })).toEqual({ 'x-api-key': 'key', Accept: 'application/json' });+ });++ it('adds x-org-id when an organization ID is set', () => {+ expect(jumpcloudApi.authHeaders({ apiKey: 'key', orgId: ' org-1 ' })).toEqual({+ 'x-api-key': 'key',+ Accept: 'application/json',+ 'x-org-id': 'org-1',+ });+ });++ it('skips a blank organization ID', () => {+ expect(jumpcloudApi.authHeaders({ apiKey: 'key', orgId: ' ' })).not.toHaveProperty('x-org-id');+ });+});++describe('describeError', () => {+ it('adds the API message and a hint for known statuses', () => {+ const error = new HttpError({}, { status: 401, responseBody: { message: 'Unauthorized' } });+ expect(jumpcloudApi.describeError(error)).toBe(+ 'JumpCloud API error (HTTP 401): Unauthorized. Check the API key in the connection. In the JumpCloud Admin Portal, open your account menu and choose My API Key.',+ );+ });++ it('reads nested and string error bodies', () => {+ expect(jumpcloudApi.describeError(new HttpError({}, { status: 500, responseBody: { error: { message: 'boom' } } }))).toBe(+ 'JumpCloud API error (HTTP 500): boom',+ );+ expect(jumpcloudApi.describeError(new HttpError({}, { status: 500, responseBody: '{"error":"bad"}' }))).toBe(+ 'JumpCloud API error (HTTP 500): bad',+ );+ expect(jumpcloudApi.describeError(new HttpError({}, { status: 502, responseBody: 'Bad Gateway' }))).toBe(+ 'JumpCloud API error (HTTP 502): Bad Gateway',+ );+ });++ it('omits the detail when the body has no message', () => {+ expect(jumpcloudApi.describeError(new HttpError({}, { status: 429, responseBody: {} }))).toBe(+ 'JumpCloud API error (HTTP 429). JumpCloud is rate-limiting requests. Wait a minute and run the step again.',+ );+ });++ it('drops HTML error pages', () => {+ expect(jumpcloudApi.describeError(new HttpError({}, { status: 404, responseBody: '<html><body>404 Not Found</body></html>' }))).toBe(+ 'JumpCloud API error (HTTP 404). Check that the object exists, and that the connection region is correct.',+ );+ });++ it('explains network failures', () => {+ const refused = new TypeError('fetch failed', { cause: { code: 'ECONNREFUSED' } });+ expect(jumpcloudApi.describeError(refused)).toBe(+ 'Could not reach the JumpCloud API (ECONNREFUSED). Check the connection region and your network.',+ );+ expect(jumpcloudApi.describeError(new TypeError('fetch failed'))).toContain('Could not reach the JumpCloud API (fetch failed)');+ });++ it('passes through other errors', () => {+ expect(jumpcloudApi.describeError(new Error('boom'))).toBe('boom');+ expect(jumpcloudApi.describeError('boom')).toBe('boom');+ });+});++describe('validateConnection', () => {+ it('calls the users endpoint of the selected region with the connection headers', async () => {+ sendRequest.mockResolvedValue({ status: 200, body: { totalCount: 0, results: [] } });++ const result = await jumpcloudApi.validateConnection({ apiKey: 'key', region: JUMPCLOUD_REGION.EU, orgId: 'org-1' });++ expect(result).toEqual({ valid: true });+ expect(sendRequest).toHaveBeenCalledWith({+ method: HttpMethod.GET,+ url: 'https://console.eu.jumpcloud.com/api/systemusers',+ headers: { 'x-api-key': 'key', Accept: 'application/json', 'x-org-id': 'org-1' },+ queryParams: { limit: '1' },+ });+ });++ it('returns an actionable error for a rejected key', async () => {+ sendRequest.mockRejectedValue(new HttpError({}, { status: 401, responseBody: { message: 'Unauthorized' } }));++ const result = await jumpcloudApi.validateConnection({ apiKey: 'bad', region: JUMPCLOUD_REGION.US });++ expect(result).toEqual({ valid: false, error: expect.stringContaining('HTTP 401') });+ });++ it('returns an actionable error when JumpCloud is unreachable', async () => {+ sendRequest.mockRejectedValue(new TypeError('fetch failed', { cause: { code: 'ENOTFOUND' } }));++ const result = await jumpcloudApi.validateConnection({ apiKey: 'key', region: JUMPCLOUD_REGION.IN });++ expect(result).toEqual({ valid: false, error: expect.stringContaining('Could not reach the JumpCloud API (ENOTFOUND)') });+ });+});diff --git a/packages/pieces/community/jumpcloud/test/common.test.ts b/packages/pieces/community/jumpcloud/test/common.test.tsnew file mode 100644index 00000000000..ba527d7d178--- /dev/null+++ b/packages/pieces/community/jumpcloud/test/common.test.ts@@ -0,0 +1,385 @@+import { HttpError, httpClient, HttpMethod } from '@activepieces/pieces-common';+import { AppConnectionType, AppConnectionValueForAuthProperty, createMockActionContext, PropertyContext } from '@activepieces/pieces-framework';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { jumpcloudAuth } from '../src/lib/auth';+import { jumpcloudApi } from '../src/lib/common/client';+import { jumpcloudFields } from '../src/lib/common/fields';+import { jumpcloudObjects } from '../src/lib/common/objects';+import { jumpcloudOutput } from '../src/lib/common/output';+import { jumpcloudProps } from '../src/lib/common/props';+import { ListPage, PageRequest } from '../src/lib/common/types';++const sendRequest = vi.fn();++const AUTH = { apiKey: 'key', region: 'us', orgId: undefined };+const V1 = 'https://console.jumpcloud.com/api';+const V2 = 'https://console.jumpcloud.com/api/v2';+const HEADERS = { 'x-api-key': 'key', Accept: 'application/json' };++beforeEach(() => {+ sendRequest.mockReset();+ vi.spyOn(httpClient, 'sendRequest').mockImplementation((request) => sendRequest(request));+});++afterEach(() => {+ vi.restoreAllMocks();+});++describe('send', () => {+ it('builds v1 and v2 URLs with the connection headers', async () => {+ sendRequest.mockResolvedValue({ status: 200, body: { ok: true } });++ await jumpcloudApi.send({ auth: AUTH, method: HttpMethod.GET, path: '/systemusers/u1' });+ await jumpcloudApi.send({ auth: AUTH, method: HttpMethod.POST, path: '/usergroups', version: 'v2', body: { name: 'Eng' } });++ expect(sendRequest).toHaveBeenNthCalledWith(1, { method: HttpMethod.GET, url: `${V1}/systemusers/u1`, headers: HEADERS });+ expect(sendRequest).toHaveBeenNthCalledWith(2, {+ method: HttpMethod.POST,+ url: `${V2}/usergroups`,+ headers: HEADERS,+ body: { name: 'Eng' },+ });+ });++ it('turns API failures into actionable errors', async () => {+ sendRequest.mockRejectedValue(new HttpError({}, { status: 404, responseBody: { message: 'user not found' } }));++ await expect(jumpcloudApi.send({ auth: AUTH, method: HttpMethod.GET, path: '/systemusers/missing' })).rejects.toThrow(+ 'JumpCloud API error (HTTP 404): user not found. Check that the object exists, and that the connection region is correct.',+ );+ });+});++describe('fetchListPage', () => {+ it('reads v1 results with their total count', async () => {+ sendRequest.mockResolvedValue({ status: 200, body: { totalCount: 3, results: [{ _id: 'a' }, 'junk', { _id: 'b' }] } });++ const page = await jumpcloudApi.fetchListPage({ auth: AUTH, method: HttpMethod.GET, path: '/systemusers' });++ expect(page).toEqual({ items: [{ _id: 'a' }, { _id: 'b' }], totalCount: 3 });+ });++ it('reads v2 plain arrays without a total count', async () => {+ sendRequest.mockResolvedValue({ status: 200, body: [{ id: 'g1' }] });++ const page = await jumpcloudApi.fetchListPage({ auth: AUTH, method: HttpMethod.GET, path: '/usergroups', version: 'v2' });++ expect(page).toEqual({ items: [{ id: 'g1' }] });+ });++ it('ignores a negative total count', async () => {+ sendRequest.mockResolvedValue({ status: 200, body: { totalCount: -1, results: [] } });++ expect(await jumpcloudApi.fetchListPage({ auth: AUTH, method: HttpMethod.GET, path: '/systemusers' })).toEqual({ items: [] });+ });++ it('rejects an unexpected body', async () => {+ sendRequest.mockResolvedValue({ status: 200, body: { foo: 'bar' } });++ await expect(jumpcloudApi.fetchListPage({ auth: AUTH, method: HttpMethod.GET, path: '/systemusers' })).rejects.toThrow(+ 'unexpected list response',+ );+ });+});++describe('collectPages', () => {+ it('returns one page and the next skip when more objects exist', async () => {+ const fetchPage = pagesOf({ total: 250, withTotalCount: true });++ const result = await jumpcloudApi.collectPages({ fetchPage, limit: 20, skip: 40 });++ expect(fetchPage).toHaveBeenCalledTimes(1);+ expect(fetchPage).toHaveBeenCalledWith({ limit: 20, skip: 40 });+ expect(result.items.map((item) => item['_id'])).toEqual(range(40, 60));+ expect(result).toMatchObject({ total_count: 250, next_skip: 60 });+ });++ it('stops at the end of the collection', async () => {+ const result = await jumpcloudApi.collectPages({ fetchPage: pagesOf({ total: 5, withTotalCount: true }), limit: 50 });++ expect(result.items).toHaveLength(5);+ expect(result).toMatchObject({ total_count: 5, next_skip: null });+ });++ it('fetches every page up to the end when Fetch All Pages is on', async () => {+ const fetchPage = pagesOf({ total: 230, withTotalCount: false });++ const result = await jumpcloudApi.collectPages({ fetchPage, fetchAll: true, maxItems: 1000 });++ expect(fetchPage.mock.calls.map(([page]) => page)).toEqual([+ { limit: 100, skip: 0 },+ { limit: 100, skip: 100 },+ { limit: 100, skip: 200 },+ ]);+ expect(result.items).toHaveLength(230);+ expect(result).toEqual(expect.objectContaining({ total_count: null, next_skip: null }));+ });++ it('stops at Max Objects and reports where to continue', async () => {+ const fetchPage = pagesOf({ total: 1000, withTotalCount: true });++ const result = await jumpcloudApi.collectPages({ fetchPage, fetchAll: true, maxItems: 150 });++ expect(fetchPage.mock.calls.map(([page]) => page)).toEqual([+ { limit: 100, skip: 0 },+ { limit: 50, skip: 100 },+ ]);+ expect(result).toMatchObject({ total_count: 1000, next_skip: 150 });+ expect(result.items).toHaveLength(150);+ });++ it('clamps out-of-range inputs', async () => {+ const fetchPage = pagesOf({ total: 1000, withTotalCount: true });++ await jumpcloudApi.collectPages({ fetchPage, limit: 5000, skip: -3 });+ await jumpcloudApi.collectPages({ fetchPage, limit: 0 });+ await jumpcloudApi.collectPages({ fetchPage, limit: Number.NaN });++ expect(fetchPage.mock.calls.map(([page]) => page)).toEqual([+ { limit: 100, skip: 0 },+ { limit: 1, skip: 0 },+ { limit: 50, skip: 0 },+ ]);+ });+});++describe('objects', () => {+ it('lists only creatable types when asked', () => {+ expect(jumpcloudObjects.typeOptions({ creatableOnly: false }).map((option) => option.value)).toEqual([+ 'user',+ 'system',+ 'user_group',+ 'system_group',+ 'application',+ ]);+ expect(jumpcloudObjects.typeOptions({ creatableOnly: true }).map((option) => option.value)).not.toContain('system');+ });++ it('parses object types and rejects unknown ones', () => {+ expect(jumpcloudObjects.parseType('system')).toBe('system');+ expect(() => jumpcloudObjects.parseType('printer')).toThrow('Select a valid Object Type');+ });++ it('guards object type values', () => {+ expect(jumpcloudObjects.isObjectType('user_group')).toBe(true);+ expect(jumpcloudObjects.isObjectType('toString')).toBe(false);+ expect(jumpcloudObjects.isObjectType(undefined)).toBe(false);+ });++ it('builds item paths and rejects a blank ID', () => {+ expect(jumpcloudObjects.itemPath({ type: 'system_group', id: ' a/b ' })).toBe('/systemgroups/a%2Fb');+ expect(() => jumpcloudObjects.itemPath({ type: 'user', id: ' ' })).toThrow('Select or enter the User ID.');+ });++ it('reads the ID field of each type', () => {+ expect(jumpcloudObjects.readId({ type: 'user', record: { _id: 'u1', id: 'x' } })).toBe('u1');+ expect(jumpcloudObjects.readId({ type: 'user_group', record: { _id: 'x', id: 'g1' } })).toBe('g1');+ expect(jumpcloudObjects.readId({ type: 'application', record: {} })).toBeNull();+ });++ it('lists with a stable sort and an optional filter', async () => {+ sendRequest.mockResolvedValue({ status: 200, body: [] });++ await jumpcloudObjects.listPage({ auth: AUTH, type: 'user_group', page: { limit: 10, skip: 20 }, filter: 'name:eq:Eng' });+ await jumpcloudObjects.listPage({ auth: AUTH, type: 'system', page: { limit: 5, skip: 0 } });++ expect(sendRequest).toHaveBeenNthCalledWith(1, {+ method: HttpMethod.GET,+ url: `${V2}/usergroups`,+ headers: HEADERS,+ queryParams: { limit: '10', skip: '20', sort: 'name', filter: 'name:eq:Eng' },+ });+ expect(sendRequest).toHaveBeenNthCalledWith(2, {+ method: HttpMethod.GET,+ url: `${V1}/systems`,+ headers: HEADERS,+ queryParams: { limit: '5', skip: '0', sort: '_id' },+ });+ });++ it('searches users and systems through the search endpoints', async () => {+ sendRequest.mockResolvedValue({ status: 200, body: { totalCount: 0, results: [] } });++ await jumpcloudObjects.searchPage({ auth: AUTH, type: 'user', term: ' jane ', page: { limit: 50, skip: 0 } });++ expect(sendRequest).toHaveBeenCalledWith({+ method: HttpMethod.POST,+ url: `${V1}/search/systemusers`,+ headers: HEADERS,+ queryParams: { limit: '50', skip: '0' },+ body: { searchFilter: { searchTerm: 'jane', fields: ['username', 'email', 'firstname', 'lastname', 'displayname'] } },+ });+ });++ it('searches groups with the v2 search filter', async () => {+ sendRequest.mockResolvedValue({ status: 200, body: [] });++ await jumpcloudObjects.searchPage({ auth: AUTH, type: 'system_group', term: 'mac', page: { limit: 50, skip: 0 } });++ expect(sendRequest.mock.calls[0][0]).toMatchObject({ url: `${V2}/systemgroups`, queryParams: { filter: 'name:search:mac' } });+ });++ it('filters applications locally, ignoring case', async () => {+ sendRequest.mockResolvedValue({+ status: 200,+ body: { totalCount: 2, results: [{ _id: 'a1', displayLabel: 'Slack' }, { _id: 'a2', displayLabel: 'Zoom' }] },+ });++ const page = await jumpcloudObjects.searchPage({ auth: AUTH, type: 'application', term: 'sla', page: { limit: 50, skip: 0 } });++ expect(page.items).toEqual([{ _id: 'a1', displayLabel: 'Slack' }]);+ expect(sendRequest.mock.calls[0][0].queryParams).toEqual({ limit: '100', skip: '0', sort: 'displayLabel' });+ });++ it('searches every application page, not only the first thousand', async () => {+ sendRequest.mockImplementation(async (request: { queryParams?: Record<string, string> }) => {+ const skip = Number(request.queryParams?.['skip']);+ const count = Math.max(0, Math.min(100, 1201 - skip));+ const results = Array.from({ length: count }, (_, index) => {+ const position = skip + index;+ return position === 1200 ? { _id: 'late', displayLabel: 'Slack' } : { _id: `a${position}`, displayLabel: `App ${position}` };+ });+ return { status: 200, body: { totalCount: 1201, results } };+ });++ const page = await jumpcloudObjects.searchPage({ auth: AUTH, type: 'application', term: 'slack', page: { limit: 50, skip: 0 } });++ expect(page).toEqual({ items: [{ _id: 'late', displayLabel: 'Slack' }], totalCount: 1 });+ });++ it('lists by picker sort when the search term is empty', async () => {+ sendRequest.mockResolvedValue({ status: 200, body: { totalCount: 0, results: [] } });++ await jumpcloudObjects.searchPage({ auth: AUTH, type: 'user', term: ' ', page: { limit: 50, skip: 0 } });++ expect(sendRequest.mock.calls[0][0]).toMatchObject({ method: HttpMethod.GET, url: `${V1}/systemusers`, queryParams: { sort: 'username' } });+ });++ it.each([+ ['user', { _id: 'u1', firstname: 'Jane', lastname: 'Doe', email: '[email protected]' }, 'Jane Doe ([email protected])'],+ ['user', { _id: 'u1', displayname: 'JD', username: 'jdoe' }, 'JD'],+ ['user', { _id: 'u1', username: 'jdoe' }, 'jdoe'],+ ['system', { _id: 's1', hostname: 'mac-01', os: 'Mac OS X' }, 'mac-01 (Mac OS X)'],+ ['system', { _id: 's1' }, 's1'],+ ['user_group', { id: 'g1', name: 'Engineering' }, 'Engineering'],+ ['application', { _id: 'a1', name: 'slack', displayLabel: 'Slack' }, 'Slack'],+ ] as const)('labels a %s as %s', (type, record, label) => {+ expect(jumpcloudObjects.optionLabel({ type, record })).toBe(label);+ });+});++describe('fields', () => {+ it('lets typed fields win over additional fields and drops blanks', () => {+ expect(+ jumpcloudFields.buildChanges({+ type: 'user',+ fields: { username: ' jdoe ', email: '', unknown: 'x' },+ additionalFields: '{"username": "other", "location": "Remote"}',+ }),+ ).toEqual({ username: 'jdoe', location: 'Remote' });+ });++ it.each([+ ['not json', 'not valid JSON'],+ ['[1, 2]', 'must be a JSON object'],+ [[1, 2], 'must be a JSON object'],+ ])('rejects Additional Fields %s', (additionalFields, message) => {+ expect(() => jumpcloudFields.buildChanges({ type: 'user_group', fields: { name: 'Eng' }, additionalFields })).toThrow(message);+ });++ it('drops read-only keys before a full replace', () => {+ expect(+ jumpcloudFields.mergeForReplace({+ type: 'application',+ current: { _id: 'a1', created: 'x', organization: 'o', name: 'bookmark', config: {}, displayLabel: 'Old' },+ changes: { displayLabel: 'New' },+ }),+ ).toEqual({ name: 'bookmark', config: {}, displayLabel: 'New' });+ });+});++describe('output', () => {+ it('flattens a user with consistent keys', () => {+ const flat = jumpcloudOutput.flatten({+ type: 'user',+ record: { _id: 'u1', username: 'jdoe', email: '[email protected]', account_locked: false, mfa: { configured: true }, employeeIdentifier: 'E1' },+ });++ expect(flat).toMatchObject({ id: 'u1', username: 'jdoe', account_locked: false, mfa_configured: true, employee_id: 'E1', department: null });+ expect(Object.keys(jumpcloudOutput.flatten({ type: 'user', record: {} }))).toEqual(Object.keys(flat));+ });++ it('flattens systems, groups and applications', () => {+ expect(jumpcloudOutput.flatten({ type: 'system', record: { _id: 's1', hostname: 'mac', active: true } })).toMatchObject({+ id: 's1',+ hostname: 'mac',+ active: true,+ serial_number: null,+ });+ expect(jumpcloudOutput.flatten({ type: 'system_group', record: { id: 'g1', name: 'Macs', membershipMethod: 'STATIC' } })).toEqual({+ id: 'g1',+ name: 'Macs',+ description: null,+ email: null,+ type: null,+ membership_method: 'STATIC',+ });+ expect(jumpcloudOutput.flatten({ type: 'application', record: { _id: 'a1', displayLabel: 'Slack' } })).toMatchObject({+ id: 'a1',+ display_label: 'Slack',+ });+ });+});++describe('objectId dropdown', () => {+ const dropdown = jumpcloudProps.objectId();++ it('asks for a connection and a type first', async () => {+ expect(await dropdown.options({ auth: undefined, objectType: 'user' }, propertyContext())).toMatchObject({+ disabled: true,+ placeholder: 'Connect your JumpCloud account first.',+ });+ expect(await dropdown.options({ auth: CONNECTION, objectType: undefined }, propertyContext())).toMatchObject({+ disabled: true,+ placeholder: 'Select an object type first.',+ });+ });++ it('offers labelled options from a search', async () => {+ sendRequest.mockResolvedValue({ status: 200, body: { totalCount: 1, results: [{ _id: 'u1', username: 'jdoe', email: '[email protected]' }, { foo: 1 }] } });++ const state = await dropdown.options({ auth: CONNECTION, objectType: 'user' }, propertyContext('jd'));++ expect(state).toEqual({ disabled: false, options: [{ label: 'jdoe ([email protected])', value: 'u1' }], placeholder: undefined });+ expect(sendRequest.mock.calls[0][0].url).toBe(`${V1}/search/systemusers`);+ });++ it('shows the API error instead of failing', async () => {+ sendRequest.mockRejectedValue(new HttpError({}, { status: 401, responseBody: {} }));++ const state = await dropdown.options({ auth: CONNECTION, objectType: 'user_group' }, propertyContext());++ expect(state).toMatchObject({ disabled: true, options: [], placeholder: expect.stringContaining('HTTP 401') });+ });+});++function pagesOf({ total, withTotalCount }: { total: number; withTotalCount: boolean }) {+ return vi.fn(async ({ limit, skip }: PageRequest): Promise<ListPage> => {+ const items = range(skip, Math.min(total, skip + limit)).map((index) => ({ _id: index }));+ return withTotalCount ? { items, totalCount: total } : { items };+ });+}++function range(start: number, end: number): number[] {+ return Array.from({ length: Math.max(0, end - start) }, (_, index) => start + index);+}++function propertyContext(searchValue?: string): PropertyContext {+ const { server, project, flows, connections } = createMockActionContext({ propsValue: {} });+ return { server, project, flows, connections, searchValue };+}++const CONNECTION: AppConnectionValueForAuthProperty<typeof jumpcloudAuth> = {+ type: AppConnectionType.CUSTOM_AUTH,+ props: { apiKey: 'key', region: 'us', orgId: undefined },+};diff --git a/packages/pieces/community/jumpcloud/test/trigger.test.ts b/packages/pieces/community/jumpcloud/test/trigger.test.tsnew file mode 100644index 00000000000..f8f514b3e46--- /dev/null+++ b/packages/pieces/community/jumpcloud/test/trigger.test.ts@@ -0,0 +1,234 @@+import { httpClient } from '@activepieces/pieces-common';+import {+ AppConnectionType,+ AppConnectionValueForAuthProperty,+ createMockActionContext,+ createMockPollingTriggerContext,+ InputPropertyMap,+ StaticPropsValue,+ TriggerStrategy,+} from '@activepieces/pieces-framework';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { jumpcloud } from '../src';+import { jumpcloudAuth } from '../src/lib/auth';+import { jumpcloudObjects } from '../src/lib/common/objects';+import { jumpcloudOutput } from '../src/lib/common/output';+import { newObjectTrigger } from '../src/lib/triggers/new-object';++const sendRequest = vi.fn();++const V1 = 'https://console.jumpcloud.com/api';+const V2 = 'https://console.jumpcloud.com/api/v2';+const LAST_POLL = Date.parse('2026-10-06T12:00:00.000Z');++beforeEach(() => {+ sendRequest.mockReset();+ vi.spyOn(httpClient, 'sendRequest').mockImplementation((request) => sendRequest(request));+});++afterEach(() => {+ vi.restoreAllMocks();+});++describe('createdAt', () => {+ it('reads the created timestamp', () => {+ expect(jumpcloudObjects.createdAt({ type: 'user', record: { _id: 'x', created: '2026-10-06T12:00:01.500Z' } })).toBe(LAST_POLL + 1500);+ });++ it('falls back to the time inside the object ID', () => {+ const seconds = Math.floor(LAST_POLL / 1000) + 30;+ expect(jumpcloudObjects.createdAt({ type: 'user_group', record: { id: objectId(seconds) } })).toBe(seconds * 1000);+ });++ it('gives up without a usable timestamp or ID', () => {+ expect(jumpcloudObjects.createdAt({ type: 'user_group', record: { id: 'not-an-object-id' } })).toBeNull();+ expect(jumpcloudObjects.createdAt({ type: 'user', record: { _id: 'u1', created: 'yesterday' } })).toBeNull();+ });+});++describe('New Object trigger', () => {+ it('is registered and tagged for agents', () => {+ expect(Object.keys(jumpcloud.triggers())).toEqual(['new_object']);+ expect(newObjectTrigger.classification).toBe('READ');+ expect(newObjectTrigger.aiMetadata?.description?.length ?? 0).toBeGreaterThan(40);+ });++ it('emits only users created since the checkpoint, newest first', async () => {+ sendRequest.mockResolvedValue({+ status: 200,+ body: {+ totalCount: 3,+ results: [user('u3', LAST_POLL + 2000), user('u2', LAST_POLL + 1000), user('u1', LAST_POLL - 1000)],+ },+ });+ const store = memoryStore({ checkpoint: createdCheckpoint({ type: 'user', since: LAST_POLL }) });++ const result = await pollingTrigger().run(triggerContext<typeof newObjectTrigger.props>({ propsValue: { objectType: 'user' }, store }));++ expect(sendRequest.mock.calls[0][0]).toMatchObject({ url: `${V1}/systemusers`, queryParams: { sort: '-created', skip: '0', limit: '100' } });+ expect(sendRequest).toHaveBeenCalledTimes(1);+ expect(result).toEqual([+ expect.objectContaining({ object_type: 'user', id: 'u3' }),+ expect.objectContaining({ object_type: 'user', id: 'u2' }),+ ]);+ expect(store.data.get('checkpoint')).toEqual(createdCheckpoint({ type: 'user', since: LAST_POLL + 2000, boundaryIds: ['u3'] }));+ });++ it('pages through every new object without a cap', async () => {+ const total = 1250;+ sendRequest.mockImplementation(async (request: Request) => {+ const skip = Number(request.queryParams?.['skip']);+ const count = Math.max(0, Math.min(100, total + 1 - skip));+ const page = Array.from({ length: count }, (_, index) => {+ const position = skip + index;+ return position === total ? user('old', LAST_POLL - 1000) : user(`u${position}`, LAST_POLL + 100000 - position);+ });+ return { status: 200, body: { totalCount: total + 1, results: page } };+ });++ const result = await pollingTrigger().run(+ triggerContext<typeof newObjectTrigger.props>({ propsValue: { objectType: 'system' }, store: memoryStore({ checkpoint: createdCheckpoint({ type: 'system', since: LAST_POLL }) }) }),+ );++ expect(sendRequest).toHaveBeenCalledTimes(13);+ expect(result).toHaveLength(total);+ });++ it('emits an object created in the same millisecond as the checkpoint once', async () => {+ sendRequest.mockResolvedValue({ status: 200, body: { totalCount: 2, results: [user('u2', LAST_POLL), user('u1', LAST_POLL)] } });+ const store = memoryStore({ checkpoint: createdCheckpoint({ type: 'user', since: LAST_POLL, boundaryIds: ['u1'] }) });+ const context = triggerContext<typeof newObjectTrigger.props>({ propsValue: { objectType: 'user' }, store });++ expect(await pollingTrigger().run(context)).toEqual([expect.objectContaining({ id: 'u2' })]);+ expect(store.data.get('checkpoint')).toEqual(createdCheckpoint({ type: 'user', since: LAST_POLL, boundaryIds: ['u1', 'u2'] }));+ expect(await pollingTrigger().run(context)).toEqual([]);+ });++ it('detects new groups by ID, including several created in the same second', async () => {+ const seconds = Math.floor(LAST_POLL / 1000);+ const groups = [+ { id: objectId(seconds), name: 'Old' },+ { id: `${objectId(seconds).slice(0, 23)}1`, name: 'Same second' },+ { id: objectId(seconds - 60), name: 'Older' },+ ];+ sendRequest.mockResolvedValue({ status: 200, body: groups });+ const store = memoryStore({ checkpoint: { kind: 'ids', type: 'user_group', ids: [groups[0].id] } });++ const result = await pollingTrigger().run(triggerContext<typeof newObjectTrigger.props>({ propsValue: { objectType: 'user_group' }, store }));++ expect(sendRequest.mock.calls[0][0]).toMatchObject({ url: `${V2}/usergroups`, queryParams: { sort: 'name' } });+ expect(result).toEqual([+ expect.objectContaining({ object_type: 'user_group', name: 'Same second' }),+ expect.objectContaining({ object_type: 'user_group', name: 'Older' }),+ ]);+ expect(store.data.get('checkpoint')).toEqual({ kind: 'ids', type: 'user_group', ids: groups.map((group) => group.id) });+ });++ it('snapshots existing groups when enabled and emits nothing', async () => {+ sendRequest.mockResolvedValue({ status: 200, body: [{ id: 'g1', name: 'Existing' }] });+ const store = memoryStore();++ await pollingTrigger().onEnable(triggerContext<typeof newObjectTrigger.props>({ propsValue: { objectType: 'system_group' }, store }));++ expect(store.data.get('checkpoint')).toEqual({ kind: 'ids', type: 'system_group', ids: ['g1'] });+ });++ it('starts from now when enabled and keeps the checkpoint on republish', async () => {+ const store = memoryStore();+ await pollingTrigger().onEnable(triggerContext<typeof newObjectTrigger.props>({ propsValue: { objectType: 'user' }, store }));+ const first = store.data.get('checkpoint');++ expect(first).toEqual(expect.objectContaining({ kind: 'created', type: 'user', boundaryIds: [] }));+ expect(sendRequest).not.toHaveBeenCalled();++ await pollingTrigger().onDisable(triggerContext<typeof newObjectTrigger.props>({ propsValue: { objectType: 'user' }, store }));+ expect(store.data.get('checkpoint')).toEqual(first);++ await pollingTrigger().onEnable({ ...triggerContext<typeof newObjectTrigger.props>({ propsValue: { objectType: 'user' }, store }), isRepublish: true });+ expect(store.data.get('checkpoint')).toEqual(first);+ });++ it('emits objects created between the last poll and a republish', async () => {+ const store = memoryStore({ checkpoint: createdCheckpoint({ type: 'user', since: LAST_POLL }) });+ const props = { propsValue: { objectType: 'user' }, store };++ await pollingTrigger().onDisable(triggerContext<typeof newObjectTrigger.props>(props));+ await pollingTrigger().onEnable({ ...triggerContext<typeof newObjectTrigger.props>(props), isRepublish: true });+ sendRequest.mockResolvedValue({ status: 200, body: { totalCount: 1, results: [user('u9', LAST_POLL + 5000)] } });++ expect(await pollingTrigger().run(triggerContext<typeof newObjectTrigger.props>(props))).toEqual([expect.objectContaining({ id: 'u9' })]);+ });++ it('returns up to five recent objects when testing', async () => {+ sendRequest.mockResolvedValue({+ status: 200,+ body: { totalCount: 7, results: Array.from({ length: 7 }, (_, index) => user(`u${index}`, LAST_POLL - index * 1000)) },+ });++ const result = await pollingTrigger().test(triggerContext<typeof newObjectTrigger.props>({ propsValue: { objectType: 'user' }, store: memoryStore() }));++ expect(result).toHaveLength(5);+ expect(result[0]).toMatchObject({ id: 'u0' });+ });++ it('keeps the sample data in the shape of a user output', () => {+ expect(Object.keys(newObjectTrigger.sampleData ?? {})).toEqual([+ 'object_type',+ ...Object.keys(jumpcloudOutput.flatten({ type: 'user', record: {} })),+ ]);+ });+});++function pollingTrigger() {+ const trigger = newObjectTrigger;+ if (trigger.type !== TriggerStrategy.POLLING) {+ throw new Error('expected a polling trigger');+ }+ return trigger;+}++function user(id: string, epochMs: number) {+ return { _id: id, username: id, created: new Date(epochMs).toISOString() };+}++function createdCheckpoint({ type, since, boundaryIds = [] }: { type: string; since: number; boundaryIds?: string[] }) {+ return { kind: 'created', type, since, boundaryIds };+}++function objectId(seconds: number): string {+ return `${seconds.toString(16).padStart(8, '0')}0000000000000000`;+}++function triggerContext<Props extends InputPropertyMap>({ propsValue, store }: { propsValue: StaticPropsValue<Props>; store: ReturnType<typeof memoryStore> }) {+ const { files } = createMockActionContext<Props>({ propsValue });+ return { ...createMockPollingTriggerContext<Props>({ propsValue }), auth: CONNECTION, store, files };+}++function memoryStore(initial: Record<string, unknown> = {}) {+ const data = new Map<string, unknown>(Object.entries(initial));+ return {+ data,+ put: async <T>(key: string, value: T): Promise<T> => {+ data.set(key, value);+ return value;+ },+ get: async <T>(key: string): Promise<T | null> => {+ const value = data.get(key);+ return value === undefined ? null : JSON.parse(JSON.stringify(value));+ },+ delete: async (key: string): Promise<void> => {+ data.delete(key);+ },+ };+}++const CONNECTION: AppConnectionValueForAuthProperty<typeof jumpcloudAuth> = {+ type: AppConnectionType.CUSTOM_AUTH,+ props: { apiKey: 'key', region: 'us', orgId: undefined },+};++type Request = {+ method: string;+ url: string;+ queryParams?: Record<string, string>;+};diff --git a/packages/pieces/community/jumpcloud/test/user-actions.test.ts b/packages/pieces/community/jumpcloud/test/user-actions.test.tsnew file mode 100644index 00000000000..0d6e7a3d677--- /dev/null+++ b/packages/pieces/community/jumpcloud/test/user-actions.test.ts@@ -0,0 +1,525 @@+import { HttpError, httpClient, HttpMethod } from '@activepieces/pieces-common';+import {+ AppConnectionType,+ AppConnectionValueForAuthProperty,+ createMockActionContext,+ InputPropertyMap,+ OutputSchema,+ StaticPropsValue,+} from '@activepieces/pieces-framework';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { createAssociationAction } from '../src/lib/actions/create-association';+import { deleteAssociationAction } from '../src/lib/actions/delete-association';+import { findUserByEmployeeIdAction } from '../src/lib/actions/find-user-by-employee-id';+import { lockUserAction } from '../src/lib/actions/lock-user';+import { resetUserMfaAction } from '../src/lib/actions/reset-user-mfa';+import { runTriggerCommandAction } from '../src/lib/actions/run-trigger-command';+import { unlockUserAction } from '../src/lib/actions/unlock-user';+import { updateUserOnSystemAction } from '../src/lib/actions/update-user-on-system';+import { jumpcloudAuth } from '../src/lib/auth';+import { jumpcloudAssociations } from '../src/lib/common/associations';+import { ObjectTypeKey } from '../src/lib/common/types';+import {+ associationOutputSchema,+ findUserOutputSchema,+ resetMfaOutputSchema,+ runCommandOutputSchema,+ userOnSystemOutputSchema,+ userOutputSchema,+} from '../src/lib/output-schemas';++const sendRequest = vi.fn();++const V1 = 'https://console.jumpcloud.com/api';+const V2 = 'https://console.jumpcloud.com/api/v2';++beforeEach(() => {+ sendRequest.mockReset();+ vi.spyOn(httpClient, 'sendRequest').mockImplementation((request) => sendRequest(request));+});++afterEach(() => {+ vi.useRealTimers();+ vi.restoreAllMocks();+});++describe('association routing', () => {+ it.each(ROUTE_CASES)('routes %s %s', (sourceType, sourceId, targetType, targetId, path, type, id) => {+ expect(jumpcloudAssociations.route({ sourceType, sourceId, targetType, targetId })).toEqual({ path, type, id });+ });++ it('lists the valid targets for an impossible pair', () => {+ expect(() => jumpcloudAssociations.route({ sourceType: 'application', sourceId: 'a1', targetType: 'system', targetId: 's1' })).toThrow(+ 'JumpCloud cannot associate a Application (SSO) with a System (device). Pick one of: User, User Group.',+ );+ });+});++describe('Create / Delete Association', () => {+ it('adds group membership through the members endpoint', async () => {+ sendRequest.mockResolvedValue({ status: 204, body: '' });++ const result = await createAssociationAction.run(+ context<typeof createAssociationAction.props>({ objectType: 'user', objectId: ' u1 ', targetType: 'user_group', targetId: 'g1' }),+ );++ expect(lastRequest()).toEqual({+ method: HttpMethod.POST,+ url: `${V2}/usergroups/g1/members`,+ headers: expect.any(Object),+ body: { op: 'add', type: 'user', id: 'u1' },+ });+ expect(result).toEqual({ object_type: 'user', object_id: 'u1', associated_type: 'user_group', associated_id: 'g1', associated: true });+ expectSchemaResolves({ schema: associationOutputSchema, output: result });+ });++ it('removes an application association', async () => {+ sendRequest.mockResolvedValue({ status: 204, body: '' });++ const result = await deleteAssociationAction.run(+ context<typeof deleteAssociationAction.props>({ objectType: 'user', objectId: 'u1', targetType: 'application', targetId: 'a1' }),+ );++ expect(lastRequest()).toMatchObject({ url: `${V2}/users/u1/associations`, body: { op: 'remove', type: 'application', id: 'a1' } });+ expect(result).toMatchObject({ associated: false });+ });++ it('requires both objects', async () => {+ await expect(+ createAssociationAction.run(+ context<typeof createAssociationAction.props>({ objectType: 'user', objectId: 'u1', targetType: 'system', targetId: ' ' }),+ ),+ ).rejects.toThrow('Select both objects');+ expect(sendRequest).not.toHaveBeenCalled();+ });+});++describe('Search User by Employee ID', () => {+ it('returns the matching user', async () => {+ sendRequest.mockResolvedValue({ status: 200, body: { totalCount: 1, results: [{ _id: 'u1', employeeIdentifier: 'E-1' }] } });++ const result = await findUserByEmployeeIdAction.run(context<typeof findUserByEmployeeIdAction.props>({ employeeId: ' E-1 ' }));++ expect(lastRequest()).toMatchObject({+ url: `${V1}/systemusers`,+ queryParams: { limit: '2', skip: '0', sort: '_id', filter: 'employeeIdentifier:$eq:E-1' },+ });+ expect(result).toMatchObject({ found: true, id: 'u1', employee_id: 'E-1' });+ expectSchemaResolves({ schema: findUserOutputSchema, output: result });+ });++ it('returns found=false with empty fields when nobody matches', async () => {+ sendRequest.mockResolvedValue({ status: 200, body: { totalCount: 0, results: [] } });++ const result = await findUserByEmployeeIdAction.run(context<typeof findUserByEmployeeIdAction.props>({ employeeId: 'E-9' }));++ expect(result).toMatchObject({ found: false, id: null, email: null });+ expectSchemaResolves({ schema: findUserOutputSchema, output: result });+ });++ it('requires an employee ID', async () => {+ await expect(findUserByEmployeeIdAction.run(context<typeof findUserByEmployeeIdAction.props>({ employeeId: ' ' }))).rejects.toThrow(+ 'Enter the Employee ID',+ );+ });+});++describe('Lock / Unlock User', () => {+ it('locks the user and returns it', async () => {+ sendRequest.mockResolvedValue({ status: 200, body: { _id: 'u1', account_locked: true } });++ const result = await lockUserAction.run(context<typeof lockUserAction.props>({ userId: 'u1' }));++ expect(lastRequest()).toMatchObject({ method: HttpMethod.PUT, url: `${V1}/systemusers/u1`, body: { account_locked: true } });+ expect(result).toMatchObject({ id: 'u1', account_locked: true });+ expectSchemaResolves({ schema: userOutputSchema, output: result });+ });++ it('unlocks the user and returns its fresh state', async () => {+ sendRequest.mockImplementation(async (request: Request) =>+ request.method === HttpMethod.POST ? { status: 200, body: 'ok' } : { status: 200, body: { _id: 'u1', account_locked: false } },+ );++ const result = await unlockUserAction.run(context<typeof unlockUserAction.props>({ userId: 'u1' }));++ expect(sendRequest.mock.calls.map(([request]) => `${request.method} ${request.url}`)).toEqual([+ `POST ${V1}/systemusers/u1/unlock`,+ `GET ${V1}/systemusers/u1`,+ ]);+ expect(result).toMatchObject({ id: 'u1', account_locked: false });+ });+});++describe('Reset User MFA', () => {+ it('resets without a grace period by default', async () => {+ sendRequest.mockResolvedValue({ status: 200, body: '' });++ const result = await resetUserMfaAction.run(+ context<typeof resetUserMfaAction.props>({ userId: 'u1', allowGracePeriod: false, gracePeriodDays: 7 }),+ );++ expect(lastRequest()).toMatchObject({ url: `${V1}/systemusers/u1/resetmfa`, body: { exclusion: false } });+ expect(result).toEqual({ user_id: 'u1', mfa_reset: true, grace_period_days: null });+ expectSchemaResolves({ schema: resetMfaOutputSchema, output: result });+ });++ it('sends the grace period when allowed', async () => {+ sendRequest.mockResolvedValue({ status: 200, body: '' });++ await resetUserMfaAction.run(context<typeof resetUserMfaAction.props>({ userId: 'u1', allowGracePeriod: true, gracePeriodDays: 3 }));++ expect(lastRequest().body).toEqual({ exclusion: true, exclusionDays: 3 });+ });++ it.each([0, 1.5, 400, undefined])('rejects a grace period of %s days', async (gracePeriodDays) => {+ await expect(+ resetUserMfaAction.run(context<typeof resetUserMfaAction.props>({ userId: 'u1', allowGracePeriod: true, gracePeriodDays })),+ ).rejects.toThrow('Grace Period must be');+ expect(sendRequest).not.toHaveBeenCalled();+ });+});++describe('Update User on System', () => {+ it('updates the sudo attributes of an existing binding', async () => {+ sendRequest.mockResolvedValue({ status: 204, body: '' });++ const result = await updateUserOnSystemAction.run(+ context<typeof updateUserOnSystemAction.props>({+ userId: 'u1',+ systemId: 's1',+ sudoEnabled: true,+ sudoWithoutPassword: true,+ bindIfNeeded: false,+ }),+ );++ expect(lastRequest()).toMatchObject({+ url: `${V2}/users/u1/associations`,+ body: { op: 'update', type: 'system', id: 's1', attributes: { sudo: { enabled: true, withoutPassword: true } } },+ });+ expect(result).toEqual({ user_id: 'u1', system_id: 's1', sudo_enabled: true, sudo_without_password: true });+ expectSchemaResolves({ schema: userOnSystemOutputSchema, output: result });+ });++ it('binds when asked and ignores passwordless sudo without sudo', async () => {+ sendRequest.mockResolvedValue({ status: 204, body: '' });++ await updateUserOnSystemAction.run(+ context<typeof updateUserOnSystemAction.props>({+ userId: 'u1',+ systemId: 's1',+ sudoEnabled: false,+ sudoWithoutPassword: true,+ bindIfNeeded: true,+ }),+ );++ expect(sendRequest.mock.calls[0][0]).toMatchObject({+ method: HttpMethod.GET,+ url: `${V2}/users/u1/associations`,+ queryParams: { targets: 'system', limit: '100', skip: '0' },+ });+ expect(lastRequest().body).toMatchObject({ op: 'add', attributes: { sudo: { enabled: false, withoutPassword: false } } });+ });++ it('updates an existing binding when asked to bind if needed', async () => {+ const otherSystems = Array.from({ length: 100 }, (_, index) => ({ to: { id: `other${index}`, type: 'system' } }));+ sendRequest.mockImplementation(async (request: Request) => {+ if (request.method !== HttpMethod.GET) {+ return { status: 204, body: '' };+ }+ return request.queryParams?.['skip'] === '0'+ ? { status: 200, body: otherSystems }+ : { status: 200, body: [{ to: { id: 's1', type: 'system' } }] };+ });++ await updateUserOnSystemAction.run(+ context<typeof updateUserOnSystemAction.props>({+ userId: 'u1',+ systemId: 's1',+ sudoEnabled: true,+ sudoWithoutPassword: false,+ bindIfNeeded: true,+ }),+ );++ expect(sendRequest).toHaveBeenCalledTimes(3);+ expect(lastRequest().body).toMatchObject({ op: 'update', type: 'system', id: 's1' });+ });+});++describe('Run Trigger Command', () => {+ const base = { instructions: undefined, variables: { env: 'prod' }, waitForResults: false, waitSeconds: 60 };++ it('launches the commands and returns their IDs', async () => {+ sendRequest.mockImplementation(async (request: Request) =>+ request.url === `${V1}/commands` ? commandList(request) : { status: 200, body: { triggered: ['Deploy', 'Cleanup'] } },+ );++ const result = await runTriggerCommandAction.run(context<typeof runTriggerCommandAction.props>({ ...base, triggerName: ' deploy app ' }));++ expect(lastRequest()).toMatchObject({ method: HttpMethod.POST, url: `${V1}/command/trigger/deploy%20app`, body: { env: 'prod' } });+ expect(result).toEqual({ trigger_name: 'deploy app', command_ids: ['c1', 'c2'], waited: false, completed: false, results: [] });+ });++ it('explains a trigger name that launches nothing', async () => {+ sendRequest.mockImplementation(async (request: Request) =>+ request.url === `${V1}/commands` ? { status: 200, body: { totalCount: 0, results: [] } } : { status: 200, body: { triggered: [] } },+ );++ await expect(+ runTriggerCommandAction.run(context<typeof runTriggerCommandAction.props>({ ...base, triggerName: 'nope' })),+ ).rejects.toThrow('No JumpCloud command uses the trigger name "nope"');+ });++ it('polls until every command reports', async () => {+ vi.useFakeTimers();+ const resultsCalls = { count: 0 };+ sendRequest.mockImplementation(async (request: Request) => {+ if (request.url === `${V1}/commands`) {+ return commandList(request);+ }+ if (request.method === HttpMethod.POST) {+ return { status: 200, body: { triggered: ['Deploy'] } };+ }+ if (request.url === `${V2}/commands/c1/systems`) {+ return { status: 200, body: [{ id: 's1', type: 'system' }] };+ }+ resultsCalls.count += 1;+ return resultsCalls.count < 3+ ? { status: 200, body: [] }+ : { status: 200, body: [commandResult({ systemId: 's1', system: 'mac-01', requestTime: new Date().toISOString() })] };+ });++ const pending = runTriggerCommandAction.run(+ context<typeof runTriggerCommandAction.props>({ ...base, triggerName: 'deploy', waitForResults: true, waitSeconds: 60 }),+ );+ await vi.advanceTimersByTimeAsync(5000);+ const result = await pending;++ expect(resultsCalls.count).toBe(3);+ expect(result).toMatchObject({+ waited: true,+ completed: true,+ results: [{ command_id: 'c1', command_name: 'Deploy', system_id: 's1', system_name: 'mac-01', exit_code: 0, output: 'done', error: null }],+ });+ expectSchemaResolves({ schema: runCommandOutputSchema, output: result });+ });++ it('keeps waiting until every device bound to the command reports', async () => {+ vi.useFakeTimers();+ const resultsCalls = { count: 0 };+ sendRequest.mockImplementation(async (request: Request) => {+ if (request.url === `${V1}/commands`) {+ return commandList(request);+ }+ if (request.method === HttpMethod.POST) {+ return { status: 200, body: { triggered: ['Deploy'] } };+ }+ if (request.url === `${V2}/commands/c1/systems`) {+ return { status: 200, body: [{ id: 's1', type: 'system' }, { id: 's2', type: 'system' }] };+ }+ resultsCalls.count += 1;+ const now = new Date().toISOString();+ if (resultsCalls.count === 1) {+ return { status: 200, body: [] };+ }+ const fast = commandResult({ systemId: 's1', system: 'mac-01', requestTime: now });+ return { status: 200, body: resultsCalls.count < 4 ? [fast] : [fast, commandResult({ systemId: 's2', system: 'mac-02', requestTime: now })] };+ });++ const pending = runTriggerCommandAction.run(+ context<typeof runTriggerCommandAction.props>({ ...base, triggerName: 'deploy', waitForResults: true, waitSeconds: 60 }),+ );+ await vi.advanceTimersByTimeAsync(10000);+ const result = await pending;++ expect(resultsCalls.count).toBe(4);+ expect(result).toMatchObject({ completed: true });+ expect(result.results.map((entry) => entry['system_id'])).toEqual(['s1', 's2']);+ });++ it('ignores results from earlier runs of the command', async () => {+ vi.useFakeTimers();+ sendRequest.mockImplementation(async (request: Request) => {+ if (request.url === `${V1}/commands`) {+ return commandList(request);+ }+ if (request.method === HttpMethod.POST) {+ return { status: 200, body: { triggered: ['Deploy'] } };+ }+ if (request.url === `${V2}/commands/c1/systems`) {+ return { status: 200, body: [{ id: 's1', type: 'system' }] };+ }+ return { status: 200, body: [commandResult({ systemId: 's1', system: 'mac-01', requestTime: '2020-01-01T00:00:00.000Z' })] };+ });++ const pending = runTriggerCommandAction.run(+ context<typeof runTriggerCommandAction.props>({ ...base, triggerName: 'deploy', waitForResults: true, waitSeconds: 10 }),+ );+ await vi.advanceTimersByTimeAsync(20000);++ expect(await pending).toMatchObject({ waited: true, completed: false, results: [] });+ });++ it('ignores a result from a run a few seconds before this launch', async () => {+ vi.useFakeTimers();+ const recent = commandResult({ systemId: 's1', system: 'mac-01', requestTime: new Date(Date.now() - 3000).toISOString() });+ sendRequest.mockImplementation(async (request: Request) => {+ if (request.url === `${V1}/commands`) {+ return commandList(request);+ }+ if (request.method === HttpMethod.POST) {+ return { status: 200, body: { triggered: ['Deploy'] } };+ }+ if (request.url === `${V2}/commands/c1/systems`) {+ return { status: 200, body: [{ id: 's1', type: 'system' }] };+ }+ return { status: 200, body: [recent] };+ });++ const pending = runTriggerCommandAction.run(+ context<typeof runTriggerCommandAction.props>({ ...base, triggerName: 'deploy', waitForResults: true, waitSeconds: 10 }),+ );+ await vi.advanceTimersByTimeAsync(20000);++ expect(await pending).toMatchObject({ waited: true, completed: false, results: [] });+ });++ it('keeps a result that lands right after the launch', async () => {+ vi.useFakeTimers();+ const launched = { done: false };+ sendRequest.mockImplementation(async (request: Request) => {+ if (request.url === `${V1}/commands`) {+ return commandList(request);+ }+ if (request.method === HttpMethod.POST) {+ launched.done = true;+ return { status: 200, body: { triggered: ['Deploy'] } };+ }+ if (request.url === `${V2}/commands/c1/systems`) {+ return { status: 200, body: [{ id: 's1', type: 'system' }] };+ }+ return { status: 200, body: launched.done ? [commandResult({ systemId: 's1', system: 'mac-01', requestTime: new Date().toISOString() })] : [] };+ });++ const result = await runTriggerCommandAction.run(+ context<typeof runTriggerCommandAction.props>({ ...base, triggerName: 'deploy', waitForResults: true, waitSeconds: 10 }),+ );++ expect(result).toMatchObject({ completed: true, results: [{ system_id: 's1' }] });+ const order = sendRequest.mock.calls.map(([request]) => `${request.method} ${request.url}`);+ expect(order.indexOf(`GET ${V1}/commands/c1/results`)).toBeLessThan(order.indexOf(`POST ${V1}/command/trigger/deploy`));+ expect(sendRequest.mock.calls.find(([request]) => request.url === `${V1}/commands`)?.[0].queryParams).toMatchObject({ filter: 'trigger:eq:deploy' });+ });++ it('stops waiting at the deadline', async () => {+ vi.useFakeTimers();+ sendRequest.mockImplementation(async (request: Request) => {+ if (request.url === `${V1}/commands`) {+ return commandList(request);+ }+ if (request.method === HttpMethod.POST) {+ return { status: 200, body: { triggered: ['Deploy'] } };+ }+ return { status: 200, body: [] };+ });++ const pending = runTriggerCommandAction.run(+ context<typeof runTriggerCommandAction.props>({ ...base, triggerName: 'deploy', waitForResults: true, waitSeconds: 10 }),+ );+ await vi.advanceTimersByTimeAsync(20000);++ expect(await pending).toMatchObject({ waited: true, completed: false, results: [] });+ expect(sendRequest.mock.calls.filter(([request]) => request.url === `${V1}/commands/c1/results`)).toHaveLength(4);+ });++ it.each([1, 301])('rejects a wait of %s seconds', async (waitSeconds) => {+ sendRequest.mockImplementation(async (request: Request) =>+ request.url === `${V1}/commands` ? commandList(request) : { status: 200, body: { triggered: ['Deploy'] } },+ );++ await expect(+ runTriggerCommandAction.run(+ context<typeof runTriggerCommandAction.props>({ ...base, triggerName: 'deploy', waitForResults: true, waitSeconds }),+ ),+ ).rejects.toThrow('Max Wait must be from 5 to 300 seconds.');+ expect(sendRequest).not.toHaveBeenCalled();+ });++ it('surfaces API errors', async () => {+ sendRequest.mockRejectedValue(new HttpError({}, { status: 403, responseBody: { message: 'forbidden' } }));++ await expect(+ runTriggerCommandAction.run(context<typeof runTriggerCommandAction.props>({ ...base, triggerName: 'deploy' })),+ ).rejects.toThrow('JumpCloud API error (HTTP 403): forbidden');+ });+});++function expectSchemaResolves({ schema, output }: { schema: OutputSchema; output: unknown }): void {+ expect(output).toBeTypeOf('object');+ schema.fields.forEach((field) => {+ const path = field.value ?? field.key;+ expect(output, `missing output field ${path}`).toHaveProperty([path]);+ const items = readList({ output, key: path });+ field.listItems?.forEach((item) => {+ items.forEach((entry) => expect(entry, `missing list field ${path}[].${item.key}`).toHaveProperty([item.value ?? item.key]));+ });+ });+}++function readList({ output, key }: { output: unknown; key: string }): unknown[] {+ if (output === null || typeof output !== 'object' || !(key in output)) {+ return [];+ }+ const value = Object.entries(output).find(([entryKey]) => entryKey === key)?.[1];+ return Array.isArray(value) ? value : [];+}++function context<Props extends InputPropertyMap>(propsValue: StaticPropsValue<Props>) {+ return { ...createMockActionContext<Props>({ propsValue }), auth: CONNECTION };+}++// JumpCloud's trigger endpoint answers with command names, so the lookup maps them back to IDs.+function commandList(request: Request) {+ const trigger = String(request.queryParams?.['filter'] ?? '').replace('trigger:eq:', '');+ return {+ status: 200,+ body: {+ totalCount: 2,+ results: [+ { _id: 'c1', name: 'Deploy', trigger },+ { _id: 'c2', name: 'Cleanup', trigger },+ ],+ },+ };+}++function commandResult({ systemId, system, requestTime }: { systemId: string; system: string; requestTime: string }) {+ return { name: 'Deploy', systemId, system, requestTime, response: { data: { exitCode: 0, output: 'done' }, error: '' } };+}++function lastRequest(): Request {+ return sendRequest.mock.calls[sendRequest.mock.calls.length - 1][0];+}++const ROUTE_CASES: [ObjectTypeKey, string, ObjectTypeKey, string, string, ObjectTypeKey, string][] = [+ ['user_group', 'g1', 'user', 'u1', '/usergroups/g1/members', 'user', 'u1'],+ ['user', 'u1', 'user_group', 'g1', '/usergroups/g1/members', 'user', 'u1'],+ ['system', 's1', 'system_group', 'g2', '/systemgroups/g2/members', 'system', 's1'],+ ['user', 'u1', 'system', 's1', '/users/u1/associations', 'system', 's1'],+ ['application', 'a1', 'user_group', 'g1', '/applications/a1/associations', 'user_group', 'g1'],+ ['system_group', 'g2', 'user_group', 'g1', '/systemgroups/g2/associations', 'user_group', 'g1'],+];++const CONNECTION: AppConnectionValueForAuthProperty<typeof jumpcloudAuth> = {+ type: AppConnectionType.CUSTOM_AUTH,+ props: { apiKey: 'key', region: 'us', orgId: undefined },+};++type Request = {+ method: string;+ url: string;+ body?: unknown;+ queryParams?: Record<string, string>;+};diff --git a/packages/pieces/community/jumpcloud/tsconfig.json b/packages/pieces/community/jumpcloud/tsconfig.jsonnew file mode 100644index 00000000000..71bc5814f5d--- /dev/null+++ b/packages/pieces/community/jumpcloud/tsconfig.json@@ -0,0 +1,15 @@+{+ "extends": "../../../../tsconfig.base.json",+ "compilerOptions": {+ "module": "commonjs",+ "forceConsistentCasingInFileNames": true,+ "strict": true,+ "noImplicitOverride": true,+ "noPropertyAccessFromIndexSignature": true,+ "noImplicitReturns": true,+ "noFallthroughCasesInSwitch": true+ },+ "files": [],+ "include": [],+ "references": [{ "path": "./tsconfig.lib.json" }]+}diff --git a/packages/pieces/community/jumpcloud/tsconfig.lib.json b/packages/pieces/community/jumpcloud/tsconfig.lib.jsonnew file mode 100644index 00000000000..a648eb45d7f--- /dev/null+++ b/packages/pieces/community/jumpcloud/tsconfig.lib.json@@ -0,0 +1,13 @@+{+ "extends": "./tsconfig.json",+ "compilerOptions": {+ "rootDir": ".",+ "baseUrl": ".",+ "paths": {},+ "outDir": "./dist",+ "declaration": true,+ "types": ["node"]+ },+ "include": ["src/**/*.ts"],+ "exclude": ["jest.config.ts", "src/**/*.spec.ts", "src/**/*.test.ts"]+}diff --git a/packages/pieces/community/jumpcloud/vitest.config.ts b/packages/pieces/community/jumpcloud/vitest.config.tsnew file mode 100644index 00000000000..79c97261904--- /dev/null+++ b/packages/pieces/community/jumpcloud/vitest.config.ts@@ -0,0 +1,19 @@+import path from 'path'+import { defineConfig } from 'vitest/config'++const repoRoot = path.resolve(__dirname, '../../../..')++export default defineConfig({+ root: __dirname,+ test: {+ globals: true,+ environment: 'node',+ include: ['test/**/*.test.ts'],+ },+ resolve: {+ alias: {+ '@activepieces/pieces-framework': path.resolve(repoRoot, 'packages/pieces/framework/src/index.ts'),+ '@activepieces/pieces-common': path.resolve(repoRoot, 'packages/pieces/common/src/index.ts'),+ },+ },+})diff --git a/tsconfig.base.json b/tsconfig.base.jsonindex 5a9d5c6ffcc..1d8f8104aff 100644--- a/tsconfig.base.json+++ b/tsconfig.base.json@@ -721,6 +721,9 @@"@activepieces/piece-json": ["packages/pieces/community/json/src/index.ts"],+ "@activepieces/piece-jumpcloud": [+ "packages/pieces/community/jumpcloud/src/index.ts"+ ],"@activepieces/piece-kallabot-ai": ["packages/pieces/community/kallabot-ai/src/index.ts"],