提交 2d74c6fa 编写于 作者: Huan (李卓桓)'s avatar Huan (李卓桓)

prepare to use tslint:recommend (#1303)

上级 fcde806d
......@@ -84,14 +84,14 @@ test('validApiHost()', async t => {
// })
test('systemPuppetName ()', async t => {
const WECHATY_PUPPET_ORIG = process.env['WECHATY_PUPPET']
const WECHATY_PUPPET_ORIG = process.env.WECHATY_PUPPET
delete process.env['WECHATY_PUPPET']
delete process.env.WECHATY_PUPPET
t.equal(config.systemPuppetName(), 'default', 'should get default as pupet name')
process.env['WECHATY_PUPPET'] = 'mock'
process.env.WECHATY_PUPPET = 'mock'
t.equal(config.systemPuppetName(), 'mock', 'should get pupet name from process.env')
// restore the original value
process.env['WECHATY_PUPPET'] = WECHATY_PUPPET_ORIG
process.env.WECHATY_PUPPET = WECHATY_PUPPET_ORIG
})
......@@ -16,6 +16,7 @@
* limitations under the License.
*
*/
// tslint:disable-next-line:no-reference
/// <reference path="./typings.d.ts" />
import fs from 'fs'
......@@ -36,9 +37,9 @@ import {
} from './puppet-config'
// https://github.com/Microsoft/TypeScript/issues/14151#issuecomment-280812617
if (!Symbol.asyncIterator) {
(<any>Symbol).asyncIterator = Symbol.for('Symbol.asyncIterator')
}
// if (!Symbol.asyncIterator) {
// (Symbol as any).asyncIterator = Symbol.for('Symbol.asyncIterator')
// }
const pkg = readPkgUp.sync({ cwd: __dirname }).pkg
export const VERSION = pkg.version
......@@ -56,9 +57,9 @@ Raven
release: VERSION,
tags: {
git_commit: '',
platform: !!process.env['WECHATY_DOCKER']
? 'docker'
: os.platform(),
platform: process.env.WECHATY_DOCKER
? 'docker'
: os.platform(),
},
},
)
......@@ -76,7 +77,7 @@ Raven.context(function () {
})
*/
const logLevel = process.env['WECHATY_LOG']
const logLevel = process.env.WECHATY_LOG
if (logLevel) {
log.level(logLevel.toLowerCase() as any)
log.silly('Config', 'WECHATY_LOG set level to %s', logLevel)
......@@ -115,21 +116,21 @@ const DEFAULT_SETTING = pkg.wechaty as DefaultSetting
export class Config {
public default = DEFAULT_SETTING
public apihost = process.env['WECHATY_APIHOST'] || DEFAULT_SETTING.DEFAULT_APIHOST
public head = ('WECHATY_HEAD' in process.env) ? (!!process.env['WECHATY_HEAD']) : (!!(DEFAULT_SETTING.DEFAULT_HEAD))
public apihost = process.env.WECHATY_APIHOST || DEFAULT_SETTING.DEFAULT_APIHOST
public head = ('WECHATY_HEAD' in process.env) ? (!!process.env.WECHATY_HEAD) : (!!(DEFAULT_SETTING.DEFAULT_HEAD))
public systemPuppetName () {
return (
process.env['WECHATY_PUPPET'] || 'default'
process.env.WECHATY_PUPPET || 'default'
).toLowerCase() as PuppetName
}
public profile = process.env['WECHATY_PROFILE'] || null // DO NOT set DEFAULT_PROFILE, because sometimes user do not want to save session
public token = process.env['WECHATY_TOKEN'] || null // DO NOT set DEFAULT, because sometimes user do not want to connect to io cloud service
public debug = !!(process.env['WECHATY_DEBUG'])
public profile = process.env.WECHATY_PROFILE || null // DO NOT set DEFAULT_PROFILE, because sometimes user do not want to save session
public token = process.env.WECHATY_TOKEN || null // DO NOT set DEFAULT, because sometimes user do not want to connect to io cloud service
public debug = !!(process.env.WECHATY_DEBUG)
public httpPort = process.env['PORT'] || process.env['WECHATY_PORT'] || DEFAULT_SETTING.DEFAULT_PORT
public docker = !!(process.env['WECHATY_DOCKER'])
public httpPort = process.env.PORT || process.env.WECHATY_PORT || DEFAULT_SETTING.DEFAULT_PORT
public docker = !!(process.env.WECHATY_DOCKER)
// private _puppetInstance: Puppet | null = null
......@@ -217,10 +218,6 @@ export function qrCodeForChatie(): FileBox {
return FileBox.fromStream(qrStream, name)
}
export interface Sayable {
say(text: string, replyTo?: any|any[]): Promise<void>
}
// http://jkorpela.fi/chars/spaces.html
// String.fromCharCode(8197)
export const FOUR_PER_EM_SPACE = String.fromCharCode(0x2005)
......
......@@ -123,7 +123,7 @@ export class IoClient {
// }
const app = express()
app.get('/', function (_ /* req */, res) {
app.get('/', (_ /* req */, res) => {
res.send('Wechaty IO Bot Alive!')
})
......
......@@ -16,8 +16,8 @@
* limitations under the License.
*
*/
import WebSocket from 'ws'
import { StateSwitch } from 'state-switch'
import WebSocket from 'ws'
import {
Message,
......@@ -31,6 +31,9 @@ import {
config,
log,
} from './config'
import {
AnyFunction,
} from './types'
import {
Wechaty,
} from './wechaty'
......@@ -84,7 +87,7 @@ export class Io {
private lifeTimer? : NodeJS.Timer
private onMessage: undefined | Function
private onMessage: undefined | AnyFunction
private scanPayload?: PuppetQrcodeScanEvent
......@@ -226,7 +229,7 @@ export class Io {
// const auth = 'Basic ' + new Buffer(this.setting.token + ':X').toString('base64')
const auth = 'Token ' + this.options.token
const headers = { 'Authorization': auth }
const headers = { Authorization: auth }
if (!this.options.apihost) {
throw new Error('no apihost')
......@@ -446,15 +449,18 @@ export class Io {
return
}
const list: Promise<any>[] = []
const list: Array<Promise<any>> = []
while (this.eventBuffer.length) {
const p = new Promise((resolve, reject) => ws.send(
JSON.stringify(
this.eventBuffer.shift(),
),
(err: Error) => {
if (err) { reject(err) }
else { resolve() }
if (err) {
reject(err)
} else {
resolve()
}
},
))
list.push(p)
......
......@@ -135,7 +135,7 @@ async function installPuppet (
function validatePuppetConfig () {
let puppetName: PuppetName
for (puppetName in PUPPET_DICT) {
for (puppetName of Object.keys(PUPPET_DICT) as PuppetName[]) {
const puppetConfig = PUPPET_DICT[puppetName]
const version = puppetConfig.npm.version || '*'
......
import {
Contact,
} from './user'
export type AnyFunction = (...args: any[]) => any
export interface Sayable {
say (text: string, replyTo?: Contact | Contact[]): Promise<void>
}
export interface Invitation {
accept: () => Promise<void>
reject: () => Promise<void>
}
......@@ -23,14 +23,14 @@ import { instanceToClass } from 'clone-class'
import {
log,
Raven,
Sayable,
qrCodeForChatie,
} from '../config'
import {
Accessory,
} from '../accessory'
// import Message from './message'
import {
Sayable,
} from '../types'
import {
ContactGender,
......@@ -206,7 +206,7 @@ export class Contact extends Accessory implements Sayable {
public static async findAll<T extends typeof Contact>(
this : T,
query? : string | ContactQueryFilter,
): Promise<T['prototype'][]> {
): Promise<Array<T['prototype']>> {
log.verbose('Contact', 'findAll(%s)', JSON.stringify(query))
if (query && Object.keys(query).length !== 1) {
......@@ -691,6 +691,8 @@ export class Contact extends Accessory implements Sayable {
}
}
// tslint:disable:max-classes-per-file
export class ContactSelf extends Contact {
constructor(
id: string,
......@@ -705,7 +707,8 @@ export class ContactSelf extends Contact {
log.verbose('Contact', 'avatar(%s)', file ? file.name : '')
if (!file) {
return await super.avatar()
const filebox = await super.avatar()
return filebox
}
if (this.id !== this.puppet.selfId()) {
......@@ -722,7 +725,8 @@ export class ContactSelf extends Contact {
throw new Error('only can get qrcode for the login userself')
}
return await this.puppet.contactQrcode(this.id)
const qrcodeData = await this.puppet.contactQrcode(this.id)
return qrcodeData
}
}
......
......@@ -28,9 +28,11 @@ import {
import {
log,
Sayable,
FOUR_PER_EM_SPACE,
} from '../config'
import {
Sayable,
} from '../types'
import {
Accessory,
} from '../accessory'
......@@ -683,7 +685,8 @@ export class Message extends Accessory implements Sayable {
public async forward(to: Room | Contact): Promise<void> {
log.verbose('Message', 'forward(%s)', to)
let roomId, contactId
let roomId
let contactId
if (to instanceof Room) {
roomId = to.id
......
......@@ -27,10 +27,12 @@ import {
import {
// config,
Raven,
Sayable,
log,
FOUR_PER_EM_SPACE,
} from '../config'
import {
Sayable,
} from '../types'
import {
Accessory,
} from '../accessory'
......@@ -122,7 +124,7 @@ export class Room extends Accessory implements Sayable {
public static async findAll<T extends typeof Room>(
this : T,
query : RoomQueryFilter = { topic: /.*/ },
): Promise<T['prototype'][]> {
): Promise<Array<T['prototype']>> {
log.verbose('Room', 'findAll()', JSON.stringify(query))
if (!query.topic) {
......@@ -710,7 +712,8 @@ export class Room extends Accessory implements Sayable {
if (text) {
await this.puppet.roomAnnounce(this.id, text)
} else {
return await this.puppet.roomAnnounce(this.id)
const announcement = await this.puppet.roomAnnounce(this.id)
return announcement
}
}
......
......@@ -58,9 +58,13 @@ import {
isProduction,
log,
Raven,
Sayable,
} from './config'
import {
AnyFunction,
Sayable,
} from './types'
import {
Io,
} from './io'
......@@ -287,15 +291,13 @@ export class Wechaty extends Accessory implements Sayable {
public emit(event: 'error' , error: Error) : boolean
public emit(event: 'friendship' , friendship: Friendship) : boolean
public emit(event: 'heartbeat' , data: any) : boolean
public emit(event: 'logout' , user: ContactSelf) : boolean
public emit(event: 'login' , user: ContactSelf) : boolean
public emit(event: 'login' | 'logout', user: ContactSelf) : boolean
public emit(event: 'message' , message: Message) : boolean
public emit(event: 'room-join' , room: Room, inviteeList : Contact[], inviter : Contact) : boolean
public emit(event: 'room-leave' , room: Room, leaverList : Contact[], remover? : Contact) : boolean
public emit(event: 'room-topic' , room: Room, newTopic: string, oldTopic: string, changer: Contact) : boolean
public emit(event: 'scan' , qrcode: string, status: number, data?: string) : boolean
public emit(event: 'start') : boolean
public emit(event: 'stop') : boolean
public emit(event: 'start' | 'stop') : boolean
// guard for the above event: make sure it includes all the possible values
public emit(event: never, listener: never): never
......@@ -311,15 +313,13 @@ export class Wechaty extends Accessory implements Sayable {
public on(event: 'error' , listener: string | ((this: Wechaty, error: Error) => void)) : this
public on(event: 'friendship' , listener: string | ((this: Wechaty, friendship: Friendship) => void)) : this
public on(event: 'heartbeat' , listener: string | ((this: Wechaty, data: any) => void)) : this
public on(event: 'logout' , listener: string | ((this: Wechaty, user: ContactSelf) => void)) : this
public on(event: 'login' , listener: string | ((this: Wechaty, user: ContactSelf) => void)) : this
public on(event: 'login' | 'logout' , listener: string | ((this: Wechaty, user: ContactSelf) => void)) : this
public on(event: 'message' , listener: string | ((this: Wechaty, message: Message) => void)) : this
public on(event: 'room-join' , listener: string | ((this: Wechaty, room: Room, inviteeList: Contact[], inviter: Contact) => void)) : this
public on(event: 'room-leave' , listener: string | ((this: Wechaty, room: Room, leaverList: Contact[], remover?: Contact) => void)) : this
public on(event: 'room-topic' , listener: string | ((this: Wechaty, room: Room, newTopic: string, oldTopic: string, changer: Contact) => void)) : this
public on(event: 'scan' , listener: string | ((this: Wechaty, qrcode: string, status: number, data?: string) => void)) : this
public on(event: 'start' , listener: string | ((this: Wechaty) => void)) : this
public on(event: 'stop' , listener: string | ((this: Wechaty) => void)) : this
public on(event: 'start' | 'stop' , listener: string | ((this: Wechaty) => void)) : this
// guard for the above event: make sure it includes all the possible values
public on(event: never, listener: never): never
......@@ -494,7 +494,7 @@ export class Wechaty extends Accessory implements Sayable {
log.verbose('Wechaty', 'onModulePath() hotImport(%s)', absoluteFilename)
hotImport(absoluteFilename)
.then((func: Function) => super.on(event, (...args: any[]) => {
.then((func: AnyFunction) => super.on(event, (...args: any[]) => {
try {
func.apply(this, args)
} catch (e) {
......@@ -516,7 +516,7 @@ export class Wechaty extends Accessory implements Sayable {
}
}
private addListenerFunction(event: WechatyEventName, listener: Function): void {
private addListenerFunction(event: WechatyEventName, listener: AnyFunction): void {
log.verbose('Wechaty', 'onFunction(%s)', event)
super.on(event, (...args: any[]) => {
......@@ -737,7 +737,7 @@ export class Wechaty extends Accessory implements Sayable {
const leaverList = leaverIdList.map(id => this.Contact.load(id))
await Promise.all(leaverList.map(c => c.ready()))
let remover: undefined | Contact = undefined
let remover: undefined | Contact
if (removerId) {
remover = this.Contact.load(removerId)
await remover.ready()
......@@ -872,9 +872,8 @@ export class Wechaty extends Accessory implements Sayable {
log.error('Wechaty', 'start() stop() exception: %s', e && e.message)
Raven.captureException(e)
this.emit('error', e)
} finally {
return
}
return
}
this.on('heartbeat', () => this.memoryCheck())
......@@ -978,7 +977,7 @@ export class Wechaty extends Accessory implements Sayable {
* console.log('Bot not logined')
* }
*/
public logonoff(): Boolean {
public logonoff(): boolean {
return this.puppet.logonoff()
}
......
{
"rulesDirectory": [
],
"extends": ["tslint:recommended", "tslint-config-standard"],
"rules": {
"no-floating-promises": true,
"align": [
true,
"parameters",
// "arguments",
"statements"
],
"jsdoc-require": [
false
],
"ban": false,
"class-name": true,
"comment-format": [
true,
"check-space"
],
"curly": false,
"eofline": true,
"forin": false,
"indent": [
true,
"spaces"
],
"interface-name": false,
"jsdoc-format": true,
"label-position": true,
"max-line-length": [
true,
180
],
"callable-types": true,
"interface-over-type-literal": true,
"no-empty-interface": true,
"no-string-throw": true,
"prefer-const": true,
"unified-signatures": false,
"no-inferrable-types": [true, "ignore-params"],
"member-access": true,
"member-ordering": [false],
"no-any": false,
"no-arg": true,
"no-bitwise": true,
"no-conditional-assignment": true,
"no-consecutive-blank-lines": true,
"no-console": [false],
"no-construct": false,
"no-debugger": true,
"no-duplicate-variable": true,
"no-empty": true,
"no-eval": true,
"no-internal-module": true,
"no-require-imports": false,
"no-shadowed-variable": true,
"no-string-literal": false,
"no-switch-case-fall-through": true,
"no-trailing-whitespace": true,
"no-unused-expression": true,
"no-use-before-declare": true,
"no-var-keyword": true,
"no-var-requires": false,
"object-literal-sort-keys": false,
"one-line": [
true,
"check-open-brace",
"check-whitespace"
],
"quotemark": [
true,
"single",
"avoid-escape"
],
"radix": false,
"semicolon": [true, "never"],
"switch-default": false,
"trailing-comma": [
true,
{
"multiline": "always",
"singleline": "never",
"esSpecCompliant": true
}
],
"triple-equals": [true],
"typedef": [false],
"typedef-whitespace": [
false,
{
"call-signature": "space",
"index-signature": "nospace",
"parameter": "nospace",
"property-declaration": "nospace",
"variable-declaration": "nospace"
}
],
"variable-name": [
true,
"check-format",
"allow-leading-underscore",
"ban-keywords"
],
"whitespace": [
true,
"check-branch",
"check-decl",
"check-operator",
"check-separator",
"check-type"
]
"interface-name": [true, "never-prefix"],
"trailing-comma": true,
"import-spacing": false,
"no-multi-spaces": false,
"no-console": false,
"space-within-parens": false,
"arrow-parens": false,
"max-line-length": false,
"unified-signatures": false,
"ter-indent": false,
"member-ordering": false,
"typedef-whitespace": false
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册