@devries-cameron20 / composio-1 / commits / 483af3607
Fork 0

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

feat(connected-accounts): bump @composio/client to alpha.71, drop casts, add tests + error mapping

Now that #77 in composio-base-ts merged and @composio/client@0.1.0-alpha.71 is published with account_type + acl_config_for_shared in the typed surface, all the forward-compat shims come out. Removed: - AclConfigWireShape, LinkCreateBodyWithAcl, ConnectedAccountPatchBodyWithAcl local types - 3x `as unknown as Parameters<typeof X>[N]` casts in ConnectedAccounts.ts + ToolRouterSession.ts Now uses the generated types directly: - ConnectedAccountPatchParams, ConnectedAccountPatchResponse from @composio/client/resources/connected-accounts - LinkCreateParams + LinkCreateParams.ACLConfigForShared from @composio/client/resources/link - SessionLinkParams + SessionLinkParams.ACLConfigForShared from @composio/client/resources/tool-router/session/session Review fixes from #3392 multi-agent review: - P1-1: moved orphaned JSDoc back onto ComposioLegacyConnectedAccountsEndpoint- RetiredError (was stranded above ComposioSharedAccessDeniedError) - P1-2: added empty-array footgun warning to updateAcl() JSDoc — passing `notAllowedUserIds: []` silently clears the deny list - P1-3: changeset reconciled with PR body (Python ships as separate PR) - P2-9: updateAcl() returns ConnectedAccountPatchResponse instead of void, matching sibling update()/refresh() ergonomics - P2-11: clarifying JSDoc on update() pointing at updateAcl() and noting the pre-existing "alias/credentials" doc is inaccurate (this PR doesn't fix it) - P3-12: callbackUrl/alias guards normalized to `!== undefined` (was a mix of `&&` and `!= null`) — empty strings now propagate correctly - P3-17: refine-guard comment on UpdateConnectedAccountAclParamsSchema noting ZodEffects doesn't expose .shape P2-6/P2-7: typed error mapping for ComposioAclOnlyForSharedError (400) wired at three call sites: - ConnectedAccounts.link() — wraps existing ComposioFailedToCreateConnectedAccountLink catch - ConnectedAccounts.updateAcl() — new catch with rethrow fallback - ToolRouterSession.authorize() — new catch with rethrow fallback Substring match on `'acl_config_for_shared is only valid on SHARED'` — verified against apps/apollo/src/lib/connected_accounts/createConnectedAccount.ts in hermes#9902. ComposioSharedAccessDeniedError and ComposioSharedConnectionNotAccessibleError remain exported but not yet thrown — they'll be wrapped when Tools.execute() and ToolRouterSession.create() error-mapping lands in a follow-up. Tests: 12 new behaviour tests in test/connectedAccounts/connectedAccounts.test.ts covering link() ACL forwarding (5), updateAcl() body construction + empty-object refine + AclOnlyForShared mapping (6), and link() error-mapping fallback (1). 911 tests pass (up from 899). Verified: pnpm typecheck clean, pnpm build clean (publint + attw clean). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

venkat82 committed May 11, 2026 at 23:55 UTC 483af3607084e79306760db18a5505713293c53a
8 files changed +285 -83
.changeset/connected-accounts-acl.md
+1 -1
@@ -29,4 +29,4 @@ New error classes:
29
30 No breaking changes. Existing `link()` callers without the new options get a `PRIVATE` connection exactly as today; existing `get()` / `list()` callers see new optional fields.
31
32 -Python SDK gets the matching change in the same release train.
32 +The Python SDK mirror ships in a separate PR — same wire contract, same release train.
pnpm-lock.yaml
+7 -7
@@ -25,8 +25,8 @@ catalogs:
25 specifier: ^4.20250917.0
26 version: 4.20260218.0
27 '@composio/client':
28 - specifier: 0.1.0-alpha.70
29 - version: 0.1.0-alpha.70
28 + specifier: 0.1.0-alpha.71
29 + version: 0.1.0-alpha.71
30 '@effect/cli':
31 specifier: ^0.73.2
32 version: 0.73.2
@@ -1079,7 +1079,7 @@ importers:
1079 version: link:../cli-local-tools
1080 '@composio/client':
1081 specifier: 'catalog:'
1082 - version: 0.1.0-alpha.70
1082 + version: 0.1.0-alpha.71
1083 '@composio/core':
1084 specifier: workspace:*
1085 version: link:../core
@@ -1249,7 +1249,7 @@ importers:
1249 dependencies:
1250 '@composio/client':
1251 specifier: 'catalog:'
1252 - version: 0.1.0-alpha.70
1252 + version: 0.1.0-alpha.71
1253 '@composio/json-schema-to-zod':
1254 specifier: workspace:*
1255 version: link:../json-schema-to-zod
@@ -1912,8 +1912,8 @@ packages:
1912 resolution: {integrity: sha512-ooWCrlZP11i8GImSjTHYHLkvFDP48nS4+204nGb1RiX/WXYHmJA2III9/e2DWVabCESdW7hBAEzHRqUn9OUVvQ==}
1913 engines: {node: '>=0.1.90'}
1914
1915 - '@composio/client@0.1.0-alpha.70':
1916 - resolution: {integrity: sha512-bANvjHL9aYwvzcrDL9S2W/uTf6EV3slIpYRL3lAv3k74tTgB1TkYzAWgxxz1OpLK86iDB5xq3RFlritVu23Erg==}
1915 + '@composio/client@0.1.0-alpha.71':
1916 + resolution: {integrity: sha512-6h1IPMbXIx5PjaU0T+a1MNnKHL/pPP7+X2nNQaler5XoENANWGm4mYePjR+7Cgtw1j6X2QkCmRLuX5q9c0INvQ==}
1917
1918 '@cspotcode/source-map-support@0.8.1':
1919 resolution: {integrity: sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==}
@@ -7286,7 +7286,7 @@ snapshots:
7286 '@colors/colors@1.5.0':
7287 optional: true
7288
7289 - '@composio/client@0.1.0-alpha.70': {}
7289 + '@composio/client@0.1.0-alpha.71': {}
7290
7291 '@cspotcode/source-map-support@0.8.1':
7292 dependencies:
pnpm-workspace.yaml
+1 -1
@@ -22,7 +22,7 @@ catalog:
22 '@clack/prompts': '^1.0.1'
23 '@cloudflare/vitest-pool-workers': ^0.9.2
24 '@cloudflare/workers-types': ^4.20250917.0
25 - '@composio/client': 0.1.0-alpha.70
25 + '@composio/client': 0.1.0-alpha.71
26 '@effect/cli': ^0.73.2
27 '@effect/eslint-plugin': ^0.3.2
28 '@effect/language-service': ^0.74.0
ts/packages/core/src/errors/ConnectedAccountsErrors.ts
+13 -13
@@ -56,19 +56,6 @@ export class ComposioFailedToCreateConnectedAccountLink extends ComposioError {
56 }
57 }
58
59 -/**
60 - * Thrown by `composio.connectedAccounts.initiate()` when the legacy
61 - * `POST /api/v3/connected_accounts` endpoint rejects a Composio-managed
62 - * OAuth (OAuth1, OAuth2, DCR_OAUTH) auth-config request.
63 - *
64 - * The retiring path is being phased out — new orgs from 2026-05-08 and
65 - * all remaining orgs from 2026-07-03. Migrate the call to
66 - * `composio.connectedAccounts.link()`, which works for every redirectable
67 - * scheme regardless of whether the auth config is Composio-managed or
68 - * custom.
69 - *
70 - * See: https://docs.composio.dev/docs/changelog/2026/04/24
71 - */
59 /**
60 * Thrown when a tool execution attempts to use a SHARED connected account
61 * but the requesting `userId` is not allowed by the connection's ACL.
@@ -146,6 +133,19 @@ export class ComposioSharedConnectionNotAccessibleError extends ComposioError {
133 }
134 }
135
136 +/**
137 + * Thrown by `composio.connectedAccounts.initiate()` when the legacy
138 + * `POST /api/v3/connected_accounts` endpoint rejects a Composio-managed
139 + * OAuth (OAuth1, OAuth2, DCR_OAUTH) auth-config request.
140 + *
141 + * The retiring path is being phased out — new orgs from 2026-05-08 and
142 + * all remaining orgs from 2026-07-03. Migrate the call to
143 + * `composio.connectedAccounts.link()`, which works for every redirectable
144 + * scheme regardless of whether the auth config is Composio-managed or
145 + * custom.
146 + *
147 + * See: https://docs.composio.dev/docs/changelog/2026/04/24
148 + */
149 export class ComposioLegacyConnectedAccountsEndpointRetiredError extends ComposioError {
150 constructor(
151 message: string = 'POST /api/v3/connected_accounts is no longer supported for Composio-managed OAuth auth configs. Use composio.connectedAccounts.link() instead.',
ts/packages/core/src/models/ConnectedAccounts.ts
+59 -49
@@ -9,6 +9,8 @@ import ComposioClient, { BadRequestError } from '@composio/client';
9 import {
10 ConnectedAccountCreateResponse,
11 ConnectedAccountDeleteResponse,
12 + ConnectedAccountPatchParams,
13 + ConnectedAccountPatchResponse,
14 ConnectedAccountRefreshParams,
15 ConnectedAccountRefreshResponse,
16 ConnectedAccountUpdateStatusParams,
@@ -16,6 +18,7 @@ import {
18 ConnectedAccountListParams as ConnectedAccountListParamsRaw,
19 ConnectedAccountCreateParams as ConnectedAccountCreateParamsRaw,
20 } from '@composio/client/resources/connected-accounts';
21 +import { LinkCreateParams } from '@composio/client/resources/link';
22 import {
23 CreateConnectedAccountOptions,
24 ConnectedAccountRetrieveResponse,
@@ -41,6 +44,7 @@ import {
44 transformConnectedAccountResponse,
45 } from '../utils/transformers/connectedAccounts';
46 import {
47 + ComposioAclOnlyForSharedError,
48 ComposioFailedToCreateConnectedAccountLink,
49 ComposioLegacyConnectedAccountsEndpointRetiredError,
50 ComposioMultipleConnectedAccountsError,
@@ -52,41 +56,13 @@ import { ConnectionData } from '../types/connectedAccountAuthStates.types';
56 // warning on every initiate() call.
57 let _legacyInitiateWarningEmitted = false;
58
55 -// Wire-level fields added by Hermes #9860 / #9882 (account_type) and
56 -// merged #9902 (ACL). 9902 nests ACL under a single `acl_config_for_shared`
57 -// object (single JSONB column under the hood). Once @composio/client is
58 -// regenerated against the post-9902 backend spec, this local extension can
59 -// be removed and we can rely on the generated `LinkCreateParams` directly.
60 -type AclConfigWireShape = {
61 - allow_all_users?: boolean;
62 - allowed_user_ids?: string[];
63 - not_allowed_user_ids?: string[];
64 -};
65 -
66 -type LinkCreateBodyWithAcl = ConnectedAccountCreateParamsRaw extends never
67 - ? never
68 - : Record<string, unknown> & {
69 - auth_config_id: string;
70 - user_id: string;
71 - alias?: string;
72 - callback_url?: string;
73 - account_type?: 'PRIVATE' | 'SHARED';
74 - acl_config_for_shared?: AclConfigWireShape;
75 - };
76 -
77 -// Wire-level body for PATCH /connected_accounts/{id} with ACL.
78 -type ConnectedAccountPatchBodyWithAcl = {
79 - alias?: string;
80 - acl_config_for_shared?: AclConfigWireShape;
81 -};
82 -
59 /**
60 * Serialise the SDK's `aclConfigForShared` (camelCase, top-level optional)
61 * to the wire's `acl_config_for_shared` block. Returns `undefined` when the
62 * caller didn't pass anything (PATCH-style "don't touch ACL"); returns
87 - * `{}` when the caller passed an explicit empty object (also "no fields to
88 - * change", but encodes the explicit intent — the backend treats both the
89 - * same way today).
63 + * `{}` when the caller passed an explicit empty object (the backend treats
64 + * both the same way today — deny-by-default — but the explicit form is
65 + * preserved so the intent is visible in network traces).
66 */
67 function serializeAclConfigForWire(
68 acl:
@@ -96,7 +72,7 @@ function serializeAclConfigForWire(
72 notAllowedUserIds?: string[];
73 }
74 | undefined
99 -): AclConfigWireShape | undefined {
75 +): LinkCreateParams.ACLConfigForShared | undefined {
76 if (acl === undefined) return undefined;
77 return {
78 ...(acl.allowAllUsers !== undefined && { allow_all_users: acl.allowAllUsers }),
@@ -423,21 +399,17 @@ export class ConnectedAccounts {
399
400 const opts = requestOptions.data;
401 const aclWire = serializeAclConfigForWire(opts.aclConfigForShared);
426 - const body: LinkCreateBodyWithAcl = {
402 + const body: LinkCreateParams = {
403 auth_config_id: authConfigId,
404 user_id: userId,
429 - ...(opts.callbackUrl && { callback_url: opts.callbackUrl }),
430 - ...(opts.alias != null && { alias: opts.alias }),
405 + ...(opts.callbackUrl !== undefined && { callback_url: opts.callbackUrl }),
406 + ...(opts.alias !== undefined && { alias: opts.alias }),
407 ...(opts.accountType !== undefined && { account_type: opts.accountType }),
408 ...(aclWire !== undefined && { acl_config_for_shared: aclWire }),
409 };
410
411 try {
436 - // Cast retained until @composio/client adds account_type / ACL fields
437 - // to LinkCreateParams.
438 - const response = await this.client.link.create(body as unknown as Parameters<
439 - typeof this.client.link.create
440 - >[0]);
412 + const response = await this.client.link.create(body);
413
414 const connectionRequest = createConnectionRequest(
415 this.client,
@@ -447,6 +419,16 @@ export class ConnectedAccounts {
419 );
420 return connectionRequest;
421 } catch (error) {
422 + // Backend rejects ACL fields on PRIVATE connections with a 400 +
423 + // `ConnectedAccount_AclOnlyForShared`. Surface it as a typed error so
424 + // callers can `instanceof` instead of grepping messages.
425 + if (
426 + error instanceof BadRequestError &&
427 + typeof error.message === 'string' &&
428 + error.message.includes('acl_config_for_shared is only valid on SHARED')
429 + ) {
430 + throw new ComposioAclOnlyForSharedError(error.message, { cause: error });
431 + }
432 throw new ComposioFailedToCreateConnectedAccountLink(
433 'Failed to create connected account link',
434 {
@@ -634,7 +616,11 @@ export class ConnectedAccounts {
616 }
617
618 /**
637 - * Update a connected account's alias and/or credentials.
619 + * Enable or disable a connected account (wraps the `/status` endpoint
620 + * — accepts only `{ enabled: boolean }` despite the historical JSDoc
621 + * mentioning "alias and/or credentials"). For ACL writes on SHARED
622 + * connections, see {@link updateAcl}. Alias / credential PATCH isn't
623 + * surfaced on the SDK yet.
624 *
625 * @param {string} nanoid - The unique identifier of the connected account
626 * @param {UpdateConnectedAccountParams} params - The update parameters
@@ -696,8 +682,24 @@ export class ConnectedAccounts {
682 * // Revoke a previously-granted allow list (back to deny-by-default)
683 * await composio.connectedAccounts.updateAcl('ca_abc', { allowedUserIds: [] });
684 * ```
685 + *
686 + * **Empty-array semantics — read carefully.** Passing `[]` for either
687 + * list **replaces** the list, it does not extend it:
688 + *
689 + * - `allowedUserIds: []` → revoke all previously-granted user IDs (state
690 + * reverts to deny-by-default unless `allowAllUsers` is true).
691 + * - `notAllowedUserIds: []` → **clears the deny list**, which silently
692 + * re-grants access to users you previously blocked. Always pair an
693 + * empty deny list with a deliberate audit of the allow side.
694 + *
695 + * @returns The PATCH response (`{ id, status, success }`). To read the
696 + * updated `aclConfigForShared` block, call `get(nanoid)` after the
697 + * promise resolves.
698 */
700 - async updateAcl(nanoid: string, params: UpdateConnectedAccountAclParams): Promise<void> {
699 + async updateAcl(
700 + nanoid: string,
701 + params: UpdateConnectedAccountAclParams
702 + ): Promise<ConnectedAccountPatchResponse> {
703 const parsedParams = UpdateConnectedAccountAclParamsSchema.safeParse(params);
704 if (!parsedParams.success) {
705 throw new ValidationError('Failed to parse connected account ACL update params', {
@@ -705,15 +707,23 @@ export class ConnectedAccounts {
707 });
708 }
709
708 - const body: ConnectedAccountPatchBodyWithAcl = {
710 + const body: ConnectedAccountPatchParams = {
711 acl_config_for_shared: serializeAclConfigForWire(parsedParams.data),
712 };
713
712 - // Cast retained until @composio/client adds acl_config_for_shared to
713 - // ConnectedAccountPatchParams.
714 - await this.client.connectedAccounts.patch(
715 - nanoid,
716 - body as unknown as Parameters<typeof this.client.connectedAccounts.patch>[1]
717 - );
714 + try {
715 + return await this.client.connectedAccounts.patch(nanoid, body);
716 + } catch (error) {
717 + // Same `AclOnlyForShared` 400 the create path can hit — backend
718 + // rejects ACL writes on a PRIVATE row at PATCH-time too.
719 + if (
720 + error instanceof BadRequestError &&
721 + typeof error.message === 'string' &&
722 + error.message.includes('acl_config_for_shared is only valid on SHARED')
723 + ) {
724 + throw new ComposioAclOnlyForSharedError(error.message, { cause: error });
725 + }
726 + throw error;
727 + }
728 }
729 }
ts/packages/core/src/models/ToolRouterSession.ts
+24 -12
@@ -1,5 +1,5 @@
1 import { telemetry } from '../telemetry/Telemetry';
2 -import { Composio as ComposioClient } from '@composio/client';
2 +import { Composio as ComposioClient, BadRequestError } from '@composio/client';
3 import { BaseComposioProvider } from '../provider/BaseProvider';
4 import { ComposioConfig } from '../composio';
5 import {
@@ -33,7 +33,7 @@ import {
33 } from '../types/connectedAccounts.types';
34 import { transform } from '../utils/transform';
35 import { ToolkitConnectionStateSchema } from '../types/toolRouter.types';
36 -import { ValidationError } from '../errors';
36 +import { ComposioAclOnlyForSharedError, ValidationError } from '../errors';
37 import { Tools } from './Tools';
38 import { ToolRouterSessionFilesMount } from './ToolRouterSessionFileMount';
39 import type {
@@ -47,6 +47,7 @@ import type { Tool, ToolExecuteResponse } from '../types/tool.types';
47 import type { SessionProxyExecuteParams } from '../types/toolRouter.types';
48 import type {
49 SessionExecuteParams,
50 + SessionLinkParams,
51 SessionSearchParams,
52 } from '@composio/client/resources/tool-router/session/session.mjs';
53 import { SessionProxyExecuteParamsSchema } from '../types/toolRouter.types';
@@ -321,7 +322,7 @@ export class ToolRouterSession<
322 aclConfigForShared?: ConnectedAccountAclConfig;
323 }
324 ): Promise<ConnectionRequest> {
324 - const aclWire =
325 + const aclWire: SessionLinkParams.ACLConfigForShared | undefined =
326 options?.aclConfigForShared === undefined
327 ? undefined
328 : {
@@ -335,19 +336,30 @@ export class ToolRouterSession<
336 not_allowed_user_ids: options.aclConfigForShared.notAllowedUserIds,
337 }),
338 };
338 - // Cast retained until @composio/client adds account_type +
339 - // acl_config_for_shared to SessionLinkParams (Hermes #9860 + #9902).
340 - const body = {
339 + const body: SessionLinkParams = {
340 toolkit,
342 - ...(options?.callbackUrl && { callback_url: options.callbackUrl }),
343 - ...(options?.alias != null && { alias: options.alias }),
341 + ...(options?.callbackUrl !== undefined && { callback_url: options.callbackUrl }),
342 + ...(options?.alias !== undefined && { alias: options.alias }),
343 ...(options?.accountType !== undefined && { account_type: options.accountType }),
344 ...(aclWire !== undefined && { acl_config_for_shared: aclWire }),
345 };
347 - const response = await this.client.toolRouter.session.link(
348 - this.sessionId,
349 - body as unknown as Parameters<typeof this.client.toolRouter.session.link>[1]
350 - );
346 +
347 + let response;
348 + try {
349 + response = await this.client.toolRouter.session.link(this.sessionId, body);
350 + } catch (error) {
351 + // Backend rejects ACL fields on PRIVATE connections with a 400 +
352 + // `ConnectedAccount_AclOnlyForShared`. Surface it as a typed error
353 + // mirroring `composio.connectedAccounts.link()`.
354 + if (
355 + error instanceof BadRequestError &&
356 + typeof error.message === 'string' &&
357 + error.message.includes('acl_config_for_shared is only valid on SHARED')
358 + ) {
359 + throw new ComposioAclOnlyForSharedError(error.message, { cause: error });
360 + }
361 + throw error;
362 + }
363
364 return createConnectionRequest(
365 this.client,
ts/packages/core/src/types/connectedAccounts.types.ts
+4
@@ -347,6 +347,10 @@ export const UpdateConnectedAccountParamsSchema = z.object({
347 * Each field is optional, but at least one must be provided — passing an
348 * empty object is rejected as a no-op.
349 */
350 +// NOTE: `UpdateConnectedAccountAclParamsSchema` is a ZodEffects (because of
351 +// the `.refine` below) — it does not expose `.shape`. If you need to reuse
352 +// individual ACL fields elsewhere, pull them from
353 +// `ConnectedAccountAclConfigSchema.shape` (the unrefined base) instead.
354 export const UpdateConnectedAccountAclParamsSchema = ConnectedAccountAclConfigSchema.refine(
355 acl =>
356 acl.allowAllUsers !== undefined ||
ts/packages/core/test/connectedAccounts/connectedAccounts.test.ts
+176
@@ -4,9 +4,11 @@ import { ConnectedAccounts } from '../../src/models/ConnectedAccounts';
4 import ComposioClient from '@composio/client';
5 import { ConnectedAccountRetrieveResponse } from '@composio/client/resources/connected-accounts.mjs';
6 import {
7 + ComposioAclOnlyForSharedError,
8 ComposioConnectedAccountNotFoundError,
9 ComposioFailedToCreateConnectedAccountLink,
10 } from '../../src/errors';
11 +import { BadRequestError } from '@composio/client';
12 import { ConnectedAccountStatuses } from '../../src/types/connectedAccounts.types';
13 import { ComposioMultipleConnectedAccountsError } from '../../src/errors';
14 import { AuthSchemeTypes } from '../../src/types/authConfigs.types';
@@ -22,6 +24,7 @@ const extendedMockClient = {
24 retrieve: vi.fn(),
25 delete: vi.fn(),
26 refresh: vi.fn(),
27 + patch: vi.fn(),
28 updateStatus: vi.fn(),
29 createConnectedAccountLink: vi.fn(),
30 },
@@ -1517,4 +1520,177 @@ describe('ConnectedAccounts', () => {
1520 expect(connectionRequest).toHaveProperty('id', 'conn_new');
1521 });
1522 });
1523 +
1524 + describe('link with accountType + ACL (Hermes #9860, #9902)', () => {
1525 + beforeEach(() => {
1526 + extendedMockClient.connectedAccounts.list.mockResolvedValue({
1527 + items: [],
1528 + next_cursor: null,
1529 + total_pages: 0,
1530 + });
1531 + extendedMockClient.link.create.mockResolvedValue({
1532 + connected_account_id: 'conn_shared_abc',
1533 + redirect_url: 'https://connect.composio.dev/auth?token=xyz',
1534 + });
1535 + });
1536 +
1537 + it('forwards accountType=SHARED + nested aclConfigForShared to client.link.create', async () => {
1538 + await connectedAccounts.link('user_123', 'auth_config_123', {
1539 + accountType: 'SHARED',
1540 + aclConfigForShared: {
1541 + allowAllUsers: true,
1542 + notAllowedUserIds: ['user_bob'],
1543 + },
1544 + });
1545 +
1546 + expect(extendedMockClient.link.create).toHaveBeenCalledWith({
1547 + auth_config_id: 'auth_config_123',
1548 + user_id: 'user_123',
1549 + account_type: 'SHARED',
1550 + acl_config_for_shared: {
1551 + allow_all_users: true,
1552 + not_allowed_user_ids: ['user_bob'],
1553 + },
1554 + });
1555 + });
1556 +
1557 + it('omits acl_config_for_shared when aclConfigForShared is undefined', async () => {
1558 + await connectedAccounts.link('user_123', 'auth_config_123', { accountType: 'SHARED' });
1559 +
1560 + const body = extendedMockClient.link.create.mock.calls[0][0];
1561 + expect(body.account_type).toBe('SHARED');
1562 + expect('acl_config_for_shared' in body).toBe(false);
1563 + });
1564 +
1565 + it('serializes only the fields the caller provided (PATCH-style on inner block)', async () => {
1566 + await connectedAccounts.link('user_123', 'auth_config_123', {
1567 + accountType: 'SHARED',
1568 + aclConfigForShared: { allowedUserIds: ['user_alice'] },
1569 + });
1570 +
1571 + expect(extendedMockClient.link.create).toHaveBeenCalledWith({
1572 + auth_config_id: 'auth_config_123',
1573 + user_id: 'user_123',
1574 + account_type: 'SHARED',
1575 + acl_config_for_shared: { allowed_user_ids: ['user_alice'] },
1576 + });
1577 + });
1578 +
1579 + it('preserves explicit empty arrays in the serialized body', async () => {
1580 + await connectedAccounts.link('user_123', 'auth_config_123', {
1581 + accountType: 'SHARED',
1582 + aclConfigForShared: { allowedUserIds: [], notAllowedUserIds: [] },
1583 + });
1584 +
1585 + expect(extendedMockClient.link.create).toHaveBeenCalledWith({
1586 + auth_config_id: 'auth_config_123',
1587 + user_id: 'user_123',
1588 + account_type: 'SHARED',
1589 + acl_config_for_shared: {
1590 + allowed_user_ids: [],
1591 + not_allowed_user_ids: [],
1592 + },
1593 + });
1594 + });
1595 +
1596 + it('maps 400 AclOnlyForShared to ComposioAclOnlyForSharedError', async () => {
1597 + extendedMockClient.link.create.mockReset();
1598 + extendedMockClient.link.create.mockRejectedValueOnce(
1599 + Object.assign(new BadRequestError(400, undefined, 'acl_config_for_shared is only valid on SHARED connections.', {}), {})
1600 + );
1601 +
1602 + await expect(
1603 + connectedAccounts.link('user_123', 'auth_config_123', {
1604 + accountType: 'PRIVATE',
1605 + aclConfigForShared: { allowAllUsers: true },
1606 + })
1607 + ).rejects.toBeInstanceOf(ComposioAclOnlyForSharedError);
1608 + });
1609 +
1610 + it('falls back to ComposioFailedToCreateConnectedAccountLink on unrelated errors', async () => {
1611 + extendedMockClient.link.create.mockReset();
1612 + extendedMockClient.link.create.mockRejectedValueOnce(new Error('network died'));
1613 +
1614 + await expect(connectedAccounts.link('user_123', 'auth_config_123')).rejects.toBeInstanceOf(
1615 + ComposioFailedToCreateConnectedAccountLink
1616 + );
1617 + });
1618 + });
1619 +
1620 + describe('updateAcl', () => {
1621 + it('serializes PATCH body with nested acl_config_for_shared', async () => {
1622 + extendedMockClient.connectedAccounts.patch.mockResolvedValueOnce({
1623 + id: 'ca_abc',
1624 + status: 'ACTIVE',
1625 + success: true,
1626 + });
1627 +
1628 + const result = await connectedAccounts.updateAcl('ca_abc', {
1629 + allowAllUsers: true,
1630 + notAllowedUserIds: ['user_bob'],
1631 + });
1632 +
1633 + expect(extendedMockClient.connectedAccounts.patch).toHaveBeenCalledWith('ca_abc', {
1634 + acl_config_for_shared: {
1635 + allow_all_users: true,
1636 + not_allowed_user_ids: ['user_bob'],
1637 + },
1638 + });
1639 + expect(result).toEqual({ id: 'ca_abc', status: 'ACTIVE', success: true });
1640 + });
1641 +
1642 + it('omits absent fields from the inner block (PATCH semantics)', async () => {
1643 + extendedMockClient.connectedAccounts.patch.mockResolvedValueOnce({
1644 + id: 'ca_abc',
1645 + status: 'ACTIVE',
1646 + success: true,
1647 + });
1648 +
1649 + await connectedAccounts.updateAcl('ca_abc', { allowedUserIds: ['user_alice'] });
1650 +
1651 + expect(extendedMockClient.connectedAccounts.patch).toHaveBeenCalledWith('ca_abc', {
1652 + acl_config_for_shared: { allowed_user_ids: ['user_alice'] },
1653 + });
1654 + });
1655 +
1656 + it('preserves empty array to clear a list', async () => {
1657 + extendedMockClient.connectedAccounts.patch.mockResolvedValueOnce({
1658 + id: 'ca_abc',
1659 + status: 'ACTIVE',
1660 + success: true,
1661 + });
1662 +
1663 + await connectedAccounts.updateAcl('ca_abc', { allowedUserIds: [] });
1664 +
1665 + expect(extendedMockClient.connectedAccounts.patch).toHaveBeenCalledWith('ca_abc', {
1666 + acl_config_for_shared: { allowed_user_ids: [] },
1667 + });
1668 + });
1669 +
1670 + it('rejects an empty params object via the refine', async () => {
1671 + await expect(connectedAccounts.updateAcl('ca_abc', {})).rejects.toMatchObject({
1672 + name: 'ValidationError',
1673 + });
1674 + expect(extendedMockClient.connectedAccounts.patch).not.toHaveBeenCalled();
1675 + });
1676 +
1677 + it('maps 400 AclOnlyForShared to ComposioAclOnlyForSharedError', async () => {
1678 + extendedMockClient.connectedAccounts.patch.mockRejectedValueOnce(
1679 + new BadRequestError(400, undefined, 'acl_config_for_shared is only valid on SHARED connections.', {})
1680 + );
1681 +
1682 + await expect(
1683 + connectedAccounts.updateAcl('ca_abc', { allowAllUsers: true })
1684 + ).rejects.toBeInstanceOf(ComposioAclOnlyForSharedError);
1685 + });
1686 +
1687 + it('rethrows non-AclOnlyForShared errors unchanged', async () => {
1688 + const otherError = new Error('connection lost');
1689 + extendedMockClient.connectedAccounts.patch.mockRejectedValueOnce(otherError);
1690 +
1691 + await expect(
1692 + connectedAccounts.updateAcl('ca_abc', { allowAllUsers: true })
1693 + ).rejects.toBe(otherError);
1694 + });
1695 + });
1696 });