Skip to content

Commit

Permalink
Merge branch 'develop'
Browse files Browse the repository at this point in the history
  • Loading branch information
shigma committed Apr 2, 2021
2 parents 79f5795 + 8a9ef60 commit 6c18929
Show file tree
Hide file tree
Showing 56 changed files with 476 additions and 377 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ temp
/tsconfig.temp.json

/addons
/public
/atri
/coverage
/docs
Expand Down
8 changes: 1 addition & 7 deletions .mocharc.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,7 @@ for (const name of readdirSync(__dirname + '/packages')) {
}

const specs = [
// 'packages/koishi-core/tests/*.spec.ts',
'packages/koishi-core/tests/command.spec.ts',
'packages/koishi-core/tests/context.spec.ts',
'packages/koishi-core/tests/help.spec.ts',
'packages/koishi-core/tests/hook.spec.ts',
'packages/koishi-core/tests/session.spec.ts',
'packages/koishi-core/tests/parser.spec.ts',
'packages/koishi-core/tests/*.spec.ts',
'packages/koishi-utils/tests/*.spec.ts',
'packages/koishi-test-utils/tests/*.spec.ts',
'packages/plugin-common/tests/*.spec.ts',
Expand Down
3 changes: 2 additions & 1 deletion .nycrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"packages/plugin-*/**/database/**",
"packages/plugin-*/**/database.js",
"packages/plugin-mongo/**",
"packages/plugin-mysql/**"
"packages/plugin-mysql/**",
"packages/plugin-webui/**"
]
}
4 changes: 2 additions & 2 deletions packages/adapter-discord/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "koishi-adapter-discord",
"description": "Discord adapter for Koishi",
"version": "1.0.5",
"version": "1.0.6",
"main": "lib/index.js",
"typings": "lib/index.d.ts",
"files": [
Expand All @@ -28,7 +28,7 @@
"koishi"
],
"peerDependencies": {
"koishi-core": "^3.6.0"
"koishi-core": "^3.6.1"
},
"devDependencies": {
"@types/ws": "^7.4.0",
Expand Down
15 changes: 3 additions & 12 deletions packages/adapter-discord/src/bot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export class DiscordBot extends Bot<'discord'> {
_ping: NodeJS.Timeout
_sessionId: string = ''

async request<T = any>(method: Method, path: string, data?: any): Promise<T> {
async request<T = any>(method: Method, path: string, data?: any, exHeaders?: any): Promise<T> {
const { axiosConfig, discord = {} } = this.app.options
const url = `https://discord.com/api/v8${path}`
const headers: Record<string, any> = {
Expand All @@ -27,7 +27,7 @@ export class DiscordBot extends Bot<'discord'> {
...discord.axiosConfig,
method,
url,
headers,
headers: { ...headers, ...exHeaders },
data,
})
return response.data
Expand All @@ -43,16 +43,7 @@ export class DiscordBot extends Bot<'discord'> {
const type = await FileType.fromBuffer(fileBuffer)
fd.append('file', fileBuffer, 'file.' + type.ext)
fd.append('payload_json', JSON.stringify(payload_json))
const headers: Record<string, any> = {
Authorization: `Bot ${this.token}`,
}
const response = await axios({
method: 'post',
url: 'https://discord.com/api/v8' + requestUrl,
headers: { ...headers, ...fd.getHeaders() },
data: fd,
})
return response.data
return this.request('POST', requestUrl, fd, fd.getHeaders())
}

private parseQuote(chain: segment.Chain) {
Expand Down
4 changes: 2 additions & 2 deletions packages/adapter-kaiheila/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "koishi-adapter-kaiheila",
"description": "Kaiheila adapter for Koishi",
"version": "1.0.3",
"version": "1.0.4",
"main": "lib/index.js",
"typings": "lib/index.d.ts",
"files": [
Expand All @@ -24,7 +24,7 @@
"koishi"
],
"peerDependencies": {
"koishi-core": "^3.6.0"
"koishi-core": "^3.6.1"
},
"devDependencies": {
"koishi-test-utils": "^6.0.0-beta.11"
Expand Down
2 changes: 2 additions & 0 deletions packages/adapter-kaiheila/src/bot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,8 @@ export class KaiheilaBot extends Bot {
} else {
params.channelId = channelId
session.subtype = 'group'
// FIXME this is incorrect but to workarournd ctx.group()
session.groupId = 'unknown'
path = '/message/create'
}

Expand Down
1 change: 1 addition & 0 deletions packages/adapter-kaiheila/src/ws.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ export default class WsClient extends Adapter.WsClient<'kaiheila'> {
}
let trials = 0
function send() {
if (!bot.socket) return
if (trials >= 2) {
return bot.socket.close(1013)
}
Expand Down
2 changes: 1 addition & 1 deletion packages/adapter-onebot/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
"koishi"
],
"peerDependencies": {
"koishi-core": "^3.6.0"
"koishi-core": "^3.6.1"
},
"devDependencies": {
"@types/ws": "^7.4.0",
Expand Down
2 changes: 1 addition & 1 deletion packages/adapter-telegram/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
"koishi"
],
"peerDependencies": {
"koishi-core": "^3.6.0"
"koishi-core": "^3.6.1"
},
"devDependencies": {
"koishi-test-utils": "^6.0.0-beta.11"
Expand Down
2 changes: 1 addition & 1 deletion packages/adapter-tomon/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
"koishi"
],
"peerDependencies": {
"koishi-core": "^3.6.0"
"koishi-core": "^3.6.1"
},
"devDependencies": {
"@types/pako": "^1.0.1",
Expand Down
2 changes: 1 addition & 1 deletion 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": "3.6.0",
"version": "3.6.1",
"main": "lib/index.js",
"typings": "lib/index.d.ts",
"engines": {
Expand Down
9 changes: 7 additions & 2 deletions packages/koishi-core/src/help.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { TableType } from './database'
import { Session, FieldCollector } from './session'
import { template } from 'koishi-utils'
import { Context } from './context'
import { Domain } from './parser'

interface HelpConfig {
showHidden?: boolean
Expand Down Expand Up @@ -111,12 +112,16 @@ function formatCommands(path: string, session: Session<ValidationField>, childre
return output
}

function getOptionVisibility(option: Domain.OptionConfig, session: Session<ValidationField>) {
if (session.user && option.authority > session.user.authority) return false
return !session.resolveValue(option.hidden)
}

function getOptions(command: Command, session: Session<ValidationField>, maxUsage: number, config: HelpConfig) {
if (command.config.hideOptions && !config.showHidden) return []
const options = config.showHidden
? Object.values(command._options)
: Object.values(command._options)
.filter(option => !option.hidden && (!session.user || option.authority <= session.user.authority))
: Object.values(command._options).filter(option => getOptionVisibility(option, session))
if (!options.length) return []

const output = config.authority && options.some(o => o.authority)
Expand Down
15 changes: 7 additions & 8 deletions packages/koishi-core/src/parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ export namespace Domain {
fallback?: any
type?: T
/** hide the option by default */
hidden?: boolean
hidden?: boolean | ((session: Session) => boolean)
authority?: number
notUsage?: boolean
}
Expand Down Expand Up @@ -533,10 +533,14 @@ export namespace Argv {
}

stringify(argv: Argv) {
return argv.tokens.reduce((prev, token) => {
const output = argv.tokens.reduce((prev, token) => {
if (token.quoted) prev += leftQuotes[rightQuotes.indexOf(token.terminator[0])]
return prev + token.content + token.terminator
}, '')
if (argv.rest && !rightQuotes.includes(output[output.length - 1]) || argv.initiator) {
return output.slice(0, -1)
}
return output
}
}

Expand All @@ -547,12 +551,7 @@ export namespace Argv {
}

export function stringify(argv: Argv) {
const source = defaultTokenizer.stringify(argv)
if (argv.rest) {
const { terminator } = argv.tokens[argv.tokens.length - 1]
if (!leftQuotes.includes(terminator[0])) return source.slice(0, -terminator.length)
}
return source
return defaultTokenizer.stringify(argv)
}

export function revert(token: Token) {
Expand Down
13 changes: 7 additions & 6 deletions packages/koishi-core/src/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ export class Session<
}))
}

private _getValue<T>(source: T | ((session: Session) => T)): T {
resolveValue<T>(source: T | ((session: Session) => T)): T {
return typeof source === 'function' ? Reflect.apply(source, null, [this]) : source
}

Expand Down Expand Up @@ -219,7 +219,7 @@ export class Session<
if (hasActiveCache) return this.channel = cache as any

// 绑定一个新的可观测频道实例
const assignee = this._getValue(this.app.options.autoAssign) ? this.selfId : ''
const assignee = this.resolveValue(this.app.options.autoAssign) ? this.selfId : ''
const data = await this.getChannel(channelId, assignee, fieldArray)
const newChannel = observe(data, diff => this.database.setChannel(platform, channelId, diff), `channel ${this.cid}`)
this.app._channelCache.set(this.cid, newChannel)
Expand Down Expand Up @@ -266,7 +266,7 @@ export class Session<
// 确保匿名消息不会写回数据库
if (this.author?.anonymous) {
const fallback = User.create(this.platform, userId)
fallback.authority = this._getValue(this.app.options.autoAuthorize)
fallback.authority = this.resolveValue(this.app.options.autoAuthorize)
const user = observe(fallback, () => Promise.resolve())
return this.user = user
}
Expand All @@ -278,7 +278,7 @@ export class Session<
if (hasActiveCache) return this.user = cache as any

// 绑定一个新的可观测用户实例
const data = await this.getUser(userId, this._getValue(this.app.options.autoAuthorize), fieldArray)
const data = await this.getUser(userId, this.resolveValue(this.app.options.autoAuthorize), fieldArray)
const newUser = observe(data, diff => this.database.setUser(this.platform, userId, diff), `user ${this.uid}`)
userCache.set(userId, newUser)
return this.user = newUser
Expand Down Expand Up @@ -358,8 +358,9 @@ export class Session<
}

const result = await argv.command.execute(argv, next)
if (shouldEmit) await this.send(result)
return result
if (!shouldEmit) return result
await this.send(result)
return ''
}

middleware(middleware: Middleware) {
Expand Down
41 changes: 20 additions & 21 deletions packages/koishi-core/tests/runtime.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { App } from 'koishi-test-utils'
import { User, Channel, Command } from 'koishi-core'
import { sleep } from 'koishi-utils'
import { User, Channel, Command, sleep } from 'koishi-core'
import { install } from '@sinonjs/fake-timers'

const app = new App({
Expand Down Expand Up @@ -33,7 +32,7 @@ const cmd2 = app.command('cmd2')
.shortcut('foo3', { prefix: true, fuzzy: true })
.option('--bar', '', { authority: 3 })
.option('--baz', '', { notUsage: true })
.action(({ session }) => session.send('cmd2:' + session.user.id))
.action(({ session }) => session.send('cmd2:' + session.userId))

before(async () => {
await app.start()
Expand Down Expand Up @@ -116,7 +115,7 @@ describe('Runtime', () => {
await session4.shouldNotReply('cmd2')
await session1.shouldReply('-cmd2', 'cmd2:123')
await session4.shouldReply('-cmd2', 'cmd2:123')
await session4.shouldNotReply(`[CQ:reply,id=123] [CQ:at,qq=${app.selfId}] cmd2`)
await session4.shouldNotReply(`[CQ:reply,id=123] [CQ:at,id=${app.selfId}] cmd2`)
})

it('single nickname', async () => {
Expand Down Expand Up @@ -173,13 +172,13 @@ describe('Runtime', () => {

it('nickname prefix & fuzzy', async () => {
await session4.shouldNotReply('foo3 -t baz')
await session4.shouldReply(`[CQ:at,qq=${app.selfId}] foo3 -t baz`, 'cmd2:123')
await session4.shouldReply(`[CQ:at,id=${app.selfId}] foo3 -t baz`, 'cmd2:123')
})

it('one argument & fuzzy', async () => {
await session4.shouldReply('foo4 bar baz', 'cmd1:bar baz')
await session4.shouldNotReply('foo4bar baz')
await session4.shouldReply(`[CQ:at,qq=${app.selfId}] foo4bar baz`, 'cmd1:bar baz')
await session4.shouldReply(`[CQ:at,id=${app.selfId}] foo4bar baz`, 'cmd1:bar baz')
})
})

Expand All @@ -193,19 +192,19 @@ describe('Runtime', () => {
await session3.shouldNotReply('cmd2')
})

it('group.assignee', async () => {
it('channel.assignee', async () => {
await session4.shouldReply('cmd1 test --baz', 'cmd1:test')
await session4.shouldReply('mid', 'mid')
await session5.shouldNotReply('cmd1 test --baz')
await session5.shouldReply(`[CQ:at,qq=${app.selfId}] cmd1 test --baz`, 'cmd1:test')
await session5.shouldReply(`[CQ:at,id=${app.selfId}] cmd1 test --baz`, 'cmd1:test')
})

it('group.flag.ignore', async () => {
it('channel.flag.ignore', async () => {
await app.database.setChannel('mock', '321', { flag: Channel.Flag.ignore })
await sleep(0)
await session4.shouldNotReply('mid')
await session4.shouldNotReply('cmd1 --baz')
await session4.shouldNotReply(`[CQ:at,qq=${app.selfId}] cmd1 --baz`)
await session4.shouldNotReply(`[CQ:at,id=${app.selfId}] cmd1 --baz`)
await app.database.setChannel('mock', '321', { flag: 0 })
})
})
Expand Down Expand Up @@ -250,7 +249,7 @@ describe('Runtime', () => {
cmd1.config.showWarning = true
await session4.shouldReply('cmd1', '缺少参数,输入帮助以查看用法。')
await session4.shouldReply('cmd1 foo', 'cmd1:foo')
await session4.shouldReply('cmd1 foo bar', '存在多余参数,请检查指令语法。')
await session4.shouldReply('cmd1 foo bar', '存在多余参数,输入帮助以查看用法。')
cmd1.config.showWarning = false
await session4.shouldNotReply('cmd1')
cmd1.config.checkArgCount = false
Expand All @@ -260,31 +259,31 @@ describe('Runtime', () => {
cmd2.config.checkUnknown = true
cmd2.config.showWarning = true
await session2.shouldReply('cmd2', 'cmd2:456')
await session2.shouldReply('cmd2 --foo', '存在未知选项 foo,请检查指令语法。')
await session2.shouldReply('cmd2 --foo', '存在未知选项 foo,输入帮助以查看用法。')
cmd2.config.showWarning = false
await session2.shouldNotReply('cmd2 --foo')
cmd2.config.checkUnknown = false
})

it('option.validate', async () => {
const cmd3 = app.command('cmd3').action(() => 'after cmd3')
cmd3.option('foo', '', { type: () => true })
cmd3.option('bar', '', { type: () => { throw new Error('SUFFIX') } })
cmd3.option('baz', '', { type: /$^/ })
cmd3.option('foo', '<foo>', { type: () => { throw new Error() } })
cmd3.option('bar', '<bar>', { type: () => { throw new Error('SUFFIX') } })
cmd3.option('baz', '<baz>', { type: /$^/ })
await session1.shouldReply('cmd3', 'after cmd3')
await session1.shouldReply('cmd3 --foo', '选项 foo 输入无效,请检查指令语法。')
await session1.shouldReply('cmd3 --bar', '选项 bar 输入无效,SUFFIX')
await session1.shouldReply('cmd3 --baz', '选项 baz 输入无效,请检查指令语法。')
await session1.shouldReply('cmd3 --foo xxx', '选项 foo 输入无效,输入帮助以查看用法。')
await session1.shouldReply('cmd3 --bar xxx', '选项 bar 输入无效,SUFFIX')
await session1.shouldReply('cmd3 --baz xxx', '选项 baz 输入无效,输入帮助以查看用法。')
cmd3.dispose()
})

it('command.before', async () => {
it('command.check', async () => {
const cmd3 = app.command('cmd3').action(() => 'after cmd3')
await session1.shouldReply('cmd3', 'after cmd3')
let value: any = 'before cmd3'
let value = 'before cmd3'
cmd3.check(() => value)
await session1.shouldReply('cmd3', 'before cmd3')
value = true
value = ''
await session1.shouldNotReply('cmd3')
cmd3.dispose()
})
Expand Down
Loading

0 comments on commit 6c18929

Please sign in to comment.