Skip to content

Commit

Permalink
refa: migrate common plugins
Browse files Browse the repository at this point in the history
  • Loading branch information
shigma committed Jul 10, 2022
1 parent 6032d82 commit ef76432
Show file tree
Hide file tree
Showing 13 changed files with 39 additions and 38 deletions.
3 changes: 0 additions & 3 deletions .eslintrc.yml
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,6 @@ rules:
no-inner-declarations: off

no-useless-constructor: off
'@typescript-eslint/no-useless-constructor': warn

node/no-callback-literal: off

Expand All @@ -159,5 +158,3 @@ rules:
asyncArrow: always
named: never
'@typescript-eslint/type-annotation-spacing': error

'@typescript-eslint/no-useless-constructor': off
6 changes: 3 additions & 3 deletions packages/cli/src/worker/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,17 @@ export * from './utils'
export { Loader, Watcher }

declare module 'koishi' {
interface EventMap {
interface Events {
'exit'(signal: NodeJS.Signals): Promise<void>
'config'(): void
}

interface App {
interface Context {
prologue: string[]
watcher: Watcher
}

namespace App {
namespace Context {
interface Config extends daemon.Config {
plugins?: Dict
timezoneOffset?: number
Expand Down
33 changes: 17 additions & 16 deletions packages/cli/src/worker/loader.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,28 @@
import { resolve } from 'path'
import { App, Context, Dict, interpolate, Logger, Plugin, Registry, valueMap } from 'koishi'
import { Context, Dict, interpolate, Logger, Plugin, valueMap } from 'koishi'
import { resolveConfig } from 'cordis'
import { patch, stripModifier } from './utils'
import ConfigLoader from '@koishijs/loader'
import * as dotenv from 'dotenv'
import ns from 'ns-require'

declare module 'koishi' {
namespace Context {
interface Services {
loader: Loader
delimiter: symbol
}
interface Context {
loader: Loader
delimiter: symbol
}
}

declare module 'cordis' {
interface Runtime {
[Loader.kWarning]?: boolean
}

// Theoretically, these properties will only appear on `Fork`.
// We define them directly on `State` for typing convenience.
interface State {
interface State<C> {
[Loader.update]?: boolean
[Loader.kRecord]?: Dict<Fork>
[Loader.kRecord]?: Dict<Fork<C>>
alias?: string
}
}
Expand All @@ -46,14 +47,14 @@ const group: Plugin.Object = {
},
}

export default class Loader extends ConfigLoader<App.Config> {
export default class Loader extends ConfigLoader<Context.Config> {
static readonly unique = Symbol.for('koishi.loader.unique')
static readonly update = Symbol.for('koishi.loader.update')
static readonly kRecord = Symbol.for('koishi.loader.record')
static readonly kWarning = Symbol.for('koishi.loader.warning')

app: App
config: App.Config
app: Context
config: Context.Config
entry: Context
cache: Dict<string> = {}
envfile: string
Expand Down Expand Up @@ -89,11 +90,11 @@ export default class Loader extends ConfigLoader<App.Config> {
// load original config file
const config = super.readConfig()

let resolved = new App.Config(config)
let resolved = new Context.Config(config)
if (this.writable) {
// schemastery may change original config
// so we need to validate config twice
resolved = new App.Config(this.interpolate(config))
resolved = new Context.Config(this.interpolate(config))
}

return resolved
Expand Down Expand Up @@ -123,7 +124,7 @@ export default class Loader extends ConfigLoader<App.Config> {
this.app.lifecycle.flush().then(() => this.check(name))
}

Registry.validate(plugin, config)
resolveConfig(plugin, config)
return parent.plugin(plugin, this.interpolate(config))
}

Expand Down Expand Up @@ -165,11 +166,11 @@ export default class Loader extends ConfigLoader<App.Config> {
}

createApp() {
const app = this.app = new App(this.config)
const app = this.app = new Context(this.config)
app.loader = this
app.baseDir = this.dirname
app.state[Loader.kRecord] = Object.create(null)
this.entry = this.reloadPlugin(app, 'group:entry', this.config.plugins).context
this.entry = this.reloadPlugin(app, 'group:entry', this.config.plugins).ctx

app.on('internal/update', (fork, value) => {
// prevent hot reload when config file is being written
Expand Down
8 changes: 4 additions & 4 deletions packages/cli/src/worker/watcher.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { App, coerce, Context, Dict, Logger, makeArray, Runtime, Schema } from 'koishi'
import { coerce, Context, Dict, Logger, makeArray, Runtime, Schema } from 'koishi'
import { FSWatcher, watch, WatchOptions } from 'chokidar'
import { relative, resolve } from 'path'
import { debounce } from 'throttle-debounce'
Expand Down Expand Up @@ -149,7 +149,7 @@ class Watcher {
} else if (!(key in neo)) {
this.ctx.loader.unloadPlugin(ctx, key)
} else if (key.startsWith('group:')) {
this.triggerGroupReload(key, neo[key] || {}, old[key] || {}, fork.context)
this.triggerGroupReload(key, neo[key] || {}, old[key] || {}, fork.ctx)
} else if (!deepEqual(old[key], neo[key])) {
this.ctx.loader.reloadPlugin(ctx, key, neo[key])
}
Expand Down Expand Up @@ -225,7 +225,7 @@ class Watcher {
for (const filename in require.cache) {
const module = require.cache[filename]
const plugin = ns.unwrapExports(module.exports)
const runtime = this.ctx.app.registry.get(plugin)
const runtime = this.ctx.registry.get(plugin)
if (!runtime || this.declined.has(filename)) continue
pending.set(filename, runtime)
if (!plugin['sideEffect']) this.declined.add(filename)
Expand Down Expand Up @@ -343,7 +343,7 @@ namespace Watcher {
]).description('要忽略的文件或目录。'),
}).description('热重载设置')

App.Config.list.push(Schema.object({
Context.Config.list.push(Schema.object({
watch: Config,
}))
}
Expand Down
2 changes: 1 addition & 1 deletion plugins/a11y/bind/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ export function apply(ctx: Context, config: Config = {}) {
const data = tokens[session.content]
if (!data) return next()
if (data[2] < 0) {
const sess = new Session(session.bot, session)
const sess = session.bot.session(session)
sess.platform = data[0]
sess.userId = data[1]
const user = await sess.observeUser([session.platform as never])
Expand Down
2 changes: 1 addition & 1 deletion plugins/a11y/callme/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Context, RuntimeError, Schema } from 'koishi'

declare module 'koishi' {
interface EventMap {
interface Events {
'common/callme'(name: string, session: Session): string | void
}
}
Expand Down
2 changes: 1 addition & 1 deletion plugins/a11y/schedule/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ export function apply(ctx: Context, { minInterval }: Config) {

data.forEach((schedule) => {
const { session, assignee } = schedule
const bot = ctx.bots.get(assignee)
const bot = ctx.bots[assignee]
if (bot) {
prepareSchedule(schedule, new Session(bot, session))
} else {
Expand Down
6 changes: 4 additions & 2 deletions plugins/a11y/schedule/tests/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@ import * as schedule from '@koishijs/plugin-schedule'
import memory from '@koishijs/plugin-database-memory'
import mock from '@koishijs/plugin-mock'
import * as jest from 'jest-mock'
import { expect } from 'chai'
import 'chai-shape'
import { expect, use } from 'chai'
import shape from 'chai-shape'

use(shape)

describe('@koishijs/plugin-switch', () => {
const app = new App()
Expand Down
3 changes: 1 addition & 2 deletions plugins/a11y/suggest/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { distance } from 'fastest-levenshtein'
import { Awaitable } from 'cosmokit'
import { Context, Next, Schema, Session } from 'koishi'
import { Awaitable, Context, Next, Schema, Session } from 'koishi'

declare module 'koishi' {
interface Context {
Expand Down
6 changes: 4 additions & 2 deletions plugins/common/echo/tests/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ import { App, Bot } from 'koishi'
import * as echo from '@koishijs/plugin-echo'
import mock from '@koishijs/plugin-mock'
import * as jest from 'jest-mock'
import { expect } from 'chai'
import 'chai-shape'
import { expect, use } from 'chai'
import shape from 'chai-shape'

use(shape)

const app = new App()

Expand Down
2 changes: 1 addition & 1 deletion plugins/common/feedback/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,6 @@ export function apply(ctx: Context, { operators = [], replyTimeout = Time.day }:
if (!parsed.content || !quote) return next()
const data = feedbacks[quote.messageId]
if (!data) return next()
await ctx.bots.get(data[0]).sendMessage(data[1], parsed.content, data[2])
await ctx.bots[data[0]].sendMessage(data[1], parsed.content, data[2])
})
}
2 changes: 1 addition & 1 deletion plugins/common/forward/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ export function apply(ctx: Context, { rules, interval }: Config) {
rule.guildId = channel.guildId
}

const bot = ctx.bots.get(`${platform}:${rule.selfId}`)
const bot = ctx.bots[`${platform}:${rule.selfId}`]
const chain = segment.parse(parsed.content)

// replace all mentions (koishijs/koishi#506)
Expand Down
2 changes: 1 addition & 1 deletion plugins/common/repeater/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ export function apply(ctx: Context, config: Config = {}) {
const { content, uid, userId } = session

// never respond to messages from self
if (ctx.bots.get(uid)) return
if (ctx.bots[uid]) return

const state = getState(session.cid)
const check = (handle: StateCallback) => {
Expand Down

0 comments on commit ef76432

Please sign in to comment.