@inixiative/integrations 0.0.0-stage → 0.2.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.
- package/LICENSE +21 -0
- package/README.md +50 -2
- package/package.json +56 -4
- package/src/catalog/declaredOperations.ts +9 -0
- package/src/catalog/eventLeaves.ts +5 -0
- package/src/catalog/familyProducts.ts +5 -0
- package/src/catalog/findProvider.ts +5 -0
- package/src/catalog/integrationEventResource.ts +20 -0
- package/src/catalog/integrationKeyedKinds.ts +4 -0
- package/src/catalog/isAccountSuppliedByHost.ts +6 -0
- package/src/catalog/isEventLeaf.ts +1 -0
- package/src/catalog/isFamilyManaged.ts +7 -0
- package/src/catalog/isUncalledLeaf.ts +6 -0
- package/src/catalog/operationLeaves.ts +6 -0
- package/src/catalog/providerEvent.ts +3 -0
- package/src/catalog/providerEventSchema.ts +3 -0
- package/src/catalog/providerFamily.ts +4 -0
- package/src/catalog/providerHasEvents.ts +8 -0
- package/src/catalog/providerModel.ts +12 -0
- package/src/catalog/providers.ts +54 -0
- package/src/contracts.ts +107 -0
- package/src/credentials/codexClientId.ts +2 -0
- package/src/credentials/codexTokenUrl.ts +1 -0
- package/src/credentials/consentReason.ts +4 -0
- package/src/credentials/consentReasonSchema.ts +21 -0
- package/src/credentials/credentialClient.ts +4 -0
- package/src/credentials/exchangeOauthCode.ts +61 -0
- package/src/credentials/fetchRenewalResponse.ts +41 -0
- package/src/credentials/mintProviderCredential.ts +68 -0
- package/src/credentials/providerExchangeTimeoutMs.ts +1 -0
- package/src/credentials/refreshProviderCredential.ts +172 -0
- package/src/credentials/renewalRequest.ts +1 -0
- package/src/credentials/subscriptionAccountId.ts +12 -0
- package/src/credentials/validateCredentialSecret.ts +18 -0
- package/src/index.ts +3 -0
- package/src/operations/buildProviderRequest.ts +54 -0
- package/src/operations/executeProvider.ts +26 -0
- package/src/operations/findOperationHandler.ts +6 -0
- package/src/operations/operationHandler.ts +8 -0
- package/src/operations/operationHandlers.ts +41 -0
- package/src/operations/operationRequestInput.ts +12 -0
- package/src/operations/providerRequestSpec.ts +1 -0
- package/src/providers/anthropic/anthropicProvider.ts +16 -0
- package/src/providers/archive/archiveCandidate.ts +1 -0
- package/src/providers/archive/archiveConfigurationSchema.ts +3 -0
- package/src/providers/archive/archiveProvider.ts +21 -0
- package/src/providers/archive/isLocalArchive.ts +5 -0
- package/src/providers/archive/localArchiveConfigurationSchema.ts +5 -0
- package/src/providers/archive/localArchiveSourceId.ts +8 -0
- package/src/providers/chorus/chorusProvider.ts +22 -0
- package/src/providers/claude/claudeProvider.ts +17 -0
- package/src/providers/codex/codexProvider.ts +17 -0
- package/src/providers/confluence/confluenceOperationHandler.ts +14 -0
- package/src/providers/confluence/confluenceProvider.ts +16 -0
- package/src/providers/discord/discordOperationHandler.ts +30 -0
- package/src/providers/discord/discordProvider.ts +22 -0
- package/src/providers/drive/driveOperationHandler.ts +21 -0
- package/src/providers/drive/driveProvider.ts +18 -0
- package/src/providers/foundry/foundryProvider.ts +33 -0
- package/src/providers/geminiApi/geminiApiProvider.ts +16 -0
- package/src/providers/github/auth/fetchGithubAppInstallation.ts +21 -0
- package/src/providers/github/auth/fetchGithubOrganizationRole.ts +27 -0
- package/src/providers/github/auth/fetchGithubUser.ts +11 -0
- package/src/providers/github/auth/fetchGithubUserInstallation.ts +21 -0
- package/src/providers/github/auth/githubAppClient.ts +4 -0
- package/src/providers/github/auth/githubAppInstallUrl.ts +20 -0
- package/src/providers/github/auth/githubAppJwt.ts +16 -0
- package/src/providers/github/auth/githubClientForApp.ts +11 -0
- package/src/providers/github/auth/githubInstallation.ts +4 -0
- package/src/providers/github/auth/githubInstallationAccountId.ts +4 -0
- package/src/providers/github/auth/githubInstallationFromAccountId.ts +4 -0
- package/src/providers/github/auth/githubInstallationSchema.ts +12 -0
- package/src/providers/github/auth/githubPermissionCovers.ts +14 -0
- package/src/providers/github/auth/githubPermissionScopes.ts +4 -0
- package/src/providers/github/auth/githubProviderForOwner.ts +6 -0
- package/src/providers/github/auth/githubUserAuthorizeUrl.ts +10 -0
- package/src/providers/github/events/githubEventRepositoryId.ts +10 -0
- package/src/providers/github/events/githubNotification.ts +4 -0
- package/src/providers/github/events/githubNotificationSchema.ts +9 -0
- package/src/providers/github/events/listGithubNotifications.ts +27 -0
- package/src/providers/github/events/normalizeGithubEvent.ts +200 -0
- package/src/providers/github/events/normalizeGithubNotification.ts +56 -0
- package/src/providers/github/events/verifyGithubSignature.ts +7 -0
- package/src/providers/github/fetchAllGithubPages.ts +12 -0
- package/src/providers/github/githubApiVersion.ts +1 -0
- package/src/providers/github/githubOrganizationProvider.ts +13 -0
- package/src/providers/github/githubPagination.ts +7 -0
- package/src/providers/github/githubProvider.ts +13 -0
- package/src/providers/github/githubRequestHeaders.ts +9 -0
- package/src/providers/github/githubUserProvider.ts +13 -0
- package/src/providers/github/iterateGithubPages.ts +12 -0
- package/src/providers/github/models/account/githubAccount.ts +17 -0
- package/src/providers/github/models/repository/githubOperationHandler.ts +36 -0
- package/src/providers/github/models/repository/githubRepository.ts +40 -0
- package/src/providers/github/models/repository/githubRepositoryIdSchema.ts +3 -0
- package/src/providers/github/models/repository/githubRepositoryMetadataSchema.ts +6 -0
- package/src/providers/github/models/repository/githubRepositoryName.ts +4 -0
- package/src/providers/github/models/repository/githubRepositoryNameSchema.ts +9 -0
- package/src/providers/github/models/repository/githubTreeEntryModeSchema.ts +3 -0
- package/src/providers/github/models/repository/githubTreeEntryTypeForMode.ts +14 -0
- package/src/providers/github/models/repository/githubTreeEntryTypeSchema.ts +3 -0
- package/src/providers/github/models/repository/listInstallationRepositories.ts +31 -0
- package/src/providers/github/models/repository/listUserRepositories.ts +36 -0
- package/src/providers/github/models/repository/readGithubObject.ts +85 -0
- package/src/providers/github/models/repository/readGithubRepositoryName.ts +4 -0
- package/src/providers/github/requestGithub.ts +18 -0
- package/src/providers/gmail/buildGmailMessageRequest.ts +22 -0
- package/src/providers/gmail/fetchGmailMessages.ts +81 -0
- package/src/providers/gmail/gmailOperationHandler.ts +12 -0
- package/src/providers/gmail/gmailProvider.ts +19 -0
- package/src/providers/google/auth/buildGoogleAuthorizationUrl.ts +33 -0
- package/src/providers/google/auth/verifyGoogleIdToken.ts +22 -0
- package/src/providers/google/googleProvider.ts +13 -0
- package/src/providers/jira/jiraOperationHandler.ts +14 -0
- package/src/providers/jira/jiraProvider.ts +16 -0
- package/src/providers/linear/auth/linearIntegrationSecret.ts +6 -0
- package/src/providers/linear/events/createLinearWebhook.ts +30 -0
- package/src/providers/linear/events/deleteLinearWebhook.ts +13 -0
- package/src/providers/linear/events/linearUserSchema.ts +3 -0
- package/src/providers/linear/events/linearWebhook.ts +3 -0
- package/src/providers/linear/events/linearWebhookPayload.ts +4 -0
- package/src/providers/linear/events/linearWebhookPayloadSchema.ts +13 -0
- package/src/providers/linear/events/listLinearWebhooks.ts +44 -0
- package/src/providers/linear/events/normalizeLinearEvent.ts +127 -0
- package/src/providers/linear/events/repairLinearWebhook.ts +17 -0
- package/src/providers/linear/events/verifyLinearSignature.ts +25 -0
- package/src/providers/linear/fetchAllLinearPages.ts +40 -0
- package/src/providers/linear/linearClient.ts +5 -0
- package/src/providers/linear/linearPagination.ts +13 -0
- package/src/providers/linear/linearProvider.ts +12 -0
- package/src/providers/linear/linearRequestInput.ts +1 -0
- package/src/providers/linear/models/issue/linearIssue.ts +11 -0
- package/src/providers/linear/models/issue/linearOperationHandler.ts +30 -0
- package/src/providers/linear/models/team/fetchLinearWorkspace.ts +30 -0
- package/src/providers/linear/models/team/linearTeam.ts +18 -0
- package/src/providers/linear/requestLinear.ts +51 -0
- package/src/providers/muse/museProvider.ts +17 -0
- package/src/providers/notion/notionOperationHandler.ts +32 -0
- package/src/providers/notion/notionProvider.ts +22 -0
- package/src/providers/openai/openaiProvider.ts +16 -0
- package/src/providers/oracle/oracleProvider.ts +10 -0
- package/src/providers/railway/railwayProvider.ts +9 -0
- package/src/providers/render/renderProvider.ts +9 -0
- package/src/providers/slack/auth/fetchSlackIdentity.ts +10 -0
- package/src/providers/slack/events/normalizeSlackEvent.ts +64 -0
- package/src/providers/slack/events/slackAccountIdOf.ts +1 -0
- package/src/providers/slack/events/slackEventEnvelope.ts +4 -0
- package/src/providers/slack/events/slackEventEnvelopeSchema.ts +16 -0
- package/src/providers/slack/events/slackTeamPrefix.ts +1 -0
- package/src/providers/slack/events/slackTokensRevokedSchema.ts +13 -0
- package/src/providers/slack/events/slackUserOfAccountId.ts +2 -0
- package/src/providers/slack/events/verifySlackSignature.ts +17 -0
- package/src/providers/slack/fetchAllSlackPages.ts +12 -0
- package/src/providers/slack/models/account/slackAccount.ts +13 -0
- package/src/providers/slack/models/channel/listSlackChannels.ts +26 -0
- package/src/providers/slack/models/channel/slackChannel.ts +31 -0
- package/src/providers/slack/models/channel/slackOperationHandler.ts +30 -0
- package/src/providers/slack/requestSlack.ts +22 -0
- package/src/providers/slack/slackPagination.ts +12 -0
- package/src/providers/slack/slackProvider.ts +12 -0
- package/src/providers/slack/slackProviderError.ts +12 -0
- package/src/providers/teams/teamsOperationHandler.ts +24 -0
- package/src/providers/teams/teamsProvider.ts +17 -0
- package/src/resources/integrationConfigurationSchemas.ts +11 -0
- package/src/resources/perProvider.ts +20 -0
- package/src/resources/resourceExternalIdSchema.ts +4 -0
- package/src/resources/resourceExternalIdSchemas.ts +18 -0
- package/src/resources/resourceMetadataSchema.ts +4 -0
- package/src/resources/resourceMetadataSchemas.ts +9 -0
- package/src/utils/capacityWindowSchema.ts +7 -0
- package/src/utils/headerNumber.ts +6 -0
- package/src/utils/jwtClaims.ts +14 -0
- package/src/utils/matchesHmacSha256.ts +11 -0
- package/src/utils/objectSchema.ts +3 -0
- package/src/utils/pagination/applyCaps.ts +18 -0
- package/src/utils/pagination/byCursorKeys.ts +7 -0
- package/src/utils/pagination/byCursorOptions.ts +7 -0
- package/src/utils/pagination/byPageKeys.ts +7 -0
- package/src/utils/pagination/byPageOptions.ts +8 -0
- package/src/utils/pagination/collectPages.ts +27 -0
- package/src/utils/pagination/compactRequest.ts +4 -0
- package/src/utils/pagination/fetchAllByCursor.ts +6 -0
- package/src/utils/pagination/fetchAllByPage.ts +6 -0
- package/src/utils/pagination/fetchAllRequestPages.ts +16 -0
- package/src/utils/pagination/incompletePageWalkError.ts +8 -0
- package/src/utils/pagination/isAnotherPage.ts +20 -0
- package/src/utils/pagination/iterateByCursor.ts +49 -0
- package/src/utils/pagination/iterateByPage.ts +59 -0
- package/src/utils/pagination/iterateProviderPages.ts +27 -0
- package/src/utils/pagination/iterateRequestPages.ts +18 -0
- package/src/utils/pagination/pageWalkError.ts +6 -0
- package/src/utils/pagination/paginationOptions.ts +9 -0
- package/src/utils/pagination/providerPagesOptions.ts +8 -0
- package/src/utils/pagination/providerPagination.ts +6 -0
- package/src/utils/pagination/readPage.ts +29 -0
- package/src/utils/pagination/readPath.ts +12 -0
- package/src/utils/pagination/repeatedCursorError.ts +10 -0
- package/src/utils/providerClient.ts +3 -0
- package/src/utils/providerCooldown.ts +23 -0
- package/src/utils/providerCooldownState.ts +4 -0
- package/src/utils/providerError.ts +10 -0
- package/src/utils/providerReading.ts +4 -0
- package/src/utils/providerReadingSchema.ts +8 -0
- package/src/utils/providerRequest.ts +22 -0
- package/src/utils/providerRequestInput.ts +7 -0
- package/src/utils/providerResponseLimit.ts +1 -0
- package/src/utils/providerSend.ts +1 -0
- package/src/utils/readProviderJson.ts +38 -0
- package/src/utils/readProviderLimits.ts +66 -0
- package/src/utils/readRateLimit.ts +29 -0
- package/src/utils/requestProviderJson.ts +13 -0
- package/src/utils/responseBudget.ts +1 -0
- package/src/utils/select.ts +6 -0
- package/src/utils/sendProviderRequest.ts +33 -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,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,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,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,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 @@
|
|
|
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,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
|
+
};
|