New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@koishijs/core

Package Overview
Dependencies
Maintainers
1
Versions
167
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@koishijs/core - npm Package Compare versions

Comparing version 4.8.2 to 4.8.3

4

lib/browser.js

@@ -1,2 +0,2 @@

var me=Object.defineProperty;var Ke=(m,e,t)=>e in m?me(m,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):m[e]=t;var h=(m,e)=>me(m,"name",{value:e,configurable:!0});var q=(m,e)=>()=>(e||m((e={exports:{}}).exports,e),e.exports);var U=(m,e,t)=>(Ke(m,typeof e!="symbol"?e+"":e,t),t);var Te=q((Tn,et)=>{et.exports={general:{name:"中文",paren:"({0})",quote:"“{0}”",comma:",",and:"和",or:"或",day:"天",hour:"小时",minute:"分钟",second:"秒"},internal:{"low-authority":"权限不足。","insufficient-arguments":"缺少参数,输入帮助以查看用法。","redunant-arguments":"存在多余参数,输入帮助以查看用法。","invalid-argument":"参数 {0} 输入无效,{1}","unknown-option":"存在未知选项 {0},输入帮助以查看用法。","invalid-option":"选项 {0} 输入无效,{1}","check-syntax":"输入帮助以查看用法。","invalid-number":"请提供一个数字。","invalid-integer":"请提供一个整数。","invalid-posint":"请提供一个正整数。","invalid-natural":"请提供一个非负整数。","invalid-date":"请输入合法的时间。","invalid-user":"请指定正确的用户。","invalid-channel":"请指定正确的频道。"}}});var Ae=q((An,tt)=>{tt.exports={general:{name:"English",paren:" ({0}) ",quote:'"{0}"',comma:", ",and:"and",or:"or",day:"day",hour:"hour",minute:"minute",second:"second"},internal:{"low-authority":"Low authority.","insufficient-arguments":"Insufficient arguments, type help to see usage.","redunant-arguments":"Redunant arguments, type help to see usage.","invalid-argument":"Invalid argument {0}, {1}","unknown-option":"Unknown option {0}, type help to see usage.","invalid-option":"Invalid option {0}, {1}","check-syntax":"Type help to see usage.","invalid-number":"Expect a number.","invalid-integer":"Expect an integer.","invalid-posint":"Expect a positive integer.","invalid-natural":"Expect a non-negative integer.","invalid-date":"Expect a valid date.","invalid-user":"Expect a valid user.","invalid-channel":"Expect a valid channel."}}});var ke=q((kn,nt)=>{nt.exports={general:{name:"日本語",paren:"({0})",quote:"「{0}」",comma:"、",and:"と",or:"や",day:"日",hour:"時間",minute:"分",second:"秒"},internal:{"low-authority":"実行できる権限が付与されていません","insufficient-arguments":"パラメータが不足しています、「help」を送信して使い方を確認してください。","redunant-arguments":"パラメータ数が多すぎます、「help」を送信して使い方を確認してください。","invalid-argument":"無効なパラメータ「{0}」、{1}","unknown-option":"未知なオプション「{0}」、「help」を送信して使い方を確認してください。","invalid-option":"無効なオプション「{0}」、{1}","check-syntax":"「help」を送信して使い方を検索してください。","invalid-number":"数字を指定してください。","invalid-integer":"整数を指定してください。","invalid-posint":"正の整数を指定してください。","invalid-natural":"自然数を指定してください。","invalid-date":"日付を指定してください。","invalid-user":"ユーザー名を指定してください。","invalid-channel":"チャンネル名を指定してください。"}}});var Ee=q((En,rt)=>{rt.exports={general:{name:"francais",paren:" ({0}) ",quote:'"{0}"',comma:", ",and:"et",or:"ou",day:"jour",hour:"heure",minute:"minute",second:"seconde"},internal:{"low-authority":"Droits insuffisants.","insufficient-arguments":`Arguments insuffisants, tapez "help" pour afficher l'aide`,"redunant-arguments":`Arguments redondants, tapez "help" pour afficher l'aide`,"invalid-argument":"Arguments {0} invalides, {1}","unknown-option":`Option {0} inconnue, tapez "help" pour afficher l'aide`,"invalid-option":"Option {0} invalide, {1}","check-syntax":`Tapez "help" pour afficher l'aide`,"invalid-number":"Entrez un nombre.","invalid-integer":"Entrez un entier.","invalid-posint":"Entrez un entier positif.","invalid-natural":"Entrez un entier non négatif.","invalid-date":"Entrez une date valide.","invalid-user":"Entrez un nom d'utilisateur valide.","invalid-channel":"Entrez un nom de canal valide."}}});var $e=q(($n,it)=>{it.exports={general:{name:"中文",paren:"({0})",quote:"「{0}」",comma:",",and:"和",or:"或",day:"天",hour:"小時",minute:"分鐘",second:"秒"},internal:{"low-authority":"權限不足。","insufficient-arguments":"參數個數不足,輸入「help」檢視用法。","redunant-arguments":"參數個數冗餘,輸入「help」檢視用法。","invalid-argument":"參數 {0} 無效,{1}","unknown-option":"存在未知選項 {0},輸入「help」檢視用法。","invalid-option":"選項 {0} 無效,{1}","check-syntax":"輸入「help」檢視用法。","invalid-number":"請輸入有效數字。","invalid-integer":"請輸入有效整數。","invalid-posint":"請輸入有效正整數。","invalid-natural":"請輸入有效非負整數。","invalid-date":"請輸入有效時間。","invalid-user":"請指定有效用戶。","invalid-channel":"請指定有效頻道。"}}});var Fe=q((Pn,at)=>{at.exports={name:"@koishijs/core",description:"Core Features for Koishi",version:"4.8.2",main:"lib/node.js",module:"lib/browser.js",typings:"lib/index.d.ts",files:["lib"],author:"Shigma <shigma10826@gmail.com>",license:"MIT",repository:{type:"git",url:"git+https://github.com/koishijs/koishi.git",directory:"packages/core"},bugs:{url:"https://github.com/koishijs/koishi/issues"},homepage:"https://koishi.js.org",keywords:["bot","chatbot","koishi"],devDependencies:{chai:"^4.3.6","chai-as-promised":"^7.1.1","chai-shape":"^1.0.0"},dependencies:{"@koishijs/utils":"^6.0.0","@satorijs/core":"^1.0.4",cordis:"^2.0.6","fastest-levenshtein":"^1.0.12",minato:"^1.2.3"}}});export*from"@koishijs/utils";export*from"minato";import{defineProperty as Ue,Logger as Ie,remove as Re}from"@koishijs/utils";import{defineProperty as J,Schema as w,Time as Z}from"@koishijs/utils";import*as he from"@satorijs/core";import*as fe from"cordis";import{Disposable as ft}from"cordis";var pt=fe.Service,y=class extends he.Context{constructor(e){super(e)}get app(){return this.root}};h(y,"Context");(e=>(e.Config=w.intersect([]),J(e.Config,"Basic",w.object({locale:w.string().default("zh").description("默认使用的语言。"),prefix:w.union([w.array(String),w.transform(String,t=>[t])]).default([""]).description("指令前缀字符,可以是字符串或字符串数组。将用于指令前缀的匹配。"),nickname:w.union([w.array(String),w.transform(String,t=>[t])]).description("机器人的昵称,可以是字符串或字符串数组。将用于指令前缀的匹配。"),autoAssign:w.union([Boolean,Function]).default(!0).description("当获取不到频道数据时,是否使用接受者作为代理者。"),autoAuthorize:w.union([w.natural(),Function]).default(1).description("当获取不到用户数据时默认使用的权限等级。")}).description("基础设置")),J(e.Config,"Message",w.object({delay:w.object({character:w.natural().role("ms").default(0).description("调用 `session.sendQueued()` 时消息间发送的最小延迟,按前一条消息的字数计算。"),message:w.natural().role("ms").default(.1*Z.second).description("调用 `session.sendQueued()` 时消息间发送的最小延迟,按固定值计算。"),cancel:w.natural().role("ms").default(0).description("调用 `session.cancelQueued()` 时默认的延迟。"),broadcast:w.natural().role("ms").default(.5*Z.second).description("调用 `bot.broadcast()` 时默认的延迟。"),prompt:w.natural().role("ms").default(Z.minute).description("调用 `session.prompt()` 时默认的等待时间。")})}).description("消息设置")),J(e.Config,"Advanced",w.object({prettyErrors:w.boolean().default(!0).description("启用报错优化模式。在此模式下 Koishi 会对程序抛出的异常进行整理,过滤掉框架内部的调用记录,输出更易读的提示信息。"),maxListeners:w.natural().default(64).description("每种监听器的最大数量。如果超过这个数量,Koishi 会认定为发生了内存泄漏,将产生一个警告。")}).description("高级设置")),e.Config.list.push(e.Config.Basic,e.Config.Message,e.Config.Advanced)))(y||={});function ut(m){return m}h(ut,"defineConfig");var z=class{constructor(e){this.app=e;Ue(this,y.current,e),e.on("internal/warning",(t,...n)=>{this.logger("app").warn(t,...n)})}get caller(){return this[y.current]}logger(e){return new Ie(e)}async waterfall(...e){let t=typeof e[0]=="object"?e.shift():null,n=e.shift();for(let r of this.app.lifecycle.getHooks(n,t)){let i=await r.apply(t,e);e[0]=i}return e[0]}chain(...e){let t=typeof e[0]=="object"?e.shift():null,n=e.shift();for(let r of this.app.lifecycle.getHooks(n,t)){let i=r.apply(t,e);e[0]=i}return e[0]}before(e,t,n=!1){let r=e.split("/");return r[r.length-1]="before-"+r[r.length-1],this.caller.on(r.join("/"),t,!n)}createTimerDispose(e){let t=h(()=>{if(clearTimeout(e),!!this.caller.state)return Re(this.caller.state.disposables,t)},"dispose");return this.caller.state.disposables.push(t),t}setTimeout(e,t,...n){let r=this.createTimerDispose(setTimeout(()=>{r(),e()},t,...n));return r}setInterval(e,t,...n){return this.createTimerDispose(setInterval(e,t,...n))}};h(z,"SelectorService"),U(z,"methods",["chain","waterfall","before","logger","setTimeout","setInterval"]);y.service("selector",z);import{makeArray as Je,sleep as Ze}from"@koishijs/utils";import{defineProperty as N,isNullable as Ve,Logger as Xe,makeArray as Ye,observe as ce}from"@koishijs/utils";import*as X from"@satorijs/core";import{defineProperty as Qe}from"@koishijs/utils";import{coerce as Be,Logger as ze,remove as j,Schema as Q}from"@koishijs/utils";import{camelCase as ge,escapeRegExp as xe,paramCase as ye,Time as Me}from"@koishijs/utils";import{segment as ee}from"@satorijs/core";var te=`"'“‘`,ne=`"'”’`,R;(E=>{let m={};function e(o,s,c){m[o]={terminator:s,parse:c}}E.interpolate=e,h(e,"interpolate"),e("$(",")");class t{bracs;constructor(){this.bracs=Object.create(m)}interpolate(s,c,u){this.bracs[s]={terminator:c,parse:u}}parseToken(s,c="$"){let u={inters:[]},f=te.indexOf(s[0]),C=ne[f],A="";C&&(s=s.slice(1),c=`${C}(?=${c})|$`),c+=`|${Object.keys({...this.bracs,...m}).map(xe).join("|")}`;let x=new RegExp(c);for(;;){let b=x.exec(s);if(A+=s.slice(0,b.index),b[0]in this.bracs){s=s.slice(b.index+b[0].length).trimStart();let{parse:S,terminator:P}=this.bracs[b[0]],$=S?.(s)||this.parse(s,P);s=$.rest,u.inters.push({...$,pos:A.length,initiator:b[0]})}else{let S=b[0]===C,P=s.slice(b.index+ +S);return u.rest=P.trimStart(),u.quoted=S,u.terminator=b[0],S?u.terminator+=P.slice(0,-u.rest.length):C&&(A=te[f]+A,u.inters.forEach($=>$.pos+=1)),u.content=A,C==="'"&&E.revert(u),u}}}parse(s,c=""){let u=[],f=s,C="",A=`\\s+|[${xe(c)}]|$`;for(;f&&!(c&&f.startsWith(c));){let x=this.parseToken(f,A);u.push(x),f=x.rest,C=x.terminator,delete x.rest}return f.startsWith(c)&&(f=f.slice(1)),s=s.slice(0,-(f+C).length),{tokens:u,rest:f,source:s}}stringify(s){let c=s.tokens.reduce((u,f)=>(f.quoted&&(u+=te[ne.indexOf(f.terminator[0])]||""),u+f.content+f.terminator),"");return s.rest&&!ne.includes(c[c.length-1])||s.initiator?c.slice(0,-1):c}}h(t,"Tokenizer"),E.Tokenizer=t;let n=new t;function r(o,s=""){return n.parse(o,s)}E.parse=r,h(r,"parse");function i(o){return n.stringify(o)}E.stringify=i,h(i,"stringify");function l(o){for(;o.inters.length;){let{pos:s,source:c,initiator:u}=o.inters.pop();o.content=o.content.slice(0,s)+u+c+m[u].terminator+o.content.slice(s)}}E.revert=l,h(l,"revert");function d(o){return typeof o=="string"?p[o]||{}:{}}h(d,"resolveConfig");function a(o){return typeof o=="function"?o:o instanceof RegExp?s=>{if(o.test(s))return s;throw new Error}:Array.isArray(o)?s=>{if(o.includes(s))return s;throw new Error}:p[o]?.transform}h(a,"resolveType");let p={};function g(o,s,c){p[o]={...c,transform:s}}E.createDomain=g,h(g,"createDomain"),g("rawtext",o=>o),g("string",o=>o),g("text",o=>o,{greedy:!0}),g("rawtext",o=>ee.unescape(o),{greedy:!0}),g("boolean",()=>!0),g("number",(o,s)=>{let c=+o;if(Number.isFinite(c))return c;throw new Error("internal.invalid-number")}),g("integer",(o,s)=>{let c=+o;if(c*0===0&&Math.floor(c)===c)return c;throw new Error("internal.invalid-integer")}),g("posint",(o,s)=>{let c=+o;if(c*0===0&&Math.floor(c)===c&&c>0)return c;throw new Error("internal.invalid-posint")}),g("natural",(o,s)=>{let c=+o;if(c*0===0&&Math.floor(c)===c&&c>=0)return c;throw new Error("internal.invalid-natural")}),g("date",(o,s)=>{let c=Me.parseDate(o);if(+c)return c;throw new Error("internal.invalid-date")}),g("user",(o,s)=>{if(o.startsWith("@"))return o=o.slice(1),o.includes(":")?o:`${s.platform}:${o}`;let c=ee.from(o);if(c&&c.type==="at")return`${s.platform}:${c.data.id}`;throw new Error("internal.invalid-user")}),g("channel",(o,s)=>{if(o.startsWith("#"))return o=o.slice(1),o.includes(":")?o:`${s.platform}:${o}`;let c=ee.from(o);if(c&&c.type==="sharp")return`${s.platform}:${c.data.id}`;throw new Error("internal.invalid-channel")});let _=/<[^>]+>|\[[^\]]+\]/g;function T(o){let s,c=[];for(;s=_.exec(o);){let u=s[0].slice(1,-1),f=!1;u.startsWith("...")&&(u=u.slice(3),f=!0);let[C,A]=u.split(":"),x=A?A.trim():void 0;c.push({name:C,variadic:f,type:x,required:s[0][0]==="<"})}return c.stripped=o.replace(/:[\w-]+[>\]]/g,u=>u.slice(-1)).trimEnd(),c}h(T,"parseDecl");function I(o,s,c,u,f={}){let{name:C,type:A,fallback:x}=f,b=o===""&&!s;if(b&&x!==void 0)return x;let S=a(A);if(S)try{return S(o,u.session)}catch($){if(!u.session)u.error=`internal.invalid-${c}`;else{let O=u.session.text($.message||"internal.check-syntax");u.error=u.session.text(`internal.invalid-${c}`,[C,O])}return}if(b)return!0;if(s)return o;let P=+o;return P*0===0?P:o}E.parseValue=I,h(I,"parseValue");class F{constructor(s,c,u){this.name=s;this.ctx=u;if(!s)throw new Error("expect a command name");let f=this._arguments=T(c);this.declaration=f.stripped}declaration;_arguments;_options={};_namedOptions={};_symbolicOptions={};_createOption(s,c,u){let f=ye(s),C=c.replace(/(?<=^|\s)[\w\x80-\uffff].*/,""),A=c.slice(C.length),x=C.replace(/(?<=^|\s)(<[^<]+>|\[[^[]+\]).*/,""),b=C.slice(x.length);x=x.trim()||"--"+f;let S=[],P=[];for(let k of x.trim().split(",")){k=k.trimStart();let B=k.replace(/^-+/,"");!B||!k.startsWith("-")?P.push(k):S.push(B)}!("value"in u)&&!S.includes(f)&&(x+=", --"+f);let $=T(b);$.stripped&&(x+=" "+$.stripped);let O=this._options[s]||={...K.defaultOptionConfig,...$[0],...u,name:s,values:{},valuesSyntax:{},syntax:x},v=`commands.${this.name}.options.${s}`,D=typeof O.fallback;"value"in u?(v+="."+u.value,O.valuesSyntax[u.value]=x,S.forEach(k=>O.values[k]=u.value)):b.trim()?!O.type&&(D==="string"||D==="number")&&(O.type=D):O.type="boolean",A&&this.ctx.i18n.define("",v,A),this._assignOption(O,S,this._namedOptions),this._assignOption(O,P,this._symbolicOptions),this._namedOptions[f]||(this._namedOptions[f]=O)}_assignOption(s,c,u){for(let f of c){if(f in u)throw new Error(`duplicate option name "${f}" for command "${this.name}"`);u[f]=s}}removeOption(s){if(!this._options[s])return!1;let c=this._options[s];delete this._options[s];for(let u in this._namedOptions)this._namedOptions[u]===c&&delete this._namedOptions[u];for(let u in this._symbolicOptions)this._symbolicOptions[u]===c&&delete this._symbolicOptions[u];return!0}parse(s,c,u=[],f={}){typeof s=="string"&&(s=E.parse(s,c));let C=this.name+" "+E.stringify(s);for(;!s.error&&s.tokens.length;){let A=s.tokens[0],{content:x,quoted:b}=A,S=this._arguments[u.length];if(x[0]!=="-"&&d(S?.type).greedy){u.push(E.parseValue(E.stringify(s),!0,"argument",s,S));break}s.tokens.shift();let P,$,O;if(!b&&(P=this._symbolicOptions[x]))$=[ye(P.name)];else{if(x[0]!=="-"||b){u.push(E.parseValue(x,b,"argument",s,S||{type:"string"}));continue}let v=0,D;for(;v<x.length&&x.charCodeAt(v)===45;++v);if(x.slice(v,v+3)==="no-"&&!this._namedOptions[x.slice(v)]){D=x.slice(v+3),f[ge(D)]=!1;continue}let k=v+1;for(;k<x.length&&x.charCodeAt(k)!==61;k++);D=x.slice(v,k),$=v>1?[D]:D,O=x.slice(++k),P=this._namedOptions[$[$.length-1]]}if(b=!1,!O){let{type:v}=P||{};if(d(v).greedy)O=E.stringify(s),b=!0,s.tokens=[];else if(v!=="boolean"&&s.tokens.length&&(v||s.tokens[0]?.content!=="-")){let D=s.tokens.shift();O=D.content,b=D.quoted}}for(let v=0;v<$.length;v++){let D=$[v],k=this._namedOptions[D],B=k?k.name:ge(D);if(k&&D in k.values)f[B]=k.values[D];else{let Pe=v+1<$.length?"":O;f[B]=E.parseValue(Pe,b,"option",s,k)}if(s.error)break}}for(let{name:A,fallback:x}of Object.values(this._options))x!==void 0&&!(A in f)&&(f[A]=x);return delete s.tokens,{options:f,args:u,source:C,rest:s.rest,error:s.error||""}}stringifyArg(s){return s=""+s,s.includes(" ")?`"${s}"`:s}stringify(s,c){let u=this.name;for(let f in c){let C=c[f];C===!0?u+=` --${f}`:C===!1?u+=` --no-${f}`:u+=` --${f} ${this.stringifyArg(C)}`}for(let f of s)u+=" "+this.stringifyArg(f);return u}}h(F,"CommandBase"),E.CommandBase=F})(R||={});import{coerce as Ge,defineProperty as Ce,escapeRegExp as qe,makeArray as Le}from"@koishijs/utils";import{defineProperty as je}from"@koishijs/utils";import{Database as be}from"minato";var re;(t=>{let m;(r=>r[r.ignore=1]="ignore")(m=t.Flag||={}),t.fields=[]})(re||={});var ie;(t=>{let m;(i=>(i[i.ignore=1]="ignore",i[i.silent=4]="silent"))(m=t.Flag||={}),t.fields=[]})(ie||={});var L=class extends be{constructor(t){super();this.app=t;je(this,y.current,t),this.extend("user",{id:"string(63)",name:{type:"string",length:63},flag:"unsigned(20)",authority:"unsigned(4)",locale:"string(63)"},{autoInc:!0}),this.extend("channel",{id:"string(63)",platform:"string(63)",flag:"unsigned(20)",assignee:"string(63)",guildId:"string(63)",locale:"string(63)"},{primary:["id","platform"]}),t.on("bot-added",n=>{n.platform in this.tables.user.fields||this.extend("user",{[n.platform]:{type:"string",length:63}},{unique:[n.platform]})})}async getUser(t,n,r){let i=await this.get("user",{[t]:n},r);return Array.isArray(n)?i:(i[0]&&Object.assign(i[0],{[t]:n}),i[0])}setUser(t,n,r){return this.set("user",{[t]:n},r)}createUser(t,n,r){return this.create("user",{[t]:n,...r})}async getChannel(t,n,r){let i=await this.get("channel",{platform:t,id:n},r);return Array.isArray(n)?i:(i[0]&&Object.assign(i[0],{platform:t,id:n}),i[0])}getSelfIds(t,n){if(t)return n||=this.app.bots.filter(i=>i.platform===t).map(i=>i.selfId),{[t]:n};let r={};for(let i of this.app.bots)(r[i.platform]||=[]).push(i.selfId);return r}async getAssignedChannels(t,n=this.getSelfIds()){return this.get("channel",{$or:Object.entries(n).map(([r,i])=>({platform:r,assignee:i}))},t)}setChannel(t,n,r){return this.set("channel",{platform:t,id:n},r)}createChannel(t,n,r){return this.create("channel",{platform:t,id:n,...r})}async broadcast(...t){let n;Array.isArray(t[0])&&(n=t.shift());let[r,i]=t;if(!r)return[];let l=await this.getAssignedChannels(["id","assignee","flag","platform","guildId"]),d={};for(let{id:a,assignee:p,flag:g,platform:_,guildId:T}of l)n&&!n.includes(`${_}:${a}`)||!i&&g&4||((d[_]||={})[p]||=[]).push([a,T]);return(await Promise.all(Object.entries(d).flatMap(([a,p])=>this.app.bots.map(g=>g.platform!==a?Promise.resolve([]):g.broadcast(p[g.selfId]||[],r))))).flat(1)}};h(L,"DatabaseService"),U(L,"methods",["getSelfIds","broadcast"]);L.prototype.extend=h(function(e,t,n){be.prototype.extend.call(this,e,t,{...n,driver:this[y.current].mapping.database}),this.app.emit("model",e)},"extend");y.service("database");y.service("model",L);var Ut=h((m,e,t)=>({name:m.name,reusable:!0,Config:e,apply(n,r){t?.(n,r);let i=new m(n.model,r),l=n.mapping.database||"default";n.on("ready",async()=>{await i.start(),n.model.drivers[l]=i,n.model.refresh();let d=Object.create(n.model);n.database=d}),n.on("dispose",async()=>{n.database=null,delete n.model.drivers[l],await i.stop()})}}),"defineDriver");function Ne(m,e="",t=""){return m.length?new RegExp(`^${e}(${m.map(qe).join("|")})${t}`):/$^/}h(Ne,"createLeadingRE");var M;(t=>{t.MAX_DEPTH=64;async function e(n,r){return typeof n=="function"?n(r):n}t.compose=e,h(e,"compose")})(M||={});var W=class{constructor(e,t){this.ctx=e;this.config=t;Ce(this,y.current,e),this.prepare(),this.middleware(this._process.bind(this)),e.on("message",this._handleMessage.bind(this)),e.before("attach-user",(n,r)=>{n.collect("user",n.argv,r)}),e.before("attach-channel",(n,r)=>{n.collect("channel",n.argv,r)}),this.middleware((n,r)=>n.resolve(n.argv)?n.execute(n.argv,r):r())}_hooks=[];_nameRE;_sessions=Object.create(null);_userCache=new H;_channelCache=new H;get caller(){return this[y.current]}middleware(e,t=!1){return this.caller.lifecycle.register("middleware",this._hooks,e,t)}prepare(){this._nameRE=Ne(Le(this.config.nickname),"@?","([,,]\\s*|\\s+)")}_resolvePrefixes(e){let t=e.resolveValue(this.config.prefix);return Array.isArray(t)?t:[t||""]}async _process(e,t){let n,r=!1,i=!1,l=null,d=/^\[CQ:(\w+)((,\w+=[^,\]]*)*)\]/,a=await e.preprocess();e.subtype!=="private"&&(n=a.match(d))&&n[1]==="at"&&n[2].includes("id="+e.selfId)?(r=i=!0,a=a.slice(n[0].length).trimStart()):(n=a.match(this._nameRE))&&(i=!0,a=a.slice(n[0].length));for(let p of this._resolvePrefixes(e))!a.startsWith(p)||(l=p,a=a.slice(p.length));if(Ce(e,"parsed",{content:a,appel:i,prefix:l}),this.ctx.emit(e,"before-attach",e),this.ctx.database){if(e.subtype==="group"){let _=new Set(["flag","assignee","guildId","locale"]);this.ctx.emit("before-attach-channel",e,_);let T=await e.observeChannel(_);if(T.guildId=e.guildId,await this.ctx.serial(e,"attach-channel",e)||T.flag&ie.Flag.ignore||T.assignee!==e.selfId&&!r)return}let p=new Set(["flag","authority","locale"]);this.ctx.emit("before-attach-user",e,p);let g=await e.observeUser(p);if(await this.ctx.serial(e,"attach-user",e)||g.flag&re.Flag.ignore)return}return this.ctx.emit(e,"attach",e),t()}async _handleMessage(e){if(e.selfId===e.userId)return;this._sessions[e.id]=e;let t=this._hooks.filter(([a])=>a.filter(e)).map(([,a])=>a.bind(null,e)),n=0,r="",i="",{prettyErrors:l}=this.ctx.options,d=h(async a=>{if(l&&(i=new Error().stack.split(`
var me=Object.defineProperty;var Ke=(m,e,t)=>e in m?me(m,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):m[e]=t;var h=(m,e)=>me(m,"name",{value:e,configurable:!0});var q=(m,e)=>()=>(e||m((e={exports:{}}).exports,e),e.exports);var U=(m,e,t)=>(Ke(m,typeof e!="symbol"?e+"":e,t),t);var Te=q((Tn,et)=>{et.exports={general:{name:"中文",paren:"({0})",quote:"“{0}”",comma:",",and:"和",or:"或",day:"天",hour:"小时",minute:"分钟",second:"秒"},internal:{"low-authority":"权限不足。","insufficient-arguments":"缺少参数,输入帮助以查看用法。","redunant-arguments":"存在多余参数,输入帮助以查看用法。","invalid-argument":"参数 {0} 输入无效,{1}","unknown-option":"存在未知选项 {0},输入帮助以查看用法。","invalid-option":"选项 {0} 输入无效,{1}","check-syntax":"输入帮助以查看用法。","invalid-number":"请提供一个数字。","invalid-integer":"请提供一个整数。","invalid-posint":"请提供一个正整数。","invalid-natural":"请提供一个非负整数。","invalid-date":"请输入合法的时间。","invalid-user":"请指定正确的用户。","invalid-channel":"请指定正确的频道。"}}});var Ae=q((An,tt)=>{tt.exports={general:{name:"English",paren:" ({0}) ",quote:'"{0}"',comma:", ",and:"and",or:"or",day:"day",hour:"hour",minute:"minute",second:"second"},internal:{"low-authority":"Low authority.","insufficient-arguments":"Insufficient arguments, type help to see usage.","redunant-arguments":"Redunant arguments, type help to see usage.","invalid-argument":"Invalid argument {0}, {1}","unknown-option":"Unknown option {0}, type help to see usage.","invalid-option":"Invalid option {0}, {1}","check-syntax":"Type help to see usage.","invalid-number":"Expect a number.","invalid-integer":"Expect an integer.","invalid-posint":"Expect a positive integer.","invalid-natural":"Expect a non-negative integer.","invalid-date":"Expect a valid date.","invalid-user":"Expect a valid user.","invalid-channel":"Expect a valid channel."}}});var ke=q((kn,nt)=>{nt.exports={general:{name:"日本語",paren:"({0})",quote:"「{0}」",comma:"、",and:"と",or:"や",day:"日",hour:"時間",minute:"分",second:"秒"},internal:{"low-authority":"実行できる権限が付与されていません","insufficient-arguments":"パラメータが不足しています、「help」を送信して使い方を確認してください。","redunant-arguments":"パラメータ数が多すぎます、「help」を送信して使い方を確認してください。","invalid-argument":"無効なパラメータ「{0}」、{1}","unknown-option":"未知なオプション「{0}」、「help」を送信して使い方を確認してください。","invalid-option":"無効なオプション「{0}」、{1}","check-syntax":"「help」を送信して使い方を検索してください。","invalid-number":"数字を指定してください。","invalid-integer":"整数を指定してください。","invalid-posint":"正の整数を指定してください。","invalid-natural":"自然数を指定してください。","invalid-date":"日付を指定してください。","invalid-user":"ユーザー名を指定してください。","invalid-channel":"チャンネル名を指定してください。"}}});var Ee=q((En,rt)=>{rt.exports={general:{name:"francais",paren:" ({0}) ",quote:'"{0}"',comma:", ",and:"et",or:"ou",day:"jour",hour:"heure",minute:"minute",second:"seconde"},internal:{"low-authority":"Droits insuffisants.","insufficient-arguments":`Arguments insuffisants, tapez "help" pour afficher l'aide`,"redunant-arguments":`Arguments redondants, tapez "help" pour afficher l'aide`,"invalid-argument":"Arguments {0} invalides, {1}","unknown-option":`Option {0} inconnue, tapez "help" pour afficher l'aide`,"invalid-option":"Option {0} invalide, {1}","check-syntax":`Tapez "help" pour afficher l'aide`,"invalid-number":"Entrez un nombre.","invalid-integer":"Entrez un entier.","invalid-posint":"Entrez un entier positif.","invalid-natural":"Entrez un entier non négatif.","invalid-date":"Entrez une date valide.","invalid-user":"Entrez un nom d'utilisateur valide.","invalid-channel":"Entrez un nom de canal valide."}}});var $e=q(($n,it)=>{it.exports={general:{name:"中文",paren:"({0})",quote:"「{0}」",comma:",",and:"和",or:"或",day:"天",hour:"小時",minute:"分鐘",second:"秒"},internal:{"low-authority":"權限不足。","insufficient-arguments":"參數個數不足,輸入「help」檢視用法。","redunant-arguments":"參數個數冗餘,輸入「help」檢視用法。","invalid-argument":"參數 {0} 無效,{1}","unknown-option":"存在未知選項 {0},輸入「help」檢視用法。","invalid-option":"選項 {0} 無效,{1}","check-syntax":"輸入「help」檢視用法。","invalid-number":"請輸入有效數字。","invalid-integer":"請輸入有效整數。","invalid-posint":"請輸入有效正整數。","invalid-natural":"請輸入有效非負整數。","invalid-date":"請輸入有效時間。","invalid-user":"請指定有效用戶。","invalid-channel":"請指定有效頻道。"}}});var Fe=q((Pn,at)=>{at.exports={name:"@koishijs/core",description:"Core Features for Koishi",version:"4.8.3",main:"lib/node.js",module:"lib/browser.js",typings:"lib/index.d.ts",files:["lib"],author:"Shigma <shigma10826@gmail.com>",license:"MIT",repository:{type:"git",url:"git+https://github.com/koishijs/koishi.git",directory:"packages/core"},bugs:{url:"https://github.com/koishijs/koishi/issues"},homepage:"https://koishi.js.org",keywords:["bot","chatbot","koishi"],devDependencies:{chai:"^4.3.6","chai-as-promised":"^7.1.1","chai-shape":"^1.0.0"},dependencies:{"@koishijs/utils":"^6.0.0","@satorijs/core":"^1.0.6",cordis:"^2.0.6","fastest-levenshtein":"^1.0.12",minato:"^1.2.3"}}});export*from"@koishijs/utils";export*from"minato";import{defineProperty as Ue,Logger as Ie,remove as Re}from"@koishijs/utils";import{defineProperty as J,Schema as w,Time as Z}from"@koishijs/utils";import*as he from"@satorijs/core";import*as fe from"cordis";import{Disposable as ft}from"cordis";var pt=fe.Service,y=class extends he.Context{constructor(e){super(e)}get app(){return this.root}};h(y,"Context");(e=>(e.Config=w.intersect([]),J(e.Config,"Basic",w.object({locale:w.string().default("zh").description("默认使用的语言。"),prefix:w.union([w.array(String),w.transform(String,t=>[t])]).default([""]).description("指令前缀字符构成的数组。将被用于指令的匹配。"),nickname:w.union([w.array(String),w.transform(String,t=>[t])]).description("机器人昵称构成的数组。将被用于指令的匹配。"),autoAssign:w.union([Boolean,Function]).default(!0).description("当获取不到频道数据时,是否使用接受者作为代理者。"),autoAuthorize:w.union([w.natural(),Function]).default(1).description("当获取不到用户数据时默认使用的权限等级。")}).description("基础设置")),J(e.Config,"Message",w.object({delay:w.object({character:w.natural().role("ms").default(0).description("调用 `session.sendQueued()` 时消息间发送的最小延迟,按前一条消息的字数计算。"),message:w.natural().role("ms").default(.1*Z.second).description("调用 `session.sendQueued()` 时消息间发送的最小延迟,按固定值计算。"),cancel:w.natural().role("ms").default(0).description("调用 `session.cancelQueued()` 时默认的延迟。"),broadcast:w.natural().role("ms").default(.5*Z.second).description("调用 `bot.broadcast()` 时默认的延迟。"),prompt:w.natural().role("ms").default(Z.minute).description("调用 `session.prompt()` 时默认的等待时间。")})}).description("消息设置")),J(e.Config,"Advanced",w.object({prettyErrors:w.boolean().default(!0).description("启用报错优化模式。在此模式下 Koishi 会对程序抛出的异常进行整理,过滤掉框架内部的调用记录,输出更易读的提示信息。"),maxListeners:w.natural().default(64).description("每种监听器的最大数量。如果超过这个数量,Koishi 会认定为发生了内存泄漏,将产生一个警告。")}).description("高级设置")),e.Config.list.push(e.Config.Basic,e.Config.Message,e.Config.Advanced)))(y||={});function ut(m){return m}h(ut,"defineConfig");var z=class{constructor(e){this.app=e;Ue(this,y.current,e),e.on("internal/warning",(t,...n)=>{this.logger("app").warn(t,...n)})}get caller(){return this[y.current]}logger(e){return new Ie(e)}async waterfall(...e){let t=typeof e[0]=="object"?e.shift():null,n=e.shift();for(let r of this.app.lifecycle.getHooks(n,t)){let i=await r.apply(t,e);e[0]=i}return e[0]}chain(...e){let t=typeof e[0]=="object"?e.shift():null,n=e.shift();for(let r of this.app.lifecycle.getHooks(n,t)){let i=r.apply(t,e);e[0]=i}return e[0]}before(e,t,n=!1){let r=e.split("/");return r[r.length-1]="before-"+r[r.length-1],this.caller.on(r.join("/"),t,!n)}createTimerDispose(e){let t=h(()=>{if(clearTimeout(e),!!this.caller.state)return Re(this.caller.state.disposables,t)},"dispose");return this.caller.state.disposables.push(t),t}setTimeout(e,t,...n){let r=this.createTimerDispose(setTimeout(()=>{r(),e()},t,...n));return r}setInterval(e,t,...n){return this.createTimerDispose(setInterval(e,t,...n))}};h(z,"SelectorService"),U(z,"methods",["chain","waterfall","before","logger","setTimeout","setInterval"]);y.service("selector",z);import{makeArray as Je,sleep as Ze}from"@koishijs/utils";import{defineProperty as N,isNullable as Ve,Logger as Xe,makeArray as Ye,observe as ce}from"@koishijs/utils";import*as X from"@satorijs/core";import{defineProperty as Qe}from"@koishijs/utils";import{coerce as Be,Logger as ze,remove as j,Schema as Q}from"@koishijs/utils";import{camelCase as ge,escapeRegExp as xe,paramCase as ye,Time as Me}from"@koishijs/utils";import{segment as ee}from"@satorijs/core";var te=`"'“‘`,ne=`"'”’`,R;(E=>{let m={};function e(o,s,c){m[o]={terminator:s,parse:c}}E.interpolate=e,h(e,"interpolate"),e("$(",")");class t{bracs;constructor(){this.bracs=Object.create(m)}interpolate(s,c,u){this.bracs[s]={terminator:c,parse:u}}parseToken(s,c="$"){let u={inters:[]},f=te.indexOf(s[0]),C=ne[f],A="";C&&(s=s.slice(1),c=`${C}(?=${c})|$`),c+=`|${Object.keys({...this.bracs,...m}).map(xe).join("|")}`;let x=new RegExp(c);for(;;){let b=x.exec(s);if(A+=s.slice(0,b.index),b[0]in this.bracs){s=s.slice(b.index+b[0].length).trimStart();let{parse:S,terminator:P}=this.bracs[b[0]],$=S?.(s)||this.parse(s,P);s=$.rest,u.inters.push({...$,pos:A.length,initiator:b[0]})}else{let S=b[0]===C,P=s.slice(b.index+ +S);return u.rest=P.trimStart(),u.quoted=S,u.terminator=b[0],S?u.terminator+=P.slice(0,-u.rest.length):C&&(A=te[f]+A,u.inters.forEach($=>$.pos+=1)),u.content=A,C==="'"&&E.revert(u),u}}}parse(s,c=""){let u=[],f=s,C="",A=`\\s+|[${xe(c)}]|$`;for(;f&&!(c&&f.startsWith(c));){let x=this.parseToken(f,A);u.push(x),f=x.rest,C=x.terminator,delete x.rest}return f.startsWith(c)&&(f=f.slice(1)),s=s.slice(0,-(f+C).length),{tokens:u,rest:f,source:s}}stringify(s){let c=s.tokens.reduce((u,f)=>(f.quoted&&(u+=te[ne.indexOf(f.terminator[0])]||""),u+f.content+f.terminator),"");return s.rest&&!ne.includes(c[c.length-1])||s.initiator?c.slice(0,-1):c}}h(t,"Tokenizer"),E.Tokenizer=t;let n=new t;function r(o,s=""){return n.parse(o,s)}E.parse=r,h(r,"parse");function i(o){return n.stringify(o)}E.stringify=i,h(i,"stringify");function l(o){for(;o.inters.length;){let{pos:s,source:c,initiator:u}=o.inters.pop();o.content=o.content.slice(0,s)+u+c+m[u].terminator+o.content.slice(s)}}E.revert=l,h(l,"revert");function d(o){return typeof o=="string"?p[o]||{}:{}}h(d,"resolveConfig");function a(o){return typeof o=="function"?o:o instanceof RegExp?s=>{if(o.test(s))return s;throw new Error}:Array.isArray(o)?s=>{if(o.includes(s))return s;throw new Error}:p[o]?.transform}h(a,"resolveType");let p={};function g(o,s,c){p[o]={...c,transform:s}}E.createDomain=g,h(g,"createDomain"),g("rawtext",o=>o),g("string",o=>o),g("text",o=>o,{greedy:!0}),g("rawtext",o=>ee.unescape(o),{greedy:!0}),g("boolean",()=>!0),g("number",(o,s)=>{let c=+o;if(Number.isFinite(c))return c;throw new Error("internal.invalid-number")}),g("integer",(o,s)=>{let c=+o;if(c*0===0&&Math.floor(c)===c)return c;throw new Error("internal.invalid-integer")}),g("posint",(o,s)=>{let c=+o;if(c*0===0&&Math.floor(c)===c&&c>0)return c;throw new Error("internal.invalid-posint")}),g("natural",(o,s)=>{let c=+o;if(c*0===0&&Math.floor(c)===c&&c>=0)return c;throw new Error("internal.invalid-natural")}),g("date",(o,s)=>{let c=Me.parseDate(o);if(+c)return c;throw new Error("internal.invalid-date")}),g("user",(o,s)=>{if(o.startsWith("@"))return o=o.slice(1),o.includes(":")?o:`${s.platform}:${o}`;let c=ee.from(o);if(c&&c.type==="at")return`${s.platform}:${c.data.id}`;throw new Error("internal.invalid-user")}),g("channel",(o,s)=>{if(o.startsWith("#"))return o=o.slice(1),o.includes(":")?o:`${s.platform}:${o}`;let c=ee.from(o);if(c&&c.type==="sharp")return`${s.platform}:${c.data.id}`;throw new Error("internal.invalid-channel")});let _=/<[^>]+>|\[[^\]]+\]/g;function T(o){let s,c=[];for(;s=_.exec(o);){let u=s[0].slice(1,-1),f=!1;u.startsWith("...")&&(u=u.slice(3),f=!0);let[C,A]=u.split(":"),x=A?A.trim():void 0;c.push({name:C,variadic:f,type:x,required:s[0][0]==="<"})}return c.stripped=o.replace(/:[\w-]+[>\]]/g,u=>u.slice(-1)).trimEnd(),c}h(T,"parseDecl");function I(o,s,c,u,f={}){let{name:C,type:A,fallback:x}=f,b=o===""&&!s;if(b&&x!==void 0)return x;let S=a(A);if(S)try{return S(o,u.session)}catch($){if(!u.session)u.error=`internal.invalid-${c}`;else{let O=u.session.text($.message||"internal.check-syntax");u.error=u.session.text(`internal.invalid-${c}`,[C,O])}return}if(b)return!0;if(s)return o;let P=+o;return P*0===0?P:o}E.parseValue=I,h(I,"parseValue");class F{constructor(s,c,u){this.name=s;this.ctx=u;if(!s)throw new Error("expect a command name");let f=this._arguments=T(c);this.declaration=f.stripped}declaration;_arguments;_options={};_namedOptions={};_symbolicOptions={};_createOption(s,c,u){let f=ye(s),C=c.replace(/(?<=^|\s)[\w\x80-\uffff].*/,""),A=c.slice(C.length),x=C.replace(/(?<=^|\s)(<[^<]+>|\[[^[]+\]).*/,""),b=C.slice(x.length);x=x.trim()||"--"+f;let S=[],P=[];for(let k of x.trim().split(",")){k=k.trimStart();let B=k.replace(/^-+/,"");!B||!k.startsWith("-")?P.push(k):S.push(B)}!("value"in u)&&!S.includes(f)&&(x+=", --"+f);let $=T(b);$.stripped&&(x+=" "+$.stripped);let O=this._options[s]||={...K.defaultOptionConfig,...$[0],...u,name:s,values:{},valuesSyntax:{},syntax:x},v=`commands.${this.name}.options.${s}`,D=typeof O.fallback;"value"in u?(v+="."+u.value,O.valuesSyntax[u.value]=x,S.forEach(k=>O.values[k]=u.value)):b.trim()?!O.type&&(D==="string"||D==="number")&&(O.type=D):O.type="boolean",A&&this.ctx.i18n.define("",v,A),this._assignOption(O,S,this._namedOptions),this._assignOption(O,P,this._symbolicOptions),this._namedOptions[f]||(this._namedOptions[f]=O)}_assignOption(s,c,u){for(let f of c){if(f in u)throw new Error(`duplicate option name "${f}" for command "${this.name}"`);u[f]=s}}removeOption(s){if(!this._options[s])return!1;let c=this._options[s];delete this._options[s];for(let u in this._namedOptions)this._namedOptions[u]===c&&delete this._namedOptions[u];for(let u in this._symbolicOptions)this._symbolicOptions[u]===c&&delete this._symbolicOptions[u];return!0}parse(s,c,u=[],f={}){typeof s=="string"&&(s=E.parse(s,c));let C=this.name+" "+E.stringify(s);for(;!s.error&&s.tokens.length;){let A=s.tokens[0],{content:x,quoted:b}=A,S=this._arguments[u.length];if(x[0]!=="-"&&d(S?.type).greedy){u.push(E.parseValue(E.stringify(s),!0,"argument",s,S));break}s.tokens.shift();let P,$,O;if(!b&&(P=this._symbolicOptions[x]))$=[ye(P.name)];else{if(x[0]!=="-"||b){u.push(E.parseValue(x,b,"argument",s,S||{type:"string"}));continue}let v=0,D;for(;v<x.length&&x.charCodeAt(v)===45;++v);if(x.slice(v,v+3)==="no-"&&!this._namedOptions[x.slice(v)]){D=x.slice(v+3),f[ge(D)]=!1;continue}let k=v+1;for(;k<x.length&&x.charCodeAt(k)!==61;k++);D=x.slice(v,k),$=v>1?[D]:D,O=x.slice(++k),P=this._namedOptions[$[$.length-1]]}if(b=!1,!O){let{type:v}=P||{};if(d(v).greedy)O=E.stringify(s),b=!0,s.tokens=[];else if(v!=="boolean"&&s.tokens.length&&(v||s.tokens[0]?.content!=="-")){let D=s.tokens.shift();O=D.content,b=D.quoted}}for(let v=0;v<$.length;v++){let D=$[v],k=this._namedOptions[D],B=k?k.name:ge(D);if(k&&D in k.values)f[B]=k.values[D];else{let Pe=v+1<$.length?"":O;f[B]=E.parseValue(Pe,b,"option",s,k)}if(s.error)break}}for(let{name:A,fallback:x}of Object.values(this._options))x!==void 0&&!(A in f)&&(f[A]=x);return delete s.tokens,{options:f,args:u,source:C,rest:s.rest,error:s.error||""}}stringifyArg(s){return s=""+s,s.includes(" ")?`"${s}"`:s}stringify(s,c){let u=this.name;for(let f in c){let C=c[f];C===!0?u+=` --${f}`:C===!1?u+=` --no-${f}`:u+=` --${f} ${this.stringifyArg(C)}`}for(let f of s)u+=" "+this.stringifyArg(f);return u}}h(F,"CommandBase"),E.CommandBase=F})(R||={});import{coerce as Ge,defineProperty as Ce,escapeRegExp as qe,makeArray as Le}from"@koishijs/utils";import{defineProperty as je}from"@koishijs/utils";import{Database as be}from"minato";var re;(t=>{let m;(r=>r[r.ignore=1]="ignore")(m=t.Flag||={}),t.fields=[]})(re||={});var ie;(t=>{let m;(i=>(i[i.ignore=1]="ignore",i[i.silent=4]="silent"))(m=t.Flag||={}),t.fields=[]})(ie||={});var L=class extends be{constructor(t){super();this.app=t;je(this,y.current,t),this.extend("user",{id:"string(63)",name:{type:"string",length:63},flag:"unsigned(20)",authority:"unsigned(4)",locale:"string(63)"},{autoInc:!0}),this.extend("channel",{id:"string(63)",platform:"string(63)",flag:"unsigned(20)",assignee:"string(63)",guildId:"string(63)",locale:"string(63)"},{primary:["id","platform"]}),t.on("bot-added",n=>{n.platform in this.tables.user.fields||this.extend("user",{[n.platform]:{type:"string",length:63}},{unique:[n.platform]})})}async getUser(t,n,r){let i=await this.get("user",{[t]:n},r);return Array.isArray(n)?i:(i[0]&&Object.assign(i[0],{[t]:n}),i[0])}setUser(t,n,r){return this.set("user",{[t]:n},r)}createUser(t,n,r){return this.create("user",{[t]:n,...r})}async getChannel(t,n,r){let i=await this.get("channel",{platform:t,id:n},r);return Array.isArray(n)?i:(i[0]&&Object.assign(i[0],{platform:t,id:n}),i[0])}getSelfIds(t,n){if(t)return n||=this.app.bots.filter(i=>i.platform===t).map(i=>i.selfId),{[t]:n};let r={};for(let i of this.app.bots)(r[i.platform]||=[]).push(i.selfId);return r}async getAssignedChannels(t,n=this.getSelfIds()){return this.get("channel",{$or:Object.entries(n).map(([r,i])=>({platform:r,assignee:i}))},t)}setChannel(t,n,r){return this.set("channel",{platform:t,id:n},r)}createChannel(t,n,r){return this.create("channel",{platform:t,id:n,...r})}async broadcast(...t){let n;Array.isArray(t[0])&&(n=t.shift());let[r,i]=t;if(!r)return[];let l=await this.getAssignedChannels(["id","assignee","flag","platform","guildId"]),d={};for(let{id:a,assignee:p,flag:g,platform:_,guildId:T}of l)n&&!n.includes(`${_}:${a}`)||!i&&g&4||((d[_]||={})[p]||=[]).push([a,T]);return(await Promise.all(Object.entries(d).flatMap(([a,p])=>this.app.bots.map(g=>g.platform!==a?Promise.resolve([]):g.broadcast(p[g.selfId]||[],r))))).flat(1)}};h(L,"DatabaseService"),U(L,"methods",["getSelfIds","broadcast"]);L.prototype.extend=h(function(e,t,n){be.prototype.extend.call(this,e,t,{...n,driver:this[y.current].mapping.database}),this.app.emit("model",e)},"extend");y.service("database");y.service("model",L);var Ut=h((m,e,t)=>({name:m.name,reusable:!0,Config:e,apply(n,r){t?.(n,r);let i=new m(n.model,r),l=n.mapping.database||"default";n.on("ready",async()=>{await i.start(),n.model.drivers[l]=i,n.model.refresh();let d=Object.create(n.model);n.database=d}),n.on("dispose",async()=>{n.database=null,delete n.model.drivers[l],await i.stop()})}}),"defineDriver");function Ne(m,e="",t=""){return m.length?new RegExp(`^${e}(${m.map(qe).join("|")})${t}`):/$^/}h(Ne,"createLeadingRE");var M;(t=>{t.MAX_DEPTH=64;async function e(n,r){return typeof n=="function"?n(r):n}t.compose=e,h(e,"compose")})(M||={});var W=class{constructor(e,t){this.ctx=e;this.config=t;Ce(this,y.current,e),this.prepare(),this.middleware(this._process.bind(this)),e.on("message",this._handleMessage.bind(this)),e.before("attach-user",(n,r)=>{n.collect("user",n.argv,r)}),e.before("attach-channel",(n,r)=>{n.collect("channel",n.argv,r)}),this.middleware((n,r)=>n.resolve(n.argv)?n.execute(n.argv,r):r())}_hooks=[];_nameRE;_sessions=Object.create(null);_userCache=new H;_channelCache=new H;get caller(){return this[y.current]}middleware(e,t=!1){return this.caller.lifecycle.register("middleware",this._hooks,e,t)}prepare(){this._nameRE=Ne(Le(this.config.nickname),"@?","([,,]\\s*|\\s+)")}_resolvePrefixes(e){let t=e.resolveValue(this.config.prefix);return Array.isArray(t)?t:[t||""]}async _process(e,t){let n,r=!1,i=!1,l=null,d=/^\[CQ:(\w+)((,\w+=[^,\]]*)*)\]/,a=await e.preprocess();e.subtype!=="private"&&(n=a.match(d))&&n[1]==="at"&&n[2].includes("id="+e.selfId)?(r=i=!0,a=a.slice(n[0].length).trimStart()):(n=a.match(this._nameRE))&&(i=!0,a=a.slice(n[0].length));for(let p of this._resolvePrefixes(e))!a.startsWith(p)||(l=p,a=a.slice(p.length));if(Ce(e,"parsed",{content:a,appel:i,prefix:l}),this.ctx.emit(e,"before-attach",e),this.ctx.database){if(e.subtype==="group"){let _=new Set(["flag","assignee","guildId","locale"]);this.ctx.emit("before-attach-channel",e,_);let T=await e.observeChannel(_);if(T.guildId=e.guildId,await this.ctx.serial(e,"attach-channel",e)||T.flag&ie.Flag.ignore||T.assignee!==e.selfId&&!r)return}let p=new Set(["flag","authority","locale"]);this.ctx.emit("before-attach-user",e,p);let g=await e.observeUser(p);if(await this.ctx.serial(e,"attach-user",e)||g.flag&re.Flag.ignore)return}return this.ctx.emit(e,"attach",e),t()}async _handleMessage(e){if(e.selfId===e.userId)return;this._sessions[e.id]=e;let t=this._hooks.filter(([a])=>a.filter(e)).map(([,a])=>a.bind(null,e)),n=0,r="",i="",{prettyErrors:l}=this.ctx.options,d=h(async a=>{if(l&&(i=new Error().stack.split(`
`,3)[2],n)){let p=i.match(/\((.+)\)/);r=`

@@ -6,3 +6,3 @@ - ${p?p[1]:i.slice(7)}${r}`}try{if(!this._sessions[e.id])throw new Error("isolated next function detected");if(a!==void 0&&(t.push(p=>M.compose(a,p)),t.length>M.MAX_DEPTH))throw new Error(`middleware stack exceeded ${M.MAX_DEPTH}`);return await t[n++]?.(d)}catch(p){let g=Ge(p);if(l){let _=g.indexOf(i);_>=0?g=g.slice(0,_):g+=`

${g}`)}},"next");try{let a=await d();a&&await e.send(a)}finally{delete this._sessions[e.id],this.ctx.emit(e,"middleware",e),this._userCache.delete(e.id),this._channelCache.delete(e.id),await e.user?.$update(),await e.channel?.$update(),await e.guild?.$update()}}};h(W,"Internal"),U(W,"methods",["middleware"]);y.service("$internal",W);var H=class{#e=Object.create(null);get(e,t){let n=this.#e[t];if(!!n)return n.refs.add(e),n.value}set(e,t,n){let r=this.#e[t];r?r.value=n:r=this.#e[t]={value:n,key:t,refs:new Set},r.refs.add(e)}delete(e){for(let t in this.#e){let{refs:n}=this.#e[t];n.delete(e),n.size||delete this.#e[t]}}};h(H,"SharedCache");var se=new ze("command"),oe=class extends R.CommandBase{config;children=[];parent=null;_aliases=[];_examples=[];_usage;_disposed;_disposables;_userFields=[["locale"]];_channelFields=[["locale"]];_actions=[];_checkers=[async e=>this.ctx.serial(e.session,"command/before-execute",e)];static userFields(e){return this._userFields.push(e),this}static channelFields(e){return this._channelFields.push(e),this}constructor(e,t,n){super(e,t,n),this.config={...oe.defaultConfig},this._registerAlias(e),n.$commander._commandList.push(this)}get displayName(){return this._aliases[0]}set displayName(e){this._registerAlias(e,!0)}_registerAlias(e,t=!1){if(e=e.toLowerCase(),this._aliases.includes(e)){t&&(j(this._aliases,e),this._aliases.unshift(e));return}else t?this._aliases.unshift(e):this._aliases.push(e);let r=this.ctx.$commander.getCommand(e);if(!r)this.ctx.$commander._commands.set(e,this);else if(r!==this)throw new Error(`duplicate command names: "${e}"`);this._disposables?.push(()=>{j(this._aliases,e),this.ctx.$commander._commands.delete(e)})}[Symbol.for("nodejs.util.inspect.custom")](){return`Command <${this.name}>`}userFields(e){return this._userFields.push(e),this}channelFields(e){return this._channelFields.push(e),this}alias(...e){if(this._disposed)return this;for(let t of e)this._registerAlias(t);return this}shortcut(e,t={}){return this._disposed?this:(t.name=e,t.command=this,this.ctx.$commander._shortcuts.push(t),this._disposables?.push(()=>j(this.ctx.$commander._shortcuts,t)),this)}subcommand(e,...t){e=this.name+(e.charCodeAt(0)===46?"":"/")+e;let n=typeof t[0]=="string"?t.shift():"",r=t[0]||{};return this._disposed&&(r.patch=!0),this.ctx.command(e,n,r)}usage(e){return this._usage=e,this}example(e){return this._examples.push(e),this}option(e,...t){let n="";typeof t[0]=="string"&&(n=t.shift());let r=t[0];return this._createOption(e,n,r||{}),this._disposables?.push(()=>this.removeOption(e)),this}match(e){let{authority:t=1/0}=e.user||{};return this.ctx.filter(e)&&this.config.authority<=t}getConfig(e,t){let n=this.config[e];return typeof n=="function"?n(t):n}check(e,t=!1){return this.before(e,t)}before(e,t=!1){return t?this._checkers.push(e):this._checkers.unshift(e),this._disposables?.push(()=>j(this._checkers,e)),this}action(e,t=!1){return t?this._actions.unshift(e):this._actions.push(e),this._disposables?.push(()=>j(this._actions,e)),this}use(e,...t){return e(this,...t)}async execute(e,t=M.compose){e.command??=this,e.args??=[],e.options??={};let{args:n,options:r,error:i}=e;if(i)return i;se.level>=3&&se.debug(e.source||=this.stringify(n,r));for(let p of this._checkers){let g=await p.call(this,e,...n);if(typeof g=="string")return g}if(!this._actions.length)return"";let l=0,d=this._actions.map(p=>async()=>await p.call(this,e,...n));d.push(t);let a=d.length;e.next=async p=>{if(p!==void 0&&(d.push(g=>M.compose(p,g)),d.length>M.MAX_DEPTH))throw new Error(`middleware stack exceeded ${M.MAX_DEPTH}`);return d[l++]?.(e.next)};try{let p=await e.next();if(typeof p=="string")return p}catch(p){if(l===a)throw p;let g=Be(p);se.warn(`${e.source||=this.stringify(n,r)}
${g}`),this.ctx.emit(e.session,"command-error",e,p)}return""}dispose(){this._disposed=!0,this.ctx.emit("command-removed",this);for(let e of this.children.slice())e.dispose();this.ctx.$commander._shortcuts=this.ctx.$commander._shortcuts.filter(e=>e.command!==this),this._aliases.forEach(e=>this.ctx.$commander._commands.delete(e)),j(this.ctx.$commander._commandList,this),this.parent&&j(this.parent.children,this)}},K=oe;h(K,"Command"),U(K,"defaultConfig",{authority:1,showWarning:!0}),U(K,"defaultOptionConfig",{authority:0}),U(K,"_userFields",[]),U(K,"_channelFields",[]);(e=>e.Config=Q.object({authority:Q.natural().default(1),hidden:Q.boolean().default(!1),checkArgCount:Q.boolean().default(!1),checkUnknown:Q.boolean().default(!1)}))(K||={});import{defineProperty as We,valueMap as He}from"@koishijs/utils";function ae(m){m.before("parse",(t,n)=>{let r=R.parse(t);return n.quote&&r.tokens.push({content:n.quote.content,quoted:!0,inters:[],terminator:""}),r}),m.before("parse",(t,n)=>{let{parsed:r,quote:i}=n;if(!(r.prefix||i))for(let l of m.$commander._shortcuts){let{name:d,fuzzy:a,command:p,prefix:g,options:_={},args:T=[]}=l;if(!(g&&!r.appel||!p.ctx.filter(n)))if(typeof d=="string"){if(!a&&t!==d||!t.startsWith(d))continue;let I=t.slice(d.length);if(a&&!r.appel&&I.match(/^\S/))continue;let F=R.parse(I.trim());return F.session=n,F=p.parse(F,"",[...T],{..._}),F.command=p,F}else{let F=function(E){return typeof E!="string"?E:(E=E.replace(/\$\$/g,"@@__PLACEHOLDER__@@"),I.forEach((o,s)=>{!s||s>9||(E=E.replace(new RegExp(`\\$${s}`,"g"),(o||"").replace(/\$/g,"@@__PLACEHOLDER__@@")))}),E.replace(/@@__PLACEHOLDER__@@/g,"$"))};h(F,"escape");let I=d.exec(t);if(!I)continue;return{command:p,args:T.map(F),options:He(_,F)}}}}),m.before("attach",t=>{We(t,"argv",m.bail("before-parse",t.parsed.content,t)),t.argv.root=!0,t.argv.session=t});function e(t,n){if(!!m.$commander.getCommand("help"))return t.execute({name:"help",args:[n]})}h(e,"executeHelp"),m.before("command/execute",t=>{let{args:n,command:r,options:i,session:l}=t;if(i.help&&r._options.help)return e(l,r.name);if(r._actions.length)return;let d=n.shift()||"",a=m.$commander.getCommand(r.name+"."+d);if(a){let p=l.__redirected_commands||=[`(${r.name}${r._aliases.length!==0?"|"+r._aliases.join("|"):""})`];p.push(d);let g=new RegExp(`^${p.join("[. ]")}( |$)`);return t=R.parse(l.parsed.content.replace(g,"")),t.session=l,t=a.parse(t),l.execute({...t,command:a})}else return e(l,r.name)})}h(ae,"runtime");function le(m){m.on("command-added",e=>{e.userFields(({tokens:t,command:n,options:r={}},i)=>{if(!n)return;let{authority:l}=n.config,d=l>0;for(let{name:a,authority:p}of Object.values(n._options))a in r?p>0&&(d=!0):t&&p>0&&(d=!0);d&&i.add("authority")})}),m.before("command/execute",e=>{let{session:t,options:n,command:r}=e;if(!t.user)return;function i(l,...d){return r.config.showWarning?t.text(l,d):""}if(h(i,"sendHint"),t.user.authority&&r.getConfig("authority",t)>t.user.authority)return i("internal.low-authority");for(let l of Object.values(r._options))if(l.name in n&&l.authority>t.user.authority)return i("internal.low-authority")}),m.before("command/execute",e=>{let{args:t,options:n,command:r,session:i}=e;function l(d,...a){return r.config.showWarning?i.text(d,a):""}if(h(l,"sendHint"),r.config.checkArgCount){if((r._arguments[t.length]||{}).required)return l("internal.insufficient-arguments");let a=r._arguments[r._arguments.length-1]||{};if(t.length>r._arguments.length&&a.type!=="text"&&!a.variadic)return l("internal.redunant-arguments")}if(r.config.checkUnknown){let d=Object.keys(n).filter(a=>!r._options[a]);if(d.length)return l("internal.unknown-option",d.join(", "))}})}h(le,"validate");var G=class{constructor(e,t={}){this.ctx=e;this.config=t;Qe(this,y.current,e),e.plugin(ae),e.plugin(le)}_commandList=[];_commands=new Map;_shortcuts=[];get caller(){return this[y.current]}resolve(e){if(!e)return;let t=e.split("."),n=1,r=t[0],i;for(;(i=this.getCommand(r))&&n<t.length;)r=i.name+"."+t[n++];return i}getCommand(e){return this._commands.get(e)}command(e,...t){let n=typeof t[0]=="string"?t.shift():"",r=t[0],i=e.split(" ",1)[0].toLowerCase(),l=e.slice(i.length),d=i.split(/(?=[./])/g),a,p,g=[];if(d.forEach((T,I)=>{let F=T.charCodeAt(0),E=F===46?a.name+T:F===47?T.slice(1):T,o=this.getCommand(E);if(o){if(a){if(o===a)throw new Error(`cannot set a command (${o.name}) as its own subcommand`);if(o.parent){if(o.parent!==a)throw new Error(`cannot create subcommand ${i}: ${o.parent.name}/${o.name} already exists`)}else o.parent=a,a.children.push(o)}return a=o}o=new K(E,l,this.caller),g.push(o),p||(p=o),a&&(o.parent=a,o.config.authority=a.config.authority,a.children.push(o)),a=o}),n&&this.caller.i18n.define("",`commands.${a.name}.description`,n),Object.assign(a.config,r),g.forEach(T=>this.caller.emit("command-added",T)),!r?.patch)return p&&this.caller.state.disposables.unshift(()=>p.dispose()),a;p&&p.dispose();let _=Object.create(a);return _._disposables=this.caller.state.disposables,_}};h(G,"Commander"),U(G,"key","$commander"),U(G,"methods",["command"]);y.service(G.key,G);var de=new Xe("session"),V=class extends X.Session{argv;user;channel;guild;parsed;scope;_promise;_queuedTasks;_queuedTimeout;constructor(e,t){super(e,t),N(this,"scope",null),N(this,"user",null),N(this,"channel",null),N(this,"guild",null),N(this,"_queuedTasks",[]),N(this,"_queuedTimeout",null)}async _preprocess(){let e,t=this.content.trim();return(e=X.segment.from(t,{type:"quote",caret:!0}))&&(t=t.slice(e.capture[0].length).trimStart(),this.quote=await this.bot.getMessage(e.data.channelId||this.channelId,e.data.id).catch(n=>{de.warn(n)})),t}async preprocess(){return this._promise||=this._preprocess()}get username(){let e=this.user&&this.user.name?this.user.name:this.author?this.author.nickname||this.author.username:this.userId;return this.app.chain("appellation",e,this)}async send(e){if(!!e)return this.bot.sendMessage(this.channelId,e,this.guildId).catch(t=>(de.warn(t),[]))}cancelQueued(e=this.app.options.delay.cancel){clearTimeout(this._queuedTimeout),this._queuedTasks=[],this._queuedTimeout=setTimeout(()=>this._next(),e)}_next(){let e=this._queuedTasks.shift();if(!e){this._queuedTimeout=null;return}this.send(e.content).then(e.resolve,e.reject),this._queuedTimeout=setTimeout(()=>this._next(),e.delay)}async sendQueued(e,t){if(!!e){if(Ve(t)){let{message:n,character:r}=this.app.options.delay;t=Math.max(n,r*e.length)}return new Promise((n,r)=>{this._queuedTasks.push({content:e,delay:t,resolve:n,reject:r}),this._queuedTimeout||this._next()})}}resolveValue(e){return typeof e=="function"?Reflect.apply(e,null,[this]):e}async getChannel(e=this.channelId,t=[]){let{app:n,platform:r,guildId:i}=this;if(!t.length)return{platform:r,id:e,guildId:i};let l=await n.database.getChannel(r,e,t);if(l)return l;let d=await this.resolveValue(n.options.autoAssign)?this.selfId:"";if(d)return n.database.createChannel(r,e,{assignee:d,guildId:i});{let a=n.model.tables.channel.create();return Object.assign(a,{platform:r,id:e,guildId:i,$detached:!0}),a}}async _observeChannelLike(e,t=[]){let n=new Set(t),{platform:r}=this,i=`${r}:${e}`,l=this.app.$internal._channelCache.get(this.id,i);if(l){for(let a in l)n.delete(a);if(!n.size)return l}let d=await this.getChannel(e,[...n]);return l=this.app.$internal._channelCache.get(this.id,i),l?l.$merge(d):(l=ce(d,a=>this.app.database.setChannel(r,e,a),`channel ${i}`),this.app.$internal._channelCache.set(this.id,i,l)),l}async observeChannel(e=[]){let t=[this._observeChannelLike(this.channelId,e)];this.channelId!==this.guildId&&t.push(this._observeChannelLike(this.guildId,e));let[n,r=n]=await Promise.all(t);return this.guild=r,this.channel=n,n}async getUser(e=this.userId,t=[]){let{app:n,platform:r}=this;if(!t.length)return{[r]:e};let i=await n.database.getUser(r,e,t);if(i)return i;let l=await this.resolveValue(n.options.autoAuthorize);if(l)return n.database.createUser(r,e,{authority:l});{let d=n.model.tables.user.create();return Object.assign(d,{[r]:e,authority:l,$detached:!0}),d}}async observeUser(e=[]){let t=new Set(e),{userId:n,platform:r}=this,i=this.app.$internal._userCache.get(this.id,this.uid);if(i){for(let d in i)t.delete(d);if(!t.size)return this.user=i}if(this.author?.anonymous){let d=this.app.model.tables.user.create();d[r]=n,d.authority=await this.resolveValue(this.app.options.autoAuthorize);let a=ce(d,()=>Promise.resolve());return this.user=a}let l=await this.getUser(n,[...t]);return i=this.app.$internal._userCache.get(this.id,this.uid),i?i.$merge(l):(i=ce(l,d=>this.app.database.setUser(this.platform,n,d),`user ${this.uid}`),this.app.$internal._userCache.set(this.id,this.uid,i)),this.user=i}async withScope(e,t){let n=this.scope;try{return this.scope=e,await t()}finally{this.scope=n}}text(e,t={}){let n=[this.app.options.locale];n.unshift(this.user?.locale),this.subtype==="group"&&(n.unshift(this.guild?.locale),n.unshift(this.channel?.locale));let r=Ye(e).map(i=>i.startsWith(".")?this.scope?this.scope+i:(this.app.logger("i18n").warn(new Error("missing scope")),""):i);return this.app.i18n.text(n,r,t)}collect(e,t,n=new Set){let r=h(i=>{if(i.session=this,i.tokens)for(let{inters:l}of i.tokens)l.forEach(r);!this.resolve(i)||(this.app.emit(i.session,`command/before-attach-${e}`,i,n),we(i,K[`_${e}Fields`],n),we(i,i.command[`_${e}Fields`],n))},"collect");return r(t),n}inferCommand(e){if(e.command)return e.command;if(e.name)return e.command=this.app.$commander.resolve(e.name);let{parsed:t,subtype:n}=this;if(e.root&&n!=="private"&&t.prefix===null&&!t.appel||!e.tokens.length)return;let r=this.app.$commander.resolve(e.tokens[0].content);if(r)return e.tokens.shift(),e.command=r}resolve(e){if(!!this.inferCommand(e)){if(e.tokens?.every(t=>!t.inters.length)){let{options:t,args:n,error:r}=e.command.parse(e);e.options={...e.options,...t},e.args=[...e.args||[],...n],e.error=r}return e.command}}async execute(e,t){if(typeof e=="string"&&(e=R.parse(e)),e.session=this,e.tokens){for(let i of e.tokens){let{inters:l}=i,d=[];for(let a=0;a<l.length;++a)d.push(await this.execute(l[a],!0));for(let a=l.length-1;a>=0;--a){let{pos:p}=l[a];i.content=i.content.slice(0,p)+d[a]+i.content.slice(p)}i.inters=[]}if(!this.resolve(e))return""}else if(e.command||=this.app.$commander.getCommand(e.name),!e.command)return de.warn(new Error(`cannot find command ${e.name}`)),"";let{command:n}=e;if(!n.ctx.filter(this))return"";this.app.database&&(this.subtype==="group"&&await this.observeChannel(this.collect("channel",e)),await this.observeUser(this.collect("user",e)));let r=!0;return t===!0&&(r=!1,t=void 0),this.withScope(`commands.${n.name}.messages`,async()=>{let i=await n.execute(e,t);return r?(await this.send(i),""):i})}middleware(e){let t=ve(this);return this.app.middleware(async(n,r)=>t&&ve(n)!==t?r():e(n,r),!0)}prompt(e=this.app.options.delay.prompt){return new Promise(t=>{let n=this.middleware(i=>{clearTimeout(r),n(),t(i.content)}),r=setTimeout(()=>{n(),t("")},e)})}};h(V,"Session");function ve(m){return""+m.userId+m.channelId}h(ve,"getSessionId");function we(m,e,t){for(let n of e){if(typeof n=="function"){n(m,t);continue}for(let r of n)t.add(r)}return t}h(we,"collectFields");import*as _e from"@satorijs/core";import{Adapter as Cn,h as vn,Message as wn,segment as _n}from"@satorijs/core";var pe=_e.Bot;pe.prototype.session=h(function(e){return new V(this,e)},"session");pe.prototype.getGuildMemberMap=h(async function(e){let t=await this.getGuildMemberList(e);return Object.fromEntries(t.map(n=>[n.userId,n.nickname||n.username]))},"getGuildMemberMap");pe.prototype.broadcast=h(async function(e,t,n=this.ctx.options.delay.broadcast){let r=[];for(let i=0;i<e.length;i++){i&&n&&await Ze(n);try{let[l,d]=Je(e[i]);r.push(...await this.sendMessage(l,t,d))}catch(l){this.ctx.logger("bot").warn(l)}}return r},"broadcast");import{isNullable as Se,Logger as st,Random as ot,Time as ue}from"@koishijs/utils";var Oe=new st("i18n"),De=Symbol("template"),Y=class{_data={};_formatters={};_presets={};constructor(e){this.define("",{"":""}),this.define("zh",Te()),this.define("en",Ae()),this.define("ja",ke()),this.define("fr",Ee()),this.define("zh-tw",$e()),this.registerBuiltins()}set(e,t,n){if(t.includes("@")||typeof n=="string"){let r=this._data[e],[i,l]=t.slice(0,-1).split("@");l&&(n[De]=l),!Se(r[i])&&!e.startsWith("$")&&Oe.warn("override",e,i),r[i]=n,this[y.current]?.on("dispose",()=>{delete r[i]})}else for(let r in n)this.set(e,t+r+".",n[r])}define(e,...t){this._data[e]||={},typeof t[0]=="string"?this.set(e,t[0]+".",t[1]):this.set(e,"",t[0])}formatter(e,t){this._formatters[e]=t}preset(e,t){this._presets[e]=t}render(e,t,n){if(e!==void 0){if(typeof e!="string"){let r=e[De],i=this._presets[r];if(!i)throw new Error(`Preset "${r}" not found`);return i(e,t,n)}return e.replace(/\{(.+?)\}/g,(r,i)=>{let[l,...d]=i.split("|"),a=l.trim().split("."),p=t;for(let g of a)if(p=p[g],Se(p))return"";for(let g of d){let _=g.trim().match(/(\w+)(?:\((.+)\))?/),T=this._formatters[_[1]];if(!T)throw new Error(`Formatter "${_[1]}" not found`);let I=_[2]?_[2].split(",").map(F=>F.trim()):[];p=T(p,I,n)}return p.toString()})}}text(e,t,n){let r=new Set;for(let i of e)!i||r.add(i);for(let i in this._data)i.startsWith("$")||r.add(i);for(let i of t)for(let l of r)for(let d of["$"+l,l]){let a=this._data[d]?.[i];if(a!==void 0)return this.render(a,n,l)}return Oe.warn("missing",t[0]),t[0]}registerBuiltins(){let e=["day","hour","minute","second"];this.formatter("time",(t,n,r)=>{for(let i=0;i<3;i++){let l=ue[e[i]],d=ue[e[i+1]];if(t>=l-d/2){t+=d/2;let a=Math.floor(t/l)+" "+this.text([r],["general."+e[i]],{});return t%l>d&&(a+=` ${Math.floor(t%l/d)} `+this.text([r],["general."+e[i+1]],{})),a}}return Math.round(t/ue.second)+" "+this.text([r],["general.second"],{})}),this.preset("plural",(t,n,r)=>{let i=n.length in t?n.length:t.length-1;return this.render(t[i],n,r)}),this.preset("random",(t,n,r)=>this.render(ot.pick(t),n,r)),this.preset("list",(t,n,r)=>{let i=Object.entries(n).map(([l,d])=>this.render(t.item,{key:l,value:d},r));return i.unshift(this.render(t.header,n,r)),i.push(this.render(t.footer,n,r)),i.join(`
${g}`),this.ctx.emit(e.session,"command-error",e,p)}return""}dispose(){this._disposed=!0,this.ctx.emit("command-removed",this);for(let e of this.children.slice())e.dispose();this.ctx.$commander._shortcuts=this.ctx.$commander._shortcuts.filter(e=>e.command!==this),this._aliases.forEach(e=>this.ctx.$commander._commands.delete(e)),j(this.ctx.$commander._commandList,this),this.parent&&j(this.parent.children,this)}},K=oe;h(K,"Command"),U(K,"defaultConfig",{authority:1,showWarning:!0}),U(K,"defaultOptionConfig",{authority:0}),U(K,"_userFields",[]),U(K,"_channelFields",[]);(e=>e.Config=Q.object({authority:Q.natural().default(1),hidden:Q.boolean().default(!1),checkArgCount:Q.boolean().default(!1),checkUnknown:Q.boolean().default(!1)}))(K||={});import{defineProperty as We,valueMap as He}from"@koishijs/utils";function ae(m){m.before("parse",(t,n)=>{let r=R.parse(t);return n.quote&&r.tokens.push({content:n.quote.content,quoted:!0,inters:[],terminator:""}),r}),m.before("parse",(t,n)=>{let{parsed:r,quote:i}=n;if(!(r.prefix||i))for(let l of m.$commander._shortcuts){let{name:d,fuzzy:a,command:p,prefix:g,options:_={},args:T=[]}=l;if(!(g&&!r.appel||!p.ctx.filter(n)))if(typeof d=="string"){if(!a&&t!==d||!t.startsWith(d))continue;let I=t.slice(d.length);if(a&&!r.appel&&I.match(/^\S/))continue;let F=R.parse(I.trim());return F.session=n,F=p.parse(F,"",[...T],{..._}),F.command=p,F}else{let F=function(E){return typeof E!="string"?E:(E=E.replace(/\$\$/g,"@@__PLACEHOLDER__@@"),I.forEach((o,s)=>{!s||s>9||(E=E.replace(new RegExp(`\\$${s}`,"g"),(o||"").replace(/\$/g,"@@__PLACEHOLDER__@@")))}),E.replace(/@@__PLACEHOLDER__@@/g,"$"))};h(F,"escape");let I=d.exec(t);if(!I)continue;return{command:p,args:T.map(F),options:He(_,F)}}}}),m.before("attach",t=>{We(t,"argv",m.bail("before-parse",t.parsed.content,t)),t.argv.root=!0,t.argv.session=t});function e(t,n){if(!!m.$commander.getCommand("help"))return t.execute({name:"help",args:[n]})}h(e,"executeHelp"),m.before("command/execute",t=>{let{args:n,command:r,options:i,session:l}=t;if(i.help&&r._options.help)return e(l,r.name);if(r._actions.length)return;let d=n.shift()||"",a=m.$commander.getCommand(r.name+"."+d);if(a){let p=l.__redirected_commands||=[`(${r.name}${r._aliases.length!==0?"|"+r._aliases.join("|"):""})`];p.push(d);let g=new RegExp(`^${p.join("[. ]")}( |$)`);return t=R.parse(l.parsed.content.replace(g,"")),t.session=l,t=a.parse(t),l.execute({...t,command:a})}else return e(l,r.name)})}h(ae,"runtime");function le(m){m.on("command-added",e=>{e.userFields(({tokens:t,command:n,options:r={}},i)=>{if(!n)return;let{authority:l}=n.config,d=l>0;for(let{name:a,authority:p}of Object.values(n._options))a in r?p>0&&(d=!0):t&&p>0&&(d=!0);d&&i.add("authority")})}),m.before("command/execute",e=>{let{session:t,options:n,command:r}=e;if(!t.user)return;function i(l,...d){return r.config.showWarning?t.text(l,d):""}if(h(i,"sendHint"),typeof t.user.authority=="number"&&r.getConfig("authority",t)>t.user.authority)return i("internal.low-authority");for(let l of Object.values(r._options))if(l.name in n&&l.authority>t.user.authority)return i("internal.low-authority")}),m.before("command/execute",e=>{let{args:t,options:n,command:r,session:i}=e;function l(d,...a){return r.config.showWarning?i.text(d,a):""}if(h(l,"sendHint"),r.config.checkArgCount){if((r._arguments[t.length]||{}).required)return l("internal.insufficient-arguments");let a=r._arguments[r._arguments.length-1]||{};if(t.length>r._arguments.length&&a.type!=="text"&&!a.variadic)return l("internal.redunant-arguments")}if(r.config.checkUnknown){let d=Object.keys(n).filter(a=>!r._options[a]);if(d.length)return l("internal.unknown-option",d.join(", "))}})}h(le,"validate");var G=class{constructor(e,t={}){this.ctx=e;this.config=t;Qe(this,y.current,e),e.plugin(ae),e.plugin(le)}_commandList=[];_commands=new Map;_shortcuts=[];get caller(){return this[y.current]}resolve(e){if(!e)return;let t=e.split("."),n=1,r=t[0],i;for(;(i=this.getCommand(r))&&n<t.length;)r=i.name+"."+t[n++];return i}getCommand(e){return this._commands.get(e)}command(e,...t){let n=typeof t[0]=="string"?t.shift():"",r=t[0],i=e.split(" ",1)[0].toLowerCase(),l=e.slice(i.length),d=i.split(/(?=[./])/g),a,p,g=[];if(d.forEach((T,I)=>{let F=T.charCodeAt(0),E=F===46?a.name+T:F===47?T.slice(1):T,o=this.getCommand(E);if(o){if(a){if(o===a)throw new Error(`cannot set a command (${o.name}) as its own subcommand`);if(o.parent){if(o.parent!==a)throw new Error(`cannot create subcommand ${i}: ${o.parent.name}/${o.name} already exists`)}else o.parent=a,a.children.push(o)}return a=o}o=new K(E,l,this.caller),g.push(o),p||(p=o),a&&(o.parent=a,o.config.authority=a.config.authority,a.children.push(o)),a=o}),n&&this.caller.i18n.define("",`commands.${a.name}.description`,n),Object.assign(a.config,r),g.forEach(T=>this.caller.emit("command-added",T)),!r?.patch)return p&&this.caller.state.disposables.unshift(()=>p.dispose()),a;p&&p.dispose();let _=Object.create(a);return _._disposables=this.caller.state.disposables,_}};h(G,"Commander"),U(G,"key","$commander"),U(G,"methods",["command"]);y.service(G.key,G);var de=new Xe("session"),V=class extends X.Session{argv;user;channel;guild;parsed;scope;_promise;_queuedTasks;_queuedTimeout;constructor(e,t){super(e,t),N(this,"scope",null),N(this,"user",null),N(this,"channel",null),N(this,"guild",null),N(this,"_queuedTasks",[]),N(this,"_queuedTimeout",null)}async _preprocess(){let e,t=this.content.trim();return(e=X.segment.from(t,{type:"quote",caret:!0}))&&(t=t.slice(e.capture[0].length).trimStart(),this.quote=await this.bot.getMessage(e.data.channelId||this.channelId,e.data.id).catch(n=>{de.warn(n)})),t}async preprocess(){return this._promise||=this._preprocess()}get username(){let e=this.user&&this.user.name?this.user.name:this.author?this.author.nickname||this.author.username:this.userId;return this.app.chain("appellation",e,this)}async send(e){if(!!e)return this.bot.sendMessage(this.channelId,e,this.guildId).catch(t=>(de.warn(t),[]))}cancelQueued(e=this.app.options.delay.cancel){clearTimeout(this._queuedTimeout),this._queuedTasks=[],this._queuedTimeout=setTimeout(()=>this._next(),e)}_next(){let e=this._queuedTasks.shift();if(!e){this._queuedTimeout=null;return}this.send(e.content).then(e.resolve,e.reject),this._queuedTimeout=setTimeout(()=>this._next(),e.delay)}async sendQueued(e,t){if(!!e){if(Ve(t)){let{message:n,character:r}=this.app.options.delay;t=Math.max(n,r*e.length)}return new Promise((n,r)=>{this._queuedTasks.push({content:e,delay:t,resolve:n,reject:r}),this._queuedTimeout||this._next()})}}resolveValue(e){return typeof e=="function"?Reflect.apply(e,null,[this]):e}async getChannel(e=this.channelId,t=[]){let{app:n,platform:r,guildId:i}=this;if(!t.length)return{platform:r,id:e,guildId:i};let l=await n.database.getChannel(r,e,t);if(l)return l;let d=await this.resolveValue(n.options.autoAssign)?this.selfId:"";if(d)return n.database.createChannel(r,e,{assignee:d,guildId:i});{let a=n.model.tables.channel.create();return Object.assign(a,{platform:r,id:e,guildId:i,$detached:!0}),a}}async _observeChannelLike(e,t=[]){let n=new Set(t),{platform:r}=this,i=`${r}:${e}`,l=this.app.$internal._channelCache.get(this.id,i);if(l){for(let a in l)n.delete(a);if(!n.size)return l}let d=await this.getChannel(e,[...n]);return l=this.app.$internal._channelCache.get(this.id,i),l?l.$merge(d):(l=ce(d,a=>this.app.database.setChannel(r,e,a),`channel ${i}`),this.app.$internal._channelCache.set(this.id,i,l)),l}async observeChannel(e=[]){let t=[this._observeChannelLike(this.channelId,e)];this.channelId!==this.guildId&&t.push(this._observeChannelLike(this.guildId,e));let[n,r=n]=await Promise.all(t);return this.guild=r,this.channel=n,n}async getUser(e=this.userId,t=[]){let{app:n,platform:r}=this;if(!t.length)return{[r]:e};let i=await n.database.getUser(r,e,t);if(i)return i;let l=await this.resolveValue(n.options.autoAuthorize);if(l)return n.database.createUser(r,e,{authority:l});{let d=n.model.tables.user.create();return Object.assign(d,{[r]:e,authority:l,$detached:!0}),d}}async observeUser(e=[]){let t=new Set(e),{userId:n,platform:r}=this,i=this.app.$internal._userCache.get(this.id,this.uid);if(i){for(let d in i)t.delete(d);if(!t.size)return this.user=i}if(this.author?.anonymous){let d=this.app.model.tables.user.create();d[r]=n,d.authority=await this.resolveValue(this.app.options.autoAuthorize);let a=ce(d,()=>Promise.resolve());return this.user=a}let l=await this.getUser(n,[...t]);return i=this.app.$internal._userCache.get(this.id,this.uid),i?i.$merge(l):(i=ce(l,d=>this.app.database.setUser(this.platform,n,d),`user ${this.uid}`),this.app.$internal._userCache.set(this.id,this.uid,i)),this.user=i}async withScope(e,t){let n=this.scope;try{return this.scope=e,await t()}finally{this.scope=n}}text(e,t={}){let n=[this.app.options.locale];n.unshift(this.user?.locale),this.subtype==="group"&&(n.unshift(this.guild?.locale),n.unshift(this.channel?.locale));let r=Ye(e).map(i=>i.startsWith(".")?this.scope?this.scope+i:(this.app.logger("i18n").warn(new Error("missing scope")),""):i);return this.app.i18n.text(n,r,t)}collect(e,t,n=new Set){let r=h(i=>{if(i.session=this,i.tokens)for(let{inters:l}of i.tokens)l.forEach(r);!this.resolve(i)||(this.app.emit(i.session,`command/before-attach-${e}`,i,n),we(i,K[`_${e}Fields`],n),we(i,i.command[`_${e}Fields`],n))},"collect");return r(t),n}inferCommand(e){if(e.command)return e.command;if(e.name)return e.command=this.app.$commander.resolve(e.name);let{parsed:t,subtype:n}=this;if(e.root&&n!=="private"&&t.prefix===null&&!t.appel||!e.tokens.length)return;let r=this.app.$commander.resolve(e.tokens[0].content);if(r)return e.tokens.shift(),e.command=r}resolve(e){if(!!this.inferCommand(e)){if(e.tokens?.every(t=>!t.inters.length)){let{options:t,args:n,error:r}=e.command.parse(e);e.options={...e.options,...t},e.args=[...e.args||[],...n],e.error=r}return e.command}}async execute(e,t){if(typeof e=="string"&&(e=R.parse(e)),e.session=this,e.tokens){for(let i of e.tokens){let{inters:l}=i,d=[];for(let a=0;a<l.length;++a)d.push(await this.execute(l[a],!0));for(let a=l.length-1;a>=0;--a){let{pos:p}=l[a];i.content=i.content.slice(0,p)+d[a]+i.content.slice(p)}i.inters=[]}if(!this.resolve(e))return""}else if(e.command||=this.app.$commander.getCommand(e.name),!e.command)return de.warn(new Error(`cannot find command ${e.name}`)),"";let{command:n}=e;if(!n.ctx.filter(this))return"";this.app.database&&(this.subtype==="group"&&await this.observeChannel(this.collect("channel",e)),await this.observeUser(this.collect("user",e)));let r=!0;return t===!0&&(r=!1,t=void 0),this.withScope(`commands.${n.name}.messages`,async()=>{let i=await n.execute(e,t);return r?(await this.send(i),""):i})}middleware(e){let t=ve(this);return this.app.middleware(async(n,r)=>t&&ve(n)!==t?r():e(n,r),!0)}prompt(e=this.app.options.delay.prompt){return new Promise(t=>{let n=this.middleware(i=>{clearTimeout(r),n(),t(i.content)}),r=setTimeout(()=>{n(),t("")},e)})}};h(V,"Session");function ve(m){return""+m.userId+m.channelId}h(ve,"getSessionId");function we(m,e,t){for(let n of e){if(typeof n=="function"){n(m,t);continue}for(let r of n)t.add(r)}return t}h(we,"collectFields");import*as _e from"@satorijs/core";import{Adapter as Cn,h as vn,Message as wn,segment as _n}from"@satorijs/core";var pe=_e.Bot;pe.prototype.session=h(function(e){return new V(this,e)},"session");pe.prototype.getGuildMemberMap=h(async function(e){let t=await this.getGuildMemberList(e);return Object.fromEntries(t.map(n=>[n.userId,n.nickname||n.username]))},"getGuildMemberMap");pe.prototype.broadcast=h(async function(e,t,n=this.ctx.options.delay.broadcast){let r=[];for(let i=0;i<e.length;i++){i&&n&&await Ze(n);try{let[l,d]=Je(e[i]);r.push(...await this.sendMessage(l,t,d))}catch(l){this.ctx.logger("bot").warn(l)}}return r},"broadcast");import{isNullable as Se,Logger as st,Random as ot,Time as ue}from"@koishijs/utils";var Oe=new st("i18n"),De=Symbol("template"),Y=class{_data={};_formatters={};_presets={};constructor(e){this.define("",{"":""}),this.define("zh",Te()),this.define("en",Ae()),this.define("ja",ke()),this.define("fr",Ee()),this.define("zh-tw",$e()),this.registerBuiltins()}set(e,t,n){if(t.includes("@")||typeof n=="string"){let r=this._data[e],[i,l]=t.slice(0,-1).split("@");l&&(n[De]=l),!Se(r[i])&&!e.startsWith("$")&&Oe.warn("override",e,i),r[i]=n,this[y.current]?.on("dispose",()=>{delete r[i]})}else for(let r in n)this.set(e,t+r+".",n[r])}define(e,...t){this._data[e]||={},typeof t[0]=="string"?this.set(e,t[0]+".",t[1]):this.set(e,"",t[0])}formatter(e,t){this._formatters[e]=t}preset(e,t){this._presets[e]=t}render(e,t,n){if(e!==void 0){if(typeof e!="string"){let r=e[De],i=this._presets[r];if(!i)throw new Error(`Preset "${r}" not found`);return i(e,t,n)}return e.replace(/\{(.+?)\}/g,(r,i)=>{let[l,...d]=i.split("|"),a=l.trim().split("."),p=t;for(let g of a)if(p=p[g],Se(p))return"";for(let g of d){let _=g.trim().match(/(\w+)(?:\((.+)\))?/),T=this._formatters[_[1]];if(!T)throw new Error(`Formatter "${_[1]}" not found`);let I=_[2]?_[2].split(",").map(F=>F.trim()):[];p=T(p,I,n)}return p.toString()})}}text(e,t,n){let r=new Set;for(let i of e)!i||r.add(i);for(let i in this._data)i.startsWith("$")||r.add(i);for(let i of t)for(let l of r)for(let d of["$"+l,l]){let a=this._data[d]?.[i];if(a!==void 0)return this.render(a,n,l)}return Oe.warn("missing",t[0]),t[0]}registerBuiltins(){let e=["day","hour","minute","second"];this.formatter("time",(t,n,r)=>{for(let i=0;i<3;i++){let l=ue[e[i]],d=ue[e[i+1]];if(t>=l-d/2){t+=d/2;let a=Math.floor(t/l)+" "+this.text([r],["general."+e[i]],{});return t%l>d&&(a+=` ${Math.floor(t%l/d)} `+this.text([r],["general."+e[i+1]],{})),a}}return Math.round(t/ue.second)+" "+this.text([r],["general.second"],{})}),this.preset("plural",(t,n,r)=>{let i=n.length in t?n.length:t.length-1;return this.render(t[i],n,r)}),this.preset("random",(t,n,r)=>this.render(ot.pick(t),n,r)),this.preset("list",(t,n,r)=>{let i=Object.entries(n).map(([l,d])=>this.render(t.item,{key:l,value:d},r));return i.unshift(this.render(t.header,n,r)),i.push(this.render(t.footer,n,r)),i.join(`
`).trim()})}};h(Y,"I18n");y.service("i18n",Y);var Kn=Fe().version;export{Cn as Adapter,y as App,R as Argv,pe as Bot,ie as Channel,K as Command,G as Commander,y as Context,L as DatabaseService,ft as Disposable,Y as I18n,W as Internal,wn as Message,M as Next,z as SelectorService,pt as Service,V as Session,H as SharedCache,re as User,ut as defineConfig,Ut as defineDriver,ve as getSessionId,vn as h,_n as segment,Kn as version};
{
"name": "@koishijs/core",
"description": "Core Features for Koishi",
"version": "4.8.2",
"version": "4.8.3",
"main": "lib/node.js",

@@ -34,3 +34,3 @@ "module": "lib/browser.js",

"@koishijs/utils": "^6.0.0",
"@satorijs/core": "^1.0.4",
"@satorijs/core": "^1.0.6",
"cordis": "^2.0.6",

@@ -37,0 +37,0 @@ "fastest-levenshtein": "^1.0.12",

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc