koishi-core
Advanced tools
Comparing version 1.0.0-alpha.8 to 1.0.0-alpha.9
@@ -8,3 +8,2 @@ import { Server, ServerType } from './server'; | ||
port?: number; | ||
name?: string; | ||
token?: string; | ||
@@ -16,3 +15,5 @@ secret?: string; | ||
database?: DatabaseConfig; | ||
commandPrefix?: string; | ||
nickname?: string | string[]; | ||
maxMiddlewares?: number; | ||
commandPrefix?: string | string[]; | ||
quickOperationTimeout?: number; | ||
@@ -32,7 +33,8 @@ similarityCoefficient?: number; | ||
export declare class App extends Context { | ||
app: this; | ||
options: AppOptions; | ||
app: this; | ||
server: Server; | ||
atMeRE: RegExp; | ||
prefixRE: RegExp; | ||
userPrefixRE: RegExp; | ||
nicknameRE: RegExp; | ||
users: MajorContext; | ||
@@ -53,4 +55,5 @@ groups: MajorContext; | ||
get version(): import("./meta").VersionInfo; | ||
_registerSelfId(selfId?: number): void; | ||
_createContext(scope: string | ContextScope): Context; | ||
prepare(selfId?: number): void; | ||
destroy(): void; | ||
createContext(scope: string | ContextScope): Context; | ||
discuss(...ids: number[]): Context; | ||
@@ -57,0 +60,0 @@ group(...ids: number[]): Context; |
151
dist/app.js
@@ -5,9 +5,2 @@ "use strict"; | ||
}; | ||
var __importStar = (this && this.__importStar) || function (mod) { | ||
if (mod && mod.__esModule) return mod; | ||
var result = {}; | ||
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; | ||
result["default"] = mod; | ||
return result; | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
@@ -22,6 +15,6 @@ const debug_1 = __importDefault(require("debug")); | ||
const koishi_utils_1 = require("koishi-utils"); | ||
const errors = __importStar(require("./errors")); | ||
const messages_1 = require("./messages"); | ||
const showLog = debug_1.default('koishi'); | ||
const showReceiverLog = debug_1.default('koishi:receiver'); | ||
const selfIds = []; | ||
const selfIds = new Set(); | ||
exports.appMap = {}; | ||
@@ -60,7 +53,7 @@ exports.appList = []; | ||
const info = await app.sender.getLoginInfo(); | ||
app._registerSelfId(info.userId); | ||
app.prepare(info.userId); | ||
})); | ||
} | ||
await getSelfIdsPromise; | ||
return selfIds; | ||
return Array.from(selfIds); | ||
} | ||
@@ -70,9 +63,13 @@ exports.getSelfIds = getSelfIds; | ||
const appIdentifier = context_1.ContextScope.stringify(appScope); | ||
function createPrefixRegExp(...patterns) { | ||
return new RegExp(`^(${patterns.join('|')})`); | ||
const nicknameSuffix = '([,,]\\s*|\\s+)'; | ||
function createLeadingRE(patterns, prefix = '', suffix = '') { | ||
return patterns.length ? new RegExp(`^${prefix}(${patterns.map(escape_string_regexp_1.default).join('|')})${suffix}`) : /^/; | ||
} | ||
const defaultOptions = { | ||
maxMiddlewares: 64, | ||
similarityCoefficient: 0.4, | ||
}; | ||
class App extends context_1.Context { | ||
constructor(options = {}) { | ||
super(appIdentifier, appScope); | ||
this.options = options; | ||
this.app = this; | ||
@@ -89,29 +86,32 @@ this._commands = []; | ||
this._preprocess = async (meta, next) => { | ||
var _a; | ||
// strip prefix | ||
let message = meta.message.trim(); | ||
let prefix = ''; | ||
if (meta.messageType === 'group') { | ||
const capture = message.match(this.prefixRE); | ||
if (capture) { | ||
prefix = capture[0]; | ||
message = message.slice(prefix.length); | ||
} | ||
const fields = []; | ||
let capture; | ||
let atMe = false, nickname = false, prefix = null; | ||
let message = koishi_utils_1.simplify(meta.message.trim()); | ||
let parsedArgv; | ||
if (meta.messageType !== 'private' && (capture = message.match(this.atMeRE))) { | ||
atMe = true; | ||
nickname = true; | ||
message = message.slice(capture[0].length); | ||
} | ||
else { | ||
message = message.replace(this.userPrefixRE, ''); | ||
if ((_a = (capture = message.match(this.nicknameRE))) === null || _a === void 0 ? void 0 : _a[0].length) { | ||
nickname = true; | ||
message = message.slice(capture[0].length); | ||
} | ||
message = koishi_utils_1.simplify(message); | ||
const fields = []; | ||
let parsedArgv; | ||
const canBeCommand = meta.messageType === 'private' || prefix; | ||
const canBeShortcut = prefix !== '.'; | ||
// parse as command | ||
if (canBeCommand && (parsedArgv = this.parseCommandLine(message, meta))) { | ||
// eslint-disable-next-line no-cond-assign | ||
if (capture = message.match(this.prefixRE)) { | ||
prefix = capture[0]; | ||
message = message.slice(capture[0].length); | ||
} | ||
if ((prefix !== null || nickname || meta.messageType === 'private') && (parsedArgv = this.parseCommandLine(message, meta))) { | ||
// parse as command | ||
fields.push(...parsedArgv.command._userFields); | ||
} | ||
else if (canBeShortcut) { | ||
else if (!prefix) { | ||
// parse as shortcut | ||
for (const shortcut of this._shortcuts) { | ||
const { name, fuzzy, command, oneArg } = shortcut; | ||
if (shortcut.prefix && !canBeCommand) | ||
const { name, fuzzy, command, oneArg, prefix, options, args = [] } = shortcut; | ||
if (prefix && !nickname) | ||
continue; | ||
@@ -122,3 +122,3 @@ if (!fuzzy && message !== name) | ||
let _message = message.slice(name.length); | ||
if (fuzzy && !shortcut.prefix && _message.match(/^\S/)) | ||
if (fuzzy && !nickname && _message.match(/^\S/)) | ||
continue; | ||
@@ -128,3 +128,4 @@ if (oneArg) | ||
const result = command.parse(_message); | ||
Object.assign(result.options, shortcut.options); | ||
result.options = { ...options, ...result.options }; | ||
result.args.unshift(...args); | ||
fields.push(...command._userFields); | ||
@@ -141,4 +142,2 @@ parsedArgv = { meta, command, ...result }; | ||
fields.push('flag'); | ||
if (!fields.includes('ignoreEnd')) | ||
fields.push('ignoreEnd'); | ||
if (parsedArgv) { | ||
@@ -163,8 +162,8 @@ if (!fields.includes('usage')) | ||
const noResponse = meta.$group.flag & database_1.GroupFlag.noResponse || !isAssignee; | ||
const originalNext = next; | ||
next = (fallback) => noResponse || originalNext(fallback); | ||
if (noCommand && parsedArgv) | ||
return; | ||
if (noResponse && !prefix.includes(`[CQ:at,qq=${this.app.options.selfId}]`)) | ||
if (noResponse && !atMe) | ||
return; | ||
const originalNext = next; | ||
next = (fallback) => noResponse || originalNext(fallback); | ||
} | ||
@@ -174,8 +173,2 @@ // ignore some user calls | ||
return; | ||
if (user.ignoreEnd) { | ||
const time = Date.now() / 1000; | ||
if (user.ignoreEnd >= time) | ||
return; | ||
user.ignoreEnd = 0; | ||
} | ||
} | ||
@@ -187,3 +180,3 @@ // execute command | ||
const target = message.split(/\s/, 1)[0].toLowerCase(); | ||
if (!target || !canBeCommand) | ||
if (!target || !capture) | ||
return next(); | ||
@@ -218,3 +211,3 @@ return utils_1.showSuggestions({ | ||
if (!this._middlewareSet.has(counter)) { | ||
return this.receiver.emit('error', new Error(errors.ISOLATED_NEXT)); | ||
return this.receiver.emit('error', new Error(messages_1.errors.ISOLATED_NEXT)); | ||
} | ||
@@ -238,2 +231,3 @@ if (fallback) | ||
}; | ||
this.options = { ...defaultOptions, ...options }; | ||
exports.appList.push(this); | ||
@@ -244,18 +238,18 @@ if (options.database && Object.keys(options.database).length) { | ||
if (!options.type && typeof options.server === 'string') { | ||
options.type = options.server.split(':', 1)[0]; | ||
this.options.type = this.options.server.split(':', 1)[0]; | ||
} | ||
if (options.type) { | ||
if (this.options.type) { | ||
this.server = server_1.createServer(this); | ||
this.sender = new sender_1.Sender(this); | ||
} | ||
if (options.selfId) | ||
this._registerSelfId(); | ||
if (this.selfId) | ||
this.prepare(); | ||
this.receiver.on('message', this._applyMiddlewares); | ||
this.middleware(this._preprocess); | ||
this.users = this._createContext([[null, []], [[], null], [[], null]]); | ||
this.groups = this._createContext([[[], null], [null, []], [[], null]]); | ||
this.discusses = this._createContext([[[], null], [[], null], [null, []]]); | ||
this.users.except = (...ids) => this._createContext([[null, ids], [[], null], [[], null]]); | ||
this.groups.except = (...ids) => this._createContext([[[], null], [null, ids], [[], null]]); | ||
this.discusses.except = (...ids) => this._createContext([[[], null], [[], null], [null, ids]]); | ||
this.users = this.createContext([[null, []], [[], null], [[], null]]); | ||
this.groups = this.createContext([[[], null], [null, []], [[], null]]); | ||
this.discusses = this.createContext([[[], null], [[], null], [null, []]]); | ||
this.users.except = (...ids) => this.createContext([[null, ids], [[], null], [[], null]]); | ||
this.groups.except = (...ids) => this.createContext([[[], null], [null, ids], [[], null]]); | ||
this.discusses.except = (...ids) => this.createContext([[[], null], [[], null], [null, ids]]); | ||
} | ||
@@ -269,3 +263,3 @@ get selfId() { | ||
} | ||
_registerSelfId(selfId) { | ||
prepare(selfId) { | ||
var _a; | ||
@@ -280,16 +274,27 @@ if (selfId) { | ||
exports.appMap[this.selfId] = this; | ||
selfIds.push(this.selfId); | ||
if (this.options.type) | ||
selfIds.add(this.selfId); | ||
if (this.server) { | ||
this.server.appMap[this.selfId] = this; | ||
const patterns = []; | ||
if (this.app.options.name) { | ||
patterns.push(`@?${escape_string_regexp_1.default(this.app.options.name)}([,,]\\s*|\\s+)`); | ||
} | ||
if (this.app.options.commandPrefix) { | ||
patterns.push(escape_string_regexp_1.default(this.app.options.commandPrefix)); | ||
const { nickname, commandPrefix } = this.options; | ||
const nicknames = Array.isArray(nickname) ? nickname : nickname ? [nickname] : []; | ||
const prefixes = Array.isArray(commandPrefix) ? commandPrefix : [commandPrefix || '']; | ||
this.atMeRE = new RegExp(`^\\[CQ:at,qq=${this.selfId}\\]${nicknameSuffix}`); | ||
this.nicknameRE = createLeadingRE(nicknames, '@?', nicknameSuffix); | ||
this.prefixRE = createLeadingRE(prefixes); | ||
} | ||
destroy() { | ||
const index = exports.appList.indexOf(this); | ||
if (index >= 0) | ||
exports.appList.splice(index, 1); | ||
delete exports.appMap[this.selfId]; | ||
selfIds.delete(this.selfId); | ||
if (this.server) { | ||
const index = this.server.appList.indexOf(this); | ||
if (index >= 0) | ||
this.server.appList.splice(index, 1); | ||
delete this.server.appMap[this.selfId]; | ||
} | ||
this.prefixRE = createPrefixRegExp(...patterns, `\\[CQ:at,qq=${this.selfId}\\] *`); | ||
this.userPrefixRE = createPrefixRegExp(...patterns); | ||
} | ||
_createContext(scope) { | ||
createContext(scope) { | ||
if (typeof scope === 'string') | ||
@@ -310,9 +315,9 @@ scope = context_1.ContextScope.parse(scope); | ||
discuss(...ids) { | ||
return this._createContext([[[], null], [[], null], [ids, null]]); | ||
return this.createContext([[[], null], [[], null], [ids, null]]); | ||
} | ||
group(...ids) { | ||
return this._createContext([[[], null], [ids, null], [[], null]]); | ||
return this.createContext([[[], null], [ids, null], [[], null]]); | ||
} | ||
user(...ids) { | ||
return this._createContext([[ids, null], [[], null], [[], null]]); | ||
return this.createContext([[ids, null], [[], null], [[], null]]); | ||
} | ||
@@ -319,0 +324,0 @@ async start() { |
import { Context, NextFunction } from './context'; | ||
import { UserData, UserField } from './database'; | ||
import { MessageMeta } from './meta'; | ||
import { CommandOption, OptionConfig, ParsedLine } from './parser'; | ||
import { CommandOption, CommandArgument, OptionConfig, ParsedLine } from './parser'; | ||
export interface ParsedCommandLine extends ParsedLine { | ||
@@ -39,2 +39,3 @@ meta: MessageMeta; | ||
fuzzy?: boolean; | ||
args?: string[]; | ||
oneArg?: boolean; | ||
@@ -55,6 +56,6 @@ options?: Record<string, any>; | ||
_shortcuts: Record<string, ShortcutConfig>; | ||
_userFields: Set<"id" | "name" | "flag" | "ignoreEnd" | "authority" | "usage">; | ||
private _argsDef; | ||
private _optsDef; | ||
private _action?; | ||
_userFields: Set<"id" | "name" | "flag" | "authority" | "usage">; | ||
_argsDef: CommandArgument[]; | ||
_optsDef: Record<string, CommandOption>; | ||
_action?: (this: Command, config: ParsedCommandLine, ...args: string[]) => any; | ||
constructor(name: string, declaration: string, context: Context, config?: CommandConfig); | ||
@@ -61,0 +62,0 @@ get app(): import("./app").App; |
"use strict"; | ||
var __importStar = (this && this.__importStar) || function (mod) { | ||
if (mod && mod.__esModule) return mod; | ||
var result = {}; | ||
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; | ||
result["default"] = mod; | ||
return result; | ||
}; | ||
var __importDefault = (this && this.__importDefault) || function (mod) { | ||
@@ -13,6 +6,5 @@ return (mod && mod.__esModule) ? mod : { "default": mod }; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
const messages_1 = require("./messages"); | ||
const koishi_utils_1 = require("koishi-utils"); | ||
const util_1 = require("util"); | ||
const messages = __importStar(require("./messages")); | ||
const errors = __importStar(require("./errors")); | ||
const debug_1 = __importDefault(require("debug")); | ||
@@ -40,3 +32,3 @@ const parser_1 = require("./parser"); | ||
if (!name) | ||
throw new Error(errors.EXPECT_COMMAND_NAME); | ||
throw new Error(messages_1.errors.EXPECT_COMMAND_NAME); | ||
this._argsDef = parser_1.parseArguments(declaration); | ||
@@ -47,3 +39,3 @@ this.config = { ...defaultConfig, ...config }; | ||
if (!config.noHelpOption) { | ||
this.option('-h, --help', messages.SHOW_THIS_MESSAGE); | ||
this.option('-h, --help', messages_1.messages.SHOW_THIS_MESSAGE); | ||
} | ||
@@ -62,3 +54,3 @@ } | ||
else if (previous !== this) { | ||
throw new Error(errors.DUPLICATE_COMMAND); | ||
throw new Error(messages_1.errors.DUPLICATE_COMMAND); | ||
} | ||
@@ -112,3 +104,3 @@ } | ||
if (name in this._optsDef) { | ||
throw new Error(errors.DUPLICATE_OPTION); | ||
throw new Error(messages_1.errors.DUPLICATE_OPTION); | ||
} | ||
@@ -157,7 +149,7 @@ this._optsDef[name] = option; | ||
if ((_a = nextArg) === null || _a === void 0 ? void 0 : _a.required) { | ||
return meta.$send(messages.INSUFFICIENT_ARGUMENTS); | ||
return meta.$send(messages_1.messages.INSUFFICIENT_ARGUMENTS); | ||
} | ||
const finalArg = this._argsDef[this._argsDef.length - 1]; | ||
if (args.length > this._argsDef.length && !finalArg.noSegment && !finalArg.variadic) { | ||
return meta.$send(messages.REDUNANT_ARGUMENTS); | ||
return meta.$send(messages_1.messages.REDUNANT_ARGUMENTS); | ||
} | ||
@@ -167,11 +159,11 @@ } | ||
if (this.config.checkUnknown && unknown.length) { | ||
return meta.$send(util_1.format(messages.UNKNOWN_OPTIONS, unknown.join(', '))); | ||
return meta.$send(util_1.format(messages_1.messages.UNKNOWN_OPTIONS, unknown.join(', '))); | ||
} | ||
// check required options | ||
if (this.config.checkRequired) { | ||
const absent = this._options.filter((option) => { | ||
return option.required && !(option.camels[0] in options); | ||
const absent = this._options.find((option) => { | ||
return option.required && !(option.longest in options); | ||
}); | ||
if (absent.length) { | ||
return meta.$send(util_1.format(messages.REQUIRED_OPTIONS, absent.join(', '))); | ||
if (absent) { | ||
return meta.$send(util_1.format(messages_1.messages.REQUIRED_OPTIONS, absent.rawName)); | ||
} | ||
@@ -201,3 +193,3 @@ } | ||
if (this.config.authority > user.authority) { | ||
return meta.$send(messages.LOW_AUTHORITY); | ||
return meta.$send(messages_1.messages.LOW_AUTHORITY); | ||
} | ||
@@ -207,3 +199,3 @@ for (const option of this._options) { | ||
if (option.authority > user.authority) | ||
return meta.$send(messages.LOW_AUTHORITY); | ||
return meta.$send(messages_1.messages.LOW_AUTHORITY); | ||
if (option.notUsage) | ||
@@ -224,3 +216,3 @@ isUsage = false; | ||
if (this.config.showWarning) { | ||
await meta.$send(messages.TOO_FREQUENT); | ||
await meta.$send(messages_1.messages.TOO_FREQUENT); | ||
} | ||
@@ -232,4 +224,3 @@ return; | ||
if (usage.count >= maxUsage && isUsage) { | ||
await meta.$send(messages.USAGE_EXHAUSTED); | ||
return; | ||
return meta.$send(messages_1.messages.USAGE_EXHAUSTED); | ||
} | ||
@@ -236,0 +227,0 @@ else { |
/// <reference types="node" /> | ||
import { Command, CommandConfig, ParsedCommandLine } from './command'; | ||
import { MessageMeta, Meta } from './meta'; | ||
import { Command, CommandConfig, ParsedCommandLine } from './command'; | ||
import { EventEmitter } from 'events'; | ||
@@ -39,3 +39,3 @@ import { Sender } from './sender'; | ||
middleware(middleware: Middleware): this; | ||
premiddleware(middleware: Middleware): this; | ||
prependMiddleware(middleware: Middleware): this; | ||
removeMiddleware(middleware: Middleware): boolean; | ||
@@ -42,0 +42,0 @@ command(rawName: string, config?: CommandConfig): Command; |
"use strict"; | ||
var __importStar = (this && this.__importStar) || function (mod) { | ||
if (mod && mod.__esModule) return mod; | ||
var result = {}; | ||
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; | ||
result["default"] = mod; | ||
return result; | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
const koishi_utils_1 = require("koishi-utils"); | ||
const command_1 = require("./command"); | ||
const meta_1 = require("./meta"); | ||
const command_1 = require("./command"); | ||
const events_1 = require("events"); | ||
const messages = __importStar(require("./messages")); | ||
const errors = __importStar(require("./errors")); | ||
const messages_1 = require("./messages"); | ||
const util_1 = require("util"); | ||
var ContextScope; | ||
@@ -32,3 +25,3 @@ (function (ContextScope) { | ||
if (!capture) | ||
throw new Error(errors.INVALID_IDENTIFIER); | ||
throw new Error(messages_1.errors.INVALID_IDENTIFIER); | ||
const [_, sign, type, list] = capture; | ||
@@ -54,3 +47,3 @@ const idList = list.split(',').map(n => +n); | ||
inverse() { | ||
return this.app._createContext(this._scope.map(([include, exclude]) => { | ||
return this.app.createContext(this._scope.map(([include, exclude]) => { | ||
return include ? [null, include.slice()] : [exclude.slice(), []]; | ||
@@ -60,3 +53,3 @@ })); | ||
plus(ctx) { | ||
return this.app._createContext(this._scope.map(([include1, exclude1], index) => { | ||
return this.app.createContext(this._scope.map(([include1, exclude1], index) => { | ||
const [include2, exclude2] = ctx._scope[index]; | ||
@@ -69,3 +62,3 @@ return include1 | ||
minus(ctx) { | ||
return this.app._createContext(this._scope.map(([include1, exclude1], index) => { | ||
return this.app.createContext(this._scope.map(([include1, exclude1], index) => { | ||
const [include2, exclude2] = ctx._scope[index]; | ||
@@ -78,3 +71,3 @@ return include1 | ||
intersect(ctx) { | ||
return this.app._createContext(this._scope.map(([include1, exclude1], index) => { | ||
return this.app.createContext(this._scope.map(([include1, exclude1], index) => { | ||
const [include2, exclude2] = ctx._scope[index]; | ||
@@ -111,7 +104,19 @@ return include1 | ||
middleware(middleware) { | ||
this.app._middlewares.push([this, middleware]); | ||
const { maxMiddlewares } = this.app.options; | ||
if (this.app._middlewares.length >= maxMiddlewares) { | ||
this.app.receiver.emit('error', new Error(util_1.format(messages_1.errors.MAX_MIDDLEWARES, maxMiddlewares))); | ||
} | ||
else { | ||
this.app._middlewares.push([this, middleware]); | ||
} | ||
return this; | ||
} | ||
premiddleware(middleware) { | ||
this.app._middlewares.unshift([this, middleware]); | ||
prependMiddleware(middleware) { | ||
const { maxMiddlewares } = this.app.options; | ||
if (this.app._middlewares.length >= maxMiddlewares) { | ||
this.app.receiver.emit('error', new Error(util_1.format(messages_1.errors.MAX_MIDDLEWARES, maxMiddlewares))); | ||
} | ||
else { | ||
this.app._middlewares.unshift([this, middleware]); | ||
} | ||
return this; | ||
@@ -139,7 +144,7 @@ } | ||
if (command === parent) { | ||
throw new Error(errors.INVALID_SUBCOMMAND); | ||
throw new Error(messages_1.errors.INVALID_SUBCOMMAND); | ||
} | ||
if (command.parent) { | ||
if (command.parent !== parent) { | ||
throw new Error(errors.INVALID_SUBCOMMAND); | ||
throw new Error(messages_1.errors.INVALID_SUBCOMMAND); | ||
} | ||
@@ -152,3 +157,3 @@ } | ||
else { | ||
throw new Error(errors.INVALID_CONTEXT); | ||
throw new Error(messages_1.errors.INVALID_CONTEXT); | ||
} | ||
@@ -160,3 +165,3 @@ } | ||
if (context.identifier === noopIdentifier) { | ||
throw new Error(errors.INVALID_CONTEXT); | ||
throw new Error(messages_1.errors.INVALID_CONTEXT); | ||
} | ||
@@ -187,5 +192,6 @@ command = new command_1.Command(name, declaration, context); | ||
if (!command || !command.context.match(meta) || command.getConfig('disable', meta)) { | ||
return meta.$send(messages.COMMAND_NOT_FOUND); | ||
return meta.$send(messages_1.messages.COMMAND_NOT_FOUND); | ||
} | ||
return command.execute({ meta, command, args, options, rest, unknown: [] }); | ||
const unknown = Object.keys(options).filter(key => !command._optsDef[key]); | ||
return command.execute({ meta, command, args, options, rest, unknown }); | ||
} | ||
@@ -192,0 +198,0 @@ end() { |
@@ -15,3 +15,2 @@ import { Observed } from 'koishi-utils'; | ||
flag: number; | ||
ignoreEnd: number; | ||
authority: number; | ||
@@ -18,0 +17,0 @@ usage: Record<string, Usage>; |
@@ -19,3 +19,2 @@ "use strict"; | ||
flag: 0, | ||
ignoreEnd: 0, | ||
name: String(id), | ||
@@ -22,0 +21,0 @@ usage: {}, |
@@ -6,4 +6,5 @@ export * from './app'; | ||
export * from './meta'; | ||
export * from './messages'; | ||
export * from './sender'; | ||
export * from './server'; | ||
export * from './utils'; |
@@ -11,4 +11,5 @@ "use strict"; | ||
__export(require("./meta")); | ||
__export(require("./messages")); | ||
__export(require("./sender")); | ||
__export(require("./server")); | ||
__export(require("./utils")); |
@@ -1,9 +0,28 @@ | ||
export declare const COMMAND_NOT_FOUND = "\u6307\u4EE4\u672A\u627E\u5230\u3002"; | ||
export declare const LOW_AUTHORITY = "\u6743\u9650\u4E0D\u8DB3\u3002"; | ||
export declare const TOO_FREQUENT = "\u8C03\u7528\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5\u3002"; | ||
export declare const INSUFFICIENT_ARGUMENTS = "\u7F3A\u5C11\u53C2\u6570\uFF0C\u8BF7\u68C0\u67E5\u6307\u4EE4\u8BED\u6CD5\u3002"; | ||
export declare const REDUNANT_ARGUMENTS = "\u5B58\u5728\u591A\u4F59\u53C2\u6570\uFF0C\u8BF7\u68C0\u67E5\u6307\u4EE4\u8BED\u6CD5\u3002"; | ||
export declare const REQUIRED_OPTIONS = "\u7F3A\u5C11\u5FC5\u9700\u5C5E\u6027 %s\uFF0C\u8BF7\u68C0\u67E5\u6307\u4EE4\u8BED\u6CD5\u3002"; | ||
export declare const SHOW_THIS_MESSAGE = "\u663E\u793A\u672C\u4FE1\u606F"; | ||
export declare const UNKNOWN_OPTIONS = "\u5B58\u5728\u672A\u77E5\u5C5E\u6027 %s\uFF0C\u8BF7\u68C0\u67E5\u6307\u4EE4\u8BED\u6CD5\u3002"; | ||
export declare const USAGE_EXHAUSTED = "\u8C03\u7528\u6B21\u6570\u5DF2\u8FBE\u4E0A\u9650\u3002"; | ||
export declare const messages: { | ||
readonly COMMAND_NOT_FOUND: "指令未找到。"; | ||
readonly LOW_AUTHORITY: "权限不足。"; | ||
readonly TOO_FREQUENT: "调用过于频繁,请稍后再试。"; | ||
readonly INSUFFICIENT_ARGUMENTS: "缺少参数,请检查指令语法。"; | ||
readonly REDUNANT_ARGUMENTS: "存在多余参数,请检查指令语法。"; | ||
readonly REQUIRED_OPTIONS: "缺少必需属性 %s,请检查指令语法。"; | ||
readonly SHOW_THIS_MESSAGE: "显示本信息"; | ||
readonly UNKNOWN_OPTIONS: "存在未知属性 %s,请检查指令语法。"; | ||
readonly USAGE_EXHAUSTED: "调用次数已达上限。"; | ||
readonly COMMAND_SUGGESTION_PREFIX: "没有此命令。"; | ||
readonly COMMAND_SUGGESTION_SUFFIX: "发送空行以调用推测的指令。"; | ||
readonly SUGGESTION_TEXT: "你要找的是不是%s?"; | ||
}; | ||
export declare const errors: { | ||
readonly DUPLICATE_COMMAND: "duplicate command names"; | ||
readonly DUPLICATE_OPTION: "duplicate option names"; | ||
readonly EXPECT_COMMAND_NAME: "expect a command name"; | ||
readonly INVALID_CONTEXT: "invalid context path"; | ||
readonly INVALID_IDENTIFIER: "invalid context identifier"; | ||
readonly INVALID_SUBCOMMAND: "invalid subcommand"; | ||
readonly ISOLATED_NEXT: "isolated next function detected"; | ||
readonly UNSUPPORTED_SERVER_TYPE: "unsupported server type, expect \"http\" or \"ws\""; | ||
readonly MISSING_CONFIGURATION: "missing configuration \"%s\""; | ||
readonly MAX_MIDDLEWARES: "max middleware count (%d) exceeded, which may be caused by a memory leak"; | ||
readonly UNSUPPORTED_CQHTTP_VERSION: "your cqhttp version is not compatible with koishi, please upgrade your cqhttp to 3.0 or above"; | ||
readonly MULTIPLE_ANONYMOUS_BOTS: "your cqhttp version does not support multiple anonymous bots, please upgrade your cqhttp to 3.4 or above"; | ||
}; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.COMMAND_NOT_FOUND = '指令未找到。'; | ||
exports.LOW_AUTHORITY = '权限不足。'; | ||
exports.TOO_FREQUENT = '调用过于频繁,请稍后再试。'; | ||
exports.INSUFFICIENT_ARGUMENTS = '缺少参数,请检查指令语法。'; | ||
exports.REDUNANT_ARGUMENTS = '存在多余参数,请检查指令语法。'; | ||
exports.REQUIRED_OPTIONS = '缺少必需属性 %s,请检查指令语法。'; | ||
exports.SHOW_THIS_MESSAGE = '显示本信息'; | ||
exports.UNKNOWN_OPTIONS = '存在未知属性 %s,请检查指令语法。'; | ||
exports.USAGE_EXHAUSTED = '调用次数已达上限。'; | ||
exports.messages = { | ||
COMMAND_NOT_FOUND: '指令未找到。', | ||
LOW_AUTHORITY: '权限不足。', | ||
TOO_FREQUENT: '调用过于频繁,请稍后再试。', | ||
INSUFFICIENT_ARGUMENTS: '缺少参数,请检查指令语法。', | ||
REDUNANT_ARGUMENTS: '存在多余参数,请检查指令语法。', | ||
REQUIRED_OPTIONS: '缺少必需属性 %s,请检查指令语法。', | ||
SHOW_THIS_MESSAGE: '显示本信息', | ||
UNKNOWN_OPTIONS: '存在未知属性 %s,请检查指令语法。', | ||
USAGE_EXHAUSTED: '调用次数已达上限。', | ||
COMMAND_SUGGESTION_PREFIX: '没有此命令。', | ||
COMMAND_SUGGESTION_SUFFIX: '发送空行以调用推测的指令。', | ||
SUGGESTION_TEXT: '你要找的是不是%s?', | ||
}; | ||
exports.errors = { | ||
DUPLICATE_COMMAND: 'duplicate command names', | ||
DUPLICATE_OPTION: 'duplicate option names', | ||
EXPECT_COMMAND_NAME: 'expect a command name', | ||
INVALID_CONTEXT: 'invalid context path', | ||
INVALID_IDENTIFIER: 'invalid context identifier', | ||
INVALID_SUBCOMMAND: 'invalid subcommand', | ||
ISOLATED_NEXT: 'isolated next function detected', | ||
UNSUPPORTED_SERVER_TYPE: 'unsupported server type, expect "http" or "ws"', | ||
MISSING_CONFIGURATION: 'missing configuration "%s"', | ||
MAX_MIDDLEWARES: 'max middleware count (%d) exceeded, which may be caused by a memory leak', | ||
UNSUPPORTED_CQHTTP_VERSION: 'your cqhttp version is not compatible with koishi, please upgrade your cqhttp to 3.0 or above', | ||
MULTIPLE_ANONYMOUS_BOTS: 'your cqhttp version does not support multiple anonymous bots, please upgrade your cqhttp to 3.4 or above', | ||
}; |
@@ -45,15 +45,15 @@ "use strict"; | ||
const names = removeBrackets(rawName).split(',').map((name) => { | ||
name = name.trim(); | ||
if (name.length > longest.length) | ||
longest = name; | ||
name = name.replace(/^-{1,2}/, ''); | ||
name = name.trim().replace(/^-{1,2}/, ''); | ||
let camel; | ||
if (name.startsWith('no-') && !config.noNegated && !optsDef[name.slice(3)]) { | ||
name = name.slice(3); | ||
const camel = koishi_utils_1.camelCase(name); | ||
camel = koishi_utils_1.camelCase(name); | ||
negated.push(camel); | ||
camels.push(camel); | ||
} | ||
else { | ||
camels.push(koishi_utils_1.camelCase(name)); | ||
camel = koishi_utils_1.camelCase(name); | ||
} | ||
camels.push(camel); | ||
if (camel.length > longest.length) | ||
longest = camel; | ||
return name; | ||
@@ -60,0 +60,0 @@ }); |
@@ -402,8 +402,8 @@ "use strict"; | ||
const data = await this.get('get_version_info'); | ||
const match = /^(\d+)\.(\d+)\.(\d+)/.exec(data.pluginVersion); | ||
const match = /^(\d+)(?:\.(\d+)(?:\.(\d+)?))?/.exec(data.pluginVersion); | ||
if (match) { | ||
const [, major, minor, patch] = match; | ||
data.pluginMajorVersion = +major; | ||
data.pluginMinorVersion = +minor; | ||
data.pluginPatchVersion = +patch; | ||
data.pluginMinorVersion = +minor || 0; | ||
data.pluginPatchVersion = +patch || 0; | ||
} | ||
@@ -416,3 +416,3 @@ return data; | ||
} | ||
async setRestartPlugin(delay = 0) { | ||
async setRestartPlugin(delay) { | ||
this._assertVersion('sender.setRestartPlugin()', 3, 2); | ||
@@ -419,0 +419,0 @@ await this.get('set_restart_plugin', { delay }); |
@@ -13,3 +13,3 @@ /// <reference types="node" /> | ||
protected abstract _listen(): Promise<void>; | ||
abstract close(): void; | ||
protected abstract _close(): void; | ||
constructor(app: App); | ||
@@ -21,2 +21,3 @@ protected prepareMeta(data: any): Meta<import("./meta").PostType>; | ||
listen(): Promise<void>; | ||
close(): void; | ||
} | ||
@@ -27,3 +28,3 @@ export declare class HttpServer extends Server { | ||
_listen(): Promise<void>; | ||
close(): void; | ||
_close(): void; | ||
} | ||
@@ -36,5 +37,5 @@ export declare class WsClient extends Server { | ||
_listen(): Promise<void>; | ||
close(): void; | ||
_close(): void; | ||
} | ||
export declare type ServerType = 'http' | 'ws'; | ||
export declare function createServer(app: App): Server; |
@@ -16,5 +16,6 @@ "use strict"; | ||
const http = __importStar(require("http")); | ||
const errors = __importStar(require("./errors")); | ||
const messages_1 = require("./messages"); | ||
const crypto_1 = require("crypto"); | ||
const koishi_utils_1 = require("koishi-utils"); | ||
const util_1 = require("util"); | ||
const showServerLog = debug_1.default('koishi:server'); | ||
@@ -40,3 +41,3 @@ // @ts-ignore: @types/debug does not include the property | ||
return; | ||
app._registerSelfId(meta.selfId); | ||
app.prepare(meta.selfId); | ||
} | ||
@@ -76,3 +77,3 @@ return meta; | ||
} | ||
else if (meta.postType === 'request') { | ||
else if (meta.postType === 'request' && meta.message) { | ||
meta.comment = meta.message; | ||
@@ -182,3 +183,3 @@ delete meta.message; | ||
if (this.versionLessThan(3)) { | ||
throw new Error(errors.UNSUPPORTED_CQHTTP_VERSION); | ||
throw new Error(messages_1.errors.UNSUPPORTED_CQHTTP_VERSION); | ||
} | ||
@@ -188,7 +189,11 @@ else if (this.versionLessThan(3, 4)) { | ||
if (apps.length > 1) | ||
throw new Error(errors.MULTIPLE_ANONYMOUS_BOTS); | ||
throw new Error(messages_1.errors.MULTIPLE_ANONYMOUS_BOTS); | ||
const info = await apps[0].sender.getLoginInfo(); | ||
apps[0]._registerSelfId(info.userId); | ||
apps[0].prepare(info.userId); | ||
} | ||
} | ||
close() { | ||
this.isListening = false; | ||
this._close(); | ||
} | ||
} | ||
@@ -264,3 +269,3 @@ exports.Server = Server; | ||
} | ||
close() { | ||
_close() { | ||
if (this.server) | ||
@@ -336,3 +341,3 @@ this.server.close(); | ||
} | ||
close() { | ||
_close() { | ||
if (this.socket) | ||
@@ -350,7 +355,7 @@ this.socket.close(); | ||
if (typeof app.options.type !== 'string') { | ||
throw new Error(errors.UNSUPPORTED_SERVER_TYPE); | ||
throw new Error(messages_1.errors.UNSUPPORTED_SERVER_TYPE); | ||
} | ||
app.options.type = app.options.type.toLowerCase(); | ||
if (!serverTypes[app.options.type]) { | ||
throw new Error(errors.UNSUPPORTED_SERVER_TYPE); | ||
throw new Error(messages_1.errors.UNSUPPORTED_SERVER_TYPE); | ||
} | ||
@@ -360,3 +365,3 @@ const [key, serverMap, Server] = serverTypes[app.options.type]; | ||
if (!value) { | ||
throw new Error(`missing configuration "${key}"`); | ||
throw new Error(util_1.format(messages_1.errors.MISSING_CONFIGURATION, key)); | ||
} | ||
@@ -363,0 +368,0 @@ if (value in serverMap) { |
@@ -7,2 +7,4 @@ "use strict"; | ||
const koishi_utils_1 = require("koishi-utils"); | ||
const messages_1 = require("./messages"); | ||
const util_1 = require("util"); | ||
const leven_1 = __importDefault(require("leven")); | ||
@@ -29,4 +31,3 @@ function getSenderName(meta) { | ||
exports.getTargetId = getTargetId; | ||
const SIMILARITY_COEFFICIENT = 0.4; | ||
function findSimilar(target, coefficient = SIMILARITY_COEFFICIENT) { | ||
function findSimilar(target, coefficient) { | ||
return (name) => name.length > 2 && leven_1.default(name, target) <= name.length * coefficient; | ||
@@ -40,3 +41,3 @@ } | ||
return next(async () => { | ||
let message = `${prefix}你要找的是不是${suggestions.map(name => `“${name}”`).join('或')}?`; | ||
let message = prefix + util_1.format(messages_1.messages.SUGGESTION_TEXT, suggestions.map(name => `“${name}”`).join('或')); | ||
if (suggestions.length === 1) { | ||
@@ -68,3 +69,3 @@ const [suggestion] = suggestions; | ||
}; | ||
command.context.premiddleware(middleware); | ||
command.context.prependMiddleware(middleware); | ||
message += suffix; | ||
@@ -71,0 +72,0 @@ } |
{ | ||
"name": "koishi-core", | ||
"description": "Core features for Koishi", | ||
"version": "1.0.0-alpha.8", | ||
"version": "1.0.0-alpha.9", | ||
"main": "dist/index.js", | ||
@@ -37,3 +37,4 @@ "typings": "dist/index.d.ts", | ||
"@types/ws": "^6.0.4", | ||
"koishi-test-utils": "^1.0.0-alpha.7" | ||
"koishi-database-level": "^1.0.0-alpha.9", | ||
"koishi-test-utils": "^1.0.0-alpha.8" | ||
}, | ||
@@ -44,3 +45,3 @@ "dependencies": { | ||
"escape-string-regexp": "^2.0.0", | ||
"koishi-utils": "^1.0.0-alpha.3", | ||
"koishi-utils": "^1.0.0-alpha.4", | ||
"leven": "^3.1.0", | ||
@@ -47,0 +48,0 @@ "ws": "^7.2.0" |
111557
2780
4
24
Updatedkoishi-utils@^1.0.0-alpha.4