Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Tie internal and external typings together #890

Merged
merged 7 commits into from
Feb 23, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 25 additions & 26 deletions common/lib/client/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,7 @@ import HmacSHA256 from 'crypto-js/build/hmac-sha256';
import { stringify as stringifyBase64 } from 'crypto-js/build/enc-base64';
import { createHmac } from 'crypto';
import { ErrnoException, RequestCallback, RequestParams } from '../../types/http';
import TokenDetails from '../../types/TokenDetails';
import TokenParams from '../../types/TokenParams';
import * as API from '../../../ably';
import { StandardCallback } from '../../types/utils';

// TODO: replace these with the real types once these classes are in TypeScript
Expand Down Expand Up @@ -120,11 +119,11 @@ function getTokenRequestId() {

class Auth {
client: Rest | Realtime;
tokenParams: TokenParams;
tokenParams: API.Types.TokenParams;
currentTokenRequestId: number | null;
waitingForTokenRequest: ReturnType<typeof Multicaster.create> | null;
authOptions: AuthOptions;
tokenDetails?: TokenDetails | null;
tokenDetails?: API.Types.TokenDetails | null;
method?: string;
key?: string;
basicKey?: string;
Expand Down Expand Up @@ -194,7 +193,7 @@ class Auth {
*
* @param callback (err, tokenDetails)
*/
authorize(tokenParams: TokenParams | null, callback: Function): void;
authorize(tokenParams: API.Types.TokenParams | null, callback: Function): void;

/**
* Instructs the library to get a token immediately and ensures Token Auth
Expand Down Expand Up @@ -250,7 +249,7 @@ class Auth {
*
* @param callback (err, tokenDetails)
*/
authorize(tokenParams: TokenParams | null, authOptions: AuthOptions, callback: Function): void;
authorize(tokenParams: API.Types.TokenParams | null, authOptions: AuthOptions, callback: Function): void;

authorize(tokenParams: Record<string, any> | Function | null, authOptions?: AuthOptions | Function, callback?: Function): void | Promise<void> {
/* shuffle and normalise arguments as necessary */
Expand Down Expand Up @@ -282,7 +281,7 @@ class Auth {
}
}

this._forceNewToken(tokenParams as TokenParams, authOptions, (err: ErrorInfo, tokenDetails: TokenDetails) => {
this._forceNewToken(tokenParams as API.Types.TokenParams, authOptions, (err: ErrorInfo, tokenDetails: API.Types.TokenDetails) => {
if(err) {
if((this.client as Realtime).connection) {
/* We interpret RSA4d as including requests made by a client lib to
Expand All @@ -307,15 +306,15 @@ class Auth {
})
}

authorise(tokenParams: TokenParams | null, authOptions: AuthOptions, callback: Function): void {
authorise(tokenParams: API.Types.TokenParams | null, authOptions: AuthOptions, callback: Function): void {
Logger.deprecated('Auth.authorise', 'Auth.authorize');
this.authorize(tokenParams, authOptions, callback);
}

/* For internal use, eg by connectionManager - useful when want to call back
* as soon as we have the new token, rather than waiting for it to take
* effect on the connection as #authorize does */
_forceNewToken(tokenParams: TokenParams | null, authOptions: AuthOptions, callback: Function) {
_forceNewToken(tokenParams: API.Types.TokenParams | null, authOptions: AuthOptions, callback: Function) {
/* get rid of current token even if still valid */
this.tokenDetails = null;

Expand All @@ -326,7 +325,7 @@ class Auth {

logAndValidateTokenAuthMethod(this.authOptions);

this._ensureValidAuthCredentials(true, (err: ErrorInfo | null, tokenDetails?: TokenDetails) => {
this._ensureValidAuthCredentials(true, (err: ErrorInfo | null, tokenDetails?: API.Types.TokenDetails) => {
/* RSA10g */
delete this.tokenParams.timestamp;
delete this.authOptions.queryTime;
Expand All @@ -338,7 +337,7 @@ class Auth {
* Request an access token
* @param callback (err, tokenDetails)
*/
requestToken(callback: StandardCallback<TokenDetails>): void;
requestToken(callback: StandardCallback<API.Types.TokenDetails>): void;

/**
* Request an access token
Expand All @@ -360,7 +359,7 @@ class Auth {
*
* @param callback (err, tokenDetails)
*/
requestToken(tokenParams: TokenParams | null, callback: StandardCallback<TokenDetails>): void;
requestToken(tokenParams: API.Types.TokenParams | null, callback: StandardCallback<API.Types.TokenDetails>): void;

/**
* Request an access token
Expand Down Expand Up @@ -408,9 +407,9 @@ class Auth {
*
* @param callback (err, tokenDetails)
*/
requestToken(tokenParams: TokenParams | null, authOptions: AuthOptions, callback: StandardCallback<TokenDetails>): void;
requestToken(tokenParams: API.Types.TokenParams | null, authOptions: AuthOptions, callback: StandardCallback<API.Types.TokenDetails>): void;

requestToken(tokenParams: TokenParams | StandardCallback<TokenDetails> | null, authOptions?: AuthOptions | StandardCallback<TokenDetails>, callback?: StandardCallback<TokenDetails>): void | Promise<void> {
requestToken(tokenParams: API.Types.TokenParams | StandardCallback<API.Types.TokenDetails> | null, authOptions?: AuthOptions | StandardCallback<API.Types.TokenDetails>, callback?: StandardCallback<API.Types.TokenDetails>): void | Promise<void> {
/* shuffle and normalise arguments as necessary */
if(typeof(tokenParams) == 'function' && !callback) {
callback = tokenParams;
Expand Down Expand Up @@ -553,7 +552,7 @@ class Auth {
} else if((tokenRequestOrDetails[0] === '{') && !(contentType && contentType.indexOf('application/jwt') > -1)) {
_callback(new ErrorInfo('Token was double-encoded; make sure you\'re not JSON-encoding an already encoded token request or details', 40170, 401));
} else {
_callback(null, {token: tokenRequestOrDetails} as TokenDetails);
_callback(null, {token: tokenRequestOrDetails} as API.Types.TokenDetails);
}
return;
}
Expand All @@ -580,15 +579,15 @@ class Auth {
return;
}
/* it's a token request, so make the request */
tokenRequest(tokenRequestOrDetails, function(err?: ErrorInfo | ErrnoException | null, tokenResponse?: TokenDetails | string, headers?: Record<string, string>, unpacked?: boolean) {
tokenRequest(tokenRequestOrDetails, function(err?: ErrorInfo | ErrnoException | null, tokenResponse?: API.Types.TokenDetails | string, headers?: Record<string, string>, unpacked?: boolean) {
if(err) {
Logger.logAction(Logger.LOG_ERROR, 'Auth.requestToken()', 'token request API call returned error; err = ' + Utils.inspectError(err));
_callback(normaliseAuthcallbackError(err));
return;
}
if(!unpacked) tokenResponse = JSON.parse(tokenResponse as string);
Logger.logAction(Logger.LOG_MINOR, 'Auth.getToken()', 'token received');
_callback(null, tokenResponse as TokenDetails);
_callback(null, tokenResponse as API.Types.TokenDetails);
});
});
}
Expand Down Expand Up @@ -628,7 +627,7 @@ class Auth {
*
* @param callback
*/
createTokenRequest(tokenParams: TokenParams | null, authOptions: AuthOptions, callback: Function) {
createTokenRequest(tokenParams: API.Types.TokenParams | null, authOptions: AuthOptions, callback: Function) {
/* shuffle and normalise arguments as necessary */
if(typeof(tokenParams) == 'function' && !callback) {
callback = tokenParams;
Expand All @@ -643,7 +642,7 @@ class Auth {

/* RSA9h: if authOptions passed in, they're used instead of stored, don't merge them */
authOptions = authOptions || this.authOptions;
tokenParams = tokenParams || Utils.copy<TokenParams>(this.tokenParams);
tokenParams = tokenParams || Utils.copy<API.Types.TokenParams>(this.tokenParams);

const key = authOptions.key;
if(!key) {
Expand Down Expand Up @@ -720,7 +719,7 @@ class Auth {
if(this.method == 'basic')
callback(null, {key: this.key});
else
this._ensureValidAuthCredentials(false, function(err: ErrorInfo | null, tokenDetails?: TokenDetails) {
this._ensureValidAuthCredentials(false, function(err: ErrorInfo | null, tokenDetails?: API.Types.TokenDetails) {
if(err) {
callback(err);
return;
Expand All @@ -740,7 +739,7 @@ class Auth {
if(this.method == 'basic') {
callback(null, {authorization: 'Basic ' + this.basicKey});
} else {
this._ensureValidAuthCredentials(false, function(err: ErrorInfo | null, tokenDetails?: TokenDetails) {
this._ensureValidAuthCredentials(false, function(err: ErrorInfo | null, tokenDetails?: API.Types.TokenDetails) {
if(err) {
callback(err);
return;
Expand Down Expand Up @@ -785,7 +784,7 @@ class Auth {
}
}

_saveTokenOptions(tokenParams: TokenParams | null, authOptions: AuthOptions) {
_saveTokenOptions(tokenParams: API.Types.TokenParams | null, authOptions: AuthOptions) {
this.method = 'token';

if(tokenParams) {
Expand Down Expand Up @@ -816,7 +815,7 @@ class Auth {

/* @param forceSupersede: force a new token request even if there's one in
* progress, making all pending callbacks wait for the new one */
_ensureValidAuthCredentials(forceSupersede: boolean, callback: (err: ErrorInfo | null, token?: TokenDetails) => void) {
_ensureValidAuthCredentials(forceSupersede: boolean, callback: (err: ErrorInfo | null, token?: API.Types.TokenDetails) => void) {
const token = this.tokenDetails;

if(token) {
Expand Down Expand Up @@ -845,7 +844,7 @@ class Auth {

/* Request a new token */
const tokenRequestId = this.currentTokenRequestId = getTokenRequestId();
this.requestToken(this.tokenParams, this.authOptions, (err: Function, tokenResponse?: TokenDetails) => {
this.requestToken(this.tokenParams, this.authOptions, (err: Function, tokenResponse?: API.Types.TokenDetails) => {
if((this.currentTokenRequestId as number) > tokenRequestId) {
Logger.logAction(Logger.LOG_MINOR, 'Auth._ensureValidAuthCredentials()', 'Discarding token request response; overtaken by newer one');
return;
Expand All @@ -863,7 +862,7 @@ class Auth {


/* User-set: check types, '*' is disallowed, throw any errors */
_userSetClientId(clientId: string | null) {
_userSetClientId(clientId: string | undefined) {
owenpearson marked this conversation as resolved.
Show resolved Hide resolved
if(!(typeof(clientId) === 'string' || clientId === null)) {
throw new ErrorInfo('clientId must be either a string or null', 40012, 400);
} else if(clientId === '*') {
Expand All @@ -875,7 +874,7 @@ class Auth {
}

/* Ably-set: no typechecking, '*' is allowed but not set on this.clientId), return errors to the caller */
_uncheckedSetClientId(clientId: string | null) {
_uncheckedSetClientId(clientId: string | undefined) {
if(this._tokenClientIdMismatch(clientId)) {
/* Should never happen in normal circumstances as realtime should
* recognise mismatch and return an error */
Expand Down
5 changes: 3 additions & 2 deletions common/lib/client/channel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,11 @@ import Http from 'platform-http';
import Resource from './resource';
import { ChannelOptions } from '../../types/channel';
import { PaginatedResultCallback } from '../../types/utils';
import Rest from './rest';

// TODO: Replace these when Realtime and Rest are in TypeScript
type Realtime = any;
type Rest = any;


interface RestHistoryParams {
start?: number;
Expand Down Expand Up @@ -41,7 +42,7 @@ function normaliseChannelOptions(options?: ChannelOptions) {
} else if('cipher' in channelOptions) {
/* Don't deactivate an existing cipher unless options
* has a 'cipher' key that's falsey */
channelOptions.cipher = null;
channelOptions.cipher = undefined;
channelOptions.channelCipher = null;
}
return channelOptions;
Expand Down
4 changes: 1 addition & 3 deletions common/lib/client/paginatedresource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@ import Logger from '../util/logger';
import Resource from './resource';
import ErrorInfo from '../types/errorinfo';
import { PaginatedResultCallback } from '../../types/utils';

// TODO: Replace this once rest.js is converted to TypeScript
type Rest = any;
import Rest from './rest';

export type BodyHandler = (body: unknown, headers: Record<string, string>, packed?: boolean) => any;

Expand Down
4 changes: 1 addition & 3 deletions common/lib/client/push.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,7 @@ import ErrorInfo from '../types/errorinfo';
import Http from 'platform-http';
import PushChannelSubscription from '../types/pushchannelsubscription';
import { ErrCallback, PaginatedResultCallback, StandardCallback } from '../../types/utils';

// TODO: Replace this once rest.js is converted to TypeScript
type Rest = any;
import Rest from './rest';

const noop = function() {};

Expand Down
14 changes: 6 additions & 8 deletions common/lib/client/resource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,7 @@ import Auth from './auth';
import * as BufferUtils from 'platform-bufferutils';
import HttpMethods from '../../constants/HttpMethods';
import ErrorInfo from '../types/errorinfo';

// TODO: Replace this once rest.js is converted to TypeScript
type Rest = any;
import Rest from './rest';

const msgpack = Platform.msgpack;

Expand Down Expand Up @@ -100,23 +98,23 @@ function logResponseHandler(callback: Function, method: HttpMethods, path: strin
class Resource {
static get(rest: Rest, path: string, origheaders: Record<string, string>, origparams: Record<string, any>, envelope: Utils.Format | null, callback: Function): void {
Resource.do(HttpMethods.Get, rest, path, null, origheaders, origparams, envelope, callback);
}
}

static delete(rest: Rest, path: string, origheaders: Record<string, string>, origparams: Record<string, any>, envelope: Utils.Format | null, callback: Function): void {
Resource.do(HttpMethods.Delete, rest, path, null, origheaders, origparams, envelope, callback);
}
}

static post(rest: Rest, path: string, body: unknown, origheaders: Record<string, string>, origparams: Record<string, any>, envelope: Utils.Format | null, callback: Function): void {
Resource.do(HttpMethods.Post, rest, path, body, origheaders, origparams, envelope, callback);
}
}

static patch(rest: Rest, path: string, body: unknown, origheaders: Record<string, string>, origparams: Record<string, any>, envelope: Utils.Format | null, callback: Function): void {
Resource.do(HttpMethods.Patch, rest, path, body, origheaders, origparams, envelope, callback);
}
}

static put(rest: Rest, path: string, body: unknown, origheaders: Record<string, string>, origparams: Record<string, any>, envelope: Utils.Format | null, callback: Function): void {
Resource.do(HttpMethods.Put, rest, path, body, origheaders, origparams, envelope, callback);
}
}

static do(method: HttpMethods, rest: Rest, path: string, body: unknown, origheaders: Record<string, string>, origparams: Record<string, any>, envelope: Utils.Format | null, callback: Function): void {
if (Logger.shouldLog(Logger.LOG_MICRO)) {
Expand Down
4 changes: 2 additions & 2 deletions common/lib/transport/comettransport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import ConnectionErrors from './connectionerrors';
import Auth from '../client/auth';
import ErrorInfo from '../types/errorinfo';
import IXHRRequest from '../../types/IXHRRequest';
import TokenDetails from '../../types/TokenDetails';
import * as API from '../../../ably';
import ConnectionManager, { TransportParams } from './connectionmanager';
import XHRStates from '../../constants/XHRStates';

Expand Down Expand Up @@ -331,7 +331,7 @@ abstract class CometTransport extends Transport {
* we need to send an AUTH for jsonp. In which case it's simpler to keep all
* comet transports the same and do it for all of them. So we send the AUTH
* instead, and don't need to abort the recv */
onAuthUpdated = (tokenDetails: TokenDetails): void => {
onAuthUpdated = (tokenDetails: API.Types.TokenDetails): void => {
this.authParams = {access_token: tokenDetails.token};
}
}
Expand Down
4 changes: 2 additions & 2 deletions common/lib/transport/connectionmanager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import * as WebStorage from 'platform-webstorage';
import PlatformTransports from 'platform-transports';
import WebSocketTransport from './websockettransport';
import Transport from './transport';
import TokenDetails from '../../types/TokenDetails';
import * as API from '../../../ably';
import { ErrCallback } from '../../types/utils';
import HttpStatusCodes from '../../constants/HttpStatusCodes';

Expand Down Expand Up @@ -1483,7 +1483,7 @@ class ConnectionManager extends EventEmitter {
this.notifyState({state: 'closed'});
}

onAuthUpdated(tokenDetails: TokenDetails, callback: Function): void {
onAuthUpdated(tokenDetails: API.Types.TokenDetails, callback: Function): void {
switch(this.state.state) {
case 'connected':
Logger.logAction(Logger.LOG_MICRO, 'ConnectionManager.onAuthUpdated()', 'Sending AUTH message on active transport');
Expand Down
6 changes: 3 additions & 3 deletions common/lib/transport/transport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import Logger from '../util/logger';
import ConnectionErrors from './connectionerrors';
import ErrorInfo from '../types/errorinfo';
import Auth from '../client/auth';
import TokenDetails from '../../types/TokenDetails';
import * as API from '../../../ably';
import ConnectionManager, { TransportParams } from './connectionmanager';

export type TryConnectCallback = (wrappedErr: { error: ErrorInfo, event: string } | null, transport?: Transport) => void;
Expand Down Expand Up @@ -60,7 +60,7 @@ abstract class Transport extends EventEmitter {
}

abstract shortName: string;
abstract send(message: ProtocolMessage): void;
abstract send(message: ProtocolMessage): void;

connect(): void {}

Expand Down Expand Up @@ -249,7 +249,7 @@ abstract class Transport extends EventEmitter {
}

static tryConnect?: (connectionManager: ConnectionManager, auth: Auth, transportParams: TransportParams, callback: TryConnectCallback) => void;
onAuthUpdated?: (tokenDetails: TokenDetails) => void;
onAuthUpdated?: (tokenDetails: API.Types.TokenDetails) => void;
}

export default Transport;
8 changes: 4 additions & 4 deletions common/lib/types/protocolmessage.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ChannelMode } from '../../types/channel';
import { Types } from '../../../ably';
import * as Utils from '../util/utils';
import ErrorInfo from './errorinfo';
import Message from './message';
Expand Down Expand Up @@ -73,7 +73,7 @@ class ProtocolMessage {
msgSerial?: number;
messages?: Message[];
presence?: PresenceMessage[];
auth?: unknown;
auth?: unknown;
connectionDetails?: Record<string, unknown>;
timeSerial?: number;

Expand All @@ -87,15 +87,15 @@ class ProtocolMessage {
return (((this.flags as number) & flags[flag]) > 0);
};

setFlag(flag: ChannelMode): number {
setFlag(flag: Types.ChannelMode): number {
return this.flags = (this.flags as number) | flags[flag];
}

getMode(): number | undefined {
return this.flags && (this.flags & flags.MODE_ALL);
}

encodeModesToFlags(modes: ChannelMode[]): void {
encodeModesToFlags(modes: Types.ChannelMode[]): void {
modes.forEach(mode => this.setFlag(mode));
}

Expand Down
Loading