Better types for WebAPI

This commit is contained in:
Fedor Indutny 2021-09-21 17:58:03 -07:00 committed by GitHub
parent c05d23e628
commit b9d6497cb1
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
22 changed files with 156 additions and 107 deletions

View file

@ -598,7 +598,7 @@ async function _retryAjax(
const limit = providedLimit || 3;
return _promiseAjax(url, options).catch(async (e: Error) => {
if (e.name === 'HTTPError' && e.code === -1 && count < limit) {
if (e instanceof HTTPError && e.code === -1 && count < limit) {
return new Promise(resolve => {
setTimeout(() => {
resolve(_retryAjax(url, options, limit, count));
@ -615,17 +615,6 @@ async function _outerAjax(url: string | null, options: PromiseAjaxOptionsType) {
return _retryAjax(url, options);
}
declare global {
// We want to extend `Error`, so we need an interface.
// eslint-disable-next-line no-restricted-syntax
interface Error {
code?: number | string;
response?: any;
responseHeaders?: HeaderListType;
warn?: boolean;
}
}
function makeHTTPError(
message: string,
providedCode: number,
@ -722,7 +711,7 @@ type InitializeOptionsType = {
version: string;
};
type MessageType = any;
type MessageType = unknown;
type AjaxOptionsType = {
accessKey?: string;
@ -737,7 +726,7 @@ type AjaxOptionsType = {
password?: string;
redactUrl?: RedactUrl;
responseType?: 'json' | 'arraybuffer' | 'arraybufferwithdetails';
schema?: any;
schema?: unknown;
timeout?: number;
unauthenticated?: boolean;
urlParameters?: string;
@ -768,7 +757,7 @@ export type CapabilitiesUploadType = {
changeNumber: true;
};
type StickerPackManifestType = any;
type StickerPackManifestType = ArrayBuffer;
export type GroupCredentialType = {
credential: string;
@ -808,6 +797,20 @@ const uploadAvatarHeadersZod = z
.passthrough();
export type UploadAvatarHeadersType = z.infer<typeof uploadAvatarHeadersZod>;
export type ProfileType = Readonly<{
identityKey?: string;
name?: string;
about?: string;
aboutEmoji?: string;
avatar?: string;
unidentifiedAccess?: string;
unrestrictedUnidentifiedAccess?: string;
username?: string;
uuid?: string;
credential?: string;
capabilities?: unknown;
}>;
export type WebAPIType = {
confirmCode: (
number: string,
@ -816,14 +819,21 @@ export type WebAPIType = {
registrationId: number,
deviceName?: string | null,
options?: { accessKey?: ArrayBuffer; uuid?: string }
) => Promise<any>;
) => Promise<{ uuid?: string; deviceId: number }>;
createGroup: (
group: Proto.IGroup,
options: GroupCredentialsType
) => Promise<void>;
getAttachment: (cdnKey: string, cdnNumber?: number) => Promise<any>;
getAvatar: (path: string) => Promise<any>;
getDevices: () => Promise<any>;
getAttachment: (cdnKey: string, cdnNumber?: number) => Promise<ArrayBuffer>;
getAvatar: (path: string) => Promise<ArrayBuffer>;
getDevices: () => Promise<
Array<{
id: number;
name: string;
lastSeen: number;
created: number;
}>
>;
getGroup: (options: GroupCredentialsType) => Promise<Proto.Group>;
getGroupFromLink: (
inviteLinkPassword: string,
@ -841,7 +851,11 @@ export type WebAPIType = {
startVersion: number,
options: GroupCredentialsType
) => Promise<GroupLogResponseType>;
getIceServers: () => Promise<any>;
getIceServers: () => Promise<{
username: string;
password: string;
urls: Array<string>;
}>;
getKeysForIdentifier: (
identifier: string,
deviceId?: number
@ -858,7 +872,7 @@ export type WebAPIType = {
profileKeyVersion?: string;
profileKeyCredentialRequest?: string;
}
) => Promise<any>;
) => Promise<ProfileType>;
getProfileUnauth: (
identifier: string,
options: {
@ -866,7 +880,7 @@ export type WebAPIType = {
profileKeyVersion?: string;
profileKeyCredentialRequest?: string;
}
) => Promise<any>;
) => Promise<ProfileType>;
getProvisioningResource: (
handler: IRequestHandler
) => Promise<WebSocketResource>;
@ -892,7 +906,13 @@ export type WebAPIType = {
makeProxiedRequest: (
targetUrl: string,
options?: ProxiedRequestOptionsType
) => Promise<any>;
) => Promise<
| ArrayBufferWithDetailsType
| {
result: ArrayBufferWithDetailsType;
totalSize: number;
}
>;
makeSfuRequest: (
targetUrl: string,
type: HTTPCodeType,
@ -905,7 +925,7 @@ export type WebAPIType = {
inviteLinkBase64?: string
) => Promise<Proto.IGroupChange>;
modifyStorageRecords: MessageSender['modifyStorageRecords'];
putAttachment: (encryptedBin: ArrayBuffer) => Promise<any>;
putAttachment: (encryptedBin: ArrayBuffer) => Promise<string>;
putProfile: (
jsonData: ProfileRequestDataType
) => Promise<UploadAvatarHeadersType | undefined>;
@ -916,10 +936,10 @@ export type WebAPIType = {
onProgress?: () => void
) => Promise<string>;
registerKeys: (genKeys: KeysType) => Promise<void>;
registerSupportForUnauthenticatedDelivery: () => Promise<any>;
registerSupportForUnauthenticatedDelivery: () => Promise<void>;
reportMessage: (senderE164: string, serverGuid: string) => Promise<void>;
requestVerificationSMS: (number: string) => Promise<any>;
requestVerificationVoice: (number: string) => Promise<any>;
requestVerificationSMS: (number: string) => Promise<void>;
requestVerificationVoice: (number: string) => Promise<void>;
sendMessages: (
destination: string,
messageArray: Array<MessageType>,
@ -949,8 +969,11 @@ export type WebAPIType = {
avatarData: Uint8Array,
options: GroupCredentialsType
) => Promise<string>;
whoami: () => Promise<any>;
sendChallengeResponse: (challengeResponse: ChallengeType) => Promise<any>;
whoami: () => Promise<{
uuid?: string;
number?: string;
}>;
sendChallengeResponse: (challengeResponse: ChallengeType) => Promise<void>;
getConfig: () => Promise<
Array<{ name: string; enabled: boolean; value: string | null }>
>;
@ -1188,6 +1211,9 @@ export function initialize({
unauthenticated: param.unauthenticated,
accessKey: param.accessKey,
}).catch((e: Error) => {
if (!(e instanceof HTTPError)) {
throw e;
}
const translatedError = translateError(e);
if (translatedError) {
throw translatedError;
@ -1458,7 +1484,7 @@ export function initialize({
async function getAvatar(path: string) {
// Using _outerAJAX, since it's not hardcoded to the Signal Server. Unlike our
// attachment CDN, it uses our self-signed certificate, so we pass it in.
return _outerAjax(`${cdnUrlObject['0']}/${path}`, {
return (await _outerAjax(`${cdnUrlObject['0']}/${path}`, {
certificateAuthority,
contentType: 'application/octet-stream',
proxyUrl,
@ -1470,7 +1496,7 @@ export function initialize({
return href.replace(pattern, `[REDACTED]${path.slice(-3)}`);
},
version,
});
})) as ArrayBuffer;
}
async function reportMessage(
@ -1571,6 +1597,7 @@ export function initialize({
return _ajax({
call: 'getIceServers',
httpType: 'GET',
responseType: 'json',
});
}
@ -1832,7 +1859,7 @@ export function initialize({
if (!isPackIdValid(packId)) {
throw new Error('getSticker: pack ID was invalid');
}
return _outerAjax(
return (await _outerAjax(
`${cdnUrlObject['0']}/stickers/${packId}/full/${stickerId}`,
{
certificateAuthority,
@ -1842,14 +1869,14 @@ export function initialize({
redactUrl: redactStickerUrl,
version,
}
);
)) as ArrayBuffer;
}
async function getStickerPackManifest(packId: string) {
if (!isPackIdValid(packId)) {
throw new Error('getStickerPackManifest: pack ID was invalid');
}
return _outerAjax(
return (await _outerAjax(
`${cdnUrlObject['0']}/stickers/${packId}/manifest.proto`,
{
certificateAuthority,
@ -1859,7 +1886,7 @@ export function initialize({
redactUrl: redactStickerUrl,
version,
}
);
)) as ArrayBuffer;
}
type ServerAttachmentType = {
@ -1989,7 +2016,7 @@ export function initialize({
? cdnUrlObject[cdnNumber] || cdnUrlObject['0']
: cdnUrlObject['0'];
// This is going to the CDN, not the service, so we use _outerAjax
return _outerAjax(`${cdnUrl}/attachments/${cdnKey}`, {
return (await _outerAjax(`${cdnUrl}/attachments/${cdnKey}`, {
certificateAuthority,
proxyUrl,
responseType: 'arraybuffer',
@ -1997,7 +2024,7 @@ export function initialize({
type: 'GET',
redactUrl: _createRedactor(cdnKey),
version,
});
})) as ArrayBuffer;
}
async function putAttachment(encryptedBin: ArrayBuffer) {
@ -2066,7 +2093,7 @@ export function initialize({
headers.Range = `bytes=${start}-${end}`;
}
const result = await _outerAjax(targetUrl, {
const result = (await _outerAjax(targetUrl, {
responseType: returnArrayBuffer ? 'arraybufferwithdetails' : undefined,
proxyUrl: contentProxyUrl,
type: 'GET',
@ -2074,7 +2101,7 @@ export function initialize({
redactUrl: () => '[REDACTED_URL]',
headers,
version,
});
})) as ArrayBufferWithDetailsType;
if (!returnArrayBuffer) {
return result;