@inixiative/integrations 0.0.0-stage → 0.1.0

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 (210) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +50 -2
  3. package/package.json +56 -4
  4. package/src/archiveCandidate.ts +1 -0
  5. package/src/archiveConfigurationSchema.ts +3 -0
  6. package/src/buildProviderRequest.ts +54 -0
  7. package/src/catalog.ts +54 -0
  8. package/src/codexClientId.ts +2 -0
  9. package/src/codexTokenUrl.ts +1 -0
  10. package/src/consentReason.ts +4 -0
  11. package/src/consentReasonSchema.ts +21 -0
  12. package/src/contracts.ts +107 -0
  13. package/src/credentialClient.ts +4 -0
  14. package/src/declaredOperations.ts +9 -0
  15. package/src/eventLeaves.ts +5 -0
  16. package/src/exchangeOauthCode.ts +61 -0
  17. package/src/executeProvider.ts +26 -0
  18. package/src/familyProducts.ts +5 -0
  19. package/src/fetchRenewalResponse.ts +41 -0
  20. package/src/findOperationHandler.ts +6 -0
  21. package/src/findProvider.ts +5 -0
  22. package/src/index.ts +3 -0
  23. package/src/integrationConfigurationSchemas.ts +11 -0
  24. package/src/integrationEventResource.ts +20 -0
  25. package/src/integrationKeyedKinds.ts +4 -0
  26. package/src/isAccountSuppliedByHost.ts +6 -0
  27. package/src/isEventLeaf.ts +1 -0
  28. package/src/isFamilyManaged.ts +7 -0
  29. package/src/isLocalArchive.ts +5 -0
  30. package/src/isUncalledLeaf.ts +6 -0
  31. package/src/localArchiveConfigurationSchema.ts +5 -0
  32. package/src/localArchiveSourceId.ts +8 -0
  33. package/src/mintProviderCredential.ts +68 -0
  34. package/src/operationHandler.ts +8 -0
  35. package/src/operationHandlers.ts +41 -0
  36. package/src/operationLeaves.ts +6 -0
  37. package/src/operationRequestInput.ts +12 -0
  38. package/src/perProvider.ts +20 -0
  39. package/src/providerEvent.ts +3 -0
  40. package/src/providerEventSchema.ts +3 -0
  41. package/src/providerExchangeTimeoutMs.ts +1 -0
  42. package/src/providerFamily.ts +4 -0
  43. package/src/providerHasEvents.ts +8 -0
  44. package/src/providerModel.ts +12 -0
  45. package/src/providerRequestSpec.ts +1 -0
  46. package/src/providers/anthropic/anthropicProvider.ts +16 -0
  47. package/src/providers/archive/archiveProvider.ts +21 -0
  48. package/src/providers/chorus/chorusProvider.ts +22 -0
  49. package/src/providers/claude/claudeProvider.ts +17 -0
  50. package/src/providers/codex/codexProvider.ts +17 -0
  51. package/src/providers/confluence/confluenceOperationHandler.ts +14 -0
  52. package/src/providers/confluence/confluenceProvider.ts +16 -0
  53. package/src/providers/discord/discordOperationHandler.ts +30 -0
  54. package/src/providers/discord/discordProvider.ts +22 -0
  55. package/src/providers/drive/driveOperationHandler.ts +21 -0
  56. package/src/providers/drive/driveProvider.ts +18 -0
  57. package/src/providers/foundry/foundryProvider.ts +33 -0
  58. package/src/providers/geminiApi/geminiApiProvider.ts +16 -0
  59. package/src/providers/github/auth/fetchGithubAppInstallation.ts +21 -0
  60. package/src/providers/github/auth/fetchGithubOrganizationRole.ts +27 -0
  61. package/src/providers/github/auth/fetchGithubUser.ts +11 -0
  62. package/src/providers/github/auth/fetchGithubUserInstallation.ts +21 -0
  63. package/src/providers/github/auth/githubAppClient.ts +4 -0
  64. package/src/providers/github/auth/githubAppInstallUrl.ts +20 -0
  65. package/src/providers/github/auth/githubAppJwt.ts +16 -0
  66. package/src/providers/github/auth/githubClientForApp.ts +11 -0
  67. package/src/providers/github/auth/githubInstallation.ts +4 -0
  68. package/src/providers/github/auth/githubInstallationAccountId.ts +4 -0
  69. package/src/providers/github/auth/githubInstallationFromAccountId.ts +4 -0
  70. package/src/providers/github/auth/githubInstallationSchema.ts +12 -0
  71. package/src/providers/github/auth/githubPermissionCovers.ts +14 -0
  72. package/src/providers/github/auth/githubPermissionScopes.ts +4 -0
  73. package/src/providers/github/auth/githubProviderForOwner.ts +6 -0
  74. package/src/providers/github/auth/githubUserAuthorizeUrl.ts +10 -0
  75. package/src/providers/github/events/githubEventRepositoryId.ts +10 -0
  76. package/src/providers/github/events/githubNotification.ts +4 -0
  77. package/src/providers/github/events/githubNotificationSchema.ts +9 -0
  78. package/src/providers/github/events/listGithubNotifications.ts +27 -0
  79. package/src/providers/github/events/normalizeGithubEvent.ts +200 -0
  80. package/src/providers/github/events/normalizeGithubNotification.ts +56 -0
  81. package/src/providers/github/events/verifyGithubSignature.ts +7 -0
  82. package/src/providers/github/fetchAllGithubPages.ts +12 -0
  83. package/src/providers/github/githubApiVersion.ts +1 -0
  84. package/src/providers/github/githubOrganizationProvider.ts +13 -0
  85. package/src/providers/github/githubPagination.ts +7 -0
  86. package/src/providers/github/githubProvider.ts +13 -0
  87. package/src/providers/github/githubRequestHeaders.ts +9 -0
  88. package/src/providers/github/githubUserProvider.ts +13 -0
  89. package/src/providers/github/iterateGithubPages.ts +12 -0
  90. package/src/providers/github/models/account/githubAccount.ts +17 -0
  91. package/src/providers/github/models/repository/githubOperationHandler.ts +36 -0
  92. package/src/providers/github/models/repository/githubRepository.ts +40 -0
  93. package/src/providers/github/models/repository/githubRepositoryIdSchema.ts +3 -0
  94. package/src/providers/github/models/repository/githubRepositoryMetadataSchema.ts +6 -0
  95. package/src/providers/github/models/repository/githubRepositoryName.ts +4 -0
  96. package/src/providers/github/models/repository/githubRepositoryNameSchema.ts +9 -0
  97. package/src/providers/github/models/repository/githubTreeEntryModeSchema.ts +3 -0
  98. package/src/providers/github/models/repository/githubTreeEntryTypeForMode.ts +14 -0
  99. package/src/providers/github/models/repository/githubTreeEntryTypeSchema.ts +3 -0
  100. package/src/providers/github/models/repository/listInstallationRepositories.ts +31 -0
  101. package/src/providers/github/models/repository/listUserRepositories.ts +36 -0
  102. package/src/providers/github/models/repository/readGithubObject.ts +85 -0
  103. package/src/providers/github/models/repository/readGithubRepositoryName.ts +4 -0
  104. package/src/providers/github/requestGithub.ts +18 -0
  105. package/src/providers/gmail/buildGmailMessageRequest.ts +22 -0
  106. package/src/providers/gmail/fetchGmailMessages.ts +81 -0
  107. package/src/providers/gmail/gmailOperationHandler.ts +12 -0
  108. package/src/providers/gmail/gmailProvider.ts +19 -0
  109. package/src/providers/google/auth/buildGoogleAuthorizationUrl.ts +33 -0
  110. package/src/providers/google/auth/verifyGoogleIdToken.ts +22 -0
  111. package/src/providers/google/googleProvider.ts +13 -0
  112. package/src/providers/jira/jiraOperationHandler.ts +14 -0
  113. package/src/providers/jira/jiraProvider.ts +16 -0
  114. package/src/providers/linear/auth/linearIntegrationSecret.ts +6 -0
  115. package/src/providers/linear/events/createLinearWebhook.ts +30 -0
  116. package/src/providers/linear/events/deleteLinearWebhook.ts +13 -0
  117. package/src/providers/linear/events/linearUserSchema.ts +3 -0
  118. package/src/providers/linear/events/linearWebhook.ts +3 -0
  119. package/src/providers/linear/events/linearWebhookPayload.ts +4 -0
  120. package/src/providers/linear/events/linearWebhookPayloadSchema.ts +13 -0
  121. package/src/providers/linear/events/listLinearWebhooks.ts +44 -0
  122. package/src/providers/linear/events/normalizeLinearEvent.ts +127 -0
  123. package/src/providers/linear/events/repairLinearWebhook.ts +17 -0
  124. package/src/providers/linear/events/verifyLinearSignature.ts +25 -0
  125. package/src/providers/linear/fetchAllLinearPages.ts +40 -0
  126. package/src/providers/linear/linearClient.ts +5 -0
  127. package/src/providers/linear/linearPagination.ts +13 -0
  128. package/src/providers/linear/linearProvider.ts +25 -0
  129. package/src/providers/linear/linearRequestInput.ts +1 -0
  130. package/src/providers/linear/models/issue/linearOperationHandler.ts +30 -0
  131. package/src/providers/linear/models/team/fetchLinearWorkspace.ts +30 -0
  132. package/src/providers/linear/requestLinear.ts +51 -0
  133. package/src/providers/muse/museProvider.ts +17 -0
  134. package/src/providers/notion/notionOperationHandler.ts +32 -0
  135. package/src/providers/notion/notionProvider.ts +22 -0
  136. package/src/providers/openai/openaiProvider.ts +16 -0
  137. package/src/providers/oracle/oracleProvider.ts +10 -0
  138. package/src/providers/railway/railwayProvider.ts +9 -0
  139. package/src/providers/render/renderProvider.ts +9 -0
  140. package/src/providers/slack/auth/fetchSlackIdentity.ts +10 -0
  141. package/src/providers/slack/events/normalizeSlackEvent.ts +64 -0
  142. package/src/providers/slack/events/slackAccountIdOf.ts +1 -0
  143. package/src/providers/slack/events/slackEventEnvelope.ts +4 -0
  144. package/src/providers/slack/events/slackEventEnvelopeSchema.ts +16 -0
  145. package/src/providers/slack/events/slackTeamPrefix.ts +1 -0
  146. package/src/providers/slack/events/slackTokensRevokedSchema.ts +13 -0
  147. package/src/providers/slack/events/slackUserOfAccountId.ts +2 -0
  148. package/src/providers/slack/events/verifySlackSignature.ts +17 -0
  149. package/src/providers/slack/fetchAllSlackPages.ts +12 -0
  150. package/src/providers/slack/models/channel/listSlackChannels.ts +26 -0
  151. package/src/providers/slack/models/channel/slackOperationHandler.ts +30 -0
  152. package/src/providers/slack/requestSlack.ts +22 -0
  153. package/src/providers/slack/slackPagination.ts +12 -0
  154. package/src/providers/slack/slackProvider.ts +47 -0
  155. package/src/providers/slack/slackProviderError.ts +12 -0
  156. package/src/providers/teams/teamsOperationHandler.ts +24 -0
  157. package/src/providers/teams/teamsProvider.ts +17 -0
  158. package/src/refreshProviderCredential.ts +172 -0
  159. package/src/renewalRequest.ts +1 -0
  160. package/src/resourceExternalIdSchema.ts +4 -0
  161. package/src/resourceExternalIdSchemas.ts +18 -0
  162. package/src/resourceMetadataSchema.ts +4 -0
  163. package/src/resourceMetadataSchemas.ts +9 -0
  164. package/src/subscriptionAccountId.ts +12 -0
  165. package/src/utils/capacityWindowSchema.ts +7 -0
  166. package/src/utils/headerNumber.ts +6 -0
  167. package/src/utils/jwtClaims.ts +14 -0
  168. package/src/utils/matchesHmacSha256.ts +11 -0
  169. package/src/utils/objectSchema.ts +3 -0
  170. package/src/utils/pagination/applyCaps.ts +18 -0
  171. package/src/utils/pagination/byCursorKeys.ts +7 -0
  172. package/src/utils/pagination/byCursorOptions.ts +7 -0
  173. package/src/utils/pagination/byPageKeys.ts +7 -0
  174. package/src/utils/pagination/byPageOptions.ts +8 -0
  175. package/src/utils/pagination/collectPages.ts +27 -0
  176. package/src/utils/pagination/compactRequest.ts +4 -0
  177. package/src/utils/pagination/fetchAllByCursor.ts +6 -0
  178. package/src/utils/pagination/fetchAllByPage.ts +6 -0
  179. package/src/utils/pagination/fetchAllRequestPages.ts +16 -0
  180. package/src/utils/pagination/incompletePageWalkError.ts +8 -0
  181. package/src/utils/pagination/isAnotherPage.ts +20 -0
  182. package/src/utils/pagination/iterateByCursor.ts +49 -0
  183. package/src/utils/pagination/iterateByPage.ts +59 -0
  184. package/src/utils/pagination/iterateProviderPages.ts +27 -0
  185. package/src/utils/pagination/iterateRequestPages.ts +18 -0
  186. package/src/utils/pagination/pageWalkError.ts +6 -0
  187. package/src/utils/pagination/paginationOptions.ts +9 -0
  188. package/src/utils/pagination/providerPagesOptions.ts +8 -0
  189. package/src/utils/pagination/providerPagination.ts +6 -0
  190. package/src/utils/pagination/readPage.ts +29 -0
  191. package/src/utils/pagination/readPath.ts +12 -0
  192. package/src/utils/pagination/repeatedCursorError.ts +10 -0
  193. package/src/utils/providerClient.ts +3 -0
  194. package/src/utils/providerCooldown.ts +23 -0
  195. package/src/utils/providerCooldownState.ts +4 -0
  196. package/src/utils/providerError.ts +10 -0
  197. package/src/utils/providerReading.ts +4 -0
  198. package/src/utils/providerReadingSchema.ts +8 -0
  199. package/src/utils/providerRequest.ts +22 -0
  200. package/src/utils/providerRequestInput.ts +7 -0
  201. package/src/utils/providerResponseLimit.ts +1 -0
  202. package/src/utils/providerSend.ts +1 -0
  203. package/src/utils/readProviderJson.ts +38 -0
  204. package/src/utils/readProviderLimits.ts +66 -0
  205. package/src/utils/readRateLimit.ts +29 -0
  206. package/src/utils/requestProviderJson.ts +13 -0
  207. package/src/utils/responseBudget.ts +1 -0
  208. package/src/utils/select.ts +6 -0
  209. package/src/utils/sendProviderRequest.ts +33 -0
  210. package/src/validateCredentialSecret.ts +18 -0
@@ -0,0 +1,49 @@
1
+ import { applyCaps } from './applyCaps';
2
+ import type { ByCursorOptions } from './byCursorOptions';
3
+ import { compactRequest } from './compactRequest';
4
+ import { readPage } from './readPage';
5
+ import { readPath } from './readPath';
6
+ import { RepeatedCursorError } from './repeatedCursorError';
7
+
8
+ const label = 'iterateByCursor';
9
+
10
+ export const iterateByCursor = <R, T = unknown>(options: ByCursorOptions<R>) => ({
11
+ async *[Symbol.asyncIterator](): AsyncGenerator<
12
+ { items: T[]; page: number; cursor: string | null; nextCursor: string | null },
13
+ void
14
+ > {
15
+ const { keys } = options;
16
+ const progress = { pages: 0, rows: 0 };
17
+ let cursor = options.startCursor || null;
18
+ const sent = new Set<string>();
19
+
20
+ for (;;) {
21
+ if (cursor !== null) sent.add(cursor);
22
+ const request = compactRequest({
23
+ [keys.cursor]: cursor,
24
+ [keys.pageSize]: options.pageSize,
25
+ });
26
+ const { response, items } = await readPage<R, T>(
27
+ options,
28
+ request,
29
+ progress,
30
+ label,
31
+ keys.data,
32
+ );
33
+ const next = readPath(response, keys.nextCursor);
34
+ const isLast =
35
+ next === undefined ||
36
+ next === null ||
37
+ next === '' ||
38
+ (keys.hasMore !== undefined && readPath(response, keys.hasMore) === false);
39
+ const nextCursor = isLast ? null : String(next);
40
+ if (nextCursor !== null && sent.has(nextCursor))
41
+ throw new RepeatedCursorError(label, progress.pages, nextCursor);
42
+
43
+ const isCapped = nextCursor !== null && applyCaps(options, progress);
44
+ yield { items, page: progress.pages, cursor, nextCursor };
45
+ if (nextCursor === null || isCapped) return;
46
+ cursor = nextCursor;
47
+ }
48
+ },
49
+ });
@@ -0,0 +1,59 @@
1
+ import { applyCaps } from './applyCaps';
2
+ import type { ByPageOptions } from './byPageOptions';
3
+ import { compactRequest } from './compactRequest';
4
+ import { IncompletePageWalkError } from './incompletePageWalkError';
5
+ import { isAnotherPage } from './isAnotherPage';
6
+ import { readPage } from './readPage';
7
+ import { readPath } from './readPath';
8
+
9
+ const label = 'iterateByPage';
10
+
11
+ export const iterateByPage = <R, T = unknown>(options: ByPageOptions<R, T>) => ({
12
+ async *[Symbol.asyncIterator](): AsyncGenerator<{ items: T[]; page: number }, void> {
13
+ const { keys } = options;
14
+ const progress = { pages: 0, rows: 0 };
15
+ const seenKeys = new Set<string>();
16
+ let firstTotal: number | undefined;
17
+
18
+ for (;;) {
19
+ const request = compactRequest({
20
+ [keys.page]: progress.pages + 1,
21
+ [keys.pageSize]: options.pageSize,
22
+ });
23
+ const { response, items } = await readPage<R, T>(
24
+ options,
25
+ request,
26
+ progress,
27
+ label,
28
+ keys.data,
29
+ );
30
+ const page = progress.pages;
31
+ if (options.itemKey) {
32
+ if (keys.total === undefined)
33
+ throw new IncompletePageWalkError(label, 'itemKey needs a total key');
34
+ const total = readPath(response, keys.total);
35
+ if (typeof total !== 'number')
36
+ throw new IncompletePageWalkError(label, `page ${page} has no total at "${keys.total}"`);
37
+ firstTotal ??= total;
38
+ if (total !== firstTotal)
39
+ throw new IncompletePageWalkError(
40
+ label,
41
+ `page ${page} reports a total of ${total}, page 1 reported ${firstTotal}`,
42
+ );
43
+ for (const item of items) seenKeys.add(options.itemKey(item));
44
+ }
45
+ const isAnother = options.hasMore
46
+ ? options.hasMore(response, items, page)
47
+ : isAnotherPage(response, items.length, { keys, pageSize: options.pageSize, progress });
48
+
49
+ const isCapped = isAnother && applyCaps(options, progress);
50
+ if (options.itemKey && !isAnother && seenKeys.size !== firstTotal)
51
+ throw new IncompletePageWalkError(
52
+ label,
53
+ `the walk read ${seenKeys.size} distinct items, page 1 reported a total of ${firstTotal}`,
54
+ );
55
+ yield { items, page };
56
+ if (!isAnother || isCapped) return;
57
+ }
58
+ },
59
+ });
@@ -0,0 +1,27 @@
1
+ import { ProviderError } from '../providerError';
2
+ import type { ByCursorKeys } from './byCursorKeys';
3
+ import type { ByPageKeys } from './byPageKeys';
4
+ import { iterateByCursor } from './iterateByCursor';
5
+ import { iterateByPage } from './iterateByPage';
6
+ import { PageWalkError } from './pageWalkError';
7
+ import type { PaginationOptions } from './paginationOptions';
8
+ import type { ProviderPagination } from './providerPagination';
9
+
10
+ export const iterateProviderPages = <R, T = unknown>(
11
+ pagination: ProviderPagination,
12
+ { keys, ...options }: PaginationOptions<R> & { keys?: Partial<ByPageKeys & ByCursorKeys> },
13
+ ) => ({
14
+ async *[Symbol.asyncIterator](): AsyncGenerator<{ items: T[]; page: number }, void> {
15
+ const walk = { ...options, pageSize: options.pageSize ?? pagination.pageSize };
16
+ const pages =
17
+ pagination.strategy === 'page'
18
+ ? iterateByPage<R, T>({ ...walk, keys: { ...pagination.keys, ...keys } })
19
+ : iterateByCursor<R, T>({ ...walk, keys: { ...pagination.keys, ...keys } });
20
+ try {
21
+ yield* pages;
22
+ } catch (error) {
23
+ if (error instanceof PageWalkError) throw new ProviderError('provider_invalid_response');
24
+ throw error;
25
+ }
26
+ },
27
+ });
@@ -0,0 +1,18 @@
1
+ import type { ProviderRequestInput } from '../providerRequestInput';
2
+ import { iterateProviderPages } from './iterateProviderPages';
3
+ import type { ProviderPagesOptions } from './providerPagesOptions';
4
+ import type { ProviderPagination } from './providerPagination';
5
+
6
+ export const iterateRequestPages = (
7
+ pagination: ProviderPagination,
8
+ request: (input: ProviderRequestInput) => Promise<unknown>,
9
+ input: ProviderRequestInput,
10
+ options: ProviderPagesOptions = {},
11
+ ) => {
12
+ const pageSize = input.query?.[options.keys?.pageSize ?? pagination.keys.pageSize];
13
+ return iterateProviderPages(pagination, {
14
+ ...options,
15
+ pageSize: pageSize === undefined ? undefined : Number(pageSize),
16
+ fetchPage: (page) => request({ ...input, query: { ...input.query, ...page } }),
17
+ });
18
+ };
@@ -0,0 +1,6 @@
1
+ export class PageWalkError extends Error {
2
+ constructor(message: string) {
3
+ super(message);
4
+ this.name = 'PageWalkError';
5
+ }
6
+ }
@@ -0,0 +1,9 @@
1
+ export type PaginationOptions<R> = {
2
+ fetchPage: (request: Record<string, string | number>, page: number) => Promise<R>;
3
+ pageSize?: number;
4
+ maxPages?: number;
5
+ maxRows?: number;
6
+ onCapped?: (cap: { reason: 'maxPages' | 'maxRows'; returned: number }) => void;
7
+ isError?: (response: R) => unknown;
8
+ onResponse?: (response: R, page: number) => void;
9
+ };
@@ -0,0 +1,8 @@
1
+ import type { ByCursorKeys } from './byCursorKeys';
2
+ import type { ByPageKeys } from './byPageKeys';
3
+ import type { PaginationOptions } from './paginationOptions';
4
+
5
+ export type ProviderPagesOptions = Pick<
6
+ PaginationOptions<unknown>,
7
+ 'maxPages' | 'maxRows' | 'onCapped' | 'onResponse'
8
+ > & { keys?: Partial<ByPageKeys & ByCursorKeys> };
@@ -0,0 +1,6 @@
1
+ import type { ByCursorKeys } from './byCursorKeys';
2
+ import type { ByPageKeys } from './byPageKeys';
3
+
4
+ export type ProviderPagination =
5
+ | { strategy: 'page'; keys: ByPageKeys; pageSize: number }
6
+ | { strategy: 'cursor'; keys: ByCursorKeys; pageSize: number };
@@ -0,0 +1,29 @@
1
+ import { PageWalkError } from './pageWalkError';
2
+ import type { PaginationOptions } from './paginationOptions';
3
+ import { readPath } from './readPath';
4
+
5
+ export const readPage = async <R, T>(
6
+ options: PaginationOptions<R>,
7
+ request: Record<string, string | number>,
8
+ progress: { pages: number; rows: number },
9
+ label: string,
10
+ dataKey: string,
11
+ ): Promise<{ response: R; items: T[] }> => {
12
+ const page = progress.pages + 1;
13
+ const response = await options.fetchPage(request, page);
14
+ const requestError = options.isError?.(response);
15
+ if (requestError) {
16
+ const message = readPath(requestError, 'message');
17
+ throw new Error(
18
+ `${label}: page ${page} failed${message === undefined ? '' : `: ${String(message)}`}`,
19
+ );
20
+ }
21
+ options.onResponse?.(response, page);
22
+
23
+ const items = readPath(response, dataKey);
24
+ if (!Array.isArray(items))
25
+ throw new PageWalkError(`${label}: page ${page} has no array at "${dataKey}"`);
26
+ progress.pages = page;
27
+ progress.rows += items.length;
28
+ return { response, items };
29
+ };
@@ -0,0 +1,12 @@
1
+ export const readPath = (value: unknown, path: string): unknown =>
2
+ path === ''
3
+ ? value
4
+ : path
5
+ .split('.')
6
+ .reduce<unknown>(
7
+ (node, key) =>
8
+ typeof node === 'object' && node !== null
9
+ ? (node as Record<string, unknown>)[key]
10
+ : undefined,
11
+ value,
12
+ );
@@ -0,0 +1,10 @@
1
+ import { PageWalkError } from './pageWalkError';
2
+
3
+ export class RepeatedCursorError extends PageWalkError {
4
+ constructor(label: string, page: number, cursor: string) {
5
+ super(
6
+ `${label}: page ${page} returned a cursor this walk already sent (${cursor}) as its next cursor`,
7
+ );
8
+ this.name = 'RepeatedCursorError';
9
+ }
10
+ }
@@ -0,0 +1,3 @@
1
+ import type { ProviderSend } from './providerSend';
2
+
3
+ export type ProviderClient = { token: string; send?: ProviderSend };
@@ -0,0 +1,23 @@
1
+ import type { ProviderCooldownState } from './providerCooldownState';
2
+ import type { ProviderReading } from './providerReading';
3
+
4
+ const FIRST_COOLDOWN_MS = 60_000;
5
+ const MAXIMUM_BACKOFF_MS = 10 * 60_000;
6
+ const MAXIMUM_RETRY_AFTER_MS = 60 * 60_000;
7
+ const MAXIMUM_CONSECUTIVE_FAILURES = 32;
8
+
9
+ export const providerCooldown = (
10
+ previous: Pick<ProviderCooldownState, 'consecutiveFailures'>,
11
+ reading: Pick<ProviderReading, 'rateLimited' | 'retryAfterMs'>,
12
+ now: number,
13
+ ): ProviderCooldownState => {
14
+ if (!reading.rateLimited) return { unavailableUntil: null, consecutiveFailures: 0 };
15
+ const consecutiveFailures = Math.min(
16
+ previous.consecutiveFailures + 1,
17
+ MAXIMUM_CONSECUTIVE_FAILURES,
18
+ );
19
+ const backoff = Math.min(FIRST_COOLDOWN_MS * 2 ** (consecutiveFailures - 1), MAXIMUM_BACKOFF_MS);
20
+ // why: a provider's retry-after is a floor on the wait, never a way to park capacity for a day.
21
+ const requested = Math.min(reading.retryAfterMs ?? 0, MAXIMUM_RETRY_AFTER_MS);
22
+ return { unavailableUntil: now + Math.max(backoff, requested), consecutiveFailures };
23
+ };
@@ -0,0 +1,4 @@
1
+ export type ProviderCooldownState = {
2
+ unavailableUntil: number | null;
3
+ consecutiveFailures: number;
4
+ };
@@ -0,0 +1,10 @@
1
+ export class ProviderError extends Error {
2
+ constructor(
3
+ public code: string,
4
+ public status: number = 502,
5
+ public retryAfterMs: number | null = null,
6
+ ) {
7
+ super(code);
8
+ this.name = 'ProviderError';
9
+ }
10
+ }
@@ -0,0 +1,4 @@
1
+ import type { z } from 'zod';
2
+ import type { providerReadingSchema } from './providerReadingSchema';
3
+
4
+ export type ProviderReading = z.infer<typeof providerReadingSchema>;
@@ -0,0 +1,8 @@
1
+ import { z } from 'zod';
2
+ import { capacityWindowSchema } from './capacityWindowSchema';
3
+
4
+ export const providerReadingSchema = z.strictObject({
5
+ rateLimited: z.boolean(),
6
+ retryAfterMs: z.number().int().min(0).nullable(),
7
+ windows: z.array(capacityWindowSchema).max(10),
8
+ });
@@ -0,0 +1,22 @@
1
+ import { ProviderError } from './providerError';
2
+ import type { ProviderRequestInput } from './providerRequestInput';
3
+
4
+ export const providerRequest = (
5
+ baseUrl: string,
6
+ { path, method, query = {}, body }: ProviderRequestInput,
7
+ headers: Headers,
8
+ ) => {
9
+ const url = new URL(path, baseUrl);
10
+ // why: the request carries the provider's token, so a path may never leave the provider's base.
11
+ if (!url.href.startsWith(new URL(baseUrl).href))
12
+ throw new ProviderError('unsupported_operation', 400);
13
+ for (const [key, value] of Object.entries(query)) url.searchParams.set(key, String(value));
14
+ if (body !== undefined) headers.set('Content-Type', 'application/json');
15
+ return new Request(url.toString(), {
16
+ method: method ?? (body === undefined ? 'GET' : 'POST'),
17
+ headers,
18
+ body: body === undefined ? undefined : JSON.stringify(body),
19
+ redirect: 'error',
20
+ signal: AbortSignal.timeout(15000),
21
+ });
22
+ };
@@ -0,0 +1,7 @@
1
+ export type ProviderRequestInput = {
2
+ path: string;
3
+ method?: 'GET' | 'POST';
4
+ query?: Record<string, string | number>;
5
+ body?: unknown;
6
+ headers?: Record<string, string>;
7
+ };
@@ -0,0 +1 @@
1
+ export const providerResponseLimit = 1024 * 1024;
@@ -0,0 +1 @@
1
+ export type ProviderSend = (request: Request) => Promise<Response>;
@@ -0,0 +1,38 @@
1
+ import { ProviderError } from './providerError';
2
+ import type { ResponseBudget } from './responseBudget';
3
+
4
+ export const readProviderJson = async (
5
+ response: Response,
6
+ budget: ResponseBudget,
7
+ ): Promise<unknown> => {
8
+ if (!response.body) throw new ProviderError('provider_empty_response');
9
+ const reader = response.body.getReader();
10
+ const chunks: Uint8Array[] = [];
11
+ let size = 0;
12
+ try {
13
+ while (true) {
14
+ const { done, value } = await reader.read();
15
+ if (done) break;
16
+ size += value.byteLength;
17
+ budget.remainingBytes -= value.byteLength;
18
+ if (budget.remainingBytes < 0) {
19
+ await reader.cancel();
20
+ throw new ProviderError('provider_response_too_large');
21
+ }
22
+ chunks.push(value);
23
+ }
24
+ } finally {
25
+ reader.releaseLock();
26
+ }
27
+ const bytes = new Uint8Array(size);
28
+ let offset = 0;
29
+ for (const chunk of chunks) {
30
+ bytes.set(chunk, offset);
31
+ offset += chunk.byteLength;
32
+ }
33
+ try {
34
+ return JSON.parse(new TextDecoder().decode(bytes));
35
+ } catch {
36
+ throw new ProviderError('provider_invalid_response');
37
+ }
38
+ };
@@ -0,0 +1,66 @@
1
+ import type { InferenceProtocol } from '../contracts';
2
+ import { headerNumber } from './headerNumber';
3
+ import type { ProviderReading } from './providerReading';
4
+ import { providerReadingSchema } from './providerReadingSchema';
5
+ import { readRateLimit } from './readRateLimit';
6
+
7
+ const ANTHROPIC_WINDOWS = ['requests', 'tokens', 'input-tokens', 'output-tokens'] as const;
8
+ const OPENAI_WINDOWS = ['requests', 'tokens'] as const;
9
+
10
+ const usedPercent = (limit: string | null, remaining: string | null): number | null => {
11
+ const total = headerNumber(limit),
12
+ left = headerNumber(remaining);
13
+ if (total === null || left === null || total <= 0 || left < 0) return null;
14
+ return Math.min(100, Math.max(0, ((total - Math.min(left, total)) / total) * 100));
15
+ };
16
+
17
+ // why: OpenAI reports a duration (`6m0s`, `1.5s`, `120ms`); Anthropic an RFC3339 instant.
18
+ const resetsAt = (value: string | null, now: number): number | null => {
19
+ if (!value) return null;
20
+ const instant = Date.parse(value);
21
+ if (Number.isFinite(instant)) return instant;
22
+ const parts = value.matchAll(/(\d+(?:\.\d+)?)(ms|[hms])/g);
23
+ const unit = { ms: 1, s: 1000, m: 60_000, h: 3_600_000 };
24
+ let total = 0,
25
+ matched = false;
26
+ for (const [, amount, suffix] of parts) {
27
+ total += Number(amount) * unit[suffix as keyof typeof unit];
28
+ matched = true;
29
+ }
30
+ return matched ? Math.round(now + total) : null;
31
+ };
32
+
33
+ export const readProviderLimits = (
34
+ protocol: InferenceProtocol,
35
+ headers: Headers,
36
+ status: number,
37
+ now = Date.now(),
38
+ ): ProviderReading | null => {
39
+ const windows = (
40
+ protocol === 'messages'
41
+ ? ANTHROPIC_WINDOWS.map((id) => ({
42
+ id,
43
+ limit: headers.get(`anthropic-ratelimit-${id}-limit`),
44
+ remaining: headers.get(`anthropic-ratelimit-${id}-remaining`),
45
+ reset: headers.get(`anthropic-ratelimit-${id}-reset`),
46
+ }))
47
+ : protocol === 'responses'
48
+ ? OPENAI_WINDOWS.map((id) => ({
49
+ id,
50
+ limit: headers.get(`x-ratelimit-limit-${id}`),
51
+ remaining: headers.get(`x-ratelimit-remaining-${id}`),
52
+ reset: headers.get(`x-ratelimit-reset-${id}`),
53
+ }))
54
+ : []
55
+ ).flatMap((window) => {
56
+ const used = usedPercent(window.limit, window.remaining);
57
+ return used === null
58
+ ? []
59
+ : [{ id: window.id, usedPercent: used, resetsAt: resetsAt(window.reset, now) }];
60
+ });
61
+ const rateLimit = readRateLimit(headers, status, now);
62
+ if (!windows.length && !rateLimit.rateLimited) return null;
63
+ // why: a malformed header must never throw into the gateway; the caller treats null as "nothing learned".
64
+ const reading = providerReadingSchema.safeParse({ ...rateLimit, windows });
65
+ return reading.success ? reading.data : null;
66
+ };
@@ -0,0 +1,29 @@
1
+ import { headerNumber } from './headerNumber';
2
+ import type { ProviderReading } from './providerReading';
3
+
4
+ const retryAfterMs = (value: string | null, now: number): number | null => {
5
+ if (!value) return null;
6
+ const seconds = headerNumber(value);
7
+ if (seconds !== null) return Math.max(0, Math.round(seconds * 1000));
8
+ const instant = Date.parse(value);
9
+ return Number.isFinite(instant) ? Math.max(0, Math.round(instant - now)) : null;
10
+ };
11
+
12
+ // why: GitHub's primary limit answers 403 with `x-ratelimit-remaining: 0` and its reset in epoch seconds.
13
+ export const readRateLimit = (
14
+ headers: Headers,
15
+ status: number,
16
+ now = Date.now(),
17
+ ): Pick<ProviderReading, 'rateLimited' | 'retryAfterMs'> => {
18
+ const exhausted = headerNumber(headers.get('x-ratelimit-remaining')) === 0;
19
+ const rateLimited =
20
+ status === 429 || (status === 403 && (exhausted || headers.has('retry-after')));
21
+ if (!rateLimited) return { rateLimited, retryAfterMs: null };
22
+ const reset = exhausted ? headerNumber(headers.get('x-ratelimit-reset')) : null;
23
+ return {
24
+ rateLimited,
25
+ retryAfterMs:
26
+ retryAfterMs(headers.get('retry-after'), now) ??
27
+ (reset === null ? null : Math.max(0, Math.round(reset * 1000 - now))),
28
+ };
29
+ };
@@ -0,0 +1,13 @@
1
+ import { providerResponseLimit } from './providerResponseLimit';
2
+ import type { ProviderSend } from './providerSend';
3
+ import { readProviderJson } from './readProviderJson';
4
+ import { sendProviderRequest } from './sendProviderRequest';
5
+
6
+ export const requestProviderJson = async (
7
+ send: ProviderSend,
8
+ request: Request,
9
+ options: { readableStatuses?: number[] } = {},
10
+ ) =>
11
+ await readProviderJson(await sendProviderRequest(send, request, options), {
12
+ remainingBytes: providerResponseLimit,
13
+ });
@@ -0,0 +1 @@
1
+ export type ResponseBudget = { remainingBytes: number };
@@ -0,0 +1,6 @@
1
+ import { objectSchema } from './objectSchema';
2
+
3
+ export const select = (value: unknown, keys: string[]) => {
4
+ const record = objectSchema.parse(value);
5
+ return Object.fromEntries(keys.filter((key) => key in record).map((key) => [key, record[key]]));
6
+ };
@@ -0,0 +1,33 @@
1
+ import { ProviderError } from './providerError';
2
+ import type { ProviderSend } from './providerSend';
3
+ import { readRateLimit } from './readRateLimit';
4
+
5
+ export const sendProviderRequest = async (
6
+ send: ProviderSend,
7
+ request: Request,
8
+ { readableStatuses = [] }: { readableStatuses?: number[] } = {},
9
+ ) => {
10
+ let response: Response;
11
+ try {
12
+ response = await send(request);
13
+ } catch {
14
+ throw new ProviderError('provider_unreachable');
15
+ }
16
+ if (!response.ok && !readableStatuses.includes(response.status)) {
17
+ await response.body?.cancel();
18
+ const rateLimit = readRateLimit(response.headers, response.status);
19
+ if (rateLimit.rateLimited)
20
+ throw new ProviderError('provider_rate_limited', 502, rateLimit.retryAfterMs);
21
+ throw new ProviderError(
22
+ response.status === 401
23
+ ? 'provider_authentication_expired'
24
+ : response.status === 403
25
+ ? 'provider_access_denied'
26
+ : response.status === 404
27
+ ? 'provider_not_found'
28
+ : 'provider_failed',
29
+ );
30
+ }
31
+ if (!response.body) throw new ProviderError('provider_empty_response');
32
+ return response;
33
+ };
@@ -0,0 +1,18 @@
1
+ import { credentialSecretSchema } from './contracts';
2
+ import { ProviderError } from './utils/providerError';
3
+
4
+ export const validateCredentialSecret = (method: string, secret: unknown, provider: string) => {
5
+ const parsed = credentialSecretSchema.parse(secret);
6
+ if ((method === 'oauth2') !== Boolean(parsed.oauth))
7
+ throw new ProviderError('Credential method and OAuth bundle must match', 400);
8
+ if ((method === 'clientCredentials') !== Boolean(parsed.clientCredentials))
9
+ throw new ProviderError('Credential method and client credentials must match', 400);
10
+ if (
11
+ method === 'oauth2' &&
12
+ (!parsed.oauth?.clientId || (!parsed.oauth.clientSecret && provider !== 'codex'))
13
+ )
14
+ throw new ProviderError('OAuth requires the application client ID and secret', 400);
15
+ if (method === 'oauth2' && provider === 'teams' && !parsed.oauth?.tenantId)
16
+ throw new ProviderError('Microsoft OAuth requires a tenant UUID', 400);
17
+ return parsed;
18
+ };