@inixiative/integrations 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (197) hide show
  1. package/README.md +21 -13
  2. package/package.json +3 -2
  3. package/src/catalog/catalogOperationMeta.ts +4 -0
  4. package/src/catalog/catalogOperations.ts +10 -0
  5. package/src/catalog/providerModel.ts +0 -1
  6. package/src/catalog/refreshTokenRotates.ts +12 -0
  7. package/src/contracts.ts +5 -11
  8. package/src/credentials/credentialAuth.ts +38 -0
  9. package/src/credentials/credentialClient.ts +2 -2
  10. package/src/credentials/exchangeOauthCode.ts +30 -36
  11. package/src/credentials/mintProviderCredential.ts +26 -40
  12. package/src/credentials/providerExchangeTimeoutMs.ts +1 -1
  13. package/src/credentials/refreshProviderCredential.ts +62 -65
  14. package/src/credentials/renewalError.ts +11 -0
  15. package/src/credentials/requestOauthToken.ts +28 -0
  16. package/src/credentials/validateCredentialSecret.ts +5 -5
  17. package/src/index.ts +0 -1
  18. package/src/integrationFamilies/atlassianIntegrationFamily.ts +1 -0
  19. package/src/integrationFamilies/githubIntegrationFamily.ts +1 -0
  20. package/src/integrationFamilies/googleIntegrationFamily.ts +1 -0
  21. package/src/operations/providerOperationInput.ts +6 -0
  22. package/src/operations/providerOperationInputSchema.ts +36 -0
  23. package/src/operations/providerOperationOrThrow.ts +23 -0
  24. package/src/operations/providerOperationSet.ts +7 -0
  25. package/src/operations/providerOperations.ts +38 -0
  26. package/src/providers/confluence/confluenceApiBaseUrl.ts +1 -0
  27. package/src/providers/confluence/confluenceOperations.ts +4 -0
  28. package/src/providers/confluence/confluenceProvider.ts +5 -8
  29. package/src/providers/confluence/models/page/fetchConfluencePage.ts +23 -0
  30. package/src/providers/discord/discordApiBaseUrl.ts +1 -0
  31. package/src/providers/discord/discordOperations.ts +8 -0
  32. package/src/providers/discord/discordProvider.ts +5 -14
  33. package/src/providers/discord/models/channel/discordChannelKind.ts +1 -0
  34. package/src/providers/discord/models/channel/fetchDiscordChannel.ts +25 -0
  35. package/src/providers/discord/models/channel/fetchDiscordChannelMessages.ts +37 -0
  36. package/src/providers/drive/driveApiBaseUrl.ts +1 -0
  37. package/src/providers/drive/driveOperations.ts +4 -0
  38. package/src/providers/drive/driveProvider.ts +5 -8
  39. package/src/providers/drive/models/file/fetchDriveFile.ts +27 -0
  40. package/src/providers/github/auth/createGithubInstallationToken.ts +19 -0
  41. package/src/providers/github/auth/fetchGithubAppInstallUrl.ts +21 -0
  42. package/src/providers/github/auth/fetchGithubAppInstallation.ts +16 -19
  43. package/src/providers/github/auth/fetchGithubOrganizationRole.ts +22 -22
  44. package/src/providers/github/auth/fetchGithubUser.ts +10 -4
  45. package/src/providers/github/auth/githubAppAuth.ts +6 -0
  46. package/src/providers/github/auth/listGithubUserInstallationPage.ts +18 -0
  47. package/src/providers/github/events/listGithubNotificationPage.ts +18 -0
  48. package/src/providers/github/githubApiBaseUrl.ts +1 -0
  49. package/src/providers/github/githubOrganizationProvider.ts +5 -1
  50. package/src/providers/github/githubPagination.ts +2 -2
  51. package/src/providers/github/githubRequestHeaders.ts +4 -6
  52. package/src/providers/github/githubUserProvider.ts +5 -2
  53. package/src/providers/github/models/account/githubAccount.ts +0 -1
  54. package/src/providers/github/models/repository/fetchGithubBlob.ts +59 -0
  55. package/src/providers/github/models/repository/fetchGithubCommit.ts +38 -0
  56. package/src/providers/github/models/repository/fetchGithubTree.ts +74 -0
  57. package/src/providers/github/models/repository/githubObjectRequest.ts +15 -0
  58. package/src/providers/github/models/repository/githubRepository.ts +1 -11
  59. package/src/providers/github/models/repository/githubRepositoryOperations.ts +10 -0
  60. package/src/providers/github/models/repository/listGithubInstallationRepositoryPage.ts +18 -0
  61. package/src/providers/github/models/repository/listGithubUserInstallationRepositoryPage.ts +22 -0
  62. package/src/providers/github/models/repository/readGithubObjectIdentity.ts +9 -0
  63. package/src/providers/github/services/fetchGithubUserInstallation.ts +25 -0
  64. package/src/providers/github/services/listGithubNotifications.ts +27 -0
  65. package/src/providers/github/services/listInstallationRepositories.ts +34 -0
  66. package/src/providers/github/services/listUserRepositories.ts +43 -0
  67. package/src/providers/gmail/gmailApiBaseUrl.ts +1 -0
  68. package/src/providers/gmail/gmailOperations.ts +10 -0
  69. package/src/providers/gmail/gmailProvider.ts +6 -9
  70. package/src/providers/gmail/models/label/listGmailLabelMessages.ts +45 -0
  71. package/src/providers/gmail/models/message/fetchGmailMessage.ts +19 -0
  72. package/src/providers/gmail/models/message/fetchGmailMessageBatch.ts +20 -0
  73. package/src/providers/gmail/models/message/gmailMessageKind.ts +1 -0
  74. package/src/providers/gmail/models/message/gmailMessageRequest.ts +9 -0
  75. package/src/providers/gmail/models/message/readGmailMessage.ts +26 -0
  76. package/src/providers/google/auth/verifyGoogleIdToken.ts +3 -3
  77. package/src/providers/jira/jiraApiBaseUrl.ts +1 -0
  78. package/src/providers/jira/jiraOperations.ts +4 -0
  79. package/src/providers/jira/jiraProvider.ts +5 -8
  80. package/src/providers/jira/models/issue/fetchJiraIssue.ts +22 -0
  81. package/src/providers/linear/events/createLinearWebhook.ts +29 -20
  82. package/src/providers/linear/events/deleteLinearWebhook.ts +16 -9
  83. package/src/providers/linear/events/linearWebhook.ts +1 -1
  84. package/src/providers/linear/events/listLinearWebhookPage.ts +23 -0
  85. package/src/providers/linear/events/repairLinearWebhook.ts +17 -13
  86. package/src/providers/linear/linearApiBaseUrl.ts +1 -0
  87. package/src/providers/linear/linearGraphqlErrorCode.ts +8 -0
  88. package/src/providers/linear/linearOperations.ts +4 -0
  89. package/src/providers/linear/linearPagination.ts +3 -9
  90. package/src/providers/linear/linearProvider.ts +5 -2
  91. package/src/providers/linear/models/issue/fetchLinearIssue.ts +32 -0
  92. package/src/providers/linear/models/team/fetchLinearWorkspace.ts +23 -13
  93. package/src/providers/linear/models/team/linearTeam.ts +0 -1
  94. package/src/providers/linear/services/listLinearWebhooks.ts +45 -0
  95. package/src/providers/notion/models/page/fetchNotionPage.ts +32 -0
  96. package/src/providers/notion/models/page/fetchNotionPageBlocks.ts +39 -0
  97. package/src/providers/notion/models/page/notionPageKind.ts +1 -0
  98. package/src/providers/notion/notionApiBaseUrl.ts +1 -0
  99. package/src/providers/notion/notionOperations.ts +8 -0
  100. package/src/providers/notion/notionProvider.ts +5 -14
  101. package/src/providers/notion/notionVersion.ts +1 -0
  102. package/src/providers/slack/auth/fetchSlackIdentity.ts +14 -6
  103. package/src/providers/slack/models/account/slackAccount.ts +0 -1
  104. package/src/providers/slack/models/channel/fetchSlackChannel.ts +32 -0
  105. package/src/providers/slack/models/channel/fetchSlackChannelMessages.ts +34 -0
  106. package/src/providers/slack/models/channel/listSlackUserConversations.ts +19 -0
  107. package/src/providers/slack/models/channel/slackChannel.ts +0 -14
  108. package/src/providers/slack/readSlackBody.ts +10 -0
  109. package/src/providers/slack/services/listSlackChannels.ts +23 -0
  110. package/src/providers/slack/slackApiBaseUrl.ts +1 -0
  111. package/src/providers/slack/slackOperations.ts +8 -0
  112. package/src/providers/slack/slackPagination.ts +2 -2
  113. package/src/providers/slack/slackProvider.ts +9 -1
  114. package/src/providers/slack/slackProviderError.ts +2 -2
  115. package/src/providers/teams/models/channel/fetchTeamsChannelMessages.ts +36 -0
  116. package/src/providers/teams/teamsApiBaseUrl.ts +1 -0
  117. package/src/providers/teams/teamsOperations.ts +6 -0
  118. package/src/providers/teams/teamsProvider.ts +5 -8
  119. package/src/utils/acceptJsonHeaders.ts +1 -0
  120. package/src/utils/pageQuerySchema.ts +13 -0
  121. package/src/utils/readProviderLimits.ts +1 -2
  122. package/src/credentials/fetchRenewalResponse.ts +0 -41
  123. package/src/credentials/renewalRequest.ts +0 -1
  124. package/src/operations/buildProviderRequest.ts +0 -55
  125. package/src/operations/executeProvider.ts +0 -26
  126. package/src/operations/findOperationHandler.ts +0 -6
  127. package/src/operations/operationHandler.ts +0 -8
  128. package/src/operations/operationHandlers.ts +0 -39
  129. package/src/operations/operationRequestInput.ts +0 -12
  130. package/src/operations/providerRequestSpec.ts +0 -1
  131. package/src/providers/confluence/confluenceOperationHandler.ts +0 -14
  132. package/src/providers/discord/discordOperationHandler.ts +0 -30
  133. package/src/providers/drive/driveOperationHandler.ts +0 -21
  134. package/src/providers/github/auth/fetchGithubUserInstallation.ts +0 -21
  135. package/src/providers/github/auth/githubAppClient.ts +0 -4
  136. package/src/providers/github/auth/githubAppInstallUrl.ts +0 -20
  137. package/src/providers/github/auth/githubClientForApp.ts +0 -11
  138. package/src/providers/github/events/listGithubNotifications.ts +0 -27
  139. package/src/providers/github/fetchAllGithubPages.ts +0 -12
  140. package/src/providers/github/iterateGithubPages.ts +0 -12
  141. package/src/providers/github/models/repository/githubOperationHandler.ts +0 -36
  142. package/src/providers/github/models/repository/listInstallationRepositories.ts +0 -31
  143. package/src/providers/github/models/repository/listUserRepositories.ts +0 -36
  144. package/src/providers/github/models/repository/readGithubObject.ts +0 -85
  145. package/src/providers/github/requestGithub.ts +0 -18
  146. package/src/providers/gmail/buildGmailMessageRequest.ts +0 -22
  147. package/src/providers/gmail/fetchGmailMessages.ts +0 -81
  148. package/src/providers/gmail/gmailOperationHandler.ts +0 -12
  149. package/src/providers/jira/jiraOperationHandler.ts +0 -14
  150. package/src/providers/linear/events/listLinearWebhooks.ts +0 -44
  151. package/src/providers/linear/fetchAllLinearPages.ts +0 -40
  152. package/src/providers/linear/linearClient.ts +0 -5
  153. package/src/providers/linear/linearRequestInput.ts +0 -1
  154. package/src/providers/linear/models/issue/linearIssue.ts +0 -11
  155. package/src/providers/linear/models/issue/linearOperationHandler.ts +0 -30
  156. package/src/providers/linear/requestLinear.ts +0 -51
  157. package/src/providers/notion/notionOperationHandler.ts +0 -32
  158. package/src/providers/slack/fetchAllSlackPages.ts +0 -12
  159. package/src/providers/slack/models/channel/listSlackChannels.ts +0 -26
  160. package/src/providers/slack/models/channel/slackOperationHandler.ts +0 -30
  161. package/src/providers/slack/requestSlack.ts +0 -22
  162. package/src/providers/teams/teamsOperationHandler.ts +0 -24
  163. package/src/utils/headerNumber.ts +0 -6
  164. package/src/utils/pagination/applyCaps.ts +0 -18
  165. package/src/utils/pagination/byCursorKeys.ts +0 -7
  166. package/src/utils/pagination/byCursorOptions.ts +0 -7
  167. package/src/utils/pagination/byPageKeys.ts +0 -7
  168. package/src/utils/pagination/byPageOptions.ts +0 -8
  169. package/src/utils/pagination/collectPages.ts +0 -27
  170. package/src/utils/pagination/compactRequest.ts +0 -4
  171. package/src/utils/pagination/fetchAllByCursor.ts +0 -6
  172. package/src/utils/pagination/fetchAllByPage.ts +0 -6
  173. package/src/utils/pagination/fetchAllRequestPages.ts +0 -16
  174. package/src/utils/pagination/incompletePageWalkError.ts +0 -8
  175. package/src/utils/pagination/isAnotherPage.ts +0 -20
  176. package/src/utils/pagination/iterateByCursor.ts +0 -49
  177. package/src/utils/pagination/iterateByPage.ts +0 -59
  178. package/src/utils/pagination/iterateProviderPages.ts +0 -27
  179. package/src/utils/pagination/iterateRequestPages.ts +0 -18
  180. package/src/utils/pagination/pageWalkError.ts +0 -6
  181. package/src/utils/pagination/paginationOptions.ts +0 -9
  182. package/src/utils/pagination/providerPagesOptions.ts +0 -8
  183. package/src/utils/pagination/providerPagination.ts +0 -6
  184. package/src/utils/pagination/readPage.ts +0 -29
  185. package/src/utils/pagination/readPath.ts +0 -12
  186. package/src/utils/pagination/repeatedCursorError.ts +0 -10
  187. package/src/utils/providerClient.ts +0 -3
  188. package/src/utils/providerError.ts +0 -10
  189. package/src/utils/providerRequest.ts +0 -22
  190. package/src/utils/providerRequestInput.ts +0 -7
  191. package/src/utils/providerResponseLimit.ts +0 -1
  192. package/src/utils/providerSend.ts +0 -1
  193. package/src/utils/readProviderJson.ts +0 -38
  194. package/src/utils/readRateLimit.ts +0 -29
  195. package/src/utils/requestProviderJson.ts +0 -13
  196. package/src/utils/responseBudget.ts +0 -1
  197. package/src/utils/sendProviderRequest.ts +0 -33
@@ -1,36 +0,0 @@
1
- import { githubInputSchemas, githubOperationSchema } from '@inixiative/signet/contracts';
2
- import type { OperationHandler } from '../../../../operations/operationHandler';
3
- import { objectSchema } from '../../../../utils/objectSchema';
4
- import { githubRequestHeaders } from '../../githubRequestHeaders';
5
- import { githubRepositoryMetadataSchema } from './githubRepositoryMetadataSchema';
6
- import { readGithubObject } from './readGithubObject';
7
-
8
- const objectKinds = {
9
- 'commits.read': 'commits',
10
- 'trees.read': 'trees',
11
- 'blobs.read': 'blobs',
12
- } as const;
13
-
14
- const requestedObject = (operation: string, input: Record<string, unknown>) => {
15
- const declared = githubOperationSchema.parse(operation);
16
- return { declared, objectId: githubInputSchemas[declared].parse(input).objectId };
17
- };
18
-
19
- export const githubOperationHandler: OperationHandler = {
20
- request: ({ context, metadata, headers }) => {
21
- const { declared, objectId } = requestedObject(context.operation, context.input);
22
- const { fullName } = githubRepositoryMetadataSchema.parse(metadata);
23
- githubRequestHeaders(headers);
24
- return {
25
- url: new URL(
26
- `https://api.github.com/repos/${fullName}/git/${objectKinds[declared]}/${objectId}`,
27
- ),
28
- };
29
- },
30
- parse: (body, context) =>
31
- readGithubObject(
32
- objectSchema.parse(body),
33
- context,
34
- requestedObject(context.operation, context.input).objectId,
35
- ),
36
- };
@@ -1,31 +0,0 @@
1
- import { z } from 'zod';
2
- import { providerResourceLimit } from '../../../../contracts';
3
- import type { ProviderClient } from '../../../../utils/providerClient';
4
- import { ProviderError } from '../../../../utils/providerError';
5
- import { fetchAllGithubPages } from '../../fetchAllGithubPages';
6
- import { githubRepositoryName } from './githubRepositoryName';
7
-
8
- const totalSchema = z.object({ total_count: z.number().int().min(0) });
9
- const repositoriesSchema = z.array(
10
- z.object({ id: z.number().int().positive(), full_name: z.string() }),
11
- );
12
-
13
- export const listInstallationRepositories = async (client: ProviderClient) => {
14
- const repositories = repositoriesSchema.parse(
15
- await fetchAllGithubPages(
16
- client,
17
- { path: '/installation/repositories' },
18
- {
19
- keys: { data: 'repositories' },
20
- onResponse: (response) => {
21
- if (totalSchema.parse(response).total_count > providerResourceLimit)
22
- throw new ProviderError('too_many_repositories', 409);
23
- },
24
- },
25
- ),
26
- );
27
- const listed = new Map(
28
- repositories.map(({ id, full_name }) => [String(id), githubRepositoryName(full_name)]),
29
- );
30
- return [...listed].map(([id, fullName]) => ({ id, fullName }));
31
- };
@@ -1,36 +0,0 @@
1
- import { z } from 'zod';
2
- import { providerResourceLimit } from '../../../../contracts';
3
- import type { ProviderClient } from '../../../../utils/providerClient';
4
- import { ProviderError } from '../../../../utils/providerError';
5
- import { fetchAllGithubPages } from '../../fetchAllGithubPages';
6
- import { githubRepositoryName } from './githubRepositoryName';
7
-
8
- const installationsSchema = z.array(z.object({ id: z.number().int().positive() }));
9
- const repositoriesSchema = z.array(
10
- z.object({ id: z.number().int().positive(), full_name: z.string() }),
11
- );
12
-
13
- // why: a GitHub App user token reaches only repositories in the App's installations the user sees.
14
- export const listUserRepositories = async (client: ProviderClient) => {
15
- const installations = installationsSchema.parse(
16
- await fetchAllGithubPages(
17
- client,
18
- { path: '/user/installations' },
19
- { keys: { data: 'installations' } },
20
- ),
21
- );
22
- const listed = new Map<string, string>();
23
- for (const installation of installations) {
24
- const repositories = repositoriesSchema.parse(
25
- await fetchAllGithubPages(
26
- client,
27
- { path: `/user/installations/${installation.id}/repositories` },
28
- { keys: { data: 'repositories' } },
29
- ),
30
- );
31
- for (const repository of repositories)
32
- listed.set(String(repository.id), githubRepositoryName(repository.full_name));
33
- if (listed.size > providerResourceLimit) throw new ProviderError('too_many_repositories', 409);
34
- }
35
- return [...listed].map(([id, fullName]) => ({ id, fullName }));
36
- };
@@ -1,85 +0,0 @@
1
- import { createHash } from 'node:crypto';
2
- import { gitObjectIdSchema } from '@inixiative/signet/contracts';
3
- import { z } from 'zod';
4
- import type { ProviderContext } from '../../../../contracts';
5
- import { ProviderError } from '../../../../utils/providerError';
6
- import { githubTreeEntryModeSchema } from './githubTreeEntryModeSchema';
7
- import { githubTreeEntryTypeForMode } from './githubTreeEntryTypeForMode';
8
- import { githubTreeEntryTypeSchema } from './githubTreeEntryTypeSchema';
9
-
10
- export const readGithubObject = (data: unknown, context: ProviderContext, objectId: string) => {
11
- const identity = z.object({ sha: gitObjectIdSchema }).parse(data);
12
- if (identity.sha !== objectId) throw new ProviderError('provider_invalid_response');
13
- if (context.operation === 'commits.read')
14
- return z
15
- .object({ sha: gitObjectIdSchema, tree: z.object({ sha: gitObjectIdSchema }) })
16
- .parse(data);
17
- if (context.operation === 'trees.read') {
18
- const tree = z
19
- .object({
20
- sha: gitObjectIdSchema,
21
- truncated: z.literal(false),
22
- tree: z
23
- .array(
24
- z
25
- .object({
26
- path: z
27
- .string()
28
- .min(1)
29
- .max(255)
30
- .refine(
31
- (path) =>
32
- path !== '.' &&
33
- path !== '..' &&
34
- [...path].every(
35
- (character) =>
36
- character.charCodeAt(0) >= 32 &&
37
- character.charCodeAt(0) !== 127 &&
38
- character !== '/' &&
39
- character !== String.fromCharCode(92),
40
- ),
41
- ),
42
- mode: githubTreeEntryModeSchema,
43
- type: githubTreeEntryTypeSchema,
44
- sha: gitObjectIdSchema,
45
- size: z
46
- .number()
47
- .int()
48
- .min(0)
49
- .max(512 * 1024)
50
- .optional(),
51
- })
52
- .refine((entry) => githubTreeEntryTypeForMode[entry.mode] === entry.type),
53
- )
54
- .max(context.limit),
55
- })
56
- .parse(data);
57
- if (new Set(tree.tree.map((entry) => entry.path)).size !== tree.tree.length)
58
- throw new ProviderError('provider_invalid_response');
59
- return tree;
60
- }
61
- const blob = z
62
- .object({
63
- sha: gitObjectIdSchema,
64
- encoding: z.literal('base64'),
65
- size: z
66
- .number()
67
- .int()
68
- .min(0)
69
- .max(512 * 1024),
70
- content: z
71
- .string()
72
- .max(750000)
73
- .regex(/^[A-Za-z0-9+/=\r\n]*$/),
74
- })
75
- .parse(data);
76
- const encoded = blob.content.replace(/[\r\n]/g, '');
77
- const bytes = Buffer.from(encoded, 'base64');
78
- if (
79
- bytes.toString('base64') !== encoded ||
80
- bytes.length !== blob.size ||
81
- createHash('sha1').update(`blob ${bytes.length}\0`).update(bytes).digest('hex') !== blob.sha
82
- )
83
- throw new ProviderError('provider_invalid_response');
84
- return { sha: blob.sha, encoding: blob.encoding, size: blob.size, content: encoded };
85
- };
@@ -1,18 +0,0 @@
1
- import type { ProviderClient } from '../../utils/providerClient';
2
- import { providerRequest } from '../../utils/providerRequest';
3
- import type { ProviderRequestInput } from '../../utils/providerRequestInput';
4
- import { requestProviderJson } from '../../utils/requestProviderJson';
5
- import { githubRequestHeaders } from './githubRequestHeaders';
6
-
7
- export const requestGithub = async (
8
- { token, send = fetch }: ProviderClient,
9
- input: ProviderRequestInput,
10
- ) =>
11
- await requestProviderJson(
12
- send,
13
- providerRequest(
14
- 'https://api.github.com',
15
- input,
16
- githubRequestHeaders(new Headers(input.headers), token),
17
- ),
18
- );
@@ -1,22 +0,0 @@
1
- import { ProviderError } from '../../utils/providerError';
2
-
3
- const gmailMessageIdPattern = /^[A-Za-z0-9_-]{1,64}$/;
4
-
5
- export const buildGmailMessageRequest = (
6
- listRequest: Request,
7
- messageId: unknown,
8
- signal: AbortSignal = listRequest.signal,
9
- ) => {
10
- if (typeof messageId !== 'string' || !gmailMessageIdPattern.test(messageId))
11
- throw new ProviderError('provider_invalid_response');
12
- const url = new URL(`https://gmail.googleapis.com/gmail/v1/users/me/messages/${messageId}`);
13
- url.searchParams.set('format', 'metadata');
14
- for (const header of ['From', 'To', 'Subject', 'Date'])
15
- url.searchParams.append('metadataHeaders', header);
16
- return new Request(url.toString(), {
17
- method: 'GET',
18
- headers: listRequest.headers,
19
- redirect: 'error',
20
- signal,
21
- });
22
- };
@@ -1,81 +0,0 @@
1
- import { z } from 'zod';
2
- import type { ProviderContext } from '../../contracts';
3
- import { providerResponseLimit } from '../../utils/providerResponseLimit';
4
- import type { ProviderSend } from '../../utils/providerSend';
5
- import { readProviderJson } from '../../utils/readProviderJson';
6
- import { sendProviderRequest } from '../../utils/sendProviderRequest';
7
- import { buildGmailMessageRequest } from './buildGmailMessageRequest';
8
-
9
- const gmailConcurrency = 10;
10
- const listSchema = z.object({
11
- messages: z.array(z.object({ id: z.string() })).default([]),
12
- nextPageToken: z.string().optional(),
13
- });
14
- const messageSchema = z.object({
15
- id: z.string(),
16
- threadId: z.string(),
17
- snippet: z.string().default(''),
18
- payload: z
19
- .object({ headers: z.array(z.object({ name: z.string(), value: z.string() })).default([]) })
20
- .default({ headers: [] }),
21
- });
22
-
23
- const projectMessage = (value: unknown) => {
24
- const message = messageSchema.parse(value);
25
- const header = (name: string) =>
26
- message.payload.headers.find((item) => item.name.toLowerCase() === name.toLowerCase())?.value ??
27
- null;
28
- return {
29
- id: message.id,
30
- threadId: message.threadId,
31
- from: header('From'),
32
- to: header('To'),
33
- subject: header('Subject'),
34
- date: header('Date'),
35
- snippet: message.snippet,
36
- };
37
- };
38
-
39
- export const fetchGmailMessages = async (
40
- { send }: { send: ProviderSend },
41
- { listRequest, context }: { listRequest: Request; context: ProviderContext },
42
- ) => {
43
- const budget = { remainingBytes: providerResponseLimit };
44
- const list = listSchema.parse(
45
- await readProviderJson(await sendProviderRequest(send, listRequest), budget),
46
- );
47
- const ids = list.messages.slice(0, context.limit).map((item) => item.id);
48
- const batch = new AbortController();
49
- const signal = AbortSignal.any([listRequest.signal, batch.signal]);
50
- const fetchGmailMessage = async (id: string) => {
51
- let deleted = false;
52
- const response = await sendProviderRequest(
53
- async (request) => {
54
- const result = await send(request);
55
- if (result.status !== 404) return result;
56
- deleted = true;
57
- await result.body?.cancel();
58
- return Response.json(null);
59
- },
60
- buildGmailMessageRequest(listRequest, id, signal),
61
- );
62
- if (deleted) {
63
- await response.body?.cancel();
64
- return [];
65
- }
66
- return [projectMessage(await readProviderJson(response, budget))];
67
- };
68
- const messages: ReturnType<typeof projectMessage>[] = [];
69
- for (let start = 0; start < ids.length; start += gmailConcurrency)
70
- messages.push(
71
- ...(
72
- await Promise.all(ids.slice(start, start + gmailConcurrency).map(fetchGmailMessage)).catch(
73
- (error: unknown) => {
74
- batch.abort();
75
- throw error;
76
- },
77
- )
78
- ).flat(),
79
- );
80
- return { messages, hasMore: Boolean(list.nextPageToken) || list.messages.length > ids.length };
81
- };
@@ -1,12 +0,0 @@
1
- import type { OperationHandler } from '../../operations/operationHandler';
2
-
3
- // why: Gmail reads its own response (a label listing, then a fetch per message), so parse passes it through.
4
- export const gmailOperationHandler: OperationHandler = {
5
- request: ({ externalId, limit }) => {
6
- const url = new URL('https://gmail.googleapis.com/gmail/v1/users/me/messages');
7
- url.searchParams.set('labelIds', externalId);
8
- url.searchParams.set('maxResults', String(limit));
9
- return { url };
10
- },
11
- parse: (body) => body,
12
- };
@@ -1,14 +0,0 @@
1
- import type { OperationHandler } from '../../operations/operationHandler';
2
- import { objectSchema } from '../../utils/objectSchema';
3
- import { select } from '../../utils/select';
4
-
5
- export const jiraOperationHandler: OperationHandler = {
6
- request: ({ configuration, id }) => {
7
- const url = new URL(
8
- `https://api.atlassian.com/ex/jira/${'cloudId' in configuration ? configuration.cloudId : ''}/rest/api/3/issue/${id}`,
9
- );
10
- url.searchParams.set('fields', 'summary,description,status');
11
- return { url };
12
- },
13
- parse: (body) => select(objectSchema.parse(body), ['id', 'key', 'fields']),
14
- };
@@ -1,44 +0,0 @@
1
- import { z } from 'zod';
2
- import { ProviderError } from '../../../utils/providerError';
3
- import { fetchAllLinearPages } from '../fetchAllLinearPages';
4
- import type { LinearClient } from '../linearClient';
5
-
6
- const webhooksSchema = z.array(
7
- z.object({
8
- id: z.string(),
9
- url: z.string().nullish(),
10
- allPublicTeams: z.boolean(),
11
- enabled: z.boolean(),
12
- secret: z.string().nullish(),
13
- resourceTypes: z.array(z.string()),
14
- team: z.object({ id: z.string() }).nullish(),
15
- }),
16
- );
17
-
18
- const webhooksQuery =
19
- 'query Webhooks($first: Int, $after: String) { webhooks(first: $first, after: $after) { pageInfo { hasNextPage endCursor } nodes { id url allPublicTeams enabled secret resourceTypes team { id } } } }';
20
-
21
- export const listLinearWebhooks = async (client: LinearClient) => {
22
- const webhooks = webhooksSchema.parse(
23
- await fetchAllLinearPages(
24
- client,
25
- { query: webhooksQuery },
26
- {
27
- connection: 'webhooks',
28
- maxPages: 40,
29
- onCapped: () => {
30
- throw new ProviderError('provider_invalid_response');
31
- },
32
- },
33
- ),
34
- );
35
- return webhooks.map((webhook) => ({
36
- id: webhook.id,
37
- url: webhook.url ?? null,
38
- allPublicTeams: webhook.allPublicTeams,
39
- enabled: webhook.enabled,
40
- secret: webhook.secret ?? null,
41
- resourceTypes: webhook.resourceTypes,
42
- teamId: webhook.team?.id ?? null,
43
- }));
44
- };
@@ -1,40 +0,0 @@
1
- import { collectPages } from '../../utils/pagination/collectPages';
2
- import { iterateProviderPages } from '../../utils/pagination/iterateProviderPages';
3
- import type { ProviderPagesOptions } from '../../utils/pagination/providerPagesOptions';
4
- import { readPath } from '../../utils/pagination/readPath';
5
- import { ProviderError } from '../../utils/providerError';
6
- import type { LinearClient } from './linearClient';
7
- import { linearPagination } from './linearPagination';
8
- import type { LinearRequestInput } from './linearRequestInput';
9
- import { requestLinear } from './requestLinear';
10
-
11
- export const fetchAllLinearPages = (
12
- client: LinearClient,
13
- { query, variables }: LinearRequestInput,
14
- { connection, ...options }: Omit<ProviderPagesOptions, 'keys'> & { connection: string },
15
- ) => {
16
- const { keys } = linearPagination;
17
- const pageSize = variables?.[keys.pageSize];
18
- return collectPages(
19
- (walk: Omit<ProviderPagesOptions, 'keys'>) =>
20
- iterateProviderPages(linearPagination, {
21
- ...walk,
22
- pageSize: typeof pageSize === 'number' ? pageSize : undefined,
23
- keys: {
24
- data: `${connection}.${keys.data}`,
25
- nextCursor: `${connection}.${keys.nextCursor}`,
26
- hasMore: `${connection}.${keys.hasMore}`,
27
- },
28
- fetchPage: (page) => requestLinear(client, { query, variables: { ...variables, ...page } }),
29
- onResponse: (response, page) => {
30
- if (
31
- readPath(response, `${connection}.${keys.hasMore}`) === true &&
32
- !readPath(response, `${connection}.${keys.nextCursor}`)
33
- )
34
- throw new ProviderError('provider_invalid_response');
35
- walk.onResponse?.(response, page);
36
- },
37
- }),
38
- options,
39
- );
40
- };
@@ -1,5 +0,0 @@
1
- import type { z } from 'zod';
2
- import type { credentialMethodSchema } from '../../contracts';
3
- import type { ProviderClient } from '../../utils/providerClient';
4
-
5
- export type LinearClient = ProviderClient & { method: z.infer<typeof credentialMethodSchema> };
@@ -1 +0,0 @@
1
- export type LinearRequestInput = { query: string; variables?: Record<string, unknown> };
@@ -1,11 +0,0 @@
1
- import type { ProviderModel } from '../../../../catalog/providerModel';
2
-
3
- const kind = 'issue';
4
-
5
- export const linearIssue = {
6
- kind,
7
- operations: [
8
- { key: 'issues.read', name: 'Read an issue', resourceKind: kind, requiredScopes: ['read'] },
9
- ],
10
- events: [],
11
- } satisfies ProviderModel;
@@ -1,30 +0,0 @@
1
- import type { OperationHandler } from '../../../../operations/operationHandler';
2
- import { objectSchema } from '../../../../utils/objectSchema';
3
- import { ProviderError } from '../../../../utils/providerError';
4
- import { select } from '../../../../utils/select';
5
-
6
- export const linearOperationHandler: OperationHandler = {
7
- request: ({ externalId, headers }) => {
8
- headers.set('Content-Type', 'application/json');
9
- return {
10
- url: new URL('https://api.linear.app/graphql'),
11
- body: JSON.stringify({
12
- query:
13
- 'query OwnerIssue($id: String!) { issue(id: $id) { id identifier title description url state { name } } }',
14
- variables: { id: externalId },
15
- }),
16
- };
17
- },
18
- parse: (body) => {
19
- const data = objectSchema.parse(body);
20
- if (data.errors) throw new ProviderError('provider_failed');
21
- return select(objectSchema.parse(data.data).issue, [
22
- 'id',
23
- 'identifier',
24
- 'title',
25
- 'description',
26
- 'url',
27
- 'state',
28
- ]);
29
- },
30
- };
@@ -1,51 +0,0 @@
1
- import { z } from 'zod';
2
- import { ProviderError } from '../../utils/providerError';
3
- import { providerRequest } from '../../utils/providerRequest';
4
- import { requestProviderJson } from '../../utils/requestProviderJson';
5
- import type { LinearClient } from './linearClient';
6
- import type { LinearRequestInput } from './linearRequestInput';
7
-
8
- const resultSchema = z.object({
9
- data: z.unknown().optional(),
10
- errors: z
11
- .array(
12
- z.object({
13
- message: z.string().optional(),
14
- extensions: z
15
- .looseObject({ type: z.string().optional(), code: z.string().optional() })
16
- .optional(),
17
- }),
18
- )
19
- .optional(),
20
- });
21
-
22
- const errorCode = (extensions: { type?: string; code?: string } | undefined) => {
23
- const kind = `${extensions?.type ?? ''} ${extensions?.code ?? ''}`.toLowerCase();
24
- if (kind.includes('authentication')) return 'provider_authentication_expired';
25
- if (kind.includes('forbidden')) return 'provider_access_denied';
26
- return 'provider_failed';
27
- };
28
-
29
- export const requestLinear = async (
30
- { method, token, send = fetch }: LinearClient,
31
- { query, variables = {} }: LinearRequestInput,
32
- ) => {
33
- const headers = new Headers({
34
- Accept: 'application/json',
35
- Authorization: method === 'apiKey' ? token : `Bearer ${token}`,
36
- });
37
- const result = resultSchema.parse(
38
- await requestProviderJson(
39
- send,
40
- providerRequest(
41
- 'https://api.linear.app',
42
- { path: '/graphql', body: { query, variables } },
43
- headers,
44
- ),
45
- { readableStatuses: [400] },
46
- ),
47
- );
48
- const [error] = result.errors ?? [];
49
- if (error) throw new ProviderError(errorCode(error.extensions));
50
- return result.data;
51
- };
@@ -1,32 +0,0 @@
1
- import { z } from 'zod';
2
- import type { OperationHandler } from '../../operations/operationHandler';
3
- import { objectSchema } from '../../utils/objectSchema';
4
- import { select } from '../../utils/select';
5
-
6
- export const notionOperationHandler: OperationHandler = {
7
- request: ({ context, id, limit, headers }) => {
8
- headers.set('Notion-Version', '2026-03-11');
9
- const url = new URL(
10
- context.operation === 'pages.read'
11
- ? `https://api.notion.com/v1/pages/${id}`
12
- : `https://api.notion.com/v1/blocks/${id}/children`,
13
- );
14
- if (context.operation === 'blocks.read') url.searchParams.set('page_size', String(limit));
15
- return { url };
16
- },
17
- parse: (body, context) => {
18
- const data = objectSchema.parse(body);
19
- return context.operation === 'pages.read'
20
- ? select(data, ['id', 'properties', 'created_time', 'last_edited_time', 'archived'])
21
- : {
22
- blocks: z
23
- .array(z.unknown())
24
- .parse(data.results)
25
- .map((item) => {
26
- const block = objectSchema.parse(item);
27
- return select(block, ['id', 'type', 'has_children', String(block.type)]);
28
- }),
29
- hasMore: data.has_more === true,
30
- };
31
- },
32
- };
@@ -1,12 +0,0 @@
1
- import { fetchAllRequestPages } from '../../utils/pagination/fetchAllRequestPages';
2
- import type { ProviderPagesOptions } from '../../utils/pagination/providerPagesOptions';
3
- import type { ProviderClient } from '../../utils/providerClient';
4
- import type { ProviderRequestInput } from '../../utils/providerRequestInput';
5
- import { requestSlack } from './requestSlack';
6
- import { slackPagination } from './slackPagination';
7
-
8
- export const fetchAllSlackPages = (
9
- client: ProviderClient,
10
- input: ProviderRequestInput,
11
- options?: ProviderPagesOptions,
12
- ) => fetchAllRequestPages(slackPagination, (page) => requestSlack(client, page), input, options);
@@ -1,26 +0,0 @@
1
- import { z } from 'zod';
2
- import type { ProviderClient } from '../../../../utils/providerClient';
3
- import { fetchAllSlackPages } from '../../fetchAllSlackPages';
4
-
5
- const channelsSchema = z.array(z.object({ id: z.string().min(1), name: z.string().min(1) }));
6
-
7
- export const listSlackChannels = async (client: ProviderClient) => {
8
- let truncated = false;
9
- const channels = channelsSchema.parse(
10
- await fetchAllSlackPages(
11
- client,
12
- {
13
- path: 'users.conversations',
14
- query: { types: 'public_channel,private_channel', exclude_archived: 'true' },
15
- },
16
- {
17
- keys: { data: 'channels' },
18
- maxPages: 20,
19
- onCapped: () => {
20
- truncated = true;
21
- },
22
- },
23
- ),
24
- );
25
- return { channels, truncated };
26
- };
@@ -1,30 +0,0 @@
1
- import { z } from 'zod';
2
- import type { OperationHandler } from '../../../../operations/operationHandler';
3
- import { objectSchema } from '../../../../utils/objectSchema';
4
- import { select } from '../../../../utils/select';
5
- import { slackProviderError } from '../../slackProviderError';
6
-
7
- export const slackOperationHandler: OperationHandler = {
8
- request: ({ context, externalId, limit }) => {
9
- const url = new URL(
10
- `https://slack.com/api/${context.operation === 'messages.read' ? 'conversations.history' : 'conversations.info'}`,
11
- );
12
- url.searchParams.set('channel', externalId);
13
- if (context.operation === 'messages.read')
14
- url.searchParams.set('limit', String(Math.min(limit, 15)));
15
- return { url };
16
- },
17
- parse: (body, context) => {
18
- const data = objectSchema.parse(body);
19
- if (data.ok !== true) throw slackProviderError(data.error);
20
- return context.operation === 'conversations.read'
21
- ? select(data.channel, ['id', 'name', 'is_private', 'num_members', 'topic', 'purpose'])
22
- : {
23
- messages: z
24
- .array(z.unknown())
25
- .parse(data.messages)
26
- .map((item) => select(item, ['ts', 'text', 'user', 'type'])),
27
- hasMore: data.has_more === true,
28
- };
29
- },
30
- };
@@ -1,22 +0,0 @@
1
- import { z } from 'zod';
2
- import type { ProviderClient } from '../../utils/providerClient';
3
- import { providerRequest } from '../../utils/providerRequest';
4
- import type { ProviderRequestInput } from '../../utils/providerRequestInput';
5
- import { requestProviderJson } from '../../utils/requestProviderJson';
6
- import { slackProviderError } from './slackProviderError';
7
-
8
- const slackResultSchema = z.looseObject({ ok: z.boolean(), error: z.string().optional() });
9
-
10
- export const requestSlack = async (
11
- { token, send = fetch }: ProviderClient,
12
- input: ProviderRequestInput,
13
- ) => {
14
- const headers = new Headers(input.headers);
15
- headers.set('Authorization', `Bearer ${token}`);
16
- headers.set('Accept', 'application/json');
17
- const body = slackResultSchema.parse(
18
- await requestProviderJson(send, providerRequest('https://slack.com/api/', input, headers)),
19
- );
20
- if (!body.ok) throw slackProviderError(body.error);
21
- return body;
22
- };