Skip to content

Commit

Permalink
Typescript strict mode
Browse files Browse the repository at this point in the history
  • Loading branch information
kum-deepak committed Jun 29, 2018
1 parent dbc2fa9 commit 6138c47
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 40 deletions.
50 changes: 25 additions & 25 deletions src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export class Client {
/**
* Underlying WebSocket instance
*/
public ws: WebSocket;
public ws: any;

/**
* This function will be called for any unhandled messages. It is useful to receive messages sent to
Expand All @@ -45,33 +45,33 @@ export class Client {
* It can also be called for stray messages while the server is processing a request to unsubcribe
* from an endpoint.
*/
public onreceive: messageCallbackType;
public onreceive: messageCallbackType|null = null;

/**
* STOMP brokers can be requested to notify when an operation is actually completed.
*
* TODO: add example
*/
public onreceipt: receiptCallbackType;
public onreceipt: receiptCallbackType|null = null;

private subscriptions: any;
private partialData: any;
private escapeHeaderValues: boolean;
private escapeHeaderValues: boolean = false;
private counter: number;
private connected: boolean;
private pinger: any;
private ponger: any;
private serverActivity: any;
private headers: StompHeaders;
private headers: StompHeaders = {};
private connectCallback: any;
private errorCallback: any;
private closeEventCallback: any;
private _active: boolean;
private version: string;
private closeReceipt: string;
private _active: boolean = false;
private version: string = '';
private closeReceipt: string = '';
private _disconnectCallback: any;
private _reconnector: any;
private partial: string;
private partial: string = '';

private static now(): any {
if (Date.now) {
Expand Down Expand Up @@ -138,11 +138,11 @@ export class Client {
*
* Note: the default can generate lot of log on the console. Set it to empty function to disable.
*/
public debug = (...message) => {
public debug = (...message: any[]) => {
console.log(...message);
};

private _transmit(command, headers, body = ''): void {
private _transmit(command: string, headers: StompHeaders, body: string = ''): void {
let out = Frame.marshall(command, headers, body, this.escapeHeaderValues);
if (typeof this.debug === 'function') {
this.debug(`>>> ${out}`);
Expand All @@ -163,16 +163,16 @@ export class Client {
}
}

private _setupHeartbeat(headers): void {
let ttl;
private _setupHeartbeat(headers: StompHeaders): void {
let ttl: number;
if ((headers.version !== Stomp.VERSIONS.V1_1 && headers.version !== Stomp.VERSIONS.V1_2)) {
return;
}

// heart-beat header received from the server looks like:
//
// heart-beat: sx, sy
const [serverOutgoing, serverIncoming] = headers['heart-beat'].split(",").map((v) => parseInt(v));
const [serverOutgoing, serverIncoming] = (<string>headers['heart-beat']).split(",").map((v: string) => parseInt(v));

if ((this.heartbeat.outgoing !== 0) && (serverIncoming !== 0)) {
ttl = Math.max(this.heartbeat.outgoing, serverIncoming);
Expand Down Expand Up @@ -205,9 +205,9 @@ export class Client {
}
}

private _parseConnect(...args): any {
private _parseConnect(...args: any[]): any {
let closeEventCallback, connectCallback, errorCallback;
let headers = {};
let headers: StompHeaders = {};
if (args.length < 2) {
throw("Connect requires at least 2 arguments");
}
Expand Down Expand Up @@ -266,7 +266,7 @@ export class Client {
*
* @see http:*stomp.github.com/stomp-specification-1.2.html#CONNECT_or_STOMP_Frame CONNECT Frame
*/
public connect(...args): void {
public connect(...args: any[]): void {
this.escapeHeaderValues = false;
const out = this._parseConnect(...args);
[this.headers, this.connectCallback, this.errorCallback, this.closeEventCallback] = out;
Expand All @@ -291,7 +291,7 @@ export class Client {
// Get the actual Websocket (or a similar object)
this.ws = this.ws_fn();

this.ws.onmessage = evt => {
this.ws.onmessage = (evt: any) => {
this.debug('Received data');
const data = (() => {
if ((typeof(ArrayBuffer) !== 'undefined') && evt.data instanceof ArrayBuffer) {
Expand Down Expand Up @@ -373,12 +373,12 @@ export class Client {
// bless the frame to be a Message
const message = <Message>frame;
if (onreceive) {
let messageId;
let messageId: string;
const client = this;
if (this.version === Stomp.VERSIONS.V1_2) {
messageId = message.headers["ack"];
messageId = <string>message.headers["ack"];
} else {
messageId = message.headers["message-id"];
messageId = <string>message.headers["message-id"];
}
// add `ack()` and `nack()` methods directly to the returned frame
// so that a simple call to `message.ack()` can acknowledge the message.
Expand Down Expand Up @@ -436,7 +436,7 @@ export class Client {
}
};

this.ws.onclose = closeEvent => {
this.ws.onclose = (closeEvent: any) => {
const msg = `Whoops! Lost connection to ${this.ws.url}`;
if (typeof this.debug === 'function') {
this.debug(msg);
Expand Down Expand Up @@ -490,7 +490,7 @@ export class Client {
*
* @see http://stomp.github.com/stomp-specification-1.2.html#DISCONNECT DISCONNECT Frame
*/
public disconnect(disconnectCallback, headers = {}): void {
public disconnect(disconnectCallback: any, headers: StompHeaders = {}): void {
this._disconnectCallback = disconnectCallback;

// indicate that auto reconnect loop should terminate
Expand All @@ -500,7 +500,7 @@ export class Client {
if (!headers['receipt']) {
headers['receipt'] = `close-${this.counter++}`;
}
this.closeReceipt = headers['receipt'];
this.closeReceipt = <string>headers['receipt'];
try {
this._transmit("DISCONNECT", headers);
} catch (error) {
Expand Down Expand Up @@ -616,7 +616,7 @@ export class Client {
*
* @see http://stomp.github.com/stomp-specification-1.2.html#UNSUBSCRIBE UNSUBSCRIBE Frame
*/
public unsubscribe(id: string, headers: StompHeaders): void {
public unsubscribe(id: string, headers: StompHeaders = {}): void {
if (headers == null) {
headers = {};
}
Expand Down
25 changes: 15 additions & 10 deletions src/frame.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,8 @@ export class Frame {
*/
private static sizeOfUTF8(s: string): number {
if (s) {
return encodeURI(s).match(/%..|./g).length;
const matches = encodeURI(s).match(/%..|./g) || [];
return matches.length;
} else {
return 0;
}
Expand All @@ -87,28 +88,32 @@ export class Frame {
// search for 2 consecutives LF byte to split the command
// and headers from the body
const divider = data.search(new RegExp(`${Byte.LF}${Byte.LF}`));
const headerLines = data.substring(0, divider).split(Byte.LF);
const headerLines: string[] = data.substring(0, divider).split(Byte.LF);
const command = headerLines.shift();
const headers = {};
const headers: StompHeaders = {};
// utility function to trim any whitespace before and after a string
const trim = str => str.replace(/^\s+|\s+$/g, '');
const trim = (str: string): string => str.replace(/^\s+|\s+$/g, '');
// Parse headers in reverse order so that for repeated headers, the 1st
// value is used
for (let line of headerLines.reverse()) {
const idx = line.indexOf(':');

const key = <string>trim(line.substring(0, idx));
let value = trim(line.substring(idx + 1));

if (escapeHeaderValues && (command !== 'CONNECT') && (command !== 'CONNECTED')) {
headers[trim(line.substring(0, idx))] = Frame.frUnEscape(trim(line.substring(idx + 1)));
} else {
headers[trim(line.substring(0, idx))] = trim(line.substring(idx + 1));
value = Frame.frUnEscape(value);
}

headers[key] = value;
}
// Parse body
// check for content-length or topping at the first NULL byte found.
let body = '';
// skip the 2 LF bytes that divides the headers from the body
const start = divider + 2;
if (headers['content-length']) {
const len = parseInt(headers['content-length']);
const len = parseInt(<string>headers['content-length']);
body = (`${data}`).substring(start, start + len);
} else {
let chr = null;
Expand All @@ -120,7 +125,7 @@ export class Frame {
body += chr;
}
}
return new Frame(command, headers, body, escapeHeaderValues);
return new Frame(<string>command, headers, body, escapeHeaderValues);
}

/**
Expand All @@ -145,7 +150,7 @@ export class Frame {
frames: [],
partial: ''
};
r.frames = (frames.slice(0, -1).map((frame) => Frame.unmarshallSingle(frame, escapeHeaderValues)));
r.frames = (frames.slice(0, -1).map((frame: Frame) => Frame.unmarshallSingle(frame, escapeHeaderValues)));

// If this contains a final full message or just a acknowledgement of a PING
// without any other content, process this frame, otherwise return the
Expand Down
4 changes: 2 additions & 2 deletions src/stomp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export class Stomp {
* var client = Stomp.client(url);
* ```
*/
public static client (url, protocols): Client {
public static client (url: string, protocols: string[]): Client {
// This is a hack to allow another implementation than the standard
// HTML5 WebSocket class.
//
Expand Down Expand Up @@ -98,7 +98,7 @@ export class Stomp {
/**
* @internal
*/
public static clearInterval(id) {
public static clearInterval(id: number) {
clearInterval(id)
};
}
6 changes: 3 additions & 3 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

/* Strict Type-Checking Options */
"strict": false, /* Enable all strict type-checking options. */
"noImplicitAny": false, /* Raise error on expressions and declarations with an implied 'any' type. */
"strictNullChecks": false, /* Enable strict null checks. */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
Expand Down

0 comments on commit 6138c47

Please sign in to comment.