Skip to content

Commit

Permalink
Merge branch 'develop'
Browse files Browse the repository at this point in the history
  • Loading branch information
shigma committed Jan 17, 2020
2 parents e59a400 + 17b327c commit 294e46f
Show file tree
Hide file tree
Showing 43 changed files with 496 additions and 287 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,8 @@ koishi run
| [koishi-database-mysql](https://github.com/koishijs/koishi/tree/master/packages/database-mysql) | [![npm](https://img.shields.io/npm/v/koishi-database-mysql?style=flat-square)](https://www.npmjs.com/package/koishi-database-mysql) |
| [koishi-database-sqlite](https://github.com/koishijs/koishi/tree/master/packages/database-sqlite) | [![npm](https://img.shields.io/npm/v/koishi-database-sqlite?style=flat-square)](https://www.npmjs.com/package/koishi-database-sqlite) |
| [koishi-plugin-common](https://github.com/koishijs/koishi/tree/master/packages/plugin-common) | [![npm](https://img.shields.io/npm/v/koishi-plugin-common?style=flat-square)](https://www.npmjs.com/package/koishi-plugin-common) |
| [koishi-plugin-nlp](https://github.com/koishijs/koishi/tree/master/packages/plugin-nlp) | [![npm](https://img.shields.io/npm/v/koishi-plugin-nlp?style=flat-square)](https://www.npmjs.com/package/koishi-plugin-nlp) |
| [koishi-plugin-recorder](https://github.com/koishijs/koishi/tree/master/packages/plugin-recorder) | [![npm](https://img.shields.io/npm/v/koishi-plugin-recorder?style=flat-square)](https://www.npmjs.com/package/koishi-plugin-recorder) |
| [koishi-plugin-schedule](https://github.com/koishijs/koishi/tree/master/packages/plugin-schedule) | [![npm](https://img.shields.io/npm/v/koishi-plugin-schedule?style=flat-square)](https://www.npmjs.com/package/koishi-plugin-schedule) |
| [koishi-plugin-teach](https://github.com/koishijs/koishi/tree/master/packages/plugin-teach) | [![npm](https://img.shields.io/npm/v/koishi-plugin-teach?style=flat-square)](https://www.npmjs.com/package/koishi-plugin-teach) |

Expand Down
6 changes: 3 additions & 3 deletions packages/database-level/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "koishi-database-level",
"description": "Leveldb support for Koishi",
"version": "1.0.5",
"version": "1.0.6",
"main": "dist/index.js",
"files": [
"dist"
Expand Down Expand Up @@ -33,12 +33,12 @@
"leveldb"
],
"devDependencies": {
"koishi-test-utils": "^1.2.1"
"koishi-test-utils": "^1.2.2"
},
"dependencies": {
"@types/leveldown": "^4.0.2",
"@types/levelup": "^4.3.0",
"koishi-core": "^1.3.1",
"koishi-core": "^1.4.0",
"koishi-utils": "^1.0.2",
"leveldown": "^5.4.1",
"levelup": "^4.3.2",
Expand Down
4 changes: 2 additions & 2 deletions packages/database-mysql/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "koishi-database-mysql",
"description": "MySQL support for Koishi",
"version": "1.0.5",
"version": "1.0.6",
"main": "dist/index.js",
"typings": "dist/index.d.ts",
"files": [
Expand Down Expand Up @@ -35,7 +35,7 @@
"@types/mysql": "^2.15.8"
},
"dependencies": {
"koishi-core": "^1.3.1",
"koishi-core": "^1.4.0",
"koishi-utils": "^1.0.2",
"mysql": "^2.17.1"
}
Expand Down
6 changes: 3 additions & 3 deletions packages/database-sqlite/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "koishi-database-sqlite",
"version": "1.0.0-alpha.1",
"version": "1.0.0-alpha.2",
"main": "dist/index.js",
"typings": "dist/index.d.ts",
"files": [
Expand All @@ -22,10 +22,10 @@
"homepage": "https://github.com/koishijs/koishi/tree/master/packages/database-sqlite#readme",
"devDependencies": {
"@types/sqlite3": "^3.1.6",
"koishi-test-utils": "^1.2.1"
"koishi-test-utils": "^1.2.2"
},
"dependencies": {
"koishi-core": "^1.3.1",
"koishi-core": "^1.4.0",
"koishi-utils": "^1.0.2",
"sqlite3": "^4.1.1"
}
Expand Down
1 change: 0 additions & 1 deletion packages/database-sqlite/src/database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ export type Pragma = {
export const pragma: Pragma = {
user: {
id: 'BIGINT',
name: 'VARCHAR(64)',
flag: 'INT',
authority: 'INT',
usage: 'TEXT',
Expand Down
8 changes: 4 additions & 4 deletions packages/koishi-cli/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "koishi",
"description": "A QQ bot framework based on CQHTTP",
"version": "1.3.1",
"version": "1.4.0",
"main": "dist/index.js",
"typings": "dist/index.d.ts",
"files": [
Expand Down Expand Up @@ -40,9 +40,9 @@
"cac": "^6.5.4",
"js-yaml": "^3.13.1",
"kleur": "^3.0.3",
"koishi-core": "^1.3.1",
"koishi-plugin-common": "^1.0.5",
"koishi-plugin-schedule": "^1.0.1",
"koishi-core": "^1.4.0",
"koishi-plugin-common": "^1.0.6",
"koishi-plugin-schedule": "^1.0.2",
"koishi-utils": "^1.0.2",
"prompts": "^2.3.0"
}
Expand Down
6 changes: 5 additions & 1 deletion packages/koishi-cli/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import * as commonPlugin from 'koishi-plugin-common'
import * as schedulePlugin from 'koishi-plugin-schedule'
export { commonPlugin, schedulePlugin }

export * from 'koishi-core'
export * from 'koishi-utils'
export { AppConfig } from './worker'
export { AppConfig, PluginConfig } from './worker'

const { version } = require('../package')
export { version }
12 changes: 8 additions & 4 deletions packages/koishi-cli/src/init.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { existsSync, writeFileSync } from 'fs'
import { existsSync, writeFileSync, mkdirSync } from 'fs'
import { yellow } from 'kleur'
import { resolve, extname } from 'path'
import { resolve, extname, dirname } from 'path'
import { logger } from './utils'
import { safeDump } from 'js-yaml'
import { AppConfig } from './worker'
Expand Down Expand Up @@ -56,8 +56,8 @@ async function createConfig (options) {
return config
}

type ConfigFileType = 'js' | 'json' | 'yml' | 'yaml'
const supportedTypes: ConfigFileType[] = ['js', 'json', 'yml', 'yaml']
const supportedTypes = ['js', 'json', 'ts', 'yml', 'yaml'] as const
type ConfigFileType = typeof supportedTypes[number]

export default function (cli: CAC) {
cli.command('init [file]', 'initialize a koishi configuration file')
Expand Down Expand Up @@ -95,10 +95,14 @@ export default function (cli: CAC) {
output = JSON.stringify(config, null, 2)
if (extension === 'js') {
output = 'module.exports = ' + output.replace(/^(\s+)"([\w$]+)":/mg, '$1$2:')
} else if (extension === 'ts') {
output = 'export = ' + output.replace(/^(\s+)"([\w$]+)":/mg, '$1$2:')
}
}

// write to file
const folder = dirname(path)
if (!existsSync(folder)) mkdirSync(folder, { recursive: true })
writeFileSync(path, output)
logger.success(`created config file: ${path}`)
process.exit(0)
Expand Down
6 changes: 3 additions & 3 deletions packages/koishi-cli/src/worker.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { App, startAll, AppOptions, onStart, Context, Plugin, appList, logTypes, LogEvents } from 'koishi-core'
import { App, startAll, AppOptions, onStart, Context, Plugin, appList } from 'koishi-core'
import { resolve, extname } from 'path'
import { capitalize } from 'koishi-utils'
import { performance } from 'perf_hooks'
Expand Down Expand Up @@ -39,7 +39,7 @@ function loadEcosystem (type: string, name: string) {
throw new Error(`cannot resolve ${type} ${name}`)
}

type PluginConfig = (string | [string | Plugin, any])[]
export type PluginConfig = (string | [string | Plugin, any?])[]

export interface AppConfig extends AppOptions {
plugins?: PluginConfig | Record<string, PluginConfig>
Expand Down Expand Up @@ -87,7 +87,7 @@ function tryCallback <T> (callback: () => T) {
} catch {}
}

if (['.js', '.json'].includes(extension)) {
if (['.js', '.json', '.ts'].includes(extension)) {
config = tryCallback(() => require(configFile))
} else if (['.yaml', '.yml'].includes(extension)) {
config = tryCallback(() => safeLoad(readFileSync(configFile, 'utf8')))
Expand Down
4 changes: 2 additions & 2 deletions packages/koishi-core/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "koishi-core",
"description": "Core features for Koishi",
"version": "1.3.1",
"version": "1.4.0",
"main": "dist/index.js",
"typings": "dist/index.d.ts",
"files": [
Expand Down Expand Up @@ -35,7 +35,7 @@
"@types/debug": "^4.1.5",
"@types/ws": "^6.0.4",
"get-port": "^5.1.0",
"koishi-test-utils": "^1.2.1"
"koishi-test-utils": "^1.2.2"
},
"dependencies": {
"axios": "^0.19.1",
Expand Down
21 changes: 14 additions & 7 deletions packages/koishi-core/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,16 +41,10 @@ export function onStop (hook: (...app: App[]) => void) {

export async function startAll () {
await Promise.all(appList.map(async app => app.start()))
for (const hook of onStartHooks) {
hook(...appList)
}
}

export async function stopAll () {
await Promise.all(appList.map(async app => app.stop()))
for (const hook of onStopHooks) {
hook(...appList)
}
}

let getSelfIdsPromise: Promise<any>
Expand Down Expand Up @@ -82,6 +76,8 @@ const defaultOptions: AppOptions = {
maxMiddlewares: 64,
}

export enum Status { closed, opening, open, closing }

export class App extends Context {
app = this
options: AppOptions
Expand All @@ -99,6 +95,7 @@ export class App extends Context {
_shortcutMap: Record<string, Command> = {}
_middlewares: [Context, Middleware][] = []

private status = Status.closed
private _isReady = false
private _middlewareCounter = 0
private _middlewareSet = new Set<number>()
Expand Down Expand Up @@ -208,6 +205,7 @@ export class App extends Context {
}

async start () {
this.status = Status.opening
this.receiver.emit('before-connect')
const tasks: Promise<any>[] = []
if (this.database) {
Expand All @@ -219,15 +217,20 @@ export class App extends Context {
tasks.push(this.server.listen())
}
await Promise.all(tasks)
this.status = Status.open
this.logger('app').debug('started')
this.receiver.emit('connect')
if (this.selfId && !this._isReady) {
this.receiver.emit('ready')
this._isReady = true
}
if (appList.every(app => app.status === Status.open)) {
onStartHooks.forEach(hook => hook(...appList))
}
}

async stop () {
this.status = Status.closing
this.receiver.emit('before-disconnect')
const tasks: Promise<any>[] = []
if (this.database) {
Expand All @@ -239,8 +242,12 @@ export class App extends Context {
if (this.server) {
this.server.close()
}
this.status = Status.closed
this.logger('app').debug('stopped')
this.receiver.emit('disconnect')
if (appList.every(app => app.status === Status.closed)) {
onStopHooks.forEach(hook => hook(...appList))
}
}

emitEvent <K extends Events> (meta: Meta, event: K, ...payload: Parameters<EventMap[K]>) {
Expand Down Expand Up @@ -320,7 +327,7 @@ export class App extends Context {
}

// attach user data
const userFields = new Set<UserField>(['name', 'flag'])
const userFields = new Set<UserField>(['flag'])
this.receiver.emit('before-user', userFields, parsedArgv || { meta })
const user = await this.database.observeUser(meta.userId, Array.from(userFields))
Object.defineProperty(meta, '$user', { value: user, writable: true })
Expand Down
2 changes: 0 additions & 2 deletions packages/koishi-core/src/database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ export const userFlags: (keyof typeof UserFlag)[] = ['ignore']

export interface UserData {
id: number
name: string
flag: number
authority: number
usage: Record<string, Usage>
Expand All @@ -36,7 +35,6 @@ extendUser((id, authority) => ({
id,
authority,
flag: 0,
name: String(id),
usage: {},
}))

Expand Down
1 change: 1 addition & 0 deletions packages/koishi-core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ export * from './context'
export * from './database'
export * from './meta'
export * from './messages'
export * from './parser'
export * from './sender'
export * from './server'
export * from './utils'
1 change: 1 addition & 0 deletions packages/koishi-core/src/sender.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ export class Sender {
message,
sendType,
postType: 'send',
userId: this.app.selfId,
[$ctxType + 'Id']: $ctxId,
} as Meta<'send'>
}
Expand Down
14 changes: 4 additions & 10 deletions packages/koishi-core/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,11 @@ import { messages } from './messages'
import { format } from 'util'
import leven from 'leven'

export function getSenderName (meta: MessageMeta) {
const userId = '' + meta.userId
return meta.$user && meta.$user.name !== userId ? meta.$user.name
: meta.sender ? meta.sender.card || meta.sender.nickname : userId
}

export function getTargetId (target: string) {
if (!target) return
export function getTargetId (target: string | number) {
if (typeof target !== 'string' && typeof target !== 'number') return
let qq = +target
if (!qq) {
const capture = /\[CQ:at,qq=(\d+)\]/.exec(target)
const capture = /\[CQ:at,qq=(\d+)\]/.exec(target as any)
if (capture) qq = +capture[1]
}
if (!isInteger(qq)) return
Expand Down Expand Up @@ -51,7 +45,7 @@ export function showSuggestions (options: SuggestOptions): Promise<void> {
const [suggestion] = suggestions
const command = typeof options.command === 'function' ? options.command(suggestion) : options.command
const identifier = meta.userId + meta.$ctxType + meta.$ctxId
const userFields = new Set<UserField>(['name'])
const userFields = new Set<UserField>()
const groupFields = new Set<GroupField>()
Command.attachUserFields(userFields, { command, meta })
Command.attachGroupFields(groupFields, { command, meta })
Expand Down
38 changes: 2 additions & 36 deletions packages/koishi-core/tests/utils.spec.ts
Original file line number Diff line number Diff line change
@@ -1,39 +1,4 @@
import { getSenderName, createUser, getTargetId } from 'koishi-core'
import { createSender } from 'koishi-test-utils'
import { observe } from 'koishi-utils'

describe('getSenderName', () => {
test('userData with userId', () => {
expect(getSenderName({
userId: 123,
$user: observe(createUser(123, 1)),
})).toBe('123')
})

test('userData with name', () => {
expect(getSenderName({
userId: 123,
$user: observe({ ...createUser(123, 1), name: '456' }),
sender: createSender(123, 'bar', 'foo'),
})).toBe('456')
})

test('userData with card', () => {
expect(getSenderName({
userId: 123,
$user: observe(createUser(123, 1)),
sender: createSender(123, 'bar', 'foo'),
})).toBe('foo')
})

test('userData with nickname', () => {
expect(getSenderName({
userId: 123,
$user: observe(createUser(123, 1)),
sender: createSender(123, 'bar'),
})).toBe('bar')
})
})
import { getTargetId } from 'koishi-core'

describe('getTargetId', () => {
test('with id', () => {
Expand All @@ -46,6 +11,7 @@ describe('getTargetId', () => {

test('wrong syntax', () => {
expect(getTargetId('')).toBeFalsy()
expect(getTargetId(true as any)).toBeFalsy()
expect(getTargetId('[CQ:at,qq=]')).toBeFalsy()
expect(getTargetId('foo123')).toBeFalsy()
})
Expand Down
Loading

0 comments on commit 294e46f

Please sign in to comment.