972
});
973
974
describe('link', () => {
975
+ beforeEach(() => {
976
+ // link() now mirrors initiate() and pre-flights connectedAccounts.list to
977
+ // enforce the allowMultiple guard. Default to no existing connections so
978
+ // existing tests don't need to mock the list call themselves.
979
+ extendedMockClient.connectedAccounts.list.mockResolvedValue({
980
+ items: [],
981
+ next_cursor: null,
982
+ total_pages: 0,
983
+ });
984
+ });
985
+
986
it('should create a connected account link without options and return a ConnectionRequest', async () => {
987
const userId = 'user_123';
988
const authConfigId = 'auth_config_123';
1315
callback_url: 'https://example.com/callback',
1316
});
1317
});
1318
+
1319
+ it('throws ComposioMultipleConnectedAccountsError when an active connection exists and allowMultiple is false', async () => {
1320
+ const userId = 'user_123';
1321
+ const authConfigId = 'auth_config_123';
1322
+
1323
+ extendedMockClient.connectedAccounts.list.mockReset();
1324
+ extendedMockClient.connectedAccounts.list.mockResolvedValueOnce({
1325
+ items: [
1326
+ {
1327
+ id: 'conn_existing',
1328
+ status: ConnectedAccountStatuses.ACTIVE,
1329
+ auth_config: { id: authConfigId, auth_scheme: 'OAUTH2', is_composio_managed: true },
1330
+ toolkit: { slug: 'gmail' },
1331
+ },
1332
+ ],
1333
+ next_cursor: null,
1334
+ total_pages: 1,
1335
+ });
1336
+
1337
+ await expect(connectedAccounts.link(userId, authConfigId)).rejects.toThrow(
1338
+ ComposioMultipleConnectedAccountsError
1339
+ );
1340
+
1341
+ expect(extendedMockClient.link.create).not.toHaveBeenCalled();
1342
+ });
1343
+
1344
+ it('skips the guard when allowMultiple is true and proceeds with link.create', async () => {
1345
+ const userId = 'user_123';
1346
+ const authConfigId = 'auth_config_123';
1347
+
1348
+ extendedMockClient.connectedAccounts.list.mockReset();
1349
+ extendedMockClient.connectedAccounts.list.mockResolvedValueOnce({
1350
+ items: [
1351
+ {
1352
+ id: 'conn_existing',
1353
+ status: ConnectedAccountStatuses.ACTIVE,
1354
+ auth_config: { id: authConfigId, auth_scheme: 'OAUTH2', is_composio_managed: true },
1355
+ toolkit: { slug: 'gmail' },
1356
+ },
1357
+ ],
1358
+ next_cursor: null,
1359
+ total_pages: 1,
1360
+ });
1361
+ extendedMockClient.link.create.mockResolvedValueOnce({
1362
+ connected_account_id: 'conn_new',
1363
+ redirect_url: 'https://connect.composio.dev/auth?token=xyz',
1364
+ });
1365
+
1366
+ const connectionRequest = await connectedAccounts.link(userId, authConfigId, {
1367
+ allowMultiple: true,
1368
+ alias: 'work-gmail',
1369
+ });
1370
+
1371
+ expect(extendedMockClient.link.create).toHaveBeenCalledWith({
1372
+ auth_config_id: authConfigId,
1373
+ user_id: userId,
1374
+ alias: 'work-gmail',
1375
+ });
1376
+ expect(connectionRequest).toHaveProperty('id', 'conn_new');
1377
+ });
1378
});
1379
});