mirror of
https://github.com/sern-handler/handler
synced 2026-06-18 13:52:15 +00:00
Compare commits
103 Commits
feat/error
...
v3.0.0-rc1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
adb3d4f402 | ||
|
|
4d1e6f2a71 | ||
|
|
63e0daac16 | ||
|
|
49fb1453a5 | ||
|
|
a6db21c720 | ||
|
|
fc6206a205 | ||
|
|
d7195c45b3 | ||
|
|
698d468acb | ||
|
|
5d842fd5e7 | ||
|
|
b6ef27df88 | ||
|
|
ea78a98f69 | ||
|
|
08e358b32d | ||
|
|
47f58a9efa | ||
|
|
b8619df838 | ||
|
|
e4a9c8d551 | ||
|
|
59a13765a5 | ||
|
|
f2b53dac32 | ||
|
|
8f39fc0896 | ||
|
|
423b0d2aa7 | ||
|
|
b2ab99b7cc | ||
|
|
b06e457caa | ||
|
|
6fd9f8f032 | ||
|
|
3ed6d84727 | ||
|
|
95ec4d0e3c | ||
|
|
5e878cc97b | ||
|
|
57dfa09a73 | ||
|
|
0256a38187 | ||
|
|
e6f3a55d73 | ||
|
|
7ff8917a26 | ||
|
|
8a537d670b | ||
|
|
cd1568ff69 | ||
|
|
9718360530 | ||
|
|
6bd7573b88 | ||
|
|
993c41f37e | ||
|
|
17423b683e | ||
|
|
8d507d0520 | ||
|
|
8dacfafbac | ||
|
|
98de65965e | ||
|
|
e411f81ab9 | ||
|
|
f6e41cc9b6 | ||
|
|
9f5d2faa61 | ||
|
|
815cbf19eb | ||
|
|
4ff2f39fcf | ||
|
|
87585dcc69 | ||
|
|
8c28e00206 | ||
|
|
bf6b99ff03 | ||
|
|
9f213e9e8c | ||
|
|
4794c2655d | ||
|
|
43181bf916 | ||
|
|
8e9b3bbe04 | ||
|
|
098a440669 | ||
|
|
1e1398fade | ||
|
|
1fea6fa136 | ||
|
|
ff478123a8 | ||
|
|
29499457bb | ||
|
|
084b5adb5c | ||
|
|
397857208e | ||
|
|
ed532af7f7 | ||
|
|
6628fa7074 | ||
|
|
3d0cf62b9a | ||
|
|
8e6061b4f2 | ||
|
|
e644b184f2 | ||
|
|
dbfd8cfe40 | ||
|
|
b0f6093ac6 | ||
|
|
1288a6b5cc | ||
|
|
7f53521ef4 | ||
|
|
faa0b4882e | ||
|
|
e2fd44516a | ||
|
|
4125508cd3 | ||
|
|
2ecf3e5a5c | ||
|
|
d53b315157 | ||
|
|
b7e99a85a6 | ||
|
|
aacf47efab | ||
|
|
cae1f648f0 | ||
|
|
b7a13d6558 | ||
|
|
de654532e8 | ||
|
|
a5e8743afd | ||
|
|
3a8098e523 | ||
|
|
21a20523b8 | ||
|
|
52b186cc44 | ||
|
|
a17be67b48 | ||
|
|
6a65dac272 | ||
|
|
7f59f81b35 | ||
|
|
e6f9207a47 | ||
|
|
fa4e6c7fbd | ||
|
|
d41cc9ea2d | ||
|
|
97ad338830 | ||
|
|
dcdf120ba7 | ||
|
|
1fa7eef336 | ||
|
|
37ddef170f | ||
|
|
195c155769 | ||
|
|
458a0b978f | ||
|
|
bc4802f261 | ||
|
|
8e2ba871c4 | ||
|
|
83f6568d84 | ||
|
|
f02bbbf54e | ||
|
|
89bb50794b | ||
|
|
1a4e046f50 | ||
|
|
09e57c73ac | ||
|
|
457cb25cb2 | ||
|
|
b40f8905ea | ||
|
|
8bdb6d8216 | ||
|
|
58b3d85da8 |
1
.github/FUNDING.yml
vendored
1
.github/FUNDING.yml
vendored
@@ -1 +0,0 @@
|
|||||||
open_collective: sern
|
|
||||||
39
.github/workflows/codeql-analysis.yml
vendored
Normal file
39
.github/workflows/codeql-analysis.yml
vendored
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
name: "CodeQL"
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [ main ]
|
||||||
|
paths: ["src/**/*"]
|
||||||
|
pull_request:
|
||||||
|
branches: [ main ]
|
||||||
|
paths: ["src/**/*"]
|
||||||
|
schedule:
|
||||||
|
- cron: '37 20 * * 4'
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
analyze:
|
||||||
|
name: Analyze
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
actions: read
|
||||||
|
contents: read
|
||||||
|
security-events: write
|
||||||
|
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
language: [ 'javascript' ]
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v3
|
||||||
|
|
||||||
|
- name: Initialize CodeQL
|
||||||
|
uses: github/codeql-action/init@v2
|
||||||
|
with:
|
||||||
|
languages: ${{ matrix.language }}
|
||||||
|
- name: Autobuild
|
||||||
|
uses: github/codeql-action/autobuild@v2
|
||||||
|
|
||||||
|
- name: Perform CodeQL Analysis
|
||||||
|
uses: github/codeql-action/analyze@v2
|
||||||
4
.github/workflows/continuous-integration.yml
vendored
4
.github/workflows/continuous-integration.yml
vendored
@@ -20,7 +20,7 @@ jobs:
|
|||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Check out Git repository
|
- name: Check out Git repository
|
||||||
uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3
|
uses: actions/checkout@8f4b7f84864484a7bf31766abe9204da3cbe65b3 # v3
|
||||||
|
|
||||||
- name: Set up Node.js
|
- name: Set up Node.js
|
||||||
uses: actions/setup-node@64ed1c7eab4cce3362f8c340dee64e5eaeef8f7c # v3
|
uses: actions/setup-node@64ed1c7eab4cce3362f8c340dee64e5eaeef8f7c # v3
|
||||||
@@ -39,7 +39,7 @@ jobs:
|
|||||||
|
|
||||||
- name: Create Pull Request
|
- name: Create Pull Request
|
||||||
id: cpr
|
id: cpr
|
||||||
uses: peter-evans/create-pull-request@38e0b6e68b4c852a5500a94740f0e535e0d7ba54 # v4
|
uses: peter-evans/create-pull-request@v4
|
||||||
with:
|
with:
|
||||||
commit-message: "style: pretty please"
|
commit-message: "style: pretty please"
|
||||||
branch: prettier
|
branch: prettier
|
||||||
|
|||||||
4
.github/workflows/dependency-review.yml
vendored
4
.github/workflows/dependency-review.yml
vendored
@@ -15,6 +15,6 @@ jobs:
|
|||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: 'Checkout Repository'
|
- name: 'Checkout Repository'
|
||||||
uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3
|
uses: actions/checkout@v3
|
||||||
- name: 'Dependency Review'
|
- name: 'Dependency Review'
|
||||||
uses: actions/dependency-review-action@0efb1d1d84fc9633afcdaad14c485cbbc90ef46c # v2
|
uses: actions/dependency-review-action@v2
|
||||||
|
|||||||
10
.github/workflows/npm-publish.yml
vendored
10
.github/workflows/npm-publish.yml
vendored
@@ -2,21 +2,17 @@ name: NPM / Publish
|
|||||||
|
|
||||||
on:
|
on:
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
# We only publish if the version of sern handler is different. workflow automatically cancels if verson is the same
|
|
||||||
push:
|
|
||||||
branches:
|
|
||||||
- 'main'
|
|
||||||
jobs:
|
jobs:
|
||||||
test-and-publish:
|
test-and-publish:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3
|
- uses: actions/checkout@v3
|
||||||
- uses: actions/setup-node@5e21ff4d9bc1a8cf6de233a3057d20ec6b3fb69d # v3
|
- uses: actions/setup-node@v3
|
||||||
with:
|
with:
|
||||||
node-version: 17
|
node-version: 17
|
||||||
- run: yarn --immutable
|
- run: yarn --immutable
|
||||||
- run: yarn build:prod
|
- run: yarn build:prod
|
||||||
- uses: JS-DevTools/npm-publish@0f451a94170d1699fd50710966d48fb26194d939 # v1
|
- uses: JS-DevTools/npm-publish@v1
|
||||||
with:
|
with:
|
||||||
token: ${{ secrets.NPM_TOKEN }}
|
token: ${{ secrets.NPM_TOKEN }}
|
||||||
access: "public"
|
access: "public"
|
||||||
|
|||||||
2
.github/workflows/release-please.yml
vendored
2
.github/workflows/release-please.yml
vendored
@@ -6,7 +6,7 @@ jobs:
|
|||||||
release-please:
|
release-please:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: google-github-actions/release-please-action@ca6063f4ed81b55db15b8c42d1b6f7925866342d # v3
|
- uses: google-github-actions/release-please-action@v3
|
||||||
with:
|
with:
|
||||||
release-type: node
|
release-type: node
|
||||||
package-name: release-please-action
|
package-name: release-please-action
|
||||||
|
|||||||
29
.github/workflows/test.yml
vendored
29
.github/workflows/test.yml
vendored
@@ -1,29 +0,0 @@
|
|||||||
# This workflow will do a clean installation of node dependencies, cache/restore them, build the source code and run tests across different versions of node
|
|
||||||
# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-nodejs
|
|
||||||
|
|
||||||
name: Node.js CI
|
|
||||||
|
|
||||||
on:
|
|
||||||
pull_request:
|
|
||||||
branches: [ "main" ]
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
build:
|
|
||||||
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
|
|
||||||
strategy:
|
|
||||||
matrix:
|
|
||||||
node-version: [18.x, 19.x, 20.x]
|
|
||||||
# See supported Node.js release schedule at https://nodejs.org/en/about/releases/
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3
|
|
||||||
- name: Use Node.js ${{ matrix.node-version }}
|
|
||||||
uses: actions/setup-node@5e21ff4d9bc1a8cf6de233a3057d20ec6b3fb69d # v3
|
|
||||||
with:
|
|
||||||
node-version: ${{ matrix.node-version }}
|
|
||||||
cache: 'npm'
|
|
||||||
- run: npm install -g yarn
|
|
||||||
- run: yarn install
|
|
||||||
- run: yarn test
|
|
||||||
6
.gitignore
vendored
6
.gitignore
vendored
@@ -91,9 +91,3 @@ dist
|
|||||||
# Yarn files
|
# Yarn files
|
||||||
.yarn/install-state.gz
|
.yarn/install-state.gz
|
||||||
.yarn/build-state.yml
|
.yarn/build-state.yml
|
||||||
|
|
||||||
.yalc
|
|
||||||
|
|
||||||
yalc.lock
|
|
||||||
|
|
||||||
*.svg
|
|
||||||
|
|||||||
@@ -8,7 +8,6 @@ logs
|
|||||||
npm-debug.log*
|
npm-debug.log*
|
||||||
yarn-debug.log*
|
yarn-debug.log*
|
||||||
yarn-error.log*
|
yarn-error.log*
|
||||||
.yarn
|
|
||||||
# Runtime data
|
# Runtime data
|
||||||
pids
|
pids
|
||||||
*.pid
|
*.pid
|
||||||
@@ -81,7 +80,9 @@ typings/
|
|||||||
# FuseBox cache
|
# FuseBox cache
|
||||||
.fusebox/
|
.fusebox/
|
||||||
|
|
||||||
test
|
# TypeScript build output
|
||||||
|
dist
|
||||||
|
|
||||||
# VisualStudio Config file
|
# VisualStudio Config file
|
||||||
.vs
|
.vs
|
||||||
|
|
||||||
|
|||||||
532
.yarn/releases/yarn-3.5.1.cjs → .yarn/releases/yarn-3.5.0.cjs
vendored
Executable file → Normal file
532
.yarn/releases/yarn-3.5.1.cjs → .yarn/releases/yarn-3.5.0.cjs
vendored
Executable file → Normal file
File diff suppressed because one or more lines are too long
@@ -2,4 +2,4 @@ enableGlobalCache: true
|
|||||||
|
|
||||||
nodeLinker: node-modules
|
nodeLinker: node-modules
|
||||||
|
|
||||||
yarnPath: .yarn/releases/yarn-3.5.1.cjs
|
yarnPath: .yarn/releases/yarn-3.5.0.cjs
|
||||||
|
|||||||
52
CHANGELOG.md
52
CHANGELOG.md
@@ -1,57 +1,5 @@
|
|||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
## [3.1.0](https://github.com/sern-handler/handler/compare/v3.0.2...v3.1.0) (2023-09-04)
|
|
||||||
|
|
||||||
|
|
||||||
### Features
|
|
||||||
|
|
||||||
* add guaranteed `channelId` and `userId` getters to `Context` ([#320](https://github.com/sern-handler/handler/issues/320)) ([50253ca](https://github.com/sern-handler/handler/commit/50253ca322e7d6dbd2313139c0187a1028f71109))
|
|
||||||
* dispose hooks (deprecate useContainerRaw) ([#323](https://github.com/sern-handler/handler/issues/323)) ([26ccd11](https://github.com/sern-handler/handler/commit/26ccd118ff8cbcde94158a4d09fc0df18da9f254))
|
|
||||||
|
|
||||||
## [3.0.2](https://github.com/sern-handler/handler/compare/v3.0.1...v3.0.2) (2023-08-06)
|
|
||||||
|
|
||||||
|
|
||||||
### Bug Fixes
|
|
||||||
|
|
||||||
* invalid id for cts, mts, cjs, mjs files, node paths ([#318](https://github.com/sern-handler/handler/issues/318)) ([a7f5ea2](https://github.com/sern-handler/handler/commit/a7f5ea269fb344e221d10dbdc26a1611ffc8138f))
|
|
||||||
|
|
||||||
## [3.0.1](https://github.com/sern-handler/handler/compare/v3.0.0...v3.0.1) (2023-08-05)
|
|
||||||
|
|
||||||
|
|
||||||
### Bug Fixes
|
|
||||||
|
|
||||||
* collectors ([4134460](https://github.com/sern-handler/handler/commit/41344608c677b6069c46412f5f16e4337182ca7d))
|
|
||||||
|
|
||||||
## [3.0.0](https://github.com/sern-handler/handler/compare/v2.6.3...v3.0.0) (2023-07-29)
|
|
||||||
|
|
||||||
|
|
||||||
### ⚠ BREAKING CHANGES
|
|
||||||
|
|
||||||
* v3 ([#294](https://github.com/sern-handler/handler/issues/294))
|
|
||||||
|
|
||||||
### Features
|
|
||||||
|
|
||||||
* v3 ([#294](https://github.com/sern-handler/handler/issues/294)) ([7798e36](https://github.com/sern-handler/handler/commit/7798e36458c7f555d2bcb8a5857a6db47b7211da))
|
|
||||||
|
|
||||||
|
|
||||||
### Miscellaneous Chores
|
|
||||||
|
|
||||||
* release 3.0.0 ([70cca0d](https://github.com/sern-handler/handler/commit/70cca0dbb01e70b47a8c899b1fc4f43dee5ed8ed))
|
|
||||||
|
|
||||||
## [2.6.3](https://github.com/sern-handler/handler/compare/v2.6.2...v2.6.3) (2023-06-17)
|
|
||||||
|
|
||||||
|
|
||||||
### Bug Fixes
|
|
||||||
|
|
||||||
* autocomplete nested option and merge main ([5fdc1ed](https://github.com/sern-handler/handler/commit/5fdc1eda7f4fcc1f94af7eca661660c0edeb3251))
|
|
||||||
|
|
||||||
## [2.6.2](https://github.com/sern-handler/handler/compare/v2.6.1...v2.6.2) (2023-04-15)
|
|
||||||
|
|
||||||
|
|
||||||
### Miscellaneous Chores
|
|
||||||
|
|
||||||
* release 2.6.2 ([c1f6906](https://github.com/sern-handler/handler/commit/c1f690633c55ba41db1e035b7c16f9e19c70b385))
|
|
||||||
|
|
||||||
## [2.6.1](https://github.com/sern-handler/handler/compare/v2.6.0...v2.6.1) (2023-03-17)
|
## [2.6.1](https://github.com/sern-handler/handler/compare/v2.6.0...v2.6.1) (2023-03-17)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
36
README.md
36
README.md
@@ -15,15 +15,19 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
## Why?
|
## Why?
|
||||||
- For you. A framework that's tailored to your exact needs.
|
- Most handlers don't support discord.js 14.7+
|
||||||
- Lightweight. Does a lot while being small.
|
- Customizable, composable commands
|
||||||
- Latest features. Support for discord.js v14 and all of its interactions.
|
- Plug and play or customize to your liking
|
||||||
- Start quickly. Plug and play or customize to your liking.
|
- Embraces reactive programming for consistent and reliable backend
|
||||||
- Switch and customize how errors are handled, logging, and more.
|
- Customizable logger, error handling, and more
|
||||||
- works with [bun](https://bun.sh/) and [node](https://nodejs.org/en) out the box!
|
- Active development and growing [community](https://sern.dev/discord)
|
||||||
- Use it with TypeScript or JavaScript. CommonJS and ESM supported.
|
## 👀 Quick Look
|
||||||
- Active and growing community, always here to help. [Join us](https://sern.dev/discord)
|
|
||||||
- Unleash its full potential with a powerful CLI and awesome plugins.
|
* Support for discord.js v14 and all interactions
|
||||||
|
* Hybrid commands
|
||||||
|
* Lightweight and customizable
|
||||||
|
* ESM, CommonJS and TypeScript support
|
||||||
|
* A powerful CLI and awesome community-made plugins
|
||||||
|
|
||||||
## 📜 Installation
|
## 📜 Installation
|
||||||
|
|
||||||
@@ -76,14 +80,16 @@ export default commandModule({
|
|||||||
</details>
|
</details>
|
||||||
<details open><summary>index.ts</summary>
|
<details open><summary>index.ts</summary>
|
||||||
|
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
import { Client, GatewayIntentBits } from 'discord.js';
|
import { Client, GatewayIntentBits } from 'discord.js';
|
||||||
import { Sern, single } from '@sern/handler';
|
import { Sern, single, type Dependencies } from '@sern/handler';
|
||||||
|
|
||||||
//client has been declared previously
|
//client has been declared previously
|
||||||
//Version 3
|
|
||||||
await makeDependencies({
|
interface MyDependencies extends Dependencies {
|
||||||
|
'@sern/client': Singleton<Client>;
|
||||||
|
}
|
||||||
|
export const useContainer = Sern.makeDependencies<MyDependencies>({
|
||||||
build: root => root
|
build: root => root
|
||||||
.add({ '@sern/client': single(() => client) })
|
.add({ '@sern/client': single(() => client) })
|
||||||
});
|
});
|
||||||
@@ -93,6 +99,9 @@ Sern.init({
|
|||||||
defaultPrefix: '!', // removing defaultPrefix will shut down text commands
|
defaultPrefix: '!', // removing defaultPrefix will shut down text commands
|
||||||
commands: 'src/commands',
|
commands: 'src/commands',
|
||||||
// events: 'src/events' (optional),
|
// events: 'src/events' (optional),
|
||||||
|
containerConfig : {
|
||||||
|
get: useContainer
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
client.login("YOUR_BOT_TOKEN_HERE");
|
client.login("YOUR_BOT_TOKEN_HERE");
|
||||||
@@ -106,7 +115,6 @@ client.login("YOUR_BOT_TOKEN_HERE");
|
|||||||
- [ava](https://github.com/SrIzan10/ava), A discord bot that plays KNGI and Gensokyo Radio.
|
- [ava](https://github.com/SrIzan10/ava), A discord bot that plays KNGI and Gensokyo Radio.
|
||||||
- [Murayama](https://github.com/murayamabot/murayama), :pepega:
|
- [Murayama](https://github.com/murayamabot/murayama), :pepega:
|
||||||
- [Protector (WIP)](https://github.com/needhamgary/Protector), Just a simple bot to help enhance a private minecraft server.
|
- [Protector (WIP)](https://github.com/needhamgary/Protector), Just a simple bot to help enhance a private minecraft server.
|
||||||
- [SmokinWeed 💨](https://github.com/Peter-MJ-Parker/sern-bud), A fun bot for a small - but growing - server.
|
|
||||||
|
|
||||||
## 💻 CLI
|
## 💻 CLI
|
||||||
|
|
||||||
|
|||||||
29
package.json
29
package.json
@@ -1,15 +1,15 @@
|
|||||||
{
|
{
|
||||||
"name": "@sern/handler",
|
"name": "@sern/handler",
|
||||||
"packageManager": "yarn@3.5.0",
|
"packageManager": "yarn@3.5.0",
|
||||||
"version": "3.1.0",
|
"version": "3.0.0-rc1",
|
||||||
"description": "A complete, customizable, typesafe, & reactive framework for discord bots.",
|
"description": "A complete, customizable, typesafe, & reactive framework for discord bots.",
|
||||||
"main": "./dist/index.js",
|
"main": "./dist/esm/index.mjs",
|
||||||
"module": "./dist/index.mjs",
|
"module": "./dist/cjs/index.cjs",
|
||||||
"types": "./dist/index.d.ts",
|
"types": "dist/index.d.ts",
|
||||||
"exports": {
|
"exports": {
|
||||||
".": {
|
".": {
|
||||||
"import": "./dist/index.mjs",
|
"import": "./dist/esm/index.mjs",
|
||||||
"require": "./dist/index.js",
|
"require": "./dist/cjs/index.cjs",
|
||||||
"types": "./dist/index.d.ts"
|
"types": "./dist/index.d.ts"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -19,12 +19,11 @@
|
|||||||
"lint": "eslint src/**/*.ts",
|
"lint": "eslint src/**/*.ts",
|
||||||
"format": "eslint src/**/*.ts --fix",
|
"format": "eslint src/**/*.ts --fix",
|
||||||
"build:dev": "tsup --metafile",
|
"build:dev": "tsup --metafile",
|
||||||
"build:prod": "tsup ",
|
"build:prod": "tsup --minify",
|
||||||
"prepare": "npm run build:prod",
|
"publish": "npm run build:prod",
|
||||||
"pretty": "prettier --write .",
|
"pretty": "prettier --write .",
|
||||||
"tdd": "vitest",
|
"tdd": "vitest",
|
||||||
"test": "vitest --run",
|
"test": "vitest --run"
|
||||||
"analyze-imports": "npx depcruise src --include-only \"^src\" --output-type dot | dot -T svg > dependency-graph.svg"
|
|
||||||
},
|
},
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"sern-handler",
|
"sern-handler",
|
||||||
@@ -40,17 +39,17 @@
|
|||||||
"dependencies": {
|
"dependencies": {
|
||||||
"iti": "^0.6.0",
|
"iti": "^0.6.0",
|
||||||
"rxjs": "^7.8.0",
|
"rxjs": "^7.8.0",
|
||||||
"ts-results-es": "^4.0.0"
|
"ts-results-es": "^3.6.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@faker-js/faker": "^8.0.1",
|
"@faker-js/faker": "^8.0.1",
|
||||||
"@types/node": "^18.15.11",
|
"@types/node": "^18.15.11",
|
||||||
"@typescript-eslint/eslint-plugin": "5.58.0",
|
"@typescript-eslint/eslint-plugin": "5.58.0",
|
||||||
"@typescript-eslint/parser": "5.59.1",
|
"@typescript-eslint/parser": "5.58.0",
|
||||||
"discord.js": "14.11.0",
|
"discord.js": "14.11.0",
|
||||||
"esbuild": "^0.17.0",
|
"esbuild-ifdef": "^0.2.0",
|
||||||
"eslint": "8.39.0",
|
"eslint": "8.38.0",
|
||||||
"prettier": "2.8.8",
|
"prettier": "2.8.7",
|
||||||
"tsup": "^6.7.0",
|
"tsup": "^6.7.0",
|
||||||
"typescript": "5.0.2",
|
"typescript": "5.0.2",
|
||||||
"vitest": "latest"
|
"vitest": "latest"
|
||||||
|
|||||||
@@ -1,9 +1,4 @@
|
|||||||
{
|
{
|
||||||
"extends": [
|
|
||||||
"config:base",
|
|
||||||
"helpers:pinGitHubActionDigests",
|
|
||||||
"group:allNonMajor"
|
|
||||||
],
|
|
||||||
"major": {
|
"major": {
|
||||||
"dependencyDashboardApproval": true,
|
"dependencyDashboardApproval": true,
|
||||||
"reviewers": ["EvolutionX-10", "jacoobes", "Murtatrxx"]
|
"reviewers": ["EvolutionX-10", "jacoobes", "Murtatrxx"]
|
||||||
|
|||||||
@@ -1,10 +0,0 @@
|
|||||||
export * as Id from './id';
|
|
||||||
export * from './operators';
|
|
||||||
export * from './predicates';
|
|
||||||
export * as Files from './module-loading';
|
|
||||||
export * from './functions';
|
|
||||||
export type { VoidResult } from '../types/core-plugin';
|
|
||||||
export { SernError } from './structures/enums';
|
|
||||||
export { ModuleStore } from './structures/module-store';
|
|
||||||
export * as DefaultServices from './structures/services';
|
|
||||||
export { useContainerRaw } from './ioc/base'
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
import type { Awaitable } from '../../types/utility';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Represents a Disposable contract.
|
|
||||||
* Let dependencies implement this to dispose and cleanup.
|
|
||||||
*/
|
|
||||||
export interface Disposable {
|
|
||||||
dispose(): Awaitable<unknown>;
|
|
||||||
}
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
import type { AnyFunction } from '../../types/utility';
|
|
||||||
|
|
||||||
export interface Emitter {
|
|
||||||
addListener(eventName: string | symbol, listener: AnyFunction): this;
|
|
||||||
removeListener(eventName: string | symbol, listener: AnyFunction): this;
|
|
||||||
emit(eventName: string | symbol, ...payload: any[]): boolean;
|
|
||||||
}
|
|
||||||
@@ -1,26 +1,21 @@
|
|||||||
import type { CommandModule,Processed, EventModule } from "../../types/core-modules";
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @since 2.0.0
|
* @since 2.0.0
|
||||||
*/
|
*/
|
||||||
export interface ErrorHandling {
|
export interface ErrorHandling {
|
||||||
|
/**
|
||||||
|
* Number of times the process should throw an error until crashing and exiting
|
||||||
|
*/
|
||||||
|
keepAlive: number;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @deprecated
|
* @deprecated
|
||||||
* Version 4 will remove this method
|
* Version 4 will remove this method
|
||||||
*/
|
*/
|
||||||
crash(err: Error): never;
|
crash(err :Error) : never
|
||||||
/**
|
/**
|
||||||
* A function that is called on every throw,
|
* A function that is called on every crash. Updates keepAlive.
|
||||||
* If and only if the command is not handled properly
|
* If keepAlive is 0, the process crashes.
|
||||||
* @param error
|
* @param error
|
||||||
*/
|
*/
|
||||||
updateAlive(error: Error): void;
|
updateAlive(error: Error): void;
|
||||||
|
|
||||||
/**
|
|
||||||
* This callback is called if a module
|
|
||||||
* handles onError with type 'fail'
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
handleError(error: Error): void;
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,5 +3,3 @@ export * from './logging';
|
|||||||
export * from './module-manager';
|
export * from './module-manager';
|
||||||
export * from './module-store';
|
export * from './module-store';
|
||||||
export * from './init';
|
export * from './init';
|
||||||
export * from './emitter';
|
|
||||||
export * from './disposable'
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import type { Awaitable } from '../../types/utility';
|
import { Awaitable } from '../../shared';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Represents an initialization contract.
|
* Represents an initialization contract.
|
||||||
|
|||||||
@@ -1,32 +1,14 @@
|
|||||||
import type {
|
|
||||||
CommandMeta,
|
|
||||||
CommandModule,
|
|
||||||
CommandModuleDefs,
|
|
||||||
Module,
|
|
||||||
OnError,
|
|
||||||
} from '../../types/core-modules';
|
|
||||||
import { CommandType } from '../structures';
|
import { CommandType } from '../structures';
|
||||||
|
import { CommandMeta, CommandModule, CommandModuleDefs, Module } from '../types/modules';
|
||||||
|
|
||||||
interface MetadataAccess {
|
|
||||||
getMetadata(m: Module): CommandMeta | undefined;
|
|
||||||
setMetadata(m: Module, c: CommandMeta): void;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface OnErrorAccess {
|
|
||||||
getErrorCallback(m: Module): OnError;
|
|
||||||
setErrorCallback(m: Module, c: NonNullable<OnError>): void;
|
|
||||||
}
|
|
||||||
/**
|
/**
|
||||||
* @since 2.0.0
|
* @since 2.0.0
|
||||||
* @internal - direct access to the module manager will be removed in version 4
|
|
||||||
*/
|
*/
|
||||||
export interface ModuleManager extends MetadataAccess, OnErrorAccess {
|
export interface ModuleManager {
|
||||||
get(id: string): string | undefined;
|
get(id: string): string | undefined;
|
||||||
|
getMetadata(m: Module): CommandMeta|undefined;
|
||||||
|
setMetadata(m: Module, c: CommandMeta): void;
|
||||||
set(id: string, path: string): void;
|
set(id: string, path: string): void;
|
||||||
getPublishableCommands(): Promise<CommandModule[]>;
|
getPublishableCommands(): Promise<CommandModule[]>;
|
||||||
getByNameCommandType<T extends CommandType>(
|
getByNameCommandType<T extends CommandType>(name: string, commandType: T): Promise<CommandModuleDefs[T]>|undefined;
|
||||||
name: string,
|
|
||||||
commandType: T,
|
|
||||||
): Promise<CommandModuleDefs[T]> | undefined;
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import type { CommandMeta, Module, OnError } from '../../types/core-modules';
|
import { CommandMeta, Module } from '../types/modules';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Represents a core module store that stores IDs mapped to file paths.
|
* Represents a core module store that stores IDs mapped to file paths.
|
||||||
@@ -6,5 +6,4 @@ import type { CommandMeta, Module, OnError } from '../../types/core-modules';
|
|||||||
export interface CoreModuleStore {
|
export interface CoreModuleStore {
|
||||||
commands: Map<string, string>;
|
commands: Map<string, string>;
|
||||||
metadata: WeakMap<Module, CommandMeta>;
|
metadata: WeakMap<Module, CommandMeta>;
|
||||||
onError: WeakMap<Module, NonNullable<OnError>>;
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { CommandType, EventType, PluginType } from './structures';
|
import { CommandType, EventType, PluginType } from './structures';
|
||||||
import type { Plugin, PluginResult, EventArgs, CommandArgs } from '../types/core-plugin';
|
import type { Plugin, PluginResult, EventArgs, CommandArgs } from './types/plugins';
|
||||||
import type { ClientEvents } from 'discord.js';
|
import type { ClientEvents } from 'discord.js';
|
||||||
|
|
||||||
export function makePlugin<V extends unknown[]>(
|
export function makePlugin<V extends unknown[]>(
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
import { Err, Ok } from 'ts-results-es';
|
import { Err, Ok } from 'ts-results-es';
|
||||||
import { ApplicationCommandOptionType, AutocompleteInteraction } from 'discord.js';
|
import { ApplicationCommandOptionType, AutocompleteInteraction } from 'discord.js';
|
||||||
import type { SernAutocompleteData, SernOptionsData } from '../types/core-modules';
|
import type { SernAutocompleteData, SernOptionsData } from './types/modules';
|
||||||
import type { AnyCommandPlugin, AnyEventPlugin, Plugin } from '../types/core-plugin';
|
import { AnyCommandPlugin, AnyEventPlugin, Plugin } from './types/plugins';
|
||||||
import { PluginType } from './structures';
|
import { PluginType } from './structures';
|
||||||
import assert from 'assert';
|
|
||||||
|
|
||||||
//function wrappers for empty ok / err
|
//function wrappers for empty ok / err
|
||||||
export const ok = /* @__PURE__*/ () => Ok.EMPTY;
|
export const ok = /* @__PURE__*/ () => Ok.EMPTY;
|
||||||
@@ -14,7 +13,6 @@ export function partitionPlugins(
|
|||||||
): [Plugin[], Plugin[]] {
|
): [Plugin[], Plugin[]] {
|
||||||
const controlPlugins = [];
|
const controlPlugins = [];
|
||||||
const initPlugins = [];
|
const initPlugins = [];
|
||||||
|
|
||||||
for (const el of arr) {
|
for (const el of arr) {
|
||||||
switch (el.type) {
|
switch (el.type) {
|
||||||
case PluginType.Control:
|
case PluginType.Control:
|
||||||
@@ -36,48 +34,33 @@ export function partitionPlugins(
|
|||||||
export function treeSearch(
|
export function treeSearch(
|
||||||
iAutocomplete: AutocompleteInteraction,
|
iAutocomplete: AutocompleteInteraction,
|
||||||
options: SernOptionsData[] | undefined,
|
options: SernOptionsData[] | undefined,
|
||||||
): SernAutocompleteData & { parent?: string } | undefined {
|
): SernAutocompleteData | undefined {
|
||||||
if (options === undefined) return undefined;
|
if (options === undefined) return undefined;
|
||||||
//clone to prevent mutation of original command module
|
const _options = options.slice(); // required to prevent direct mutation of options
|
||||||
const _options = options.map(a => ({ ...a }));
|
let autocompleteData: SernAutocompleteData | undefined;
|
||||||
let subcommands = new Set();
|
|
||||||
while (_options.length > 0) {
|
while (_options.length > 0) {
|
||||||
const cur = _options.pop()!;
|
const cur = _options.pop()!;
|
||||||
switch (cur.type) {
|
switch (cur.type) {
|
||||||
case ApplicationCommandOptionType.Subcommand:
|
case ApplicationCommandOptionType.Subcommand:
|
||||||
{
|
|
||||||
subcommands.add(cur.name);
|
|
||||||
for (const option of cur.options ?? []) _options.push(option);
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
case ApplicationCommandOptionType.SubcommandGroup:
|
case ApplicationCommandOptionType.SubcommandGroup:
|
||||||
{
|
{
|
||||||
for (const command of cur.options ?? []) _options.push(command);
|
for (const option of cur.options ?? []) {
|
||||||
|
_options.push(option);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
{
|
{
|
||||||
if ('autocomplete' in cur && cur.autocomplete) {
|
if (cur.autocomplete) {
|
||||||
const choice = iAutocomplete.options.getFocused(true);
|
const choice = iAutocomplete.options.getFocused(true);
|
||||||
assert(
|
if (cur.name === choice.name && cur.autocomplete) {
|
||||||
'command' in cur,
|
autocompleteData = cur;
|
||||||
'No command property found for autocomplete option',
|
|
||||||
);
|
|
||||||
if (subcommands.size > 0) {
|
|
||||||
const parent = iAutocomplete.options.getSubcommand();
|
|
||||||
const parentAndOptionMatches =
|
|
||||||
subcommands.has(parent) && cur.name === choice.name;
|
|
||||||
if (parentAndOptionMatches) {
|
|
||||||
return { ...cur, parent };
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
if (cur.name === choice.name) {
|
|
||||||
return { ...cur, parent: undefined };
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
return autocompleteData;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,3 +2,27 @@ export * from './contracts';
|
|||||||
export * from './create-plugins';
|
export * from './create-plugins';
|
||||||
export * from './structures';
|
export * from './structures';
|
||||||
export * from './ioc';
|
export * from './ioc';
|
||||||
|
export type {
|
||||||
|
CommandModule,
|
||||||
|
EventModule,
|
||||||
|
BothCommand,
|
||||||
|
ContextMenuMsg,
|
||||||
|
ContextMenuUser,
|
||||||
|
SlashCommand,
|
||||||
|
TextCommand,
|
||||||
|
ButtonCommand,
|
||||||
|
StringSelectCommand,
|
||||||
|
MentionableSelectCommand,
|
||||||
|
UserSelectCommand,
|
||||||
|
ChannelSelectCommand,
|
||||||
|
RoleSelectCommand,
|
||||||
|
ModalSubmitCommand,
|
||||||
|
DiscordEventCommand,
|
||||||
|
SernEventCommand,
|
||||||
|
ExternalEventCommand,
|
||||||
|
CommandModuleDefs,
|
||||||
|
EventModuleDefs,
|
||||||
|
SernAutocompleteData,
|
||||||
|
SernOptionsData,
|
||||||
|
} from './types/modules';
|
||||||
|
export type { Controller, PluginResult, InitPlugin, ControlPlugin, Plugin } from './types/plugins';
|
||||||
|
|||||||
@@ -1,16 +1,14 @@
|
|||||||
import * as assert from 'assert';
|
import * as assert from 'assert';
|
||||||
import { composeRoot, useContainer } from './dependency-injection';
|
import { composeRoot, useContainer } from './dependency-injection';
|
||||||
import type { DependencyConfiguration } from '../../types/ioc';
|
import { DependencyConfiguration } from './types';
|
||||||
import { CoreContainer } from './container';
|
import { CoreContainer } from '../structures/container';
|
||||||
|
|
||||||
//SIDE EFFECT: GLOBAL DI
|
//SIDE EFFECT: GLOBAL DI
|
||||||
let containerSubject: CoreContainer<Partial<Dependencies>>;
|
let containerSubject: CoreContainer<Partial<Dependencies>>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @deprecated
|
|
||||||
* Returns the underlying data structure holding all dependencies.
|
* Returns the underlying data structure holding all dependencies.
|
||||||
* Exposes methods from iti
|
* Exposes methods from iti
|
||||||
* Use the Service API. The container should be readonly
|
|
||||||
*/
|
*/
|
||||||
export function useContainerRaw() {
|
export function useContainerRaw() {
|
||||||
assert.ok(
|
assert.ok(
|
||||||
|
|||||||
@@ -1,60 +0,0 @@
|
|||||||
import { Container } from 'iti';
|
|
||||||
import { Disposable, SernEmitter } from '../';
|
|
||||||
import * as assert from 'node:assert';
|
|
||||||
import { Subject } from 'rxjs';
|
|
||||||
import { DefaultServices, ModuleStore } from '../_internal';
|
|
||||||
import * as Hooks from './hooks'
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* A semi-generic container that provides error handling, emitter, and module store.
|
|
||||||
* For the handler to operate correctly, The only user provided dependency needs to be @sern/client
|
|
||||||
*/
|
|
||||||
export class CoreContainer<T extends Partial<Dependencies>> extends Container<T, {}> {
|
|
||||||
private ready$ = new Subject<void>();
|
|
||||||
constructor() {
|
|
||||||
super();
|
|
||||||
assert.ok(!this.isReady(), 'Listening for dispose & init should occur prior to sern being ready.');
|
|
||||||
|
|
||||||
const { unsubscribe } = Hooks.createInitListener(this);
|
|
||||||
this.ready$
|
|
||||||
.subscribe({ complete: unsubscribe });
|
|
||||||
|
|
||||||
(this as Container<{}, {}>)
|
|
||||||
.add({
|
|
||||||
'@sern/errors': () => new DefaultServices.DefaultErrorHandling(),
|
|
||||||
'@sern/emitter': () => new SernEmitter(),
|
|
||||||
'@sern/store': () => new ModuleStore(),
|
|
||||||
})
|
|
||||||
.add(ctx => {
|
|
||||||
return {
|
|
||||||
'@sern/modules': () =>
|
|
||||||
new DefaultServices.DefaultModuleManager(ctx['@sern/store']),
|
|
||||||
};
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
isReady() {
|
|
||||||
|
|
||||||
return this.ready$.closed;
|
|
||||||
}
|
|
||||||
override async disposeAll() {
|
|
||||||
|
|
||||||
const otherDisposables = Object
|
|
||||||
.entries(this._context)
|
|
||||||
.flatMap(([key, value]) =>
|
|
||||||
'dispose' in value
|
|
||||||
? [key]
|
|
||||||
: []);
|
|
||||||
|
|
||||||
for(const key of otherDisposables) {
|
|
||||||
this.addDisposer({ [key]: (dep: Disposable) => dep.dispose() } as never);
|
|
||||||
}
|
|
||||||
await super.disposeAll()
|
|
||||||
}
|
|
||||||
ready() {
|
|
||||||
this.ready$.complete();
|
|
||||||
this.ready$.unsubscribe();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -4,9 +4,13 @@
|
|||||||
|
|
||||||
/* eslint-disable @typescript-eslint/consistent-type-imports */
|
/* eslint-disable @typescript-eslint/consistent-type-imports */
|
||||||
|
|
||||||
import { CoreDependencies } from './ioc';
|
import { CoreDependencies } from './types'
|
||||||
|
|
||||||
declare global {
|
declare global {
|
||||||
interface Dependencies extends CoreDependencies {}
|
|
||||||
|
|
||||||
|
interface Dependencies extends CoreDependencies {}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -1,7 +1,12 @@
|
|||||||
import type { CoreDependencies, DependencyConfiguration, IntoDependencies } from '../../types/ioc';
|
import type {
|
||||||
import { DefaultServices } from '../_internal';
|
CoreDependencies,
|
||||||
|
DependencyConfiguration,
|
||||||
|
IntoDependencies,
|
||||||
|
} from './types';
|
||||||
|
import { DefaultLogging } from '../structures';
|
||||||
|
import { SernError } from '../structures/errors';
|
||||||
import { useContainerRaw } from './base';
|
import { useContainerRaw } from './base';
|
||||||
import { CoreContainer } from './container';
|
import { CoreContainer } from '../structures/container';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @__PURE__
|
* @__PURE__
|
||||||
@@ -22,26 +27,11 @@ export function single<T>(cb: () => T) {
|
|||||||
export function transient<T>(cb: () => () => T) {
|
export function transient<T>(cb: () => () => T) {
|
||||||
return cb;
|
return cb;
|
||||||
}
|
}
|
||||||
/**
|
|
||||||
* The new Service api, a cleaner alternative to useContainer
|
|
||||||
* To obtain intellisense, ensure a .d.ts file exists in the root of compilation.
|
|
||||||
* Usually our scaffolding tool takes care of this.
|
|
||||||
* @since 3.0.0
|
|
||||||
* @example
|
|
||||||
* ```ts
|
|
||||||
* const client = Service('@sern/client');
|
|
||||||
* ```
|
|
||||||
* @param key a key that corresponds to a dependency registered.
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
export function Service<const T extends keyof Dependencies>(key: T) {
|
export function Service<const T extends keyof Dependencies>(key: T) {
|
||||||
return useContainerRaw().get(key)!;
|
return useContainerRaw().get(key)!;
|
||||||
}
|
}
|
||||||
/**
|
|
||||||
* @since 3.0.0
|
|
||||||
* The plural version of {@link Service}
|
|
||||||
* @returns array of dependencies, in the same order of keys provided
|
|
||||||
*/
|
|
||||||
export function Services<const T extends (keyof Dependencies)[]>(...keys: [...T]) {
|
export function Services<const T extends (keyof Dependencies)[]>(...keys: [...T]) {
|
||||||
const container = useContainerRaw();
|
const container = useContainerRaw();
|
||||||
return keys.map(k => container.get(k)!) as IntoDependencies<T>;
|
return keys.map(k => container.get(k)!) as IntoDependencies<T>;
|
||||||
@@ -61,11 +51,16 @@ export async function composeRoot(
|
|||||||
const hasLogger = conf.exclude?.has('@sern/logger');
|
const hasLogger = conf.exclude?.has('@sern/logger');
|
||||||
if (!hasLogger) {
|
if (!hasLogger) {
|
||||||
container.upsert({
|
container.upsert({
|
||||||
'@sern/logger': () => new DefaultServices.DefaultLogging(),
|
'@sern/logger': () => new DefaultLogging(),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
//Build the container based on the callback provided by the user
|
//Build the container based on the callback provided by the user
|
||||||
conf.build(container as CoreContainer<Omit<CoreDependencies, '@sern/client'>>);
|
conf.build(container as CoreContainer<Omit<CoreDependencies, '@sern/client'>>);
|
||||||
|
try {
|
||||||
|
container.get('@sern/client');
|
||||||
|
} catch {
|
||||||
|
throw new Error(SernError.MissingRequired + ' No client was provided');
|
||||||
|
}
|
||||||
|
|
||||||
if (!hasLogger) {
|
if (!hasLogger) {
|
||||||
container.get('@sern/logger')?.info({ message: 'All dependencies loaded successfully.' });
|
container.get('@sern/logger')?.info({ message: 'All dependencies loaded successfully.' });
|
||||||
@@ -75,6 +70,11 @@ export async function composeRoot(
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function useContainer<const T extends Dependencies>() {
|
export function useContainer<const T extends Dependencies>() {
|
||||||
|
console.warn(`
|
||||||
|
Warning: using a container hook (useContainer) is not recommended.
|
||||||
|
Could lead to many unwanted side effects.
|
||||||
|
Use the new Service(s) api function instead.
|
||||||
|
`);
|
||||||
return <V extends (keyof T)[]>(...keys: [...V]) =>
|
return <V extends (keyof T)[]>(...keys: [...V]) =>
|
||||||
keys.map(key => useContainerRaw().get(key as keyof Dependencies)) as IntoDependencies<V>;
|
keys.map(key => useContainerRaw().get(key as keyof Dependencies)) as IntoDependencies<V>;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,40 +0,0 @@
|
|||||||
import type { CoreContainer } from "./container"
|
|
||||||
|
|
||||||
interface HookEvent {
|
|
||||||
key : PropertyKey
|
|
||||||
newContainer: any
|
|
||||||
}
|
|
||||||
type HookName = 'init';
|
|
||||||
|
|
||||||
export const createInitListener = (coreContainer : CoreContainer<any>) => {
|
|
||||||
const initCalled = new Set<PropertyKey>();
|
|
||||||
const hasCallableMethod = createPredicate(initCalled);
|
|
||||||
const unsubscribe = coreContainer.on('containerUpserted', async (event) => {
|
|
||||||
|
|
||||||
if(isNotHookable(event)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if(hasCallableMethod('init', event)) {
|
|
||||||
await event.newContainer?.init();
|
|
||||||
initCalled.add(event.key);
|
|
||||||
}
|
|
||||||
|
|
||||||
});
|
|
||||||
return { unsubscribe };
|
|
||||||
}
|
|
||||||
|
|
||||||
const isNotHookable = (hk: HookEvent) => {
|
|
||||||
return typeof hk.newContainer !== 'object'
|
|
||||||
|| Array.isArray(hk.newContainer)
|
|
||||||
|| hk.newContainer === null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const createPredicate = <T extends HookEvent>(called: Set<PropertyKey>) => {
|
|
||||||
return (hookName: HookName, event: T) => {
|
|
||||||
const hasMethod = Reflect.has(event.newContainer!, hookName);
|
|
||||||
const beenCalledOnce = !called.has(event.key)
|
|
||||||
|
|
||||||
return hasMethod && beenCalledOnce
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,2 +1,3 @@
|
|||||||
export { makeDependencies } from './base';
|
export { useContainerRaw, makeDependencies } from './base';
|
||||||
export { Service, Services, single, transient } from './dependency-injection';
|
export { Service, Services, single, transient } from './dependency-injection';
|
||||||
|
export type { Singleton, Transient, CoreDependencies } from './types';
|
||||||
|
|||||||
26
src/core/ioc/types.ts
Normal file
26
src/core/ioc/types.ts
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
import { EventEmitter } from 'node:events';
|
||||||
|
import { Container, UnpackFunction } from 'iti';
|
||||||
|
export type Singleton<T> = () => T;
|
||||||
|
export type Transient<T> = () => () => T;
|
||||||
|
|
||||||
|
export interface CoreDependencies {
|
||||||
|
'@sern/client': () => EventEmitter
|
||||||
|
'@sern/logger'?: () => import('../contracts').Logging;
|
||||||
|
'@sern/emitter': () => import('../structures/sern-emitter').SernEmitter;
|
||||||
|
'@sern/store': () => import('../contracts').CoreModuleStore;
|
||||||
|
'@sern/modules': () => import('../contracts').ModuleManager;
|
||||||
|
'@sern/errors': () => import('../contracts').ErrorHandling;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type DependencyFromKey<T extends keyof Dependencies> = Dependencies[T];
|
||||||
|
|
||||||
|
export type IntoDependencies<Tuple extends [...any[]]> = {
|
||||||
|
[Index in keyof Tuple]: UnpackFunction<DependencyFromKey<Tuple[Index]> & {}>; //Unpack and make NonNullable
|
||||||
|
} & { length: Tuple['length'] };
|
||||||
|
|
||||||
|
export interface DependencyConfiguration {
|
||||||
|
//@deprecated. Loggers will always be included in the future
|
||||||
|
exclude?: Set<'@sern/logger'>;
|
||||||
|
build: (root: Container<Omit<CoreDependencies, '@sern/client'>, {}>) => Container<Dependencies, {}>;
|
||||||
|
}
|
||||||
|
|
||||||
@@ -1,52 +1,38 @@
|
|||||||
import { Result } from 'ts-results-es';
|
import { SernError } from './structures/errors';
|
||||||
|
import { Result, Err, Ok } from 'ts-results-es';
|
||||||
|
import { Module } from './types/modules';
|
||||||
import { type Observable, from, mergeMap, ObservableInput } from 'rxjs';
|
import { type Observable, from, mergeMap, ObservableInput } from 'rxjs';
|
||||||
import { readdir, stat } from 'fs/promises';
|
import { readdir, stat } from 'fs/promises';
|
||||||
import { basename, extname, join, resolve, parse } from 'path';
|
import { basename, extname, join, resolve } from 'path';
|
||||||
import assert from 'assert';
|
import { ImportPayload } from '../handler/types';
|
||||||
import { createRequire } from 'node:module';
|
|
||||||
import type { ImportPayload, Wrapper } from '../types/core';
|
export type ModuleResult<T> = Promise<Result<ImportPayload<T>, SernError>>;
|
||||||
import type { Module, OnError } from '../types/core-modules';
|
|
||||||
|
|
||||||
export type ModuleResult<T> = Promise<ImportPayload<T>>;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Import any module based on the absolute path.
|
|
||||||
* This can accept four types of exported modules
|
|
||||||
* commonjs, javascript :
|
|
||||||
* ```js
|
|
||||||
* exports = commandModule({ })
|
|
||||||
*
|
|
||||||
* //or
|
|
||||||
* exports.default = commandModule({ })
|
|
||||||
* ```
|
|
||||||
* esm javascript, typescript, and commonjs typescript
|
|
||||||
* export default commandModule({})
|
|
||||||
*/
|
|
||||||
export async function importModule<T>(absPath: string) {
|
export async function importModule<T>(absPath: string) {
|
||||||
let fileModule = await import(absPath);
|
// prettier-ignore
|
||||||
|
let module =
|
||||||
let commandModule = fileModule.default,
|
/// #if MODE === 'esm'
|
||||||
onError = fileModule.onError;
|
import(absPath).then(i => i.default); // eslint-disable-line
|
||||||
|
/// #elif MODE === 'cjs'
|
||||||
assert(commandModule , `Found no export @ ${absPath}. Forgot to ignore with "!"? (!${basename(absPath)})?`);
|
require(absPath).default; // eslint-disable-line
|
||||||
if ('default' in commandModule ) {
|
/// #endif
|
||||||
commandModule = commandModule.default;
|
return module.then(m =>
|
||||||
}
|
Result
|
||||||
return Result
|
.wrap(() => m.getInstance())
|
||||||
.wrap(() => ({ module: commandModule.getInstance(), onError }))
|
.unwrapOr(m)
|
||||||
.unwrapOr({ module: commandModule, onError }) as T;
|
) as T;
|
||||||
}
|
}
|
||||||
interface FileExtras {
|
|
||||||
onError : OnError
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function defaultModuleLoader<T extends Module>(absPath: string): ModuleResult<T> {
|
export async function defaultModuleLoader<T extends Module>(absPath: string): ModuleResult<T> {
|
||||||
let { onError, module } = await importModule<{ module: T } & FileExtras>(absPath);
|
let module = await importModule<T>(absPath);
|
||||||
assert(module, `Found an undefined module: ${absPath}`);
|
if (module === undefined) {
|
||||||
return { module, absPath, onError };
|
return Err(SernError.UndefinedModule);
|
||||||
|
}
|
||||||
|
//todo readd class modules
|
||||||
|
return Ok({ module, absPath });
|
||||||
}
|
}
|
||||||
|
|
||||||
export const fmtFileName = (fileName: string) => parse(fileName).name;
|
export const fmtFileName = (n: string) => n.substring(0, n.length - 3);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* a directory string is converted into a stream of modules.
|
* a directory string is converted into a stream of modules.
|
||||||
@@ -56,41 +42,58 @@ export const fmtFileName = (fileName: string) => parse(fileName).name;
|
|||||||
*/
|
*/
|
||||||
export function buildModuleStream<T extends Module>(
|
export function buildModuleStream<T extends Module>(
|
||||||
input: ObservableInput<string>,
|
input: ObservableInput<string>,
|
||||||
): Observable<ImportPayload<T>> {
|
): Observable<Result<ImportPayload<T>, SernError>> {
|
||||||
return from(input)
|
return from(input).pipe(mergeMap(defaultModuleLoader<T>));
|
||||||
.pipe(mergeMap(defaultModuleLoader<T>));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export const getFullPathTree = (dir: string) => readPaths(resolve(dir));
|
export function getFullPathTree(dir: string, mode: boolean) {
|
||||||
|
return readPaths(resolve(dir), mode);
|
||||||
|
}
|
||||||
|
|
||||||
export const filename = (path: string) => fmtFileName(basename(path));
|
export function filename(path: string) {
|
||||||
|
return fmtFileName(basename(path));
|
||||||
|
}
|
||||||
|
|
||||||
const isSkippable = (filename: string) => {
|
function createSkipCondition(base: string) {
|
||||||
//empty string is for non extension files (directories)
|
const validExtensions = ['.js', '.cjs', '.mts', '.mjs', 'cts'];
|
||||||
const validExtensions = ['.js', '.cjs', '.mts', '.mjs', '.cts', '.ts', ''];
|
return ( type: 'file' | 'directory') => {
|
||||||
return filename[0] === '!' || !validExtensions.includes(extname(filename));
|
if(type === 'file') {
|
||||||
};
|
return fmtFileName(base)[0] === '!'
|
||||||
|
|| !validExtensions.includes(extname(base));
|
||||||
|
}
|
||||||
|
return base[0] === '!';
|
||||||
|
}
|
||||||
|
}
|
||||||
async function deriveFileInfo(dir: string, file: string) {
|
async function deriveFileInfo(dir: string, file: string) {
|
||||||
const fullPath = join(dir, file);
|
const fullPath = join(dir, file);
|
||||||
return {
|
return {
|
||||||
fullPath,
|
fullPath,
|
||||||
fileStats: await stat(fullPath),
|
fileStats: await stat(fullPath),
|
||||||
base: basename(file),
|
base: basename(file)
|
||||||
};
|
}
|
||||||
}
|
}
|
||||||
async function* readPaths(dir: string): AsyncGenerator<string> {
|
async function* readPaths(dir: string, shouldDebug: boolean): AsyncGenerator<string> {
|
||||||
try {
|
try {
|
||||||
const files = await readdir(dir);
|
const files = await readdir(dir);
|
||||||
for (const file of files) {
|
for (const file of files) {
|
||||||
const { fullPath, fileStats, base } = await deriveFileInfo(dir, file);
|
const { fullPath, fileStats, base } = await deriveFileInfo(dir, file);
|
||||||
|
const isSkippable = createSkipCondition(base);
|
||||||
if (fileStats.isDirectory()) {
|
if (fileStats.isDirectory()) {
|
||||||
//Todo: refactor so that i dont repeat myself for files (line 71)
|
//Todo: refactor so that i dont repeat myself for files (line 71)
|
||||||
if (!isSkippable(base)) {
|
if (isSkippable('directory')) {
|
||||||
yield* readPaths(fullPath);
|
if (shouldDebug) console.info(`ignored directory: ${fullPath}`);
|
||||||
|
} else {
|
||||||
|
yield* readPaths(fullPath, shouldDebug);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if (!isSkippable(base)) {
|
if (isSkippable('file')) {
|
||||||
|
if (shouldDebug) console.info(`ignored: ${fullPath}`);
|
||||||
|
} else {
|
||||||
|
/// #if MODE === 'esm'
|
||||||
yield 'file:///' + fullPath;
|
yield 'file:///' + fullPath;
|
||||||
|
/// #elif MODE === 'cjs'
|
||||||
|
yield fullPath;
|
||||||
|
/// #endif
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -98,34 +101,3 @@ async function* readPaths(dir: string): AsyncGenerator<string> {
|
|||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const requir = createRequire(import.meta.url);
|
|
||||||
|
|
||||||
export function loadConfig(wrapper: Wrapper | 'file'): Wrapper {
|
|
||||||
if (wrapper !== 'file') {
|
|
||||||
return wrapper;
|
|
||||||
}
|
|
||||||
console.log('Experimental loading of sern.config.json');
|
|
||||||
const config = requir(resolve('sern.config.json'));
|
|
||||||
|
|
||||||
const makePath = (dir: PropertyKey) =>
|
|
||||||
config.language === 'typescript'
|
|
||||||
? join('dist', config.paths[dir]!)
|
|
||||||
: join(config.paths[dir]!);
|
|
||||||
|
|
||||||
console.log('Loading config: ', config);
|
|
||||||
const commandsPath = makePath('commands');
|
|
||||||
|
|
||||||
console.log('Commands path is set to', commandsPath);
|
|
||||||
let eventsPath: string | undefined;
|
|
||||||
if (config.paths.events) {
|
|
||||||
eventsPath = makePath('events');
|
|
||||||
console.log('Events path is set to', eventsPath);
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
defaultPrefix: config.defaultPrefix,
|
|
||||||
commands: commandsPath,
|
|
||||||
events: eventsPath,
|
|
||||||
};
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -15,11 +15,14 @@ import {
|
|||||||
OperatorFunction,
|
OperatorFunction,
|
||||||
pipe,
|
pipe,
|
||||||
share,
|
share,
|
||||||
|
switchMap,
|
||||||
} from 'rxjs';
|
} from 'rxjs';
|
||||||
import { Emitter, ErrorHandling, Logging } from './contracts';
|
import { Result } from 'ts-results-es';
|
||||||
|
import { EventEmitter } from 'node:events';
|
||||||
|
import { ErrorHandling, Logging } from './contracts';
|
||||||
import util from 'node:util';
|
import util from 'node:util';
|
||||||
import type { PluginResult, VoidResult } from '../types/core-plugin';
|
import { Awaitable } from '../shared';
|
||||||
import type { Result } from 'ts-results-es'
|
import { PluginResult, VoidResult } from './types/plugins';
|
||||||
/**
|
/**
|
||||||
* if {src} is true, mapTo V, else ignore
|
* if {src} is true, mapTo V, else ignore
|
||||||
* @param item
|
* @param item
|
||||||
@@ -28,6 +31,20 @@ export function filterMapTo<V>(item: () => V): OperatorFunction<boolean, V> {
|
|||||||
return concatMap(shouldKeep => (shouldKeep ? of(item()) : EMPTY));
|
return concatMap(shouldKeep => (shouldKeep ? of(item()) : EMPTY));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function filterMap<In, Out>(
|
||||||
|
cb: (i: In) => Awaitable<Result<Out, unknown>>,
|
||||||
|
): OperatorFunction<In, Out> {
|
||||||
|
return pipe(
|
||||||
|
switchMap(async input => cb(input)),
|
||||||
|
concatMap(s => {
|
||||||
|
if (s.ok) {
|
||||||
|
return of(s.val);
|
||||||
|
}
|
||||||
|
return EMPTY;
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Calls any plugin with {args}.
|
* Calls any plugin with {args}.
|
||||||
* @param args if an array, its spread and plugin called.
|
* @param args if an array, its spread and plugin called.
|
||||||
@@ -48,15 +65,32 @@ export function callPlugin(args: unknown): OperatorFunction<
|
|||||||
|
|
||||||
export const arrayifySource = map(src => (Array.isArray(src) ? (src as unknown[]) : [src]));
|
export const arrayifySource = map(src => (Array.isArray(src) ? (src as unknown[]) : [src]));
|
||||||
|
|
||||||
|
/**
|
||||||
|
* If the current value in Result stream is an error, calls callback.
|
||||||
|
* This also extracts the Ok value from Result
|
||||||
|
* @param cb
|
||||||
|
* @returns Observable<{ module: T; absPath: string }>
|
||||||
|
*/
|
||||||
|
export function errTap<Ok, Err>(cb: (err: Err) => void): OperatorFunction<Result<Ok, Err>, Ok> {
|
||||||
|
return concatMap(result => {
|
||||||
|
if (result.ok) {
|
||||||
|
return of(result.val);
|
||||||
|
} else {
|
||||||
|
cb(result.val as Err);
|
||||||
|
return EMPTY;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Checks if the stream of results is all ok.
|
* Checks if the stream of results is all ok.
|
||||||
*/
|
*/
|
||||||
export const everyPluginOk: OperatorFunction<VoidResult, boolean> = pipe(
|
export const everyPluginOk: OperatorFunction<VoidResult, boolean> = pipe(
|
||||||
every(result => result.isOk()),
|
every(result => result.ok),
|
||||||
defaultIfEmpty(true),
|
defaultIfEmpty(true),
|
||||||
);
|
);
|
||||||
|
|
||||||
export const sharedEventStream = <T>(e: Emitter, eventName: string) => {
|
export const sharedObservable = <T>(e: EventEmitter, eventName: string) => {
|
||||||
return (fromEvent(e, eventName) as Observable<T>).pipe(share());
|
return (fromEvent(e, eventName) as Observable<T>).pipe(share());
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -70,17 +104,3 @@ export function handleError<C>(crashHandler: ErrorHandling, logging?: Logging) {
|
|||||||
return caught;
|
return caught;
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
// Temporary until i get rxjs operators working on ts-results-es
|
|
||||||
export const filterTap = <K, R>(onErr: (e: R) => void): OperatorFunction<Result<K, R>, K> =>
|
|
||||||
pipe(
|
|
||||||
concatMap(result => {
|
|
||||||
if(result.isOk()) {
|
|
||||||
return of(result.value)
|
|
||||||
}
|
|
||||||
onErr(result.error);
|
|
||||||
return EMPTY
|
|
||||||
|
|
||||||
})
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import type {
|
import {
|
||||||
AnySelectMenuInteraction,
|
AnySelectMenuInteraction,
|
||||||
AutocompleteInteraction,
|
AutocompleteInteraction,
|
||||||
ButtonInteraction,
|
ButtonInteraction,
|
||||||
|
|||||||
@@ -1,6 +0,0 @@
|
|||||||
import type { Logging } from "../contracts";
|
|
||||||
|
|
||||||
export interface Response {
|
|
||||||
type: 'fail' | 'handled';
|
|
||||||
log?: { type: keyof Logging; message: unknown }
|
|
||||||
}
|
|
||||||
62
src/core/structures/container.ts
Normal file
62
src/core/structures/container.ts
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
import { Container } from 'iti';
|
||||||
|
import { DefaultErrorHandling, DefaultModuleManager, SernEmitter } from '../';
|
||||||
|
import { isAsyncFunction } from 'node:util/types';
|
||||||
|
import * as assert from 'node:assert';
|
||||||
|
import { Subject } from 'rxjs';
|
||||||
|
import { ModuleStore } from './module-store';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Provides all the defaults for sern to function properly.
|
||||||
|
* The only user provided dependency needs to be @sern/client
|
||||||
|
*/
|
||||||
|
export class CoreContainer<T extends Partial<Dependencies>> extends Container<T, {}> {
|
||||||
|
private ready$ = new Subject<never>();
|
||||||
|
constructor() {
|
||||||
|
super();
|
||||||
|
|
||||||
|
this.listenForInsertions();
|
||||||
|
|
||||||
|
(this as Container<{}, {}>)
|
||||||
|
.add({
|
||||||
|
'@sern/errors': () => new DefaultErrorHandling(),
|
||||||
|
'@sern/emitter': () => new SernEmitter(),
|
||||||
|
'@sern/store': () => new ModuleStore(),
|
||||||
|
})
|
||||||
|
.add(ctx => {
|
||||||
|
return { '@sern/modules': () => new DefaultModuleManager(ctx['@sern/store']) };
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private listenForInsertions() {
|
||||||
|
assert.ok(
|
||||||
|
!this.isReady(),
|
||||||
|
'listening for init functions should only occur prior to sern being ready.',
|
||||||
|
);
|
||||||
|
const unsubscriber = this.on('containerUpserted', this.callInitHooks);
|
||||||
|
|
||||||
|
this.ready$.subscribe({
|
||||||
|
complete: unsubscriber,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private async callInitHooks(e: { key: keyof T; newContainer: T[keyof T] | null }) {
|
||||||
|
const dep = e.newContainer;
|
||||||
|
|
||||||
|
assert.ok(dep);
|
||||||
|
//Ignore any dependencies that are not objects or array
|
||||||
|
if (typeof dep !== 'object' || Array.isArray(dep)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ('init' in dep && typeof dep.init === 'function') {
|
||||||
|
isAsyncFunction(dep.init) ? await dep.init() : dep.init();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
isReady() {
|
||||||
|
return this.ready$.closed;
|
||||||
|
}
|
||||||
|
ready() {
|
||||||
|
this.ready$.unsubscribe();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -8,11 +8,10 @@ import {
|
|||||||
Snowflake,
|
Snowflake,
|
||||||
User,
|
User,
|
||||||
} from 'discord.js';
|
} from 'discord.js';
|
||||||
import { CoreContext } from '../structures/core-context';
|
import { CoreContext } from './core-context';
|
||||||
import { Result, Ok, Err } from 'ts-results-es';
|
import { Result, Ok, Err } from 'ts-results-es';
|
||||||
import * as assert from 'assert';
|
import * as assert from 'assert';
|
||||||
import { ReplyOptions } from '../../types/utility';
|
import { ReplyOptions } from '../../shared';
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @since 1.0.0
|
* @since 1.0.0
|
||||||
@@ -31,81 +30,52 @@ export class Context extends CoreContext<Message, ChatInputCommandInteraction> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public get id(): Snowflake {
|
public get id(): Snowflake {
|
||||||
return safeUnwrap(this.ctx
|
return this.ctx.val.id;
|
||||||
.map(m => m.id)
|
|
||||||
.mapErr(i => i.id));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public get channel() {
|
public get channel() {
|
||||||
return safeUnwrap(this.ctx
|
return this.ctx.val.channel;
|
||||||
.map(m => m.channel)
|
|
||||||
.mapErr(i => i.channel));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public get channelId(): Snowflake {
|
|
||||||
return safeUnwrap(this.ctx
|
|
||||||
.map(m => m.channelId)
|
|
||||||
.mapErr(i => i.channelId));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* If context is holding a message, message.author
|
* If context is holding a message, message.author
|
||||||
* else, interaction.user
|
* else, interaction.user
|
||||||
*/
|
*/
|
||||||
public get user(): User {
|
public get user(): User {
|
||||||
return safeUnwrap(this.ctx
|
return safeUnwrap(this.ctx.map(m => m.author).mapErr(i => i.user));
|
||||||
.map(m => m.author)
|
|
||||||
.mapErr(i => i.user));
|
|
||||||
}
|
|
||||||
|
|
||||||
public get userId(): Snowflake {
|
|
||||||
return this.user.id;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public get createdTimestamp(): number {
|
public get createdTimestamp(): number {
|
||||||
return safeUnwrap(this.ctx
|
return this.ctx.val.createdTimestamp;
|
||||||
.map(m => m.createdTimestamp)
|
|
||||||
.mapErr(i => i.createdTimestamp));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public get guild() {
|
public get guild() {
|
||||||
return safeUnwrap(this.ctx
|
return this.ctx.val.guild;
|
||||||
.map(m => m.guild)
|
|
||||||
.mapErr(i => i.guild));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public get guildId() {
|
public get guildId() {
|
||||||
return safeUnwrap(this.ctx
|
return this.ctx.val.guildId;
|
||||||
.map(m => m.guildId)
|
|
||||||
.mapErr(i => i.guildId));
|
|
||||||
}
|
}
|
||||||
/*
|
/*
|
||||||
* interactions can return APIGuildMember if the guild it is emitted from is not cached
|
* interactions can return APIGuildMember if the guild it is emitted from is not cached
|
||||||
*/
|
*/
|
||||||
public get member() {
|
public get member() {
|
||||||
return safeUnwrap(this.ctx
|
return this.ctx.val.member;
|
||||||
.map(m => m.member)
|
|
||||||
.mapErr(i => i.member));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public get client(): Client {
|
public get client(): Client {
|
||||||
return safeUnwrap(this.ctx
|
return this.ctx.val.client;
|
||||||
.map(m => m.client)
|
|
||||||
.mapErr(i => i.client));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public get inGuild(): boolean {
|
public get inGuild(): boolean {
|
||||||
return safeUnwrap(this.ctx
|
return this.ctx.val.inGuild();
|
||||||
.map(m => m.inGuild())
|
|
||||||
.mapErr(i => i.inGuild()));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public async reply(content: ReplyOptions) {
|
public async reply(content: ReplyOptions) {
|
||||||
return safeUnwrap(
|
return safeUnwrap(
|
||||||
this.ctx
|
this.ctx
|
||||||
.map(m => m.reply(content as MessageReplyOptions))
|
.map(m => m.reply(content as string | MessageReplyOptions))
|
||||||
.mapErr(i =>
|
.mapErr(i =>
|
||||||
i.reply(content as InteractionReplyOptions).then(() => i.fetchReply()),
|
i.reply(content as string | InteractionReplyOptions).then(() => i.fetchReply()),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -120,8 +90,5 @@ export class Context extends CoreContext<Message, ChatInputCommandInteraction> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function safeUnwrap<T>(res: Result<T, T>) {
|
function safeUnwrap<T>(res: Result<T, T>) {
|
||||||
if(res.isOk()) {
|
return res.val;
|
||||||
return res.expect("Tried unwrapping message field: " + res)
|
|
||||||
}
|
|
||||||
return res.expectErr("Tried unwrapping interaction field" + res)
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { Result as Either } from 'ts-results-es';
|
import { Result as Either } from 'ts-results-es';
|
||||||
import { SernError } from '../_internal';
|
import { SernError } from './errors';
|
||||||
import * as assert from 'node:assert';
|
import * as assert from 'node:assert';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -7,7 +7,7 @@ import * as assert from 'node:assert';
|
|||||||
*/
|
*/
|
||||||
export abstract class CoreContext<M, I> {
|
export abstract class CoreContext<M, I> {
|
||||||
protected constructor(protected ctx: Either<M, I>) {
|
protected constructor(protected ctx: Either<M, I>) {
|
||||||
assert.ok(typeof ctx === 'object' && ctx != null);
|
assert.ok(typeof ctx.val === 'object' && ctx.val != null);
|
||||||
}
|
}
|
||||||
get message(): M {
|
get message(): M {
|
||||||
return this.ctx.expect(SernError.MismatchEvent);
|
return this.ctx.expect(SernError.MismatchEvent);
|
||||||
@@ -17,7 +17,7 @@ export abstract class CoreContext<M, I> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public isMessage(): this is CoreContext<M, never> {
|
public isMessage(): this is CoreContext<M, never> {
|
||||||
return this.ctx.isOk();
|
return this.ctx.ok;
|
||||||
}
|
}
|
||||||
|
|
||||||
public isSlash(): this is CoreContext<never, I> {
|
public isSlash(): this is CoreContext<never, I> {
|
||||||
@@ -26,6 +26,8 @@ export abstract class CoreContext<M, I> {
|
|||||||
//todo: add agnostic options resolver for Context
|
//todo: add agnostic options resolver for Context
|
||||||
abstract get options(): unknown;
|
abstract get options(): unknown;
|
||||||
|
|
||||||
|
abstract get id(): string;
|
||||||
|
|
||||||
static wrap(_: unknown): unknown {
|
static wrap(_: unknown): unknown {
|
||||||
throw Error('You need to override this method; cannot wrap an abstract class');
|
throw Error('You need to override this method; cannot wrap an abstract class');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,10 +23,10 @@ export enum CommandType {
|
|||||||
Button = 1 << 4,
|
Button = 1 << 4,
|
||||||
StringSelect = 1 << 5,
|
StringSelect = 1 << 5,
|
||||||
Modal = 1 << 6,
|
Modal = 1 << 6,
|
||||||
UserSelect = 1 << 7,
|
ChannelSelect = 1 << 7,
|
||||||
RoleSelect = 1 << 8,
|
MentionableSelect = 1 << 8,
|
||||||
MentionableSelect = 1 << 9,
|
RoleSelect = 1 << 9,
|
||||||
ChannelSelect = 1 << 10,
|
UserSelect = 1 << 10,
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -101,42 +101,3 @@ export enum PayloadType {
|
|||||||
*/
|
*/
|
||||||
Warning = 'warning',
|
Warning = 'warning',
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* @enum { string }
|
|
||||||
*/
|
|
||||||
export const enum SernError {
|
|
||||||
/**
|
|
||||||
* Throws when registering an invalid module.
|
|
||||||
* This means it is undefined or an invalid command type was provided
|
|
||||||
*/
|
|
||||||
InvalidModuleType = 'Detected an unknown module type',
|
|
||||||
/**
|
|
||||||
* Attempted to lookup module in command module store. Nothing was found!
|
|
||||||
*/
|
|
||||||
UndefinedModule = `A module could not be detected`,
|
|
||||||
/**
|
|
||||||
* Attempted to lookup module in command module store. Nothing was found!
|
|
||||||
*/
|
|
||||||
MismatchModule = `A module type mismatched with event emitted!`,
|
|
||||||
/**
|
|
||||||
* Unsupported interaction at this moment.
|
|
||||||
*/
|
|
||||||
NotSupportedInteraction = `This interaction is not supported.`,
|
|
||||||
/**
|
|
||||||
* One plugin called `controller.stop()` (end command execution / loading)
|
|
||||||
*/
|
|
||||||
PluginFailure = `A plugin failed to call controller.next()`,
|
|
||||||
/**
|
|
||||||
* A crash that occurs when accessing an invalid property of Context
|
|
||||||
*/
|
|
||||||
MismatchEvent = `You cannot use message when an interaction fired or vice versa`,
|
|
||||||
/**
|
|
||||||
* Unsupported feature attempted to access at this time
|
|
||||||
*/
|
|
||||||
NotSupportedYet = `This feature is not supported yet`,
|
|
||||||
/**
|
|
||||||
* Required Dependency not found
|
|
||||||
*/
|
|
||||||
MissingRequired = `@sern/client is required but was not found`,
|
|
||||||
}
|
|
||||||
|
|||||||
38
src/core/structures/errors.ts
Normal file
38
src/core/structures/errors.ts
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
/**
|
||||||
|
* @enum { string }
|
||||||
|
*/
|
||||||
|
export const enum SernError {
|
||||||
|
/**
|
||||||
|
* Throws when registering an invalid module.
|
||||||
|
* This means it is undefined or an invalid command type was provided
|
||||||
|
*/
|
||||||
|
InvalidModuleType = 'Detected an unknown module type',
|
||||||
|
/**
|
||||||
|
* Attempted to lookup module in command module store. Nothing was found!
|
||||||
|
*/
|
||||||
|
UndefinedModule = `A module could not be detected`,
|
||||||
|
/**
|
||||||
|
* Attempted to lookup module in command module store. Nothing was found!
|
||||||
|
*/
|
||||||
|
MismatchModule = `A module type mismatched with event emitted!`,
|
||||||
|
/**
|
||||||
|
* Unsupported interaction at this moment.
|
||||||
|
*/
|
||||||
|
NotSupportedInteraction = `This interaction is not supported.`,
|
||||||
|
/**
|
||||||
|
* One plugin called `controller.stop()` (end command execution / loading)
|
||||||
|
*/
|
||||||
|
PluginFailure = `A plugin failed to call controller.next()`,
|
||||||
|
/**
|
||||||
|
* A crash that occurs when accessing an invalid property of Context
|
||||||
|
*/
|
||||||
|
MismatchEvent = `You cannot use message when an interaction fired or vice versa`,
|
||||||
|
/**
|
||||||
|
* Unsupported feature attempted to access at this time
|
||||||
|
*/
|
||||||
|
NotSupportedYet = `This feature is not supported yet`,
|
||||||
|
/**
|
||||||
|
* Required Dependency not found
|
||||||
|
*/
|
||||||
|
MissingRequired = `@sern/client is required but was not found`,
|
||||||
|
}
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
export { CommandType, PluginType, PayloadType, EventType } from './enums';
|
export * from './enums';
|
||||||
export * from './context';
|
export * from './context';
|
||||||
export * from './sern-emitter';
|
export * from './sern-emitter';
|
||||||
export * from './services';
|
export * from './services';
|
||||||
export * from './module-store';
|
export * from './module-store';
|
||||||
export * as CommandError from './command-error';
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { CommandMeta, Module, OnError } from '../../types/core-modules';
|
|
||||||
import { CoreModuleStore } from '../contracts';
|
import { CoreModuleStore } from '../contracts';
|
||||||
|
import { Module, CommandMeta } from '../types/modules';
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* @internal
|
* @internal
|
||||||
@@ -7,7 +7,6 @@ import { CoreModuleStore } from '../contracts';
|
|||||||
* For interacting with modules, use the ModuleManager instead.
|
* For interacting with modules, use the ModuleManager instead.
|
||||||
*/
|
*/
|
||||||
export class ModuleStore implements CoreModuleStore {
|
export class ModuleStore implements CoreModuleStore {
|
||||||
onError = new WeakMap<Module, NonNullable<OnError>>();
|
|
||||||
metadata = new WeakMap<Module, CommandMeta>();
|
metadata = new WeakMap<Module, CommandMeta>();
|
||||||
commands = new Map<string, string>();
|
commands = new Map<string, string>();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { EventEmitter } from 'node:events';
|
import { EventEmitter } from 'node:events';
|
||||||
import { PayloadType } from '../../core/structures';
|
import { PayloadType } from '../../core/structures';
|
||||||
import { Module } from '../../types/core-modules';
|
import { Payload, SernEventsMapping } from '../../shared';
|
||||||
import { SernEventsMapping, Payload } from '../../types/utility';
|
import { Module } from '../types/modules';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @since 1.0.0
|
* @since 1.0.0
|
||||||
|
|||||||
@@ -3,19 +3,20 @@ import { ErrorHandling } from '../../contracts';
|
|||||||
/**
|
/**
|
||||||
* @internal
|
* @internal
|
||||||
* @since 2.0.0
|
* @since 2.0.0
|
||||||
* Version 4.0.0 will internalize this api. Please refrain from using the defaults!
|
* Version 4.0.0 will internalize this api. Please refrain from using ModuleStore!
|
||||||
*/
|
*/
|
||||||
export class DefaultErrorHandling implements ErrorHandling {
|
export class DefaultErrorHandling implements ErrorHandling {
|
||||||
|
|
||||||
crash(err: Error): never {
|
crash(err: Error): never {
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
|
|
||||||
#keepAlive = 5;
|
keepAlive = 5;
|
||||||
|
|
||||||
updateAlive(err: Error) {
|
updateAlive(err: Error) {
|
||||||
this.#keepAlive--;
|
this.keepAlive--;
|
||||||
if (this.#keepAlive === 0) {
|
if(this.keepAlive === 0) {
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import * as Id from '../../../core/id';
|
import { createId } from '../../../handler/id';
|
||||||
import { CoreModuleStore, ModuleManager } from '../../contracts';
|
import { CoreModuleStore, ModuleManager } from '../../contracts';
|
||||||
import { Files } from '../../_internal';
|
import { importModule } from '../../module-loading';
|
||||||
import { CommandMeta, CommandModule, CommandModuleDefs, Module, OnError } from '../../../types/core-modules';
|
import { CommandMeta, CommandModule, CommandModuleDefs, Module } from '../../types/modules';
|
||||||
import { CommandType } from '../enums';
|
import { CommandType } from '../enums';
|
||||||
/**
|
/**
|
||||||
* @internal
|
* @internal
|
||||||
@@ -11,20 +11,12 @@ import { CommandType } from '../enums';
|
|||||||
export class DefaultModuleManager implements ModuleManager {
|
export class DefaultModuleManager implements ModuleManager {
|
||||||
constructor(private moduleStore: CoreModuleStore) {}
|
constructor(private moduleStore: CoreModuleStore) {}
|
||||||
|
|
||||||
|
|
||||||
getErrorCallback(m: Module): OnError {
|
|
||||||
return this.moduleStore.onError.get(m);
|
|
||||||
}
|
|
||||||
setErrorCallback(m: Module, c: NonNullable<OnError>): void {
|
|
||||||
this.moduleStore.onError.set(m, c);
|
|
||||||
}
|
|
||||||
|
|
||||||
getByNameCommandType<T extends CommandType>(name: string, commandType: T) {
|
getByNameCommandType<T extends CommandType>(name: string, commandType: T) {
|
||||||
const id = this.get(Id.create(name, commandType));
|
const id = this.get(createId(name, commandType));
|
||||||
if (!id) {
|
if(!id) {
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
return Files.importModule<CommandModuleDefs[T]>(id);
|
return importModule<CommandModuleDefs[T]>(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
setMetadata(m: Module, c: CommandMeta): void {
|
setMetadata(m: Module, c: CommandMeta): void {
|
||||||
@@ -34,11 +26,12 @@ export class DefaultModuleManager implements ModuleManager {
|
|||||||
getMetadata(m: Module): CommandMeta {
|
getMetadata(m: Module): CommandMeta {
|
||||||
const maybeModule = this.moduleStore.metadata.get(m);
|
const maybeModule = this.moduleStore.metadata.get(m);
|
||||||
if (!maybeModule) {
|
if (!maybeModule) {
|
||||||
throw Error('Could not find metadata in store for ' + m);
|
throw Error('Could not find metadata in store for ' + maybeModule);
|
||||||
}
|
}
|
||||||
return maybeModule;
|
return maybeModule;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
get(id: string) {
|
get(id: string) {
|
||||||
return this.moduleStore.commands.get(id);
|
return this.moduleStore.commands.get(id);
|
||||||
}
|
}
|
||||||
@@ -52,7 +45,7 @@ export class DefaultModuleManager implements ModuleManager {
|
|||||||
return Promise.all(
|
return Promise.all(
|
||||||
Array.from(entries)
|
Array.from(entries)
|
||||||
.filter(([id]) => !(Number.parseInt(id.at(-1)!) & publishable))
|
.filter(([id]) => !(Number.parseInt(id.at(-1)!) & publishable))
|
||||||
.map(([, path]) => Files.importModule<CommandModule>(path)),
|
.map(([, path]) => importModule<CommandModule>(path)),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,6 +3,8 @@ import type {
|
|||||||
APIApplicationCommandOptionBase,
|
APIApplicationCommandOptionBase,
|
||||||
ApplicationCommandOptionType,
|
ApplicationCommandOptionType,
|
||||||
BaseApplicationCommandOptionsData,
|
BaseApplicationCommandOptionsData,
|
||||||
|
} from 'discord.js';
|
||||||
|
import {
|
||||||
AutocompleteInteraction,
|
AutocompleteInteraction,
|
||||||
ButtonInteraction,
|
ButtonInteraction,
|
||||||
ChannelSelectMenuInteraction,
|
ChannelSelectMenuInteraction,
|
||||||
@@ -15,20 +17,19 @@ import type {
|
|||||||
UserContextMenuCommandInteraction,
|
UserContextMenuCommandInteraction,
|
||||||
UserSelectMenuInteraction,
|
UserSelectMenuInteraction,
|
||||||
} from 'discord.js';
|
} from 'discord.js';
|
||||||
import { CommandType, Context, EventType } from '../../src/core';
|
import { CommandType, Context, EventType } from '../structures';
|
||||||
import { AnyCommandPlugin, AnyEventPlugin, ControlPlugin, InitPlugin } from './core-plugin';
|
import { AnyCommandPlugin, AnyEventPlugin, ControlPlugin, InitPlugin } from './plugins';
|
||||||
import { Awaitable, Args, SlashOptions, SernEventsMapping, AnyFunction } from './utility';
|
import { Awaitable, SernEventsMapping } from '../../shared';
|
||||||
|
import { Processed } from '../../handler/types';
|
||||||
export type OnError = AnyFunction|undefined
|
import { Args, SlashOptions } from '../../shared';
|
||||||
|
|
||||||
|
|
||||||
export interface CommandMeta {
|
export interface CommandMeta {
|
||||||
fullPath: string;
|
fullPath: string;
|
||||||
id: string;
|
id: string;
|
||||||
isClass: boolean;
|
isClass: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
export type Processed<T> = T & { name: string; description: string };
|
export type AnyDefinedModule = Processed<CommandModule | EventModule>;
|
||||||
|
|
||||||
export interface Module {
|
export interface Module {
|
||||||
type: CommandType | EventType;
|
type: CommandType | EventType;
|
||||||
@@ -36,7 +37,7 @@ export interface Module {
|
|||||||
onEvent: ControlPlugin[];
|
onEvent: ControlPlugin[];
|
||||||
plugins: InitPlugin[];
|
plugins: InitPlugin[];
|
||||||
description?: string;
|
description?: string;
|
||||||
execute(...args: any[]): Awaitable<any>;
|
execute: (...args: any[]) => Awaitable<any>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface SernEventCommand<T extends keyof SernEventsMapping = keyof SernEventsMapping>
|
export interface SernEventCommand<T extends keyof SernEventsMapping = keyof SernEventsMapping>
|
||||||
@@ -146,6 +147,7 @@ export type CommandModule =
|
|||||||
| ModalSubmitCommand;
|
| ModalSubmitCommand;
|
||||||
|
|
||||||
export type AnyModule = CommandModule | EventModule;
|
export type AnyModule = CommandModule | EventModule;
|
||||||
|
|
||||||
//https://stackoverflow.com/questions/64092736/alternative-to-switch-statement-for-typescript-discriminated-union
|
//https://stackoverflow.com/questions/64092736/alternative-to-switch-statement-for-typescript-discriminated-union
|
||||||
// Explicit Module Definitions for mapping
|
// Explicit Module Definitions for mapping
|
||||||
export interface CommandModuleDefs {
|
export interface CommandModuleDefs {
|
||||||
@@ -191,11 +193,10 @@ export type InputEvent = {
|
|||||||
}[EventType];
|
}[EventType];
|
||||||
|
|
||||||
export type InputCommand = {
|
export type InputCommand = {
|
||||||
[T in CommandType]: CommandModuleNoPlugins[T] & {
|
[T in CommandType]: CommandModuleNoPlugins[T] & { plugins?: AnyCommandPlugin[] };
|
||||||
plugins?: AnyCommandPlugin[];
|
|
||||||
};
|
|
||||||
}[CommandType];
|
}[CommandType];
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Type that replaces autocomplete with {@link SernAutocompleteData}
|
* Type that replaces autocomplete with {@link SernAutocompleteData}
|
||||||
*/
|
*/
|
||||||
@@ -205,8 +206,7 @@ export type SernOptionsData =
|
|||||||
| APIApplicationCommandBasicOption
|
| APIApplicationCommandBasicOption
|
||||||
| SernAutocompleteData;
|
| SernAutocompleteData;
|
||||||
|
|
||||||
export interface SernSubCommandData
|
export interface SernSubCommandData extends APIApplicationCommandOptionBase<ApplicationCommandOptionType.Subcommand> {
|
||||||
extends APIApplicationCommandOptionBase<ApplicationCommandOptionType.Subcommand> {
|
|
||||||
type: ApplicationCommandOptionType.Subcommand;
|
type: ApplicationCommandOptionType.Subcommand;
|
||||||
options?: SernOptionsData[];
|
options?: SernOptionsData[];
|
||||||
}
|
}
|
||||||
@@ -24,17 +24,16 @@ import type {
|
|||||||
ExternalEventCommand,
|
ExternalEventCommand,
|
||||||
MentionableSelectCommand,
|
MentionableSelectCommand,
|
||||||
ModalSubmitCommand,
|
ModalSubmitCommand,
|
||||||
Module,
|
|
||||||
Processed,
|
|
||||||
RoleSelectCommand,
|
RoleSelectCommand,
|
||||||
SernEventCommand,
|
SernEventCommand,
|
||||||
SlashCommand,
|
SlashCommand,
|
||||||
StringSelectCommand,
|
StringSelectCommand,
|
||||||
TextCommand,
|
TextCommand,
|
||||||
UserSelectCommand,
|
UserSelectCommand,
|
||||||
} from './core-modules';
|
} from './modules';
|
||||||
import { Args, Awaitable, Payload, SlashOptions } from './utility';
|
import { Args, Awaitable, Payload, SlashOptions } from '../../shared';
|
||||||
import { CommandType, Context, EventType, PluginType } from '../core';
|
import { CommandType, Context, EventType, PluginType } from '../structures';
|
||||||
|
import { InitArgs, Processed } from '../../handler/types';
|
||||||
import {
|
import {
|
||||||
ButtonInteraction,
|
ButtonInteraction,
|
||||||
ChannelSelectMenuInteraction,
|
ChannelSelectMenuInteraction,
|
||||||
@@ -51,10 +50,6 @@ import {
|
|||||||
export type PluginResult = Awaitable<VoidResult>;
|
export type PluginResult = Awaitable<VoidResult>;
|
||||||
export type VoidResult = Result<void, void>;
|
export type VoidResult = Result<void, void>;
|
||||||
|
|
||||||
export interface InitArgs<T extends Processed<Module>> {
|
|
||||||
module: T;
|
|
||||||
absPath: string;
|
|
||||||
}
|
|
||||||
export interface Controller {
|
export interface Controller {
|
||||||
next: () => Ok<void>;
|
next: () => Ok<void>;
|
||||||
stop: () => Err<void>;
|
stop: () => Err<void>;
|
||||||
@@ -1,22 +1,22 @@
|
|||||||
import { ClientEvents } from 'discord.js';
|
import { ClientEvents } from 'discord.js';
|
||||||
import { CommandType, EventType, PluginType } from '../core/structures';
|
import { CommandType, EventType, PluginType } from '../core/structures';
|
||||||
import type {
|
import {
|
||||||
AnyCommandPlugin,
|
AnyCommandPlugin,
|
||||||
AnyEventPlugin,
|
AnyEventPlugin,
|
||||||
CommandArgs,
|
CommandArgs,
|
||||||
ControlPlugin,
|
ControlPlugin,
|
||||||
EventArgs,
|
EventArgs,
|
||||||
InitPlugin,
|
InitPlugin,
|
||||||
} from '../types/core-plugin';
|
} from '../core/types/plugins';
|
||||||
import type {
|
import {
|
||||||
CommandModule,
|
CommandModule,
|
||||||
EventModule,
|
EventModule,
|
||||||
InputCommand,
|
InputCommand,
|
||||||
InputEvent,
|
InputEvent,
|
||||||
Module,
|
Module,
|
||||||
} from '../types/core-modules';
|
} from '../core/types/modules';
|
||||||
import { partitionPlugins } from './_internal';
|
import { partitionPlugins } from '../core/functions';
|
||||||
import type { Awaitable } from '../types/utility';
|
import { Awaitable } from '../shared';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @since 1.0.0 The wrapper function to define command modules for sern
|
* @since 1.0.0 The wrapper function to define command modules for sern
|
||||||
119
src/handler/events/dispatchers.ts
Normal file
119
src/handler/events/dispatchers.ts
Normal file
@@ -0,0 +1,119 @@
|
|||||||
|
import { EventEmitter } from 'node:events';
|
||||||
|
import * as assert from 'node:assert';
|
||||||
|
import { concatMap, from, fromEvent, map, OperatorFunction, pipe } from 'rxjs';
|
||||||
|
import { arrayifySource, callPlugin } from '../../core/operators';
|
||||||
|
import { createResultResolver } from './generic';
|
||||||
|
import { AutocompleteInteraction, BaseInteraction, Message } from 'discord.js';
|
||||||
|
import { treeSearch } from '../../core/functions';
|
||||||
|
import { SernError } from '../../core/structures/errors';
|
||||||
|
import { CommandType, Context } from '../../core';
|
||||||
|
import { isAutocomplete } from '../../core/predicates';
|
||||||
|
import { Processed } from '../types';
|
||||||
|
import { BothCommand, CommandModule, Module } from '../../core/types/modules';
|
||||||
|
import { Args } from '../../shared';
|
||||||
|
|
||||||
|
|
||||||
|
function dispatchInteraction<T extends CommandModule, V extends BaseInteraction | Message>(
|
||||||
|
payload: { module: Processed<T>; event: V },
|
||||||
|
createArgs: (m: typeof payload.event) => unknown[],
|
||||||
|
) {
|
||||||
|
return {
|
||||||
|
module: payload.module,
|
||||||
|
args: createArgs(payload.event),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
//TODO: refactor dispatchers so that it implements a strategy for each different type of payload?
|
||||||
|
export function dispatchMessage(module: Processed<CommandModule>, args: [Context, Args]) {
|
||||||
|
return {
|
||||||
|
module,
|
||||||
|
args,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function dispatchAutocomplete(payload: {
|
||||||
|
module: Processed<BothCommand>;
|
||||||
|
event: AutocompleteInteraction;
|
||||||
|
}) {
|
||||||
|
const option = treeSearch(payload.event, payload.module.options);
|
||||||
|
if (option !== undefined) {
|
||||||
|
return {
|
||||||
|
module: option.command as Processed<Module>, //autocomplete is not a true "module" warning cast!
|
||||||
|
args: [payload.event],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
throw Error(
|
||||||
|
SernError.NotSupportedInteraction + ` There is no autocomplete tag for this option`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function contextArgs(wrappable: Message | BaseInteraction, messageArgs?: string[]) {
|
||||||
|
const ctx = Context.wrap(wrappable);
|
||||||
|
const args = ctx.isMessage() ? ['text', messageArgs!] : ['slash', ctx.options];
|
||||||
|
return [ctx, args] as [Context, Args];
|
||||||
|
}
|
||||||
|
|
||||||
|
function interactionArg<T extends BaseInteraction>(interaction: T) {
|
||||||
|
return [interaction] as [T];
|
||||||
|
}
|
||||||
|
|
||||||
|
function intoPayload(module: Processed<Module>) {
|
||||||
|
return pipe(
|
||||||
|
arrayifySource,
|
||||||
|
map(args => ({ module, args })),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const createResult = createResultResolver<
|
||||||
|
Processed<Module>,
|
||||||
|
{ module: Processed<Module>; args: unknown[] },
|
||||||
|
unknown[]
|
||||||
|
>({
|
||||||
|
createStream: ({ module, args }) => from(module.onEvent).pipe(callPlugin(args)),
|
||||||
|
onNext: ({ args }) => args,
|
||||||
|
});
|
||||||
|
/**
|
||||||
|
* Creates an observable from { source }
|
||||||
|
* @param module
|
||||||
|
* @param source
|
||||||
|
*/
|
||||||
|
export function eventDispatcher(module: Processed<Module>, source: unknown) {
|
||||||
|
assert.ok(source instanceof EventEmitter, `${source} is not an EventEmitter`);
|
||||||
|
|
||||||
|
const execute: OperatorFunction<unknown[], unknown> = concatMap(async args =>
|
||||||
|
module.execute(...args),
|
||||||
|
);
|
||||||
|
return fromEvent(source, module.name).pipe(
|
||||||
|
intoPayload(module),
|
||||||
|
concatMap(createResult),
|
||||||
|
execute,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createDispatcher(payload: {
|
||||||
|
module: Processed<CommandModule>;
|
||||||
|
event: BaseInteraction;
|
||||||
|
}) {
|
||||||
|
switch (payload.module.type) {
|
||||||
|
case CommandType.Text:
|
||||||
|
throw Error(
|
||||||
|
SernError.MismatchEvent +
|
||||||
|
' Found a text module in interaction stream. ' +
|
||||||
|
payload.module,
|
||||||
|
);
|
||||||
|
case CommandType.Slash:
|
||||||
|
case CommandType.Both: {
|
||||||
|
if (isAutocomplete(payload.event)) {
|
||||||
|
/**
|
||||||
|
* Autocomplete is a special case that
|
||||||
|
* must be handled separately, since it's
|
||||||
|
* too different from regular command modules
|
||||||
|
* CAST SAFETY: payload is already guaranteed to be a slash command or both command
|
||||||
|
*/
|
||||||
|
return dispatchAutocomplete(payload as never);
|
||||||
|
}
|
||||||
|
return dispatchInteraction(payload, contextArgs);
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return dispatchInteraction(payload, interactionArg);
|
||||||
|
}
|
||||||
|
}
|
||||||
232
src/handler/events/generic.ts
Normal file
232
src/handler/events/generic.ts
Normal file
@@ -0,0 +1,232 @@
|
|||||||
|
import { Interaction, Message } from 'discord.js';
|
||||||
|
import {
|
||||||
|
EMPTY,
|
||||||
|
Observable,
|
||||||
|
concatMap,
|
||||||
|
filter,
|
||||||
|
from,
|
||||||
|
of,
|
||||||
|
throwError,
|
||||||
|
tap,
|
||||||
|
MonoTypeOperatorFunction,
|
||||||
|
catchError,
|
||||||
|
finalize,
|
||||||
|
} from 'rxjs';
|
||||||
|
import { ErrorHandling, Logging, ModuleManager, useContainerRaw } from '../../core';
|
||||||
|
import { SernError } from '../../core/structures/errors';
|
||||||
|
import { callPlugin, everyPluginOk, filterMap, filterMapTo, handleError } from '../../core/operators';
|
||||||
|
import { defaultModuleLoader } from '../../core/module-loading';
|
||||||
|
import { CommandModule, Module, AnyModule } from '../../core/types/modules';
|
||||||
|
import { contextArgs, createDispatcher, dispatchMessage } from './dispatchers';
|
||||||
|
import { ObservableInput, pipe, switchMap } from 'rxjs';
|
||||||
|
import { SernEmitter } from '../../core';
|
||||||
|
import { errTap } from '../../core/operators';
|
||||||
|
import * as Files from '../../core/module-loading';
|
||||||
|
import { Err, Result } from 'ts-results-es';
|
||||||
|
import { fmt } from './messages';
|
||||||
|
import { ControlPlugin, VoidResult } from '../../core/types/plugins';
|
||||||
|
import { ImportPayload, Processed } from '../types';
|
||||||
|
import { Awaitable } from '../../shared';
|
||||||
|
import { createId, reconstructId } from '../id';
|
||||||
|
|
||||||
|
function createGenericHandler<Source, Narrowed extends Source, Output>(
|
||||||
|
source: Observable<Source>,
|
||||||
|
makeModule: (event: Narrowed) => Awaitable<Result<Output, unknown>>,
|
||||||
|
) {
|
||||||
|
return (pred: (i: Source) => i is Narrowed) => source.pipe(filter(pred), filterMap(makeModule));
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* Creates an RxJS observable that filters and maps incoming interactions to their respective modules.
|
||||||
|
* @param i An RxJS observable of interactions.
|
||||||
|
* @param mg The module manager instance used to retrieve the module path for each interaction.
|
||||||
|
* @returns A handler to create a RxJS observable of dispatchers that take incoming interactions and execute their corresponding modules.
|
||||||
|
*/
|
||||||
|
export function createInteractionHandler<T extends Interaction>(
|
||||||
|
source: Observable<Interaction>,
|
||||||
|
mg: ModuleManager,
|
||||||
|
) {
|
||||||
|
return createGenericHandler<Interaction, T, ReturnType<typeof createDispatcher>>(
|
||||||
|
source,
|
||||||
|
event => {
|
||||||
|
const fullPath = mg.get(reconstructId(event as unknown as Interaction));
|
||||||
|
if (!fullPath)
|
||||||
|
return Err(SernError.UndefinedModule + ' No full path found in module store');
|
||||||
|
return defaultModuleLoader<Processed<CommandModule>>(fullPath).then(res =>
|
||||||
|
res.map(payload => createDispatcher({ module: payload.module, event })),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createMessageHandler(
|
||||||
|
source: Observable<Message>,
|
||||||
|
defaultPrefix: string,
|
||||||
|
mg: ModuleManager,
|
||||||
|
) {
|
||||||
|
return createGenericHandler(source, event => {
|
||||||
|
const [prefix, ...rest] = fmt(event.content, defaultPrefix);
|
||||||
|
const fullPath = mg.get(`${prefix}_A0`);
|
||||||
|
if (fullPath === undefined) {
|
||||||
|
return Err(SernError.UndefinedModule + ' No full path found in module store');
|
||||||
|
}
|
||||||
|
return defaultModuleLoader<Processed<CommandModule>>(fullPath).then(result => {
|
||||||
|
const args = contextArgs(event, rest);
|
||||||
|
return result.map(payload => dispatchMessage(payload.module, args));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* IMPURE SIDE EFFECT
|
||||||
|
* This function assigns remaining, incomplete data to each imported module.
|
||||||
|
*/
|
||||||
|
function assignDefaults<T extends Module>(
|
||||||
|
moduleManager: ModuleManager,
|
||||||
|
): MonoTypeOperatorFunction<ImportPayload<T>> {
|
||||||
|
return tap(({ module, absPath }) => {
|
||||||
|
module.name ??= Files.filename(absPath);
|
||||||
|
module.description ??= '...';
|
||||||
|
moduleManager.setMetadata(module, {
|
||||||
|
isClass: module.constructor.name === 'Function',
|
||||||
|
fullPath: absPath,
|
||||||
|
id: createId(module.name, module.type),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildModules<T extends AnyModule>(
|
||||||
|
input: ObservableInput<string>,
|
||||||
|
sernEmitter: SernEmitter,
|
||||||
|
moduleManager: ModuleManager,
|
||||||
|
) {
|
||||||
|
return pipe(
|
||||||
|
switchMap(() => Files.buildModuleStream<T>(input)),
|
||||||
|
errTap(error => {
|
||||||
|
sernEmitter.emit('module.register', SernEmitter.failure(undefined, error));
|
||||||
|
}),
|
||||||
|
assignDefaults<T>(moduleManager),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function hasPrefix(prefix: string, content: string) {
|
||||||
|
const prefixInContent = content.slice(0, prefix.length);
|
||||||
|
return prefixInContent.localeCompare(prefix, undefined, { sensitivity: 'accent' }) === 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ignores messages from any person / bot except itself
|
||||||
|
* @param prefix
|
||||||
|
*/
|
||||||
|
export function isNonBot(prefix: string) {
|
||||||
|
return ({ author, content }: Message) => !author.bot && hasPrefix(prefix, content);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Wraps the task in a Result as a try / catch.
|
||||||
|
* if the task is ok, an event is emitted and the stream becomes empty
|
||||||
|
* if the task is an error, throw an error down the stream which will be handled by catchError
|
||||||
|
* @param emitter reference to SernEmitter that will emit a successful execution of module
|
||||||
|
* @param module the module that will be executed with task
|
||||||
|
* @param task the deferred execution which will be called
|
||||||
|
*/
|
||||||
|
export function executeModule(
|
||||||
|
emitter: SernEmitter,
|
||||||
|
{
|
||||||
|
module,
|
||||||
|
task,
|
||||||
|
}: {
|
||||||
|
module: Processed<Module>;
|
||||||
|
task: () => Awaitable<unknown>;
|
||||||
|
},
|
||||||
|
) {
|
||||||
|
return of(module).pipe(
|
||||||
|
//converting the task into a promise so rxjs can resolve the Awaitable properly
|
||||||
|
concatMap(() => Result.wrapAsync(async () => task())),
|
||||||
|
concatMap(result => {
|
||||||
|
if (result.ok) {
|
||||||
|
emitter.emit('module.activate', SernEmitter.success(module));
|
||||||
|
return EMPTY;
|
||||||
|
} else {
|
||||||
|
return throwError(() => SernEmitter.failure(module, result.val));
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A higher order function that
|
||||||
|
* - creates a stream of {@link VoidResult} { config.createStream }
|
||||||
|
* - any failures results to { config.onFailure } being called
|
||||||
|
* - if all results are ok, the stream is converted to { config.onNext }
|
||||||
|
* emit config.onSuccess Observable
|
||||||
|
* @param config
|
||||||
|
* @returns receiver function for flattening a stream of data
|
||||||
|
*/
|
||||||
|
export function createResultResolver<
|
||||||
|
T extends { execute: (...args: any[]) => any; onEvent: ControlPlugin[] },
|
||||||
|
Args extends { module: T; [key: string]: unknown },
|
||||||
|
Output,
|
||||||
|
>(config: {
|
||||||
|
onStop?: (module: T) => unknown;
|
||||||
|
onNext: (args: Args) => Output;
|
||||||
|
createStream: (args: Args) => Observable<VoidResult>;
|
||||||
|
}) {
|
||||||
|
return (args: Args) => {
|
||||||
|
const task$ = config.createStream(args);
|
||||||
|
return task$.pipe(
|
||||||
|
tap(result => {
|
||||||
|
result.err && config.onStop?.(args.module);
|
||||||
|
}),
|
||||||
|
everyPluginOk,
|
||||||
|
filterMapTo(() => config.onNext(args)),
|
||||||
|
);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Calls a module's init plugins and checks for Err. If so, call { onStop } and
|
||||||
|
* ignore the module
|
||||||
|
*/
|
||||||
|
export function callInitPlugins<
|
||||||
|
T extends Processed<AnyModule>,
|
||||||
|
Args extends ImportPayload<T>,
|
||||||
|
>(config: { onStop?: (module: T) => unknown; onNext: (module: Args) => T }) {
|
||||||
|
return concatMap(
|
||||||
|
createResultResolver({
|
||||||
|
createStream: args => from(args.module.plugins).pipe(callPlugin(args)),
|
||||||
|
...config,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates an executable task ( execute the command ) if all control plugins are successful
|
||||||
|
* @param onStop emits a failure response to the SernEmitter
|
||||||
|
*/
|
||||||
|
export function makeModuleExecutor<
|
||||||
|
M extends Processed<Module>,
|
||||||
|
Args extends { module: M; args: unknown[] },
|
||||||
|
>(onStop: (m: M) => unknown) {
|
||||||
|
const onNext = ({ args, module }: Args) => ({ task: () => module.execute(...args), module });
|
||||||
|
return concatMap(
|
||||||
|
createResultResolver({
|
||||||
|
onStop,
|
||||||
|
createStream: ({ args, module }) => from(module.onEvent).pipe(callPlugin(args)),
|
||||||
|
onNext,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function handleCrash(
|
||||||
|
errorHandler: ErrorHandling,
|
||||||
|
logger?: Logging,
|
||||||
|
) {
|
||||||
|
return pipe(
|
||||||
|
catchError(handleError(errorHandler, logger)),
|
||||||
|
finalize(() => {
|
||||||
|
logger?.info({ message: 'A stream closed or reached end of lifetime' });
|
||||||
|
useContainerRaw()?.disposeAll()
|
||||||
|
.then(() => logger?.info({ message: 'Cleaning container and crashing' }));
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
26
src/handler/events/interactions.ts
Normal file
26
src/handler/events/interactions.ts
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
import { Interaction } from 'discord.js';
|
||||||
|
import { concatMap, merge } from 'rxjs';
|
||||||
|
import { SernError } from '../../core/structures/errors';
|
||||||
|
import { SernEmitter } from '../../core';
|
||||||
|
import { sharedObservable } from '../../core/operators';
|
||||||
|
import { isAutocomplete, isCommand, isMessageComponent, isModal } from '../../core/predicates';
|
||||||
|
import { createInteractionHandler, executeModule, makeModuleExecutor } from './generic';
|
||||||
|
import { DependencyList } from '../types';
|
||||||
|
|
||||||
|
export function makeInteractionHandler([emitter, , , modules, client]: DependencyList) {
|
||||||
|
const interactionStream$ = sharedObservable<Interaction>(client, 'interactionCreate');
|
||||||
|
const handle = createInteractionHandler(interactionStream$, modules);
|
||||||
|
|
||||||
|
const interactionHandler$ = merge(
|
||||||
|
handle(isMessageComponent),
|
||||||
|
handle(isAutocomplete),
|
||||||
|
handle(isCommand),
|
||||||
|
handle(isModal),
|
||||||
|
);
|
||||||
|
return interactionHandler$.pipe(
|
||||||
|
makeModuleExecutor(module => {
|
||||||
|
emitter.emit('module.activate', SernEmitter.failure(module, SernError.PluginFailure));
|
||||||
|
}),
|
||||||
|
concatMap(payload => executeModule(emitter, payload)),
|
||||||
|
);
|
||||||
|
}
|
||||||
42
src/handler/events/messages.ts
Normal file
42
src/handler/events/messages.ts
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
import { concatMap, EMPTY } from 'rxjs';
|
||||||
|
import { SernError } from '../../core/structures/errors';
|
||||||
|
import type { Message } from 'discord.js';
|
||||||
|
import { SernEmitter } from '../../core';
|
||||||
|
import { sharedObservable } from '../../core/operators';
|
||||||
|
import { createMessageHandler, executeModule, isNonBot, makeModuleExecutor } from './generic';
|
||||||
|
import { DependencyList } from '../types';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Removes the first character(s) _[depending on prefix length]_ of the message
|
||||||
|
* @param msg
|
||||||
|
* @param prefix The prefix to remove
|
||||||
|
* @returns The message without the prefix
|
||||||
|
* @example
|
||||||
|
* message.content = '!ping';
|
||||||
|
* console.log(fmt(message, '!'));
|
||||||
|
* // [ 'ping' ]
|
||||||
|
*/
|
||||||
|
export function fmt(msg: string, prefix: string): string[] {
|
||||||
|
return msg.slice(prefix.length).trim().split(/\s+/g);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function makeMessageHandler(
|
||||||
|
[emitter, , log, modules, client]: DependencyList,
|
||||||
|
defaultPrefix: string | undefined,
|
||||||
|
) {
|
||||||
|
if (!defaultPrefix) {
|
||||||
|
log?.debug({ message: 'No prefix found. message handler shutting down' });
|
||||||
|
return EMPTY;
|
||||||
|
}
|
||||||
|
const messageStream$ = sharedObservable<Message>(client, 'messageCreate');
|
||||||
|
const handler = createMessageHandler(messageStream$, defaultPrefix, modules);
|
||||||
|
|
||||||
|
const prefixedMessages$ = handler(isNonBot(defaultPrefix) as (m: Message) => m is Message);
|
||||||
|
|
||||||
|
return prefixedMessages$.pipe(
|
||||||
|
makeModuleExecutor(module => {
|
||||||
|
emitter.emit('module.activate', SernEmitter.failure(module, SernError.PluginFailure));
|
||||||
|
}),
|
||||||
|
concatMap(payload => executeModule(emitter, payload)),
|
||||||
|
);
|
||||||
|
}
|
||||||
55
src/handler/events/ready.ts
Normal file
55
src/handler/events/ready.ts
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
import { ObservableInput, fromEvent, take } from 'rxjs';
|
||||||
|
import { CommandType } from '../../core/structures';
|
||||||
|
import { SernError } from '../../core/structures/errors';
|
||||||
|
import { Result } from 'ts-results-es';
|
||||||
|
import { ModuleManager } from '../../core/contracts';
|
||||||
|
import { SernEmitter } from '../../core';
|
||||||
|
import { Processed, DependencyList } from '../types';
|
||||||
|
import { buildModules, callInitPlugins } from './generic';
|
||||||
|
import { AnyModule } from '../../core/types/modules';
|
||||||
|
import * as assert from 'node:assert';
|
||||||
|
|
||||||
|
export function startReadyEvent(
|
||||||
|
[sEmitter, , , moduleManager, client]: DependencyList,
|
||||||
|
allPaths: ObservableInput<string>,
|
||||||
|
) {
|
||||||
|
const ready$ = fromEvent(client!, 'ready').pipe(take(1));
|
||||||
|
return ready$
|
||||||
|
.pipe(
|
||||||
|
buildModules<Processed<AnyModule>>(allPaths, sEmitter, moduleManager),
|
||||||
|
callInitPlugins({
|
||||||
|
onStop: module => {
|
||||||
|
sEmitter.emit(
|
||||||
|
'module.register',
|
||||||
|
SernEmitter.failure(module, SernError.PluginFailure),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
onNext: ({ module }) => {
|
||||||
|
sEmitter.emit('module.register', SernEmitter.success(module));
|
||||||
|
return module;
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.subscribe(module => {
|
||||||
|
const result = registerModule(moduleManager, module);
|
||||||
|
if (result.err) {
|
||||||
|
throw Error(SernError.InvalidModuleType + ' ' + result.val);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function registerModule<T extends Processed<AnyModule>>(
|
||||||
|
manager: ModuleManager,
|
||||||
|
module: T,
|
||||||
|
): Result<void, void> {
|
||||||
|
const { id, fullPath } = manager.getMetadata(module);
|
||||||
|
|
||||||
|
assert.ok(
|
||||||
|
module.type > 0 && module.type < 1 << 10,
|
||||||
|
`Found ${module.name} at ${fullPath}, which does not have a valid type`,
|
||||||
|
);
|
||||||
|
if (module.type === CommandType.Both || module.type === CommandType.Text) {
|
||||||
|
module.alias?.forEach(a => manager.set(`${a}_A0`, fullPath));
|
||||||
|
}
|
||||||
|
return Result.wrap(() => manager.set(id, fullPath));
|
||||||
|
}
|
||||||
59
src/handler/events/user-defined.ts
Normal file
59
src/handler/events/user-defined.ts
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
import { ObservableInput, catchError, finalize, map, mergeAll, of } from 'rxjs';
|
||||||
|
import type { CommandModule, EventModule } from '../../core/types/modules';
|
||||||
|
import { SernEmitter } from '../../core';
|
||||||
|
import { EventType } from '../../core/structures';
|
||||||
|
import { SernError } from '../../core/structures/errors';
|
||||||
|
import { eventDispatcher } from './dispatchers';
|
||||||
|
import { buildModules, callInitPlugins } from './generic';
|
||||||
|
import { handleError } from '../../core/operators';
|
||||||
|
import { Service, useContainerRaw } from '../../core/ioc';
|
||||||
|
import { DependencyList, Processed } from '../types';
|
||||||
|
|
||||||
|
export function makeEventsHandler(
|
||||||
|
[emitter, err, log, moduleManager, client]: DependencyList,
|
||||||
|
allPaths: ObservableInput<string>,
|
||||||
|
) {
|
||||||
|
//code smell
|
||||||
|
const intoDispatcher = (e: Processed<EventModule | CommandModule>) => {
|
||||||
|
switch (e.type) {
|
||||||
|
case EventType.Sern:
|
||||||
|
return eventDispatcher(e, emitter);
|
||||||
|
case EventType.Discord:
|
||||||
|
return eventDispatcher(e, client);
|
||||||
|
case EventType.External:
|
||||||
|
return eventDispatcher(e, Service(e.emitter));
|
||||||
|
default:
|
||||||
|
throw Error(SernError.InvalidModuleType + ' while creating event handler');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
of(null)
|
||||||
|
.pipe(
|
||||||
|
buildModules<Processed<EventModule>>(allPaths, emitter, moduleManager),
|
||||||
|
callInitPlugins({
|
||||||
|
onStop: module =>
|
||||||
|
emitter.emit(
|
||||||
|
'module.register',
|
||||||
|
SernEmitter.failure(module, SernError.PluginFailure),
|
||||||
|
),
|
||||||
|
onNext: ({ module }) => {
|
||||||
|
emitter.emit('module.register', SernEmitter.success(module));
|
||||||
|
return module;
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
map(intoDispatcher),
|
||||||
|
/**
|
||||||
|
* Where all events are turned on
|
||||||
|
*/
|
||||||
|
mergeAll(),
|
||||||
|
catchError(handleError(err, log)),
|
||||||
|
finalize(() => {
|
||||||
|
log?.info({ message: 'an event module reached end of lifetime' });
|
||||||
|
useContainerRaw()
|
||||||
|
?.disposeAll()
|
||||||
|
.then(() => {
|
||||||
|
log?.info({ message: 'Cleaning container and crashing' });
|
||||||
|
});
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.subscribe();
|
||||||
|
}
|
||||||
@@ -1,12 +1,12 @@
|
|||||||
import { ApplicationCommandType, ComponentType, Interaction, InteractionType } from 'discord.js';
|
import { Interaction, InteractionType } from 'discord.js';
|
||||||
import { CommandType, EventType } from './structures';
|
import { CommandType, EventType } from '../core';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Construct unique ID for a given interaction object.
|
* Construct unique ID for a given interaction object.
|
||||||
* @param event The interaction object for which to create an ID.
|
* @param event The interaction object for which to create an ID.
|
||||||
* @returns A unique string ID based on the type and properties of the interaction object.
|
* @returns A unique string ID based on the type and properties of the interaction object.
|
||||||
*/
|
*/
|
||||||
export function reconstruct<T extends Interaction>(event: T) {
|
export function reconstructId<T extends Interaction>(event: T) {
|
||||||
switch (event.type) {
|
switch (event.type) {
|
||||||
case InteractionType.MessageComponent: {
|
case InteractionType.MessageComponent: {
|
||||||
return `${event.customId}_C${event.componentType}`;
|
return `${event.customId}_C${event.componentType}`;
|
||||||
@@ -21,27 +21,8 @@ export function reconstruct<T extends Interaction>(event: T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
/**
|
|
||||||
*
|
|
||||||
* A magic number to represent any commandtype that is an ApplicationCommand.
|
|
||||||
*/
|
|
||||||
const appBitField = 0b000000001111;
|
|
||||||
|
|
||||||
// Each index represents the exponent of a CommandType.
|
const appBitField = 0b000000011111;
|
||||||
// Every CommandType is a power of two.
|
|
||||||
export const CommandTypeDiscordApi = [
|
|
||||||
1, // CommandType.Text
|
|
||||||
ApplicationCommandType.ChatInput,
|
|
||||||
ApplicationCommandType.User,
|
|
||||||
ApplicationCommandType.Message,
|
|
||||||
ComponentType.Button,
|
|
||||||
ComponentType.StringSelect,
|
|
||||||
1, // CommandType.Modal
|
|
||||||
ComponentType.UserSelect,
|
|
||||||
ComponentType.RoleSelect,
|
|
||||||
ComponentType.MentionableSelect,
|
|
||||||
ComponentType.ChannelSelect,
|
|
||||||
];
|
|
||||||
/*
|
/*
|
||||||
* Generates a number based on CommandType.
|
* Generates a number based on CommandType.
|
||||||
* This corresponds to an ApplicationCommandType or ComponentType
|
* This corresponds to an ApplicationCommandType or ComponentType
|
||||||
@@ -49,15 +30,21 @@ export const CommandTypeDiscordApi = [
|
|||||||
*/
|
*/
|
||||||
function apiType(t: CommandType | EventType) {
|
function apiType(t: CommandType | EventType) {
|
||||||
if (t === CommandType.Both || t === CommandType.Modal) return 1;
|
if (t === CommandType.Both || t === CommandType.Modal) return 1;
|
||||||
return CommandTypeDiscordApi[Math.log2(t)];
|
const log = Math.log2(t);
|
||||||
|
return (appBitField & t) !== 0 ? log : log - 2;
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Generates an id based on name and CommandType.
|
* Generates an id based on CommandType.
|
||||||
* A is for any ApplicationCommand. C is for any ComponentCommand
|
* A is for any ApplicationCommand. C is for any ComponentCommand
|
||||||
* Then, another number generated by apiType function is appended
|
* Then, another number generated by apiType function is appended
|
||||||
*/
|
*/
|
||||||
export function create(name: string, type: CommandType | EventType) {
|
function uniqueSuffix(t: CommandType | EventType) {
|
||||||
const am = (appBitField & type) !== 0 ? 'A' : 'C';
|
const am = (appBitField & t) !== 0 ? 'A' : 'C';
|
||||||
return name + '_' + am + apiType(type);
|
return am + apiType(t);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
export function createId(name: string, type: CommandType | EventType) {
|
||||||
|
return name+"_"+uniqueSuffix(type)
|
||||||
}
|
}
|
||||||
89
src/handler/sern.ts
Normal file
89
src/handler/sern.ts
Normal file
@@ -0,0 +1,89 @@
|
|||||||
|
import { makeEventsHandler } from './events/user-defined';
|
||||||
|
import { makeInteractionHandler } from './events/interactions';
|
||||||
|
import { startReadyEvent } from './events/ready';
|
||||||
|
import { makeMessageHandler } from './events/messages';
|
||||||
|
import { err, ok } from '../core/functions';
|
||||||
|
import { getFullPathTree } from '../core/module-loading';
|
||||||
|
import { merge } from 'rxjs';
|
||||||
|
import { Services } from '../core/ioc';
|
||||||
|
import { Wrapper } from '../shared';
|
||||||
|
import { handleCrash } from './events/generic';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @since 1.0.0
|
||||||
|
* @param wrapper Options to pass into sern.
|
||||||
|
* Function to start the handler up
|
||||||
|
* @example
|
||||||
|
* ```ts title="src/index.ts"
|
||||||
|
* Sern.init({
|
||||||
|
* commands: 'dist/commands',
|
||||||
|
* events: 'dist/events',
|
||||||
|
* })
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
|
||||||
|
export function init(wrapper: Wrapper) {
|
||||||
|
const startTime = performance.now();
|
||||||
|
|
||||||
|
const dependencies = useDependencies();
|
||||||
|
const logger = dependencies[2];
|
||||||
|
const errorHandler = dependencies[1];
|
||||||
|
const mode = debugModuleLoading(wrapper.mode ?? process.env.MODE);
|
||||||
|
|
||||||
|
if (wrapper.events !== undefined) {
|
||||||
|
makeEventsHandler(dependencies, getFullPathTree(wrapper.events, mode));
|
||||||
|
}
|
||||||
|
|
||||||
|
startReadyEvent(dependencies, getFullPathTree(wrapper.commands, mode))
|
||||||
|
.add(() => {
|
||||||
|
const time = ((performance.now() - startTime) / 1000).toFixed(2);
|
||||||
|
dependencies[0].emit('modulesLoaded' );
|
||||||
|
logger?.info({
|
||||||
|
message: `sern: registered all modules in ${time} s`,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
const messages$ = makeMessageHandler(dependencies, wrapper.defaultPrefix);
|
||||||
|
const interactions$ = makeInteractionHandler(dependencies);
|
||||||
|
|
||||||
|
merge(messages$, interactions$)
|
||||||
|
.pipe(handleCrash(errorHandler, logger))
|
||||||
|
.subscribe();
|
||||||
|
}
|
||||||
|
|
||||||
|
function debugModuleLoading(mode: string | undefined) {
|
||||||
|
console.info(`Detected mode: "${mode}"`);
|
||||||
|
if (mode === undefined) {
|
||||||
|
console.info('No mode found in process.env, assuming DEV');
|
||||||
|
}
|
||||||
|
switch (mode) {
|
||||||
|
case 'PROD':
|
||||||
|
return false;
|
||||||
|
case 'DEV':
|
||||||
|
case undefined:
|
||||||
|
return true;
|
||||||
|
default: {
|
||||||
|
console.warn(mode + ' is not a valid. Should be PROD or DEV');
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function useDependencies() {
|
||||||
|
return Services(
|
||||||
|
'@sern/emitter',
|
||||||
|
'@sern/errors',
|
||||||
|
'@sern/logger',
|
||||||
|
'@sern/modules',
|
||||||
|
'@sern/client',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @since 1.0.0
|
||||||
|
* The object passed into every plugin to control a command's behavior
|
||||||
|
*/
|
||||||
|
export const controller = {
|
||||||
|
next: ok,
|
||||||
|
stop: err,
|
||||||
|
};
|
||||||
24
src/handler/types.ts
Normal file
24
src/handler/types.ts
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
import { ErrorHandling, Logging, ModuleManager, SernEmitter } from '../core';
|
||||||
|
import { EventEmitter } from 'node:events';
|
||||||
|
import { Module } from '../core/types/modules';
|
||||||
|
|
||||||
|
export type Processed<T> = T & { name: string; description: string };
|
||||||
|
|
||||||
|
export type DependencyList = [
|
||||||
|
SernEmitter,
|
||||||
|
ErrorHandling,
|
||||||
|
Logging | undefined,
|
||||||
|
ModuleManager,
|
||||||
|
EventEmitter,
|
||||||
|
];
|
||||||
|
|
||||||
|
export interface InitArgs<T extends Processed<Module>> {
|
||||||
|
module: T;
|
||||||
|
absPath: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ImportPayload<T> {
|
||||||
|
module: T;
|
||||||
|
absPath: string;
|
||||||
|
[key: string]: unknown;
|
||||||
|
}
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
export * from './dispatchers';
|
|
||||||
export * from './event-utils';
|
|
||||||
@@ -1,107 +0,0 @@
|
|||||||
import { EventEmitter } from 'node:events';
|
|
||||||
import * as assert from 'node:assert';
|
|
||||||
import { concatMap, from, fromEvent, map, OperatorFunction, pipe } from 'rxjs';
|
|
||||||
import {
|
|
||||||
arrayifySource,
|
|
||||||
callPlugin,
|
|
||||||
isAutocomplete,
|
|
||||||
treeSearch,
|
|
||||||
SernError,
|
|
||||||
} from '../core/_internal';
|
|
||||||
import { createResultResolver } from './event-utils';
|
|
||||||
import { BaseInteraction, Message } from 'discord.js';
|
|
||||||
import { CommandType, Context } from '../core';
|
|
||||||
import type { AnyFunction, Args } from '../types/utility';
|
|
||||||
import type { CommandModule, Module, OnError, Processed } from '../types/core-modules';
|
|
||||||
|
|
||||||
//TODO: refactor dispatchers so that it implements a strategy for each different type of payload?
|
|
||||||
export function dispatchMessage(module: Processed<CommandModule>, args: [Context, Args]) {
|
|
||||||
return {
|
|
||||||
module,
|
|
||||||
args,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export function contextArgs(wrappable: Message | BaseInteraction, messageArgs?: string[]) {
|
|
||||||
const ctx = Context.wrap(wrappable);
|
|
||||||
const args = ctx.isMessage() ? ['text', messageArgs!] : ['slash', ctx.options];
|
|
||||||
return [ctx, args] as [Context, Args];
|
|
||||||
}
|
|
||||||
|
|
||||||
function interactionArg<T extends BaseInteraction>(interaction: T) {
|
|
||||||
return [interaction] as [T];
|
|
||||||
}
|
|
||||||
|
|
||||||
function intoPayload(module: Processed<Module>, onError: AnyFunction|undefined) {
|
|
||||||
return pipe(
|
|
||||||
arrayifySource,
|
|
||||||
map(args => ({ module, args, onError })),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const createResult = createResultResolver<
|
|
||||||
Processed<Module>,
|
|
||||||
{ module: Processed<Module>; args: unknown[], onError: AnyFunction|undefined },
|
|
||||||
unknown[]
|
|
||||||
>({
|
|
||||||
createStream: ({ module, args }) => from(module.onEvent).pipe(callPlugin(args)),
|
|
||||||
onNext: ({ args }) => args,
|
|
||||||
});
|
|
||||||
/**
|
|
||||||
* Creates an observable from { source }
|
|
||||||
* @param module
|
|
||||||
* @param source
|
|
||||||
*/
|
|
||||||
export function eventDispatcher(module: Processed<Module>, onError: OnError, source: unknown) {
|
|
||||||
assert.ok(source instanceof EventEmitter, `${source} is not an EventEmitter`);
|
|
||||||
|
|
||||||
const execute: OperatorFunction<unknown[], unknown> = concatMap(async args =>
|
|
||||||
module.execute(...args),
|
|
||||||
);
|
|
||||||
return fromEvent(source, module.name).pipe(
|
|
||||||
intoPayload(module, onError),
|
|
||||||
concatMap(createResult),
|
|
||||||
execute,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function createDispatcher(payload: {
|
|
||||||
module: Processed<CommandModule>;
|
|
||||||
event: BaseInteraction;
|
|
||||||
onError: OnError
|
|
||||||
}) {
|
|
||||||
assert.ok(
|
|
||||||
CommandType.Text !== payload.module.type,
|
|
||||||
SernError.MismatchEvent + 'Found text command in interaction stream',
|
|
||||||
);
|
|
||||||
switch (payload.module.type) {
|
|
||||||
case CommandType.Slash:
|
|
||||||
case CommandType.Both: {
|
|
||||||
if (isAutocomplete(payload.event)) {
|
|
||||||
const option = treeSearch(payload.event, payload.module.options);
|
|
||||||
assert.ok(
|
|
||||||
option,
|
|
||||||
Error(SernError.NotSupportedInteraction + ` There is no autocomplete tag for this option`),
|
|
||||||
);
|
|
||||||
const { command } = option;
|
|
||||||
return {
|
|
||||||
...payload,
|
|
||||||
module: command as Processed<Module>, //autocomplete is not a true "module" warning cast!
|
|
||||||
args: [payload.event],
|
|
||||||
onError: undefined
|
|
||||||
};
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
args: contextArgs(payload.event),
|
|
||||||
...payload,
|
|
||||||
onError: payload.onError
|
|
||||||
};
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
return {
|
|
||||||
args: interactionArg(payload.event),
|
|
||||||
...payload,
|
|
||||||
onError: payload.onError
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,288 +0,0 @@
|
|||||||
import { Interaction, Message } from 'discord.js';
|
|
||||||
import {
|
|
||||||
EMPTY,
|
|
||||||
Observable,
|
|
||||||
concatMap,
|
|
||||||
filter,
|
|
||||||
from,
|
|
||||||
of,
|
|
||||||
throwError,
|
|
||||||
tap,
|
|
||||||
MonoTypeOperatorFunction,
|
|
||||||
catchError,
|
|
||||||
finalize,
|
|
||||||
} from 'rxjs';
|
|
||||||
import {
|
|
||||||
Files,
|
|
||||||
Id,
|
|
||||||
callPlugin,
|
|
||||||
everyPluginOk,
|
|
||||||
filterMapTo,
|
|
||||||
handleError,
|
|
||||||
SernError,
|
|
||||||
VoidResult,
|
|
||||||
useContainerRaw,
|
|
||||||
} from '../core/_internal';
|
|
||||||
import { CommandError, Emitter, ErrorHandling, Logging, ModuleManager } from '../core';
|
|
||||||
import { contextArgs, createDispatcher } from './dispatchers';
|
|
||||||
import { ObservableInput, pipe } from 'rxjs';
|
|
||||||
import { SernEmitter } from '../core';
|
|
||||||
import { Err, Ok, Result } from 'ts-results-es';
|
|
||||||
import type { AnyFunction, Awaitable } from '../types/utility';
|
|
||||||
import type { ControlPlugin } from '../types/core-plugin';
|
|
||||||
import type { AnyModule, CommandModule, Module, OnError, Processed } from '../types/core-modules';
|
|
||||||
import type { ImportPayload } from '../types/core';
|
|
||||||
import assert from 'node:assert';
|
|
||||||
|
|
||||||
function createGenericHandler<Source, Narrowed extends Source, Output>(
|
|
||||||
source: Observable<Source>,
|
|
||||||
makeModule: (event: Narrowed) => Promise<Output>,
|
|
||||||
) {
|
|
||||||
return (pred: (i: Source) => i is Narrowed) =>
|
|
||||||
source.pipe(
|
|
||||||
filter(pred),
|
|
||||||
concatMap(makeModule));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Removes the first character(s) _[depending on prefix length]_ of the message
|
|
||||||
* @param msg
|
|
||||||
* @param prefix The prefix to remove
|
|
||||||
* @returns The message without the prefix
|
|
||||||
* @example
|
|
||||||
* message.content = '!ping';
|
|
||||||
* console.log(fmt(message, '!'));
|
|
||||||
* // [ 'ping' ]
|
|
||||||
*/
|
|
||||||
export function fmt(msg: string, prefix: string): string[] {
|
|
||||||
return msg.slice(prefix.length).trim().split(/\s+/g);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
*
|
|
||||||
* Creates an RxJS observable that filters and maps incoming interactions to their respective modules.
|
|
||||||
* @param i An RxJS observable of interactions.
|
|
||||||
* @param mg The module manager instance used to retrieve the module path for each interaction.
|
|
||||||
* @returns A handler to create a RxJS observable of dispatchers that take incoming interactions and execute their corresponding modules.
|
|
||||||
*/
|
|
||||||
export function createInteractionHandler<T extends Interaction>(
|
|
||||||
source: Observable<Interaction>,
|
|
||||||
mg: ModuleManager,
|
|
||||||
) {
|
|
||||||
return createGenericHandler<Interaction, T, Result<ReturnType<typeof createDispatcher>, void>>(
|
|
||||||
source,
|
|
||||||
async event => {
|
|
||||||
const fullPath = mg.get(Id.reconstruct(event));
|
|
||||||
if(!fullPath) {
|
|
||||||
return Err.EMPTY
|
|
||||||
}
|
|
||||||
return Files
|
|
||||||
.defaultModuleLoader<Processed<CommandModule>>(fullPath)
|
|
||||||
.then(payload =>
|
|
||||||
Ok(createDispatcher({
|
|
||||||
module: payload.module,
|
|
||||||
onError: payload.onError,
|
|
||||||
event,
|
|
||||||
})));
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function createMessageHandler(
|
|
||||||
source: Observable<Message>,
|
|
||||||
defaultPrefix: string,
|
|
||||||
mg: ModuleManager,
|
|
||||||
) {
|
|
||||||
return createGenericHandler(source, async event => {
|
|
||||||
const [prefix, ...rest] = fmt(event.content, defaultPrefix);
|
|
||||||
const fullPath = mg.get(`${prefix}_A1`);
|
|
||||||
|
|
||||||
if(!fullPath) {
|
|
||||||
return Err('Possibly undefined behavior: could not find a static id to resolve')
|
|
||||||
}
|
|
||||||
return Files
|
|
||||||
.defaultModuleLoader<Processed<CommandModule>>(fullPath)
|
|
||||||
.then(payload => {
|
|
||||||
const args = contextArgs(event, rest);
|
|
||||||
return Ok({ args, ...payload });
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* IMPURE SIDE EFFECT
|
|
||||||
* This function assigns remaining, incomplete data to each imported module.
|
|
||||||
*/
|
|
||||||
function assignDefaults<T extends Module>(
|
|
||||||
moduleManager: ModuleManager,
|
|
||||||
): MonoTypeOperatorFunction<ImportPayload<T>> {
|
|
||||||
return tap(({ module, absPath }) => {
|
|
||||||
module.name ??= Files.filename(absPath);
|
|
||||||
module.description ??= '...';
|
|
||||||
moduleManager.setMetadata(module, {
|
|
||||||
isClass: module.constructor.name === 'Function',
|
|
||||||
fullPath: absPath,
|
|
||||||
id: Id.create(module.name, module.type),
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export function buildModules<T extends AnyModule>(
|
|
||||||
input: ObservableInput<string>,
|
|
||||||
moduleManager: ModuleManager,
|
|
||||||
) {
|
|
||||||
return Files.buildModuleStream<Processed<T>>(input).pipe(assignDefaults(moduleManager));
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
interface ExecutePayload {
|
|
||||||
module: Processed<Module>;
|
|
||||||
task: () => Awaitable<unknown>;
|
|
||||||
onError: AnyFunction|undefined
|
|
||||||
args: unknown[]
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Wraps the task in a Result as a try / catch.
|
|
||||||
* if the task is ok, an event is emitted and the stream becomes empty
|
|
||||||
* if the task is an error, throw an error down the stream which will be handled by catchError
|
|
||||||
* @param emitter reference to SernEmitter that will emit a successful execution of module
|
|
||||||
* @param module the module that will be executed with task
|
|
||||||
* @param task the deferred execution which will be called
|
|
||||||
*/
|
|
||||||
export function executeModule(
|
|
||||||
emitter: Emitter,
|
|
||||||
logger: Logging|undefined,
|
|
||||||
errHandler: ErrorHandling,
|
|
||||||
{
|
|
||||||
module,
|
|
||||||
task,
|
|
||||||
onError,
|
|
||||||
args
|
|
||||||
}: ExecutePayload,
|
|
||||||
) {
|
|
||||||
const onError$ = (err_msg: unknown) => {
|
|
||||||
if(!onError) {
|
|
||||||
return throwError(() => SernEmitter.failure(module, err));
|
|
||||||
}
|
|
||||||
//Could be promise
|
|
||||||
const err = onError(err_msg) as CommandError.Response
|
|
||||||
if(!err) {
|
|
||||||
const failure = SernEmitter.failure(module, "onError: returned undefined/null");
|
|
||||||
return throwError(() => failure);
|
|
||||||
}
|
|
||||||
if(err.log) {
|
|
||||||
const { type, message } = err.log;
|
|
||||||
logger?.[type]({ message });
|
|
||||||
};
|
|
||||||
if(err.type === 'fail') {
|
|
||||||
|
|
||||||
} else {
|
|
||||||
|
|
||||||
}
|
|
||||||
return EMPTY;
|
|
||||||
}
|
|
||||||
return of(module).pipe(
|
|
||||||
//converting the task into a promise so rxjs can resolve the Awaitable properly
|
|
||||||
concatMap(() => Result.wrapAsync(async () => task())),
|
|
||||||
concatMap(result => {
|
|
||||||
if (result.isOk()) {
|
|
||||||
emitter.emit('module.activate', SernEmitter.success(module));
|
|
||||||
return EMPTY;
|
|
||||||
}
|
|
||||||
return onError$(result.error);
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* A higher order function that
|
|
||||||
* - creates a stream of {@link VoidResult} { config.createStream }
|
|
||||||
* - any failures results to { config.onFailure } being called
|
|
||||||
* - if all results are ok, the stream is converted to { config.onNext }
|
|
||||||
* emit config.onSuccess Observable
|
|
||||||
* @param config
|
|
||||||
* @returns receiver function for flattening a stream of data
|
|
||||||
*/
|
|
||||||
export function createResultResolver<
|
|
||||||
T extends { execute: (...args: any[]) => any; onEvent: ControlPlugin[] },
|
|
||||||
Args extends { module: T; onError: unknown, [key: string]: unknown },
|
|
||||||
Output,
|
|
||||||
>(config: {
|
|
||||||
onStop?: (module: T) => unknown;
|
|
||||||
onNext: (args: Args) => Output;
|
|
||||||
createStream: (args: Args) => Observable<VoidResult>;
|
|
||||||
}) {
|
|
||||||
return (args: Args) => {
|
|
||||||
const task$ = config.createStream(args);
|
|
||||||
return task$.pipe(
|
|
||||||
tap(result => {
|
|
||||||
result.isErr() && config.onStop?.(args.module);
|
|
||||||
}),
|
|
||||||
everyPluginOk,
|
|
||||||
filterMapTo(() => config.onNext(args)),
|
|
||||||
);
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Calls a module's init plugins and checks for Err. If so, call { onStop } and
|
|
||||||
* ignore the module
|
|
||||||
*/
|
|
||||||
export function callInitPlugins<T extends Processed<AnyModule>>(sernEmitter: Emitter) {
|
|
||||||
return concatMap(
|
|
||||||
createResultResolver({
|
|
||||||
createStream: args => from(args.module.plugins).pipe(callPlugin(args)),
|
|
||||||
onStop: (module: T) => {
|
|
||||||
sernEmitter.emit(
|
|
||||||
'module.register',
|
|
||||||
SernEmitter.failure(module, SernError.PluginFailure),
|
|
||||||
);
|
|
||||||
},
|
|
||||||
onNext: ({ module, onError }) => {
|
|
||||||
sernEmitter.emit('module.register', SernEmitter.success(module));
|
|
||||||
return { module, onError: onError as OnError };
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Creates an executable task ( execute the command ) if all control plugins are successful
|
|
||||||
* @param onStop emits a failure response to the SernEmitter
|
|
||||||
*/
|
|
||||||
export function makeModuleExecutor<
|
|
||||||
M extends Processed<Module>,
|
|
||||||
Args extends {
|
|
||||||
module: M;
|
|
||||||
args: unknown[];
|
|
||||||
onError: AnyFunction|undefined
|
|
||||||
},
|
|
||||||
>(onStop: (m: M) => unknown) {
|
|
||||||
const onNext = ({ args, module, onError }: Args) => ({
|
|
||||||
task: () => module.execute(...args),
|
|
||||||
module,
|
|
||||||
onError,
|
|
||||||
args
|
|
||||||
});
|
|
||||||
return concatMap(
|
|
||||||
createResultResolver({
|
|
||||||
onStop,
|
|
||||||
createStream: ({ args, module }) =>
|
|
||||||
from(module.onEvent)
|
|
||||||
.pipe(callPlugin(args)),
|
|
||||||
onNext,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export const handleCrash = (err: ErrorHandling, log?: Logging) =>
|
|
||||||
pipe(
|
|
||||||
catchError(handleError(err, log)),
|
|
||||||
finalize(() => {
|
|
||||||
log?.info({
|
|
||||||
message: 'A stream closed or reached end of lifetime',
|
|
||||||
});
|
|
||||||
useContainerRaw()
|
|
||||||
?.disposeAll()
|
|
||||||
.then(() => log?.info({ message: 'Cleaning container and crashing' }));
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
@@ -1,33 +0,0 @@
|
|||||||
import { Interaction } from 'discord.js';
|
|
||||||
import { concatMap, merge } from 'rxjs';
|
|
||||||
import { SernEmitter } from '../core';
|
|
||||||
import {
|
|
||||||
isAutocomplete,
|
|
||||||
isCommand,
|
|
||||||
isMessageComponent,
|
|
||||||
isModal,
|
|
||||||
sharedEventStream,
|
|
||||||
SernError,
|
|
||||||
filterTap,
|
|
||||||
} from '../core/_internal';
|
|
||||||
import { createInteractionHandler, executeModule, makeModuleExecutor } from './_internal';
|
|
||||||
import type { DependencyList } from '../types/ioc';
|
|
||||||
|
|
||||||
export function interactionHandler([emitter, err, log, modules, client]: DependencyList) {
|
|
||||||
const interactionStream$ = sharedEventStream<Interaction>(client, 'interactionCreate');
|
|
||||||
const handle = createInteractionHandler(interactionStream$, modules);
|
|
||||||
|
|
||||||
const interactionHandler$ = merge(
|
|
||||||
handle(isMessageComponent),
|
|
||||||
handle(isAutocomplete),
|
|
||||||
handle(isCommand),
|
|
||||||
handle(isModal),
|
|
||||||
);
|
|
||||||
return interactionHandler$
|
|
||||||
.pipe(
|
|
||||||
filterTap(e => emitter.emit('warning', SernEmitter.warning(e))),
|
|
||||||
makeModuleExecutor(module =>
|
|
||||||
emitter.emit('module.activate', SernEmitter.failure(module, SernError.PluginFailure))),
|
|
||||||
concatMap(payload => executeModule(emitter, log, err, payload)),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,47 +0,0 @@
|
|||||||
import { concatMap, EMPTY } from 'rxjs';
|
|
||||||
import type { Message } from 'discord.js';
|
|
||||||
import { SernEmitter } from '../core';
|
|
||||||
import { sharedEventStream, SernError, filterTap } from '../core/_internal';
|
|
||||||
import { createMessageHandler, executeModule, makeModuleExecutor } from './_internal';
|
|
||||||
import type { DependencyList } from '../types/ioc';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Ignores messages from any person / bot except itself
|
|
||||||
* @param prefix
|
|
||||||
*/
|
|
||||||
function isNonBot(prefix: string) {
|
|
||||||
return (msg: Message): msg is Message => !msg.author.bot && hasPrefix(prefix, msg.content);
|
|
||||||
}
|
|
||||||
|
|
||||||
function hasPrefix(prefix: string, content: string) {
|
|
||||||
const prefixInContent = content.slice(0, prefix.length);
|
|
||||||
return (
|
|
||||||
prefixInContent.localeCompare(prefix, undefined, {
|
|
||||||
sensitivity: 'accent',
|
|
||||||
}) === 0
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function messageHandler(
|
|
||||||
[emitter, err, log, modules, client]: DependencyList,
|
|
||||||
defaultPrefix: string | undefined,
|
|
||||||
) {
|
|
||||||
if (!defaultPrefix) {
|
|
||||||
log?.debug({
|
|
||||||
message: 'No prefix found. message handler shutting down',
|
|
||||||
});
|
|
||||||
return EMPTY;
|
|
||||||
}
|
|
||||||
const messageStream$ = sharedEventStream<Message>(client, 'messageCreate');
|
|
||||||
const handle = createMessageHandler(messageStream$, defaultPrefix, modules);
|
|
||||||
|
|
||||||
const msgCommands$ = handle(isNonBot(defaultPrefix));
|
|
||||||
|
|
||||||
return msgCommands$.pipe(
|
|
||||||
filterTap((e) => emitter.emit('warning', SernEmitter.warning(e))),
|
|
||||||
makeModuleExecutor(module => {
|
|
||||||
emitter.emit('module.activate', SernEmitter.failure(module, SernError.PluginFailure));
|
|
||||||
}),
|
|
||||||
concatMap(payload => executeModule(emitter, log, err, payload)),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,47 +0,0 @@
|
|||||||
import { ObservableInput, concat, first, fromEvent, ignoreElements, pipe } from 'rxjs';
|
|
||||||
import { CommandType } from '../core/structures';
|
|
||||||
import { SernError } from '../core/_internal';
|
|
||||||
import { Result } from 'ts-results-es';
|
|
||||||
import { ModuleManager } from '../core/contracts';
|
|
||||||
import { buildModules, callInitPlugins } from './_internal';
|
|
||||||
import * as assert from 'node:assert';
|
|
||||||
import * as util from 'node:util';
|
|
||||||
import type { DependencyList } from '../types/ioc';
|
|
||||||
import type { AnyModule, Processed } from '../types/core-modules';
|
|
||||||
|
|
||||||
export function startReadyEvent(
|
|
||||||
[sEmitter, , , moduleManager, client]: DependencyList,
|
|
||||||
allPaths: ObservableInput<string>,
|
|
||||||
) {
|
|
||||||
const ready$ = fromEvent(client!, 'ready').pipe(once());
|
|
||||||
|
|
||||||
return concat(ready$, buildModules<AnyModule>(allPaths, moduleManager))
|
|
||||||
.pipe(callInitPlugins(sEmitter))
|
|
||||||
.subscribe(({ module }) => {
|
|
||||||
register(moduleManager, module)
|
|
||||||
.expect(SernError.InvalidModuleType + ' ' + util.inspect(module));
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const once = () => pipe(
|
|
||||||
first(),
|
|
||||||
ignoreElements()
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
function register<T extends Processed<AnyModule>>(
|
|
||||||
manager: ModuleManager,
|
|
||||||
module: T,
|
|
||||||
): Result<void, void> {
|
|
||||||
const { id, fullPath } = manager.getMetadata(module)!;
|
|
||||||
|
|
||||||
const validModuleType = module.type >= 0 && module.type <= 1 << 10;
|
|
||||||
assert.ok(
|
|
||||||
validModuleType,
|
|
||||||
`Found ${module.name} at ${fullPath}, which does not have a valid type`,
|
|
||||||
);
|
|
||||||
if (module.type === CommandType.Both || module.type === CommandType.Text) {
|
|
||||||
module.alias?.forEach(a => manager.set(`${a}_A1`, fullPath));
|
|
||||||
}
|
|
||||||
return Result.wrap(() => manager.set(id, fullPath));
|
|
||||||
}
|
|
||||||
@@ -1,36 +0,0 @@
|
|||||||
import { ObservableInput, map, mergeAll } from 'rxjs';
|
|
||||||
import { EventType } from '../core/structures';
|
|
||||||
import { SernError } from '../core/_internal';
|
|
||||||
import { buildModules, callInitPlugins, handleCrash, eventDispatcher } from './_internal';
|
|
||||||
import { Service } from '../core/ioc';
|
|
||||||
import type { DependencyList } from '../types/ioc';
|
|
||||||
import type { EventModule, OnError, Processed } from '../types/core-modules';
|
|
||||||
|
|
||||||
export function eventsHandler(
|
|
||||||
[emitter, err, log, moduleManager, client]: DependencyList,
|
|
||||||
allPaths: ObservableInput<string>,
|
|
||||||
) {
|
|
||||||
//code smell
|
|
||||||
const intoDispatcher = (e: { module: Processed<EventModule>, onError: OnError }) => {
|
|
||||||
switch (e.module.type) {
|
|
||||||
case EventType.Sern:
|
|
||||||
return eventDispatcher(e.module, e.onError, emitter);
|
|
||||||
case EventType.Discord:
|
|
||||||
return eventDispatcher(e.module, e.onError, client);
|
|
||||||
case EventType.External:
|
|
||||||
return eventDispatcher(e.module, e.onError, Service(e.module.emitter));
|
|
||||||
default:
|
|
||||||
throw Error(SernError.InvalidModuleType + ' while creating event handler');
|
|
||||||
}
|
|
||||||
};
|
|
||||||
buildModules<EventModule>(allPaths, moduleManager)
|
|
||||||
.pipe(
|
|
||||||
callInitPlugins(emitter),
|
|
||||||
map(intoDispatcher),
|
|
||||||
/**
|
|
||||||
* Where all events are turned on
|
|
||||||
*/
|
|
||||||
mergeAll(),
|
|
||||||
handleCrash(err, log))
|
|
||||||
.subscribe();
|
|
||||||
}
|
|
||||||
53
src/index.ts
53
src/index.ts
@@ -1,56 +1,11 @@
|
|||||||
export * as Sern from './sern';
|
export * as Sern from './handler/sern';
|
||||||
export * from './core';
|
export * from './core';
|
||||||
export type {
|
|
||||||
CommandModule,
|
|
||||||
EventModule,
|
|
||||||
BothCommand,
|
|
||||||
ContextMenuMsg,
|
|
||||||
ContextMenuUser,
|
|
||||||
SlashCommand,
|
|
||||||
TextCommand,
|
|
||||||
ButtonCommand,
|
|
||||||
StringSelectCommand,
|
|
||||||
MentionableSelectCommand,
|
|
||||||
UserSelectCommand,
|
|
||||||
ChannelSelectCommand,
|
|
||||||
RoleSelectCommand,
|
|
||||||
ModalSubmitCommand,
|
|
||||||
DiscordEventCommand,
|
|
||||||
SernEventCommand,
|
|
||||||
ExternalEventCommand,
|
|
||||||
CommandModuleDefs,
|
|
||||||
EventModuleDefs,
|
|
||||||
SernAutocompleteData,
|
|
||||||
SernOptionsData,
|
|
||||||
SernSubCommandData,
|
|
||||||
SernSubCommandGroupData,
|
|
||||||
} from './types/core-modules';
|
|
||||||
|
|
||||||
export type {
|
|
||||||
Controller,
|
|
||||||
PluginResult,
|
|
||||||
InitPlugin,
|
|
||||||
ControlPlugin,
|
|
||||||
Plugin,
|
|
||||||
AnyEventPlugin,
|
|
||||||
AnyCommandPlugin,
|
|
||||||
} from './types/core-plugin';
|
|
||||||
|
|
||||||
export type { Wrapper } from './types/core';
|
|
||||||
|
|
||||||
export type { Args, SlashOptions, Payload, SernEventsMapping } from './types/utility';
|
|
||||||
|
|
||||||
export type { Singleton, Transient, CoreDependencies, Initializable } from './types/ioc';
|
|
||||||
|
|
||||||
export {
|
export {
|
||||||
commandModule,
|
commandModule,
|
||||||
eventModule,
|
eventModule,
|
||||||
discordEvent,
|
discordEvent,
|
||||||
EventExecutable,
|
EventExecutable,
|
||||||
CommandExecutable,
|
CommandExecutable,
|
||||||
} from './core/modules';
|
} from './handler/commands';
|
||||||
|
export { controller } from './handler/sern';
|
||||||
export {
|
export type { Wrapper, Args } from './shared';
|
||||||
useContainerRaw
|
|
||||||
} from './core/_internal'
|
|
||||||
export { controller } from './sern';
|
|
||||||
|
|||||||
66
src/sern.ts
66
src/sern.ts
@@ -1,66 +0,0 @@
|
|||||||
import { handleCrash } from './handlers/_internal';
|
|
||||||
import { err, ok, Files } from './core/_internal';
|
|
||||||
import { merge } from 'rxjs';
|
|
||||||
import { Services } from './core/ioc';
|
|
||||||
import { Wrapper } from './types/core';
|
|
||||||
import { eventsHandler } from './handlers/user-defined-events';
|
|
||||||
import { startReadyEvent } from './handlers/ready-event';
|
|
||||||
import { messageHandler } from './handlers/message-event';
|
|
||||||
import { interactionHandler } from './handlers/interaction-event';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @since 1.0.0
|
|
||||||
* @param wrapper Options to pass into sern.
|
|
||||||
* Function to start the handler up
|
|
||||||
* @example
|
|
||||||
* ```ts title="src/index.ts"
|
|
||||||
* Sern.init({
|
|
||||||
* commands: 'dist/commands',
|
|
||||||
* events: 'dist/events',
|
|
||||||
* })
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
|
|
||||||
export function init(maybeWrapper: Wrapper | 'file') {
|
|
||||||
const startTime = performance.now();
|
|
||||||
const wrapper = Files.loadConfig(maybeWrapper);
|
|
||||||
const dependencies = useDependencies();
|
|
||||||
const logger = dependencies[2],
|
|
||||||
errorHandler = dependencies[1];
|
|
||||||
|
|
||||||
if (wrapper.events !== undefined) {
|
|
||||||
eventsHandler(dependencies, Files.getFullPathTree(wrapper.events));
|
|
||||||
}
|
|
||||||
//Ready event: load all modules and when finished, time should be taken and logged
|
|
||||||
startReadyEvent(dependencies, Files.getFullPathTree(wrapper.commands)).add(() => {
|
|
||||||
const time = ((performance.now() - startTime) / 1000).toFixed(2);
|
|
||||||
dependencies[0].emit('modulesLoaded');
|
|
||||||
logger?.info({
|
|
||||||
message: `sern: registered all modules in ${time} s`,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
const messages$ = messageHandler(dependencies, wrapper.defaultPrefix);
|
|
||||||
const interactions$ = interactionHandler(dependencies);
|
|
||||||
// listening to the message stream and interaction stream
|
|
||||||
merge(messages$, interactions$).pipe(handleCrash(errorHandler, logger)).subscribe();
|
|
||||||
}
|
|
||||||
|
|
||||||
function useDependencies() {
|
|
||||||
return Services(
|
|
||||||
'@sern/emitter',
|
|
||||||
'@sern/errors',
|
|
||||||
'@sern/logger',
|
|
||||||
'@sern/modules',
|
|
||||||
'@sern/client',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @since 1.0.0
|
|
||||||
* The object passed into every plugin to control a command's behavior
|
|
||||||
*/
|
|
||||||
export const controller = {
|
|
||||||
next: ok,
|
|
||||||
stop: err,
|
|
||||||
};
|
|
||||||
@@ -1,33 +1,52 @@
|
|||||||
import type { CommandInteractionOptionResolver, InteractionReplyOptions, MessageReplyOptions } from 'discord.js';
|
import type {
|
||||||
import type { PayloadType } from '../core';
|
CommandInteractionOptionResolver,
|
||||||
import type { AnyModule } from './core-modules';
|
InteractionReplyOptions,
|
||||||
|
MessageReplyOptions,
|
||||||
|
} from 'discord.js';
|
||||||
|
import { PayloadType } from './core';
|
||||||
|
import { AnyModule } from './core/types/modules';
|
||||||
|
|
||||||
export type Awaitable<T> = PromiseLike<T> | T;
|
export type ReplyOptions =
|
||||||
|
| string
|
||||||
export type AnyFunction = (...args: unknown[]) => unknown;
|
| Omit<InteractionReplyOptions, 'fetchReply'>
|
||||||
|
| MessageReplyOptions;
|
||||||
// Thanks to @kelsny
|
|
||||||
type ParseType<T> = {
|
|
||||||
[K in keyof T]: T[K] extends unknown ? [k: K, args: T[K]] : never;
|
|
||||||
}[keyof T];
|
|
||||||
|
|
||||||
export type SlashOptions = Omit<CommandInteractionOptionResolver, 'getMessage' | 'getFocused'>;
|
|
||||||
|
|
||||||
export type Args = ParseType<{ text: string[]; slash: SlashOptions }>;
|
|
||||||
|
|
||||||
export interface SernEventsMapping {
|
|
||||||
'module.register': [Payload];
|
|
||||||
'module.activate': [Payload];
|
|
||||||
error: [Payload];
|
|
||||||
warning: [Payload];
|
|
||||||
modulesLoaded: [never?];
|
|
||||||
}
|
|
||||||
|
|
||||||
export type Payload =
|
export type Payload =
|
||||||
| { type: PayloadType.Success; module: AnyModule }
|
| { type: PayloadType.Success; module: AnyModule }
|
||||||
| { type: PayloadType.Failure; module?: AnyModule; reason: string | Error }
|
| { type: PayloadType.Failure; module?: AnyModule; reason: string | Error }
|
||||||
| { type: PayloadType.Warning; reason: string };
|
| { type: PayloadType.Warning; reason: string };
|
||||||
|
|
||||||
|
export interface SernEventsMapping {
|
||||||
|
'module.register': [Payload];
|
||||||
|
'module.activate': [Payload];
|
||||||
|
error: [Payload];
|
||||||
|
warning: [Payload];
|
||||||
|
'modulesLoaded': [never?];
|
||||||
|
}
|
||||||
|
|
||||||
|
export type Awaitable<T> = PromiseLike<T> | T;
|
||||||
|
|
||||||
export type ReplyOptions = string | Omit<InteractionReplyOptions, 'fetchReply'> | MessageReplyOptions;
|
export interface Wrapper {
|
||||||
|
commands: string;
|
||||||
|
defaultPrefix?: string;
|
||||||
|
events?: string;
|
||||||
|
/**
|
||||||
|
* Overload to enable mode in case developer does not use a .env file.
|
||||||
|
*/
|
||||||
|
mode?: 'DEV' | 'PROD';
|
||||||
|
/*
|
||||||
|
* @deprecated
|
||||||
|
*/
|
||||||
|
containerConfig?: {
|
||||||
|
get: (...keys: (keyof Dependencies)[]) => unknown[];
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Thanks to @kelsny
|
||||||
|
type ParseType<T> = {
|
||||||
|
[K in keyof T]: T[K] extends unknown ? [k: K, args: T[K]] : never;
|
||||||
|
}[keyof T];
|
||||||
|
|
||||||
|
export type Args = ParseType<{ text: string[]; slash: SlashOptions }>;
|
||||||
|
|
||||||
|
export type SlashOptions = Omit<CommandInteractionOptionResolver, 'getMessage' | 'getFocused'>;
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
import { OnError } from "./core-modules";
|
|
||||||
|
|
||||||
export interface ImportPayload<T> {
|
|
||||||
module: T;
|
|
||||||
absPath: string;
|
|
||||||
onError: OnError
|
|
||||||
[key: string]: unknown;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface Wrapper {
|
|
||||||
commands: string;
|
|
||||||
defaultPrefix?: string;
|
|
||||||
events?: string;
|
|
||||||
/**
|
|
||||||
* Overload to enable mode in case developer does not use a .env file.
|
|
||||||
* @deprecated - https://github.com/sern-handler/handler/pull/325
|
|
||||||
*/
|
|
||||||
mode?: string
|
|
||||||
/*
|
|
||||||
* @deprecated
|
|
||||||
*/
|
|
||||||
containerConfig?: {
|
|
||||||
get: (...keys: (keyof Dependencies)[]) => unknown[];
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -1,48 +0,0 @@
|
|||||||
import { Container, UnpackFunction } from 'iti';
|
|
||||||
import * as Contracts from '../core/contracts';
|
|
||||||
/**
|
|
||||||
* Type to annotate that something is a singleton.
|
|
||||||
* T is created once and lazily.
|
|
||||||
*/
|
|
||||||
export type Singleton<T> = () => T;
|
|
||||||
/**
|
|
||||||
* Type to annotate that something is transient.
|
|
||||||
* Every time this is called, a new object is created
|
|
||||||
*/
|
|
||||||
export type Transient<T> = () => () => T;
|
|
||||||
/**
|
|
||||||
* Type to annotate that something is initializable.
|
|
||||||
* If T has an init method, this will be called.
|
|
||||||
*/
|
|
||||||
export type Initializable<T extends Contracts.Init> = T
|
|
||||||
|
|
||||||
export type DependencyList = [
|
|
||||||
Contracts.Emitter,
|
|
||||||
Contracts.ErrorHandling,
|
|
||||||
Contracts.Logging | undefined,
|
|
||||||
Contracts.ModuleManager,
|
|
||||||
Contracts.Emitter,
|
|
||||||
];
|
|
||||||
|
|
||||||
export interface CoreDependencies {
|
|
||||||
'@sern/client': () => Contracts.Emitter;
|
|
||||||
'@sern/logger'?: () => Contracts.Logging;
|
|
||||||
'@sern/emitter': () => Contracts.Emitter;
|
|
||||||
'@sern/store': () => Contracts.CoreModuleStore;
|
|
||||||
'@sern/modules': () => Contracts.ModuleManager;
|
|
||||||
'@sern/errors': () => Contracts.ErrorHandling;
|
|
||||||
}
|
|
||||||
|
|
||||||
export type DependencyFromKey<T extends keyof Dependencies> = Dependencies[T];
|
|
||||||
|
|
||||||
export type IntoDependencies<Tuple extends [...any[]]> = {
|
|
||||||
[Index in keyof Tuple]: UnpackFunction<NonNullable<DependencyFromKey<Tuple[Index]>>>; //Unpack and make NonNullable
|
|
||||||
} & { length: Tuple['length'] };
|
|
||||||
|
|
||||||
export interface DependencyConfiguration {
|
|
||||||
//@deprecated. Loggers will always be included in the future
|
|
||||||
exclude?: Set<'@sern/logger'>;
|
|
||||||
build: (
|
|
||||||
root: Container<Omit<CoreDependencies, '@sern/client'>, {}>,
|
|
||||||
) => Container<Dependencies, {}>;
|
|
||||||
}
|
|
||||||
@@ -1,85 +0,0 @@
|
|||||||
import { describe, vi, it, expect } from'vitest'
|
|
||||||
import { Context } from '../../src';
|
|
||||||
import { faker } from '@faker-js/faker'
|
|
||||||
describe('Context', () => {
|
|
||||||
// Mocked message and interaction objects for testing
|
|
||||||
const mockMessage = {
|
|
||||||
id: 'messageId',
|
|
||||||
channel: 'channelId',
|
|
||||||
channelId: 'channelId',
|
|
||||||
interaction: {
|
|
||||||
id: faker.string.uuid()
|
|
||||||
},
|
|
||||||
author: { id: 'userId' },
|
|
||||||
createdTimestamp: 1234567890,
|
|
||||||
guild: 'guildId',
|
|
||||||
guildId: 'guildId',
|
|
||||||
member: { id: 'memberId' },
|
|
||||||
client: { id: 'clientId' },
|
|
||||||
inGuild: vi.fn().mockReturnValue(true),
|
|
||||||
reply: vi.fn(),
|
|
||||||
};
|
|
||||||
|
|
||||||
const mockInteraction = {
|
|
||||||
id: 'interactionId',
|
|
||||||
user: { id: 'userId' },
|
|
||||||
channel: 'channelId',
|
|
||||||
channelId: 'channelId',
|
|
||||||
createdTimestamp: 1234567890,
|
|
||||||
guild: 'guildId',
|
|
||||||
guildId: 'guildId',
|
|
||||||
fetchReply: vi.fn().mockResolvedValue({}),
|
|
||||||
member: { id: 'memberId' },
|
|
||||||
client: { id: 'clientId' },
|
|
||||||
isChatInputCommand: vi.fn().mockResolvedValue(true),
|
|
||||||
inGuild: vi.fn().mockReturnValue(true),
|
|
||||||
reply: vi.fn().mockResolvedValue({}),
|
|
||||||
};
|
|
||||||
|
|
||||||
it('should create a context from a message', () => {
|
|
||||||
//@ts-ignore
|
|
||||||
const context = Context.wrap(mockMessage);
|
|
||||||
expect(context).toBeDefined();
|
|
||||||
expect(context.id).toBe('messageId');
|
|
||||||
});
|
|
||||||
it('should throw error if accessing interaction as message', () => {
|
|
||||||
//@ts-ignore
|
|
||||||
const context = Context.wrap(mockMessage);
|
|
||||||
expect(context).toBeDefined();
|
|
||||||
expect(() => context.interaction)
|
|
||||||
.toThrowError('You cannot use message when an interaction fired or vice versa');
|
|
||||||
|
|
||||||
})
|
|
||||||
it('should throw error if accessing message as interaction', () => {
|
|
||||||
//@ts-ignore
|
|
||||||
const context = Context.wrap(mockInteraction);
|
|
||||||
expect(context).toBeDefined();
|
|
||||||
expect(() => context.message)
|
|
||||||
.toThrowError('You cannot use message when an interaction fired or vice versa');
|
|
||||||
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should create a context from an interaction', () => {
|
|
||||||
//@ts-ignore
|
|
||||||
const context = Context.wrap(mockInteraction);
|
|
||||||
expect(context).toBeDefined();
|
|
||||||
expect(context.id).toBe('interactionId');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should reply to a context with a message', async () => {
|
|
||||||
//@ts-ignore
|
|
||||||
const context = Context.wrap(mockMessage);
|
|
||||||
const replyOptions = { content: 'Hello, world!' };
|
|
||||||
await context.reply(replyOptions);
|
|
||||||
expect(mockMessage.reply).toHaveBeenCalledWith(replyOptions);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should reply to a context with an interaction', async () => {
|
|
||||||
//@ts-ignore
|
|
||||||
const context = Context.wrap(mockInteraction);
|
|
||||||
const replyOptions = { content: 'Hello, world!' };
|
|
||||||
await context.reply(replyOptions);
|
|
||||||
expect(mockInteraction.reply).toHaveBeenCalledWith(replyOptions);
|
|
||||||
});
|
|
||||||
|
|
||||||
});
|
|
||||||
@@ -1,16 +1,14 @@
|
|||||||
import { assertType, describe, it } from 'vitest';
|
import { assertType, describe, it, vi } from "vitest";
|
||||||
|
import * as DefaultContracts from '../../src/core/structures/services'
|
||||||
import { ModuleStore } from '../../src';
|
import * as Contracts from '../../src/core/contracts/index.js'
|
||||||
import * as DefaultContracts from '../../src/core/structures/services';
|
import { ModuleStore } from "../../src/core";
|
||||||
import * as Contracts from '../../src/core/contracts/index.js';
|
|
||||||
|
|
||||||
describe('default contracts', () => {
|
describe('default contracts', () => {
|
||||||
it('should satisfy contracts', () => {
|
it('should satisfy contracts', () => {
|
||||||
assertType<Contracts.Logging>(new DefaultContracts.DefaultLogging());
|
assertType<Contracts.Logging>(new DefaultContracts.DefaultLogging())
|
||||||
assertType<Contracts.ErrorHandling>(new DefaultContracts.DefaultErrorHandling());
|
assertType<Contracts.ErrorHandling>(new DefaultContracts.DefaultErrorHandling())
|
||||||
assertType<Contracts.ModuleManager>(
|
assertType<Contracts.ModuleManager>(new DefaultContracts.DefaultModuleManager(new ModuleStore()))
|
||||||
new DefaultContracts.DefaultModuleManager(new ModuleStore()),
|
assertType<Contracts.CoreModuleStore>(new ModuleStore())
|
||||||
);
|
})
|
||||||
assertType<Contracts.CoreModuleStore>(new ModuleStore());
|
|
||||||
});
|
})
|
||||||
});
|
|
||||||
|
|||||||
@@ -1,32 +1,35 @@
|
|||||||
import { describe, it, expect } from 'vitest';
|
import { describe, it, expect } from 'vitest'
|
||||||
import {
|
import { CommandControlPlugin, CommandInitPlugin, EventControlPlugin, EventInitPlugin } from '../../src/core/create-plugins'
|
||||||
CommandControlPlugin,
|
import { PluginType, controller } from '../../src/index'
|
||||||
CommandInitPlugin,
|
|
||||||
EventControlPlugin,
|
|
||||||
EventInitPlugin,
|
|
||||||
} from '../../src/core/create-plugins';
|
|
||||||
import { PluginType, controller } from '../../src';
|
|
||||||
|
|
||||||
describe('create-plugins', () => {
|
describe('create-plugins', () => {
|
||||||
it('should make proper control plugins', () => {
|
it('should make proper control plugins', () => {
|
||||||
const pl = EventControlPlugin(() => controller.next());
|
const pl = EventControlPlugin(() => controller.next())
|
||||||
expect(pl).to.have.all.keys(['type', 'execute']);
|
expect(pl)
|
||||||
expect(pl.type).toBe(PluginType.Control);
|
.to.have.all.keys(['type', 'execute'])
|
||||||
expect(pl.execute).an('function');
|
expect(pl.type).toBe(PluginType.Control)
|
||||||
const pl2 = CommandControlPlugin(() => controller.next());
|
expect(pl.execute).an('function')
|
||||||
expect(pl2).to.have.all.keys(['type', 'execute']);
|
const pl2 = CommandControlPlugin(() => controller.next())
|
||||||
expect(pl2.type).toBe(PluginType.Control);
|
expect(pl2)
|
||||||
expect(pl2.execute).an('function');
|
.to.have.all.keys(['type', 'execute'])
|
||||||
});
|
expect(pl2.type).toBe(PluginType.Control)
|
||||||
it('should make proper init plugins', () => {
|
expect(pl2.execute).an('function')
|
||||||
const pl = EventInitPlugin(() => controller.next());
|
|
||||||
expect(pl).to.have.all.keys(['type', 'execute']);
|
})
|
||||||
expect(pl.type).toBe(PluginType.Init);
|
it('should make proper init plugins', () => {
|
||||||
expect(pl.execute).an('function');
|
const pl = EventInitPlugin(() => controller.next())
|
||||||
|
expect(pl)
|
||||||
|
.to.have.all.keys(['type', 'execute'])
|
||||||
|
expect(pl.type).toBe(PluginType.Init)
|
||||||
|
expect(pl.execute).an('function')
|
||||||
|
|
||||||
|
const pl2 = CommandInitPlugin(() => controller.next())
|
||||||
|
expect(pl2)
|
||||||
|
.to.have.all.keys(['type', 'execute'])
|
||||||
|
expect(pl2.type).toBe(PluginType.Init)
|
||||||
|
expect(pl2.execute).an('function')
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
})
|
||||||
|
|
||||||
const pl2 = CommandInitPlugin(() => controller.next());
|
|
||||||
expect(pl2).to.have.all.keys(['type', 'execute']);
|
|
||||||
expect(pl2.type).toBe(PluginType.Init);
|
|
||||||
expect(pl2.execute).an('function');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|||||||
@@ -1,404 +1,208 @@
|
|||||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||||
import { PluginType, SernOptionsData, controller } from '../../src/index';
|
import { PluginType, SernOptionsData, controller } from '../../src/index'
|
||||||
import { partitionPlugins, treeSearch } from '../../src/core/functions';
|
import { partitionPlugins, treeSearch } from "../../src/core/functions";
|
||||||
import { faker } from '@faker-js/faker';
|
import { faker } from '@faker-js/faker';
|
||||||
import { ApplicationCommandOptionType, AutocompleteInteraction } from 'discord.js';
|
import { ApplicationCommandOptionType, AutocompleteInteraction } from "discord.js";
|
||||||
|
|
||||||
vi.mock('discord.js', () => {
|
vi.mock('discord.js', () => {
|
||||||
const Collection = Map;
|
|
||||||
const ModalSubmitInteraction = class {
|
|
||||||
customId;
|
|
||||||
type = 5;
|
|
||||||
isModalSubmit = vi.fn();
|
|
||||||
constructor(customId) {
|
|
||||||
this.customId = customId;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
const ButtonInteraction = class {
|
|
||||||
customId;
|
|
||||||
type = 3;
|
|
||||||
componentType = 2;
|
|
||||||
isButton = vi.fn();
|
|
||||||
constructor(customId) {
|
|
||||||
this.customId = customId;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
const AutocompleteInteraction = class {
|
|
||||||
type = 4;
|
|
||||||
option: string;
|
|
||||||
constructor(s: string) {
|
|
||||||
this.option = s;
|
|
||||||
}
|
|
||||||
options = {
|
|
||||||
getFocused: vi.fn(),
|
|
||||||
getSubcommand: vi.fn(),
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
return {
|
const Collection = Map
|
||||||
Collection,
|
const ModalSubmitInteraction = class {
|
||||||
ComponentType: {
|
customId
|
||||||
Button: 2,
|
type = 5
|
||||||
},
|
isModalSubmit = vi.fn()
|
||||||
InteractionType: {
|
constructor(customId) {
|
||||||
Ping: 1,
|
this.customId = customId
|
||||||
ApplicationCommand: 2,
|
}
|
||||||
MessageComponent: 3,
|
}
|
||||||
ApplicationCommandAutocomplete: 4,
|
const ButtonInteraction = class {
|
||||||
ModalSubmit: 5,
|
customId
|
||||||
},
|
type = 3
|
||||||
ApplicationCommandOptionType: {
|
componentType = 2
|
||||||
Subcommand: 1,
|
isButton = vi.fn()
|
||||||
SubcommandGroup: 2,
|
constructor(customId) {
|
||||||
String: 3,
|
this.customId = customId
|
||||||
Integer: 4,
|
}
|
||||||
Boolean: 5,
|
}
|
||||||
User: 6,
|
const AutocompleteInteraction = class {
|
||||||
Channel: 7,
|
type = 4;
|
||||||
Role: 8,
|
option: string
|
||||||
Mentionable: 9,
|
constructor(s: string) {
|
||||||
Number: 10,
|
this.option = s;
|
||||||
Attachment: 11,
|
}
|
||||||
},
|
options = {
|
||||||
ApplicationCommandType: {
|
getFocused : vi.fn()
|
||||||
ChatInput: 1,
|
}
|
||||||
User: 2,
|
}
|
||||||
Message: 3,
|
|
||||||
},
|
return {
|
||||||
ModalSubmitInteraction,
|
Collection,
|
||||||
ButtonInteraction,
|
ComponentType: {
|
||||||
AutocompleteInteraction,
|
Button: 2
|
||||||
};
|
},
|
||||||
});
|
InteractionType : {
|
||||||
|
Ping: 1,
|
||||||
|
ApplicationCommand: 2,
|
||||||
|
MessageComponent: 3,
|
||||||
|
ApplicationCommandAutocomplete:4,
|
||||||
|
ModalSubmit: 5
|
||||||
|
},
|
||||||
|
ApplicationCommandOptionType : {
|
||||||
|
Subcommand : 1,
|
||||||
|
SubcommandGroup : 2,
|
||||||
|
String : 3,
|
||||||
|
Integer : 4,
|
||||||
|
Boolean : 5,
|
||||||
|
User : 6,
|
||||||
|
Channel : 7,
|
||||||
|
Role : 8,
|
||||||
|
Mentionable : 9,
|
||||||
|
Number : 10,
|
||||||
|
Attachment : 11
|
||||||
|
},
|
||||||
|
ModalSubmitInteraction,
|
||||||
|
ButtonInteraction,
|
||||||
|
AutocompleteInteraction
|
||||||
|
};
|
||||||
|
})
|
||||||
|
|
||||||
describe('functions', () => {
|
describe('functions', () => {
|
||||||
afterEach(() => {
|
afterEach(() => { vi.clearAllMocks() })
|
||||||
vi.clearAllMocks();
|
|
||||||
});
|
|
||||||
function createRandomPlugins(len: number) {
|
function createRandomPlugins(len: number) {
|
||||||
const random = () => Math.floor(Math.random() * 2) + 1; // 1 or 2, plugin enum
|
const random = () => Math.floor(Math.random()*2)+1; // 1 or 2, plugin enum
|
||||||
return Array.from({ length: len }, () => ({
|
return Array.from({ length: len }, () => ({ type: random(), execute: () => random() === 1 ? controller.next():controller.stop() }))
|
||||||
type: random(),
|
|
||||||
execute: () => (random() === 1 ? controller.next() : controller.stop()),
|
|
||||||
}));
|
|
||||||
}
|
}
|
||||||
function createRandomChoice() {
|
function createRandomChoice() {
|
||||||
return {
|
return {
|
||||||
type: faker.number.int({ min: 1, max: 11 }),
|
type: faker.number.int({ min: 1, max: 11}),
|
||||||
name: faker.word.noun(),
|
name: faker.word.noun(),
|
||||||
description: faker.word.adjective(),
|
description: faker.word.adjective(),
|
||||||
};
|
}
|
||||||
}
|
}
|
||||||
it('should partition plugins correctly', () => {
|
it('should partition plugins correctly', () => {
|
||||||
const plugins = createRandomPlugins(100);
|
const plugins = createRandomPlugins(100);
|
||||||
const [onEvent, init] = partitionPlugins(plugins);
|
const [ onEvent, init ] = partitionPlugins(plugins)
|
||||||
for (const el of onEvent) expect(el.type).to.equal(PluginType.Control);
|
for(const el of onEvent)
|
||||||
|
expect(el.type).to.equal(PluginType.Control)
|
||||||
|
|
||||||
for (const el of init) expect(el.type).to.equal(PluginType.Init);
|
for(const el of init)
|
||||||
});
|
expect(el.type).to.equal(PluginType.Init)
|
||||||
|
})
|
||||||
|
|
||||||
it('should tree search options tree depth 1', () => {
|
it('should tree search options tree depth 1', () => {
|
||||||
//@ts-expect-error mocking
|
//@ts-expect-error mocking
|
||||||
let autocmpInteraction = new AutocompleteInteraction('autocomplete');
|
let autocmpInteraction = new AutocompleteInteraction('autocomplete');
|
||||||
const options: SernOptionsData[] = [
|
const options : SernOptionsData[] = [
|
||||||
createRandomChoice(),
|
createRandomChoice(),
|
||||||
createRandomChoice(),
|
createRandomChoice(),
|
||||||
createRandomChoice(),
|
createRandomChoice(),
|
||||||
{
|
{
|
||||||
type: ApplicationCommandOptionType.String,
|
type: ApplicationCommandOptionType.String,
|
||||||
name: 'autocomplete',
|
name: 'autocomplete',
|
||||||
description: 'here',
|
description: 'here',
|
||||||
autocomplete: true,
|
autocomplete: true,
|
||||||
command: { onEvent: [], execute: vi.fn() },
|
command : { onEvent: [], execute:(a) => {} }
|
||||||
},
|
}
|
||||||
];
|
];
|
||||||
autocmpInteraction.options.getFocused.mockReturnValue({
|
autocmpInteraction.options.getFocused.mockReturnValue(
|
||||||
name: 'autocomplete',
|
{
|
||||||
value: faker.string.alpha(),
|
name: 'autocomplete',
|
||||||
focused: true,
|
value: faker.string.alpha(),
|
||||||
});
|
focused: true
|
||||||
|
},
|
||||||
|
);
|
||||||
const result = treeSearch(autocmpInteraction, options);
|
const result = treeSearch(autocmpInteraction, options);
|
||||||
expect(result == undefined).to.be.false;
|
expect(result == undefined).to.be.false;
|
||||||
expect(result.name).to.be.eq('autocomplete');
|
expect(result.name).to.be.eq('autocomplete');
|
||||||
expect(result.command).to.be.not.undefined;
|
expect(result.command).to.be.not.undefined;
|
||||||
}),
|
|
||||||
it('should tree search depth 2', () => {
|
|
||||||
//@ts-expect-error mocking
|
|
||||||
let autocmpInteraction = new AutocompleteInteraction('nested');
|
|
||||||
const subcommandName = faker.string.alpha();
|
|
||||||
const options: SernOptionsData[] = [
|
|
||||||
{
|
|
||||||
type: ApplicationCommandOptionType.Subcommand,
|
|
||||||
name: subcommandName,
|
|
||||||
description: faker.string.alpha(),
|
|
||||||
options: [
|
|
||||||
createRandomChoice(),
|
|
||||||
createRandomChoice(),
|
|
||||||
createRandomChoice(),
|
|
||||||
{
|
|
||||||
type: ApplicationCommandOptionType.String,
|
|
||||||
name: 'nested',
|
|
||||||
description: faker.string.alpha(),
|
|
||||||
autocomplete: true,
|
|
||||||
command: {
|
|
||||||
onEvent: [],
|
|
||||||
execute: () => {},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
];
|
|
||||||
autocmpInteraction.options.getSubcommand.mockReturnValue(subcommandName);
|
|
||||||
autocmpInteraction.options.getFocused.mockReturnValue({
|
|
||||||
name: 'nested',
|
|
||||||
value: faker.string.alpha(),
|
|
||||||
focused: true,
|
|
||||||
});
|
|
||||||
const result = treeSearch(autocmpInteraction, options);
|
|
||||||
expect(result == undefined).to.be.false;
|
|
||||||
expect(result.name).to.be.eq('nested');
|
|
||||||
expect(result.command).to.be.not.undefined;
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should tree search depth n > 2', () => {
|
}),
|
||||||
|
it('should tree search depth 2', () => {
|
||||||
//@ts-expect-error mocking
|
//@ts-expect-error mocking
|
||||||
let autocmpInteraction = new AutocompleteInteraction('nested');
|
let autocmpInteraction = new AutocompleteInteraction('nested');
|
||||||
const subcommandName = faker.string.alpha();
|
const options : SernOptionsData[] = [
|
||||||
const options: SernOptionsData[] = [
|
|
||||||
{
|
{
|
||||||
type: ApplicationCommandOptionType.SubcommandGroup,
|
type: ApplicationCommandOptionType.Subcommand,
|
||||||
name: faker.string.alpha(),
|
name: faker.string.alpha(),
|
||||||
description: faker.string.alpha(),
|
description: faker.string.alpha(),
|
||||||
options: [
|
options: [
|
||||||
{
|
createRandomChoice(),
|
||||||
type: ApplicationCommandOptionType.Subcommand,
|
createRandomChoice(),
|
||||||
name: subcommandName,
|
createRandomChoice(),
|
||||||
description: faker.string.alpha(),
|
{
|
||||||
options: [
|
type: ApplicationCommandOptionType.String,
|
||||||
createRandomChoice(),
|
name: 'nested',
|
||||||
createRandomChoice(),
|
description: faker.string.alpha(),
|
||||||
{
|
autocomplete: true,
|
||||||
type: ApplicationCommandOptionType.String,
|
command: {
|
||||||
name: 'nested',
|
onEvent: [],
|
||||||
description: faker.string.alpha(),
|
execute:() => {}
|
||||||
autocomplete: true,
|
}
|
||||||
command: {
|
}
|
||||||
onEvent: [],
|
]
|
||||||
execute: () => {},
|
}
|
||||||
},
|
|
||||||
},
|
|
||||||
createRandomChoice(),
|
|
||||||
],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
];
|
];
|
||||||
autocmpInteraction.options.getSubcommand.mockReturnValue(subcommandName);
|
autocmpInteraction.options.getFocused.mockReturnValue(
|
||||||
autocmpInteraction.options.getFocused.mockReturnValue({
|
{
|
||||||
name: 'nested',
|
name: 'nested',
|
||||||
value: faker.string.alpha(),
|
value: faker.string.alpha(),
|
||||||
focused: true,
|
focused: true
|
||||||
});
|
}
|
||||||
|
);
|
||||||
const result = treeSearch(autocmpInteraction, options);
|
const result = treeSearch(autocmpInteraction, options);
|
||||||
expect(result == undefined).to.be.false;
|
expect(result == undefined).to.be.false;
|
||||||
expect(result.name).to.be.eq('nested');
|
expect(result.name).to.be.eq('nested');
|
||||||
expect(result.command).to.be.not.undefined;
|
expect(result.command).to.be.not.undefined;
|
||||||
});
|
|
||||||
it('should correctly resolve suboption of the same name given two subcommands ', () => {
|
})
|
||||||
|
|
||||||
|
it('should tree search depth n > 2', () => {
|
||||||
|
//@ts-expect-error mocking
|
||||||
let autocmpInteraction = new AutocompleteInteraction('nested');
|
let autocmpInteraction = new AutocompleteInteraction('nested');
|
||||||
const subcommandName = faker.string.alpha();
|
const options : SernOptionsData[] = [
|
||||||
const options: SernOptionsData[] = [
|
|
||||||
{
|
{
|
||||||
|
|
||||||
type: ApplicationCommandOptionType.SubcommandGroup,
|
type: ApplicationCommandOptionType.SubcommandGroup,
|
||||||
name: faker.string.alpha(),
|
name: faker.string.alpha(),
|
||||||
description: faker.string.alpha(),
|
description: faker.string.alpha(),
|
||||||
options: [
|
options: [
|
||||||
{
|
{
|
||||||
type: ApplicationCommandOptionType.Subcommand,
|
type: ApplicationCommandOptionType.Subcommand,
|
||||||
name: subcommandName,
|
name: faker.string.alpha(),
|
||||||
|
description: faker.string.alpha(),
|
||||||
|
options: [
|
||||||
|
createRandomChoice(),
|
||||||
|
createRandomChoice(),
|
||||||
|
createRandomChoice(),
|
||||||
|
{
|
||||||
|
type: ApplicationCommandOptionType.String,
|
||||||
|
name: 'nested',
|
||||||
description: faker.string.alpha(),
|
description: faker.string.alpha(),
|
||||||
options: [
|
autocomplete: true,
|
||||||
createRandomChoice(),
|
command: {
|
||||||
createRandomChoice(),
|
onEvent: [],
|
||||||
{
|
execute:() => {}
|
||||||
type: ApplicationCommandOptionType.String,
|
}
|
||||||
name: 'nested',
|
}
|
||||||
description: faker.string.alpha(),
|
]
|
||||||
autocomplete: true,
|
}]
|
||||||
command: {
|
|
||||||
onEvent: [],
|
|
||||||
execute: () => {},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
type: ApplicationCommandOptionType.Subcommand,
|
|
||||||
name: subcommandName + 'a',
|
|
||||||
description: faker.string.alpha(),
|
|
||||||
options: [
|
|
||||||
createRandomChoice(),
|
|
||||||
{
|
|
||||||
type: ApplicationCommandOptionType.String,
|
|
||||||
name: 'nested',
|
|
||||||
description: faker.string.alpha(),
|
|
||||||
autocomplete: true,
|
|
||||||
command: {
|
|
||||||
onEvent: [],
|
|
||||||
execute: () => {},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
autocmpInteraction.options.getSubcommand.mockReturnValue(subcommandName);
|
autocmpInteraction.options.getFocused.mockReturnValue(
|
||||||
autocmpInteraction.options.getFocused.mockReturnValue({
|
|
||||||
name: 'nested',
|
|
||||||
value: faker.string.alpha(),
|
|
||||||
focused: true,
|
|
||||||
});
|
|
||||||
const result = treeSearch(autocmpInteraction, options);
|
|
||||||
expect(result).toBeTruthy();
|
|
||||||
expect(result.name).to.be.eq('nested');
|
|
||||||
expect(result.command).to.be.not.undefined;
|
|
||||||
});
|
|
||||||
it('two subcommands with an option of the same name', () => {
|
|
||||||
let autocmpInteraction = new AutocompleteInteraction('nested');
|
|
||||||
const subcommandName = faker.string.alpha();
|
|
||||||
const options: SernOptionsData[] = [
|
|
||||||
{
|
{
|
||||||
type: ApplicationCommandOptionType.SubcommandGroup,
|
name: 'nested',
|
||||||
name: faker.string.alpha(),
|
|
||||||
description: faker.string.alpha(),
|
|
||||||
options: [
|
|
||||||
{
|
|
||||||
type: ApplicationCommandOptionType.Subcommand,
|
|
||||||
name: subcommandName,
|
|
||||||
description: faker.string.alpha(),
|
|
||||||
options: [
|
|
||||||
createRandomChoice(),
|
|
||||||
createRandomChoice(),
|
|
||||||
{
|
|
||||||
type: ApplicationCommandOptionType.String,
|
|
||||||
name: 'nested',
|
|
||||||
description: faker.string.alpha(),
|
|
||||||
autocomplete: true,
|
|
||||||
command: {
|
|
||||||
onEvent: [],
|
|
||||||
execute: () => {},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
type: ApplicationCommandOptionType.Subcommand,
|
|
||||||
name: subcommandName + 'a',
|
|
||||||
description: faker.string.alpha(),
|
|
||||||
options: [
|
|
||||||
createRandomChoice(),
|
|
||||||
{
|
|
||||||
type: ApplicationCommandOptionType.String,
|
|
||||||
name: 'nested',
|
|
||||||
description: faker.string.alpha(),
|
|
||||||
autocomplete: true,
|
|
||||||
command: {
|
|
||||||
onEvent: [],
|
|
||||||
execute: () => {},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
];
|
|
||||||
autocmpInteraction.options.getSubcommand.mockReturnValue(subcommandName);
|
|
||||||
autocmpInteraction.options.getFocused.mockReturnValue({
|
|
||||||
name: 'nested',
|
|
||||||
value: faker.string.alpha(),
|
|
||||||
focused: true,
|
|
||||||
});
|
|
||||||
const result = treeSearch(autocmpInteraction, options);
|
|
||||||
expect(result).toBeTruthy();
|
|
||||||
expect(result.name).to.be.eq('nested');
|
|
||||||
expect(result.command).to.be.not.undefined;
|
|
||||||
|
|
||||||
let autocmpInteraction2 = new AutocompleteInteraction('nested');
|
|
||||||
autocmpInteraction2.options.getSubcommand.mockReturnValue(subcommandName + 'a');
|
|
||||||
autocmpInteraction2.options.getFocused.mockReturnValue({
|
|
||||||
name: 'nested',
|
|
||||||
value: faker.string.alpha(),
|
|
||||||
focused: true,
|
|
||||||
});
|
|
||||||
const result2 = treeSearch(autocmpInteraction2, options);
|
|
||||||
expect(result2).toBeTruthy();
|
|
||||||
expect(result2?.name).toEqual('nested');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('simulates autocomplete typing and resolution', () => {
|
|
||||||
const subcommandName = faker.string.alpha();
|
|
||||||
const optionName = faker.word.noun();
|
|
||||||
const options: SernOptionsData[] = [
|
|
||||||
{
|
|
||||||
type: ApplicationCommandOptionType.SubcommandGroup,
|
|
||||||
name: faker.string.alpha(),
|
|
||||||
description: faker.string.alpha(),
|
|
||||||
options: [
|
|
||||||
{
|
|
||||||
type: ApplicationCommandOptionType.Subcommand,
|
|
||||||
name: subcommandName,
|
|
||||||
description: faker.string.alpha(),
|
|
||||||
options: [
|
|
||||||
createRandomChoice(),
|
|
||||||
createRandomChoice(),
|
|
||||||
{
|
|
||||||
type: ApplicationCommandOptionType.String,
|
|
||||||
name: optionName,
|
|
||||||
description: faker.string.alpha(),
|
|
||||||
autocomplete: true,
|
|
||||||
command: {
|
|
||||||
onEvent: [],
|
|
||||||
execute: vi.fn(),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
type: ApplicationCommandOptionType.Subcommand,
|
|
||||||
name: subcommandName + 'a',
|
|
||||||
description: faker.string.alpha(),
|
|
||||||
options: [
|
|
||||||
createRandomChoice(),
|
|
||||||
{
|
|
||||||
type: ApplicationCommandOptionType.String,
|
|
||||||
name: optionName,
|
|
||||||
description: faker.string.alpha(),
|
|
||||||
autocomplete: true,
|
|
||||||
command: {
|
|
||||||
onEvent: [],
|
|
||||||
execute: vi.fn(),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
];
|
|
||||||
let accumulator = '';
|
|
||||||
let result: unknown;
|
|
||||||
for (const char of optionName) {
|
|
||||||
accumulator += char;
|
|
||||||
|
|
||||||
const autocomplete = new AutocompleteInteraction(accumulator);
|
|
||||||
autocomplete.options.getSubcommand.mockReturnValue(subcommandName);
|
|
||||||
autocomplete.options.getFocused.mockReturnValue({
|
|
||||||
name: accumulator,
|
|
||||||
value: faker.string.alpha(),
|
value: faker.string.alpha(),
|
||||||
focused: true,
|
focused: true
|
||||||
});
|
}
|
||||||
result = treeSearch(autocomplete, options);
|
);
|
||||||
}
|
const result = treeSearch(autocmpInteraction, options);
|
||||||
expect(result).toBeTruthy();
|
expect(result == undefined).to.be.false;
|
||||||
});
|
expect(result.name).to.be.eq('nested');
|
||||||
});
|
expect(result.command).to.be.not.undefined;
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,86 +1,52 @@
|
|||||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
import { CoreContainer } from '../../src/core/ioc/container';
|
import { CoreContainer } from '../../src/core/structures/container'
|
||||||
import { EventEmitter } from 'events';
|
import { CoreDependencies } from "../../src/core/ioc";
|
||||||
import { DefaultLogging, Disposable, Init, Logging } from '../../src/core';
|
import { EventEmitter } from "events";
|
||||||
import { CoreDependencies } from '../../src/types/ioc';
|
import { DefaultLogging, Init, Logging } from "../../src/core";
|
||||||
|
|
||||||
|
|
||||||
describe('ioc container', () => {
|
describe('ioc container', () => {
|
||||||
let container: CoreContainer<{}> = new CoreContainer();
|
let container: CoreContainer<{}>;
|
||||||
let dependency: Logging & Init & Disposable;
|
let initDependency: Logging & Init;
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
dependency = {
|
initDependency = {
|
||||||
init: vi.fn(),
|
init: vi.fn(),
|
||||||
error(): void {},
|
error(): void {},
|
||||||
warning(): void {},
|
warning(): void {},
|
||||||
info(): void {},
|
info(): void {},
|
||||||
debug(): void {},
|
debug(): void {},
|
||||||
dispose: vi.fn()
|
}
|
||||||
};
|
container = new CoreContainer()
|
||||||
container = new CoreContainer();
|
|
||||||
});
|
})
|
||||||
const wait = (seconds: number) => new Promise((resolve) => setTimeout(resolve, seconds));
|
|
||||||
class DB implements Init, Disposable {
|
|
||||||
public connected = false
|
|
||||||
constructor() {}
|
|
||||||
async init() {
|
|
||||||
this.connected = true
|
|
||||||
await wait(10)
|
|
||||||
}
|
|
||||||
async dispose() {
|
|
||||||
await wait(20)
|
|
||||||
this.connected = false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
it('should be ready after calling container.ready()', () => {
|
it('should be ready after calling container.ready()', () => {
|
||||||
container.ready();
|
container.ready()
|
||||||
expect(container.isReady()).toBe(true);
|
expect(container.isReady()).toBe(true)
|
||||||
});
|
})
|
||||||
it('should container all core dependencies', async () => {
|
it('should container all core dependencies', async () => {
|
||||||
const keys = [
|
const keys = ['@sern/modules', '@sern/emitter', '@sern/logger', '@sern/errors'] satisfies (keyof CoreDependencies)[]
|
||||||
'@sern/modules',
|
|
||||||
'@sern/emitter',
|
|
||||||
'@sern/logger',
|
|
||||||
'@sern/errors',
|
|
||||||
] satisfies (keyof CoreDependencies)[];
|
|
||||||
container.add({
|
container.add({
|
||||||
'@sern/logger': () => new DefaultLogging(),
|
'@sern/logger': () => new DefaultLogging(),
|
||||||
'@sern/client': () => new EventEmitter(),
|
'@sern/client': () => new EventEmitter(),
|
||||||
});
|
})
|
||||||
for (const k of keys) {
|
for(const k of keys) {
|
||||||
//@ts-expect-error typings for iti are strict
|
//@ts-expect-error typings for iti are strict
|
||||||
expect(() => container.get(k)).not.toThrow();
|
expect(() => container.get(k)).not.toThrow();
|
||||||
}
|
}
|
||||||
});
|
})
|
||||||
it('should init modules', () => {
|
it('should init modules', () => {
|
||||||
container.upsert({ '@sern/logger': dependency });
|
container.upsert({ '@sern/logger': initDependency })
|
||||||
container.ready();
|
|
||||||
expect(dependency.init).to.toHaveBeenCalledOnce();
|
|
||||||
});
|
|
||||||
it('should dispose modules', async () => {
|
|
||||||
|
|
||||||
container.upsert({ '@sern/logger': dependency })
|
|
||||||
|
|
||||||
container.ready();
|
|
||||||
// We need to access the dependency at least once to be able to dispose of it.
|
|
||||||
container.get('@sern/logger' as never);
|
|
||||||
await container.disposeAll();
|
|
||||||
expect(dependency.dispose).toHaveBeenCalledOnce();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should init and dispose', async () => {
|
|
||||||
container.add({ db: new DB() })
|
|
||||||
container.ready()
|
container.ready()
|
||||||
const db = container.get('db' as never) as DB
|
expect(initDependency.init).to.toHaveBeenCalledOnce()
|
||||||
expect(db.connected).toBeTruthy()
|
|
||||||
|
|
||||||
await container.disposeAll();
|
|
||||||
|
|
||||||
expect(db.connected).toBeFalsy()
|
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should not lazy module', () => {
|
it('should not lazy module', () => {
|
||||||
container.upsert({ '@sern/logger': () => dependency });
|
container.upsert({ '@sern/logger': () => initDependency })
|
||||||
container.ready();
|
container.ready()
|
||||||
expect(dependency.init).toHaveBeenCalledTimes(0);
|
expect(initDependency.init).toHaveBeenCalledTimes(0);
|
||||||
});
|
})
|
||||||
});
|
|
||||||
|
|
||||||
|
|
||||||
|
})
|
||||||
|
|||||||
@@ -1,22 +0,0 @@
|
|||||||
import { describe, it, expect } from 'vitest'
|
|
||||||
import { faker } from '@faker-js/faker'
|
|
||||||
import * as Files from '../../src/core/module-loading'
|
|
||||||
describe('module-loading', () => {
|
|
||||||
it('should properly extract filename from file, nested once', () => {
|
|
||||||
const extension = faker.system.fileExt()
|
|
||||||
const name = faker.system.fileName({ extensionCount: 0 })
|
|
||||||
const filename = Files.fmtFileName(name+'.'+extension);
|
|
||||||
expect(filename).toBe(name)
|
|
||||||
})
|
|
||||||
|
|
||||||
// todo: handle commands with multiple extensions
|
|
||||||
// it('should properly extract filename from file, nested multiple', () => {
|
|
||||||
// const extension = faker.system.fileExt()
|
|
||||||
// const extension2 = faker.system.fileExt()
|
|
||||||
// const name = faker.system.fileName({ extensionCount: 0 })
|
|
||||||
// const filename = Files.fmtFileName(name+'.'+extension+'.'+extension2);
|
|
||||||
// console.log(filename, name)
|
|
||||||
// expect(filename).toBe(name)
|
|
||||||
//
|
|
||||||
// })
|
|
||||||
})
|
|
||||||
@@ -1,77 +1,80 @@
|
|||||||
import { SpyInstance, afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
import { SpyInstance, afterAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
import { CoreContainer } from '../../src/core/ioc/container';
|
import { CoreContainer } from '../../src/core/structures/container'
|
||||||
import { DefaultLogging } from '../../src/core';
|
import { DefaultLogging } from "../../src/core";
|
||||||
import { faker } from '@faker-js/faker';
|
import { faker } from '@faker-js/faker'
|
||||||
import { commandModule } from '../../src';
|
import { commandModule } from "../../src";
|
||||||
import * as Id from '../../src/core/id';
|
import { createId } from '../../src/handler/id'
|
||||||
import { CommandMeta } from '../../src/types/core-modules';
|
import { CommandMeta } from "../../src/core/types/modules";
|
||||||
|
|
||||||
describe('services', () => {
|
describe('services', () => {
|
||||||
//@ts-ignore
|
//@ts-ignore
|
||||||
let container: CoreContainer<Dependencies>;
|
let container: CoreContainer<Dependencies>;
|
||||||
let consoleMock: SpyInstance;
|
let consoleMock : SpyInstance;
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
container = new CoreContainer();
|
container = new CoreContainer()
|
||||||
container.add({ '@sern/logger': () => new DefaultLogging() });
|
container.add({ '@sern/logger': () => new DefaultLogging() })
|
||||||
container.ready();
|
container.ready()
|
||||||
consoleMock = vi.spyOn(container.get('@sern/logger'), 'error').mockImplementation(() => {});
|
consoleMock = vi.spyOn(container.get('@sern/logger'), 'error').mockImplementation(() => {})
|
||||||
});
|
})
|
||||||
|
|
||||||
afterAll(() => {
|
afterAll(() => {
|
||||||
consoleMock.mockReset();
|
consoleMock.mockReset()
|
||||||
});
|
});
|
||||||
it('module-store.ts', async () => {
|
it('module-store.ts', async () => {
|
||||||
function createRandomCommandModules() {
|
function createRandomCommandModules() {
|
||||||
return commandModule({
|
return commandModule({
|
||||||
type: faker.number.int({ min: 1 << 0, max: 1 << 10 }),
|
type: faker.number.int({ min: 1<<0, max: 1<<10 }),
|
||||||
description: faker.string.alpha(),
|
description: faker.string.alpha(),
|
||||||
name: faker.string.alpha(),
|
name: faker.string.alpha(),
|
||||||
execute: () => {},
|
execute: ()=>{}
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
const modules = faker.helpers.multiple(createRandomCommandModules, {
|
const modules = faker.helpers.multiple(createRandomCommandModules, { count: 40 })
|
||||||
count: 40,
|
|
||||||
});
|
|
||||||
|
|
||||||
const paths = faker.helpers
|
const paths = faker.helpers.multiple(faker.system.directoryPath, { count: 40 })
|
||||||
.multiple(faker.system.directoryPath, { count: 40 })
|
.map((path,i) => `${path}/${modules[i]}.js`);
|
||||||
.map((path, i) => `${path}/${modules[i]}.js`);
|
|
||||||
|
|
||||||
const metadata: CommandMeta[] = modules.map((cm, i) => ({
|
const metadata: CommandMeta[] = modules.map((cm, i) => ({
|
||||||
id: Id.create(cm.name!, cm.type),
|
id: createId(cm.name, cm.type),
|
||||||
isClass: false,
|
isClass: false,
|
||||||
fullPath: `${paths[i]}/${cm.name}.js`,
|
fullPath: `${paths[i]}/${cm.name}.js`
|
||||||
}));
|
}));
|
||||||
const moduleManager = container.get('@sern/modules');
|
const moduleManager = container.get('@sern/modules');
|
||||||
let i = 0;
|
let i =0;
|
||||||
for (const m of modules) {
|
for(const m of modules) {
|
||||||
moduleManager.set(Id.create(m.name!, m.type), paths[i]);
|
moduleManager.set(createId(m.name,m.type), paths[i]);
|
||||||
moduleManager.setMetadata(m, metadata[i]);
|
moduleManager.setMetadata(m, metadata[i]);
|
||||||
i++;
|
i++
|
||||||
}
|
}
|
||||||
for (const m of modules) {
|
for(const m of modules) {
|
||||||
expect(moduleManager.getMetadata(m), 'module references do not exist').toBeDefined();
|
expect(moduleManager.getMetadata(m), "module references do not exist").toBeDefined()
|
||||||
}
|
}
|
||||||
});
|
|
||||||
|
})
|
||||||
|
|
||||||
//todo add more
|
//todo add more
|
||||||
it('error-handling', () => {
|
it('error-handling', () => {
|
||||||
const errorHandler = container.get('@sern/errors');
|
const errorHandler = container.get('@sern/errors');
|
||||||
const lifetime = errorHandler.keepAlive;
|
const lifetime = errorHandler.keepAlive;
|
||||||
for (let i = 0; i < lifetime; i++) {
|
for(let i = 0; i< lifetime; i++) {
|
||||||
if (i == lifetime - 1) {
|
if(i == lifetime-1) {
|
||||||
expect(() => errorHandler.updateAlive(new Error('poo'))).toThrowError();
|
expect(() => errorHandler.updateAlive(new Error("poo"))).toThrowError();
|
||||||
} else {
|
} else {
|
||||||
expect(() => errorHandler.updateAlive(new Error('poo'))).not.toThrowError();
|
expect(() => errorHandler.updateAlive(new Error("poo"))).not.toThrowError();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
|
||||||
|
})
|
||||||
//todo add more, spy on every instance?
|
//todo add more, spy on every instance?
|
||||||
it('logger', () => {
|
it('logger', () => {
|
||||||
container.get('@sern/logger').error({ message: 'error' });
|
|
||||||
|
container.get('@sern/logger').error({ message: 'error' })
|
||||||
|
|
||||||
expect(consoleMock).toHaveBeenCalledOnce();
|
expect(consoleMock).toHaveBeenCalledOnce();
|
||||||
expect(consoleMock).toHaveBeenLastCalledWith({ message: 'error' });
|
expect(consoleMock).toHaveBeenLastCalledWith({ message: 'error' })
|
||||||
});
|
})
|
||||||
});
|
|
||||||
|
|
||||||
|
|
||||||
|
})
|
||||||
|
|||||||
@@ -1,45 +0,0 @@
|
|||||||
import { beforeEach, describe, expect, vi, it } from 'vitest';
|
|
||||||
import { createResultResolver, eventDispatcher } from '../../src/handlers/_internal';
|
|
||||||
import { faker } from '@faker-js/faker';
|
|
||||||
import { Module } from '../../src/core/types/modules';
|
|
||||||
import { Processed } from '../../src/handlers/types';
|
|
||||||
import { CommandType } from '../../src/core';
|
|
||||||
import { EventEmitter } from 'events';
|
|
||||||
|
|
||||||
function createRandomModule(): Processed<Module> {
|
|
||||||
return {
|
|
||||||
type: faker.number.int({
|
|
||||||
min: CommandType.Text,
|
|
||||||
max: CommandType.ChannelSelect,
|
|
||||||
}),
|
|
||||||
description: faker.string.alpha(),
|
|
||||||
name: faker.string.alpha(),
|
|
||||||
onEvent: [],
|
|
||||||
plugins: [],
|
|
||||||
execute: vi.fn(),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
describe('eventDispatcher standard', () => {
|
|
||||||
let m: Processed<Module>;
|
|
||||||
let ee: EventEmitter;
|
|
||||||
beforeEach(() => {
|
|
||||||
ee = new EventEmitter();
|
|
||||||
m = createRandomModule();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should throw', () => {
|
|
||||||
expect(() => eventDispatcher(m, 'not event emitter')).toThrowError();
|
|
||||||
});
|
|
||||||
it("Shouldn't throw", () => {
|
|
||||||
expect(() => eventDispatcher(m, ee)).not.toThrowError();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('Should be called once', () => {
|
|
||||||
const s = eventDispatcher(m, ee);
|
|
||||||
s.subscribe();
|
|
||||||
ee.emit(m.name, faker.string.alpha());
|
|
||||||
|
|
||||||
expect(m.execute).toHaveBeenCalledOnce();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,72 +0,0 @@
|
|||||||
import { describe, expect, it, vi } from 'vitest';
|
|
||||||
import * as Id from '../../src/core/id';
|
|
||||||
import { faker } from '@faker-js/faker';
|
|
||||||
import { CommandModule, CommandType, commandModule } from '../../src';
|
|
||||||
import { CommandTypeDiscordApi } from '../../src/core/id';
|
|
||||||
|
|
||||||
function createRandomCommandModules() {
|
|
||||||
const randomCommandType = [
|
|
||||||
CommandType.Text,
|
|
||||||
CommandType.Both,
|
|
||||||
CommandType.CtxMsg,
|
|
||||||
CommandType.CtxUser,
|
|
||||||
CommandType.Modal,
|
|
||||||
CommandType.ChannelSelect,
|
|
||||||
CommandType.RoleSelect,
|
|
||||||
CommandType.UserSelect,
|
|
||||||
CommandType.StringSelect,
|
|
||||||
CommandType.Button,
|
|
||||||
];
|
|
||||||
return commandModule({
|
|
||||||
type: faker.helpers.uniqueArray(randomCommandType, 1)[0],
|
|
||||||
description: faker.string.alpha(),
|
|
||||||
name: faker.string.alpha(),
|
|
||||||
execute: () => {},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
function createMetadata(c: CommandModule) {
|
|
||||||
return {
|
|
||||||
fullPath: faker.system.filePath(),
|
|
||||||
id: Id.create(c.name, c.type),
|
|
||||||
isClass: Boolean(Math.floor(Math.random())),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
const appBitField = 0b000000001111;
|
|
||||||
|
|
||||||
describe('id resolution', () => {
|
|
||||||
it('should resolve application commands correctly', () => {
|
|
||||||
const modules = faker.helpers.multiple(createRandomCommandModules, {
|
|
||||||
count: 20,
|
|
||||||
});
|
|
||||||
const metadata = modules.map(createMetadata);
|
|
||||||
metadata.forEach((meta, idx) => {
|
|
||||||
const associatedModule = modules[idx];
|
|
||||||
const am = (appBitField & associatedModule.type) !== 0 ? 'A' : 'C';
|
|
||||||
let uid = 0;
|
|
||||||
if (
|
|
||||||
associatedModule.type === CommandType.Both ||
|
|
||||||
associatedModule.type === CommandType.Modal
|
|
||||||
) {
|
|
||||||
uid = 1;
|
|
||||||
} else {
|
|
||||||
uid = CommandTypeDiscordApi[Math.log2(associatedModule.type)];
|
|
||||||
}
|
|
||||||
expect(meta.id).toBe(associatedModule.name + '_' + am + uid);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it('maps commands type to discord components or application commands', () => {
|
|
||||||
expect(CommandTypeDiscordApi[Math.log2(CommandType.Text)]).toBe(1);
|
|
||||||
|
|
||||||
expect(CommandTypeDiscordApi[1]).toBe(1);
|
|
||||||
expect(CommandTypeDiscordApi[Math.log2(CommandType.CtxUser)]).toBe(2);
|
|
||||||
expect(CommandTypeDiscordApi[Math.log2(CommandType.CtxMsg)]).toBe(3);
|
|
||||||
expect(CommandTypeDiscordApi[Math.log2(CommandType.Button)]).toBe(2);
|
|
||||||
expect(CommandTypeDiscordApi[Math.log2(CommandType.StringSelect)]).toBe(3);
|
|
||||||
expect(CommandTypeDiscordApi[Math.log2(CommandType.UserSelect)]).toBe(5);
|
|
||||||
expect(CommandTypeDiscordApi[Math.log2(CommandType.RoleSelect)]).toBe(6);
|
|
||||||
expect(CommandTypeDiscordApi[Math.log2(CommandType.MentionableSelect)]).toBe(7);
|
|
||||||
expect(CommandTypeDiscordApi[Math.log2(CommandType.ChannelSelect)]).toBe(8);
|
|
||||||
expect(CommandTypeDiscordApi[6]).toBe(1);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
19
tsconfig-base.json
Normal file
19
tsconfig-base.json
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"rootDir": "src",
|
||||||
|
"strict": true,
|
||||||
|
"esModuleInterop": true,
|
||||||
|
"noImplicitAny": true,
|
||||||
|
"experimentalDecorators": true,
|
||||||
|
"strictNullChecks": true,
|
||||||
|
"moduleResolution": "node",
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"declaration": true,
|
||||||
|
"preserveSymlinks": true,
|
||||||
|
"allowSyntheticDefaultImports": true,
|
||||||
|
"forceConsistentCasingInFileNames": true,
|
||||||
|
"isolatedModules": true
|
||||||
|
},
|
||||||
|
"exclude": ["node_modules", "dist"],
|
||||||
|
"include": ["./src", "./src/**/*.d.ts"]
|
||||||
|
}
|
||||||
8
tsconfig-cjs.json
Normal file
8
tsconfig-cjs.json
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"extends": "./tsconfig-base.json",
|
||||||
|
"compilerOptions": {
|
||||||
|
"module": "commonjs",
|
||||||
|
"outDir": "dist/cjs",
|
||||||
|
"target": "esnext"
|
||||||
|
}
|
||||||
|
}
|
||||||
8
tsconfig-esm.json
Normal file
8
tsconfig-esm.json
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"extends": "./tsconfig-base.json",
|
||||||
|
"compilerOptions": {
|
||||||
|
"module": "esnext",
|
||||||
|
"outDir": "dist/esm",
|
||||||
|
"target": "esnext"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,19 +1,3 @@
|
|||||||
{
|
{
|
||||||
"compilerOptions": {
|
"extends": "./tsconfig-esm.json"
|
||||||
"rootDir": "src",
|
|
||||||
"strict": true,
|
|
||||||
"esModuleInterop": true,
|
|
||||||
"strictNullChecks": true,
|
|
||||||
"moduleResolution": "node",
|
|
||||||
"skipLibCheck": true,
|
|
||||||
"declaration": true,
|
|
||||||
"preserveSymlinks": true,
|
|
||||||
"allowSyntheticDefaultImports": true,
|
|
||||||
"forceConsistentCasingInFileNames": true,
|
|
||||||
"isolatedModules": true,
|
|
||||||
"module": "esnext",
|
|
||||||
"target": "esnext"
|
|
||||||
},
|
|
||||||
"exclude": ["node_modules", "dist"],
|
|
||||||
"include": ["./src", "./src/**/*.d.ts"]
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,24 +1,61 @@
|
|||||||
import { defineConfig } from 'tsup';
|
import { defineConfig } from 'tsup';
|
||||||
|
import { writeFile } from 'fs/promises';
|
||||||
|
import ifdefPlugin from 'esbuild-ifdef';
|
||||||
const shared = {
|
const shared = {
|
||||||
entry: ['src/index.ts'],
|
entry: ['src/index.ts'],
|
||||||
external: ['discord.js', 'iti'],
|
external: ['discord.js', 'iti'],
|
||||||
platform: 'node',
|
platform: 'node',
|
||||||
clean: true,
|
clean: true,
|
||||||
sourcemap: true,
|
sourcemap: false,
|
||||||
treeshake: {
|
treeshake: {
|
||||||
moduleSideEffects: false,
|
moduleSideEffects: false,
|
||||||
correctVarValueBeforeDeclaration: true, //need this to treeshake esm discord.js empty import
|
correctVarValueBeforeDeclaration: true, //need this to treeshake esm discord.js empty import
|
||||||
annotations: true,
|
annotations: true,
|
||||||
},
|
},
|
||||||
|
dts: false,
|
||||||
};
|
};
|
||||||
export default defineConfig([
|
export default defineConfig([
|
||||||
{
|
{
|
||||||
format: ['esm', 'cjs'],
|
format: 'esm',
|
||||||
target: 'node18',
|
target: 'node18',
|
||||||
tsconfig: './tsconfig.json',
|
tsconfig: './tsconfig-esm.json',
|
||||||
outDir: './dist',
|
outDir: './dist/esm',
|
||||||
minify: false,
|
splitting: true,
|
||||||
dts: true,
|
esbuildPlugins: [ifdefPlugin({ variables: { MODE: 'esm' }, verbose: true })],
|
||||||
|
outExtension() {
|
||||||
|
return {
|
||||||
|
js: '.mjs',
|
||||||
|
};
|
||||||
|
},
|
||||||
|
async onSuccess() {
|
||||||
|
console.log('writing json esm');
|
||||||
|
await writeFile('./dist/esm/package.json', JSON.stringify({ type: 'module' }));
|
||||||
|
},
|
||||||
...shared,
|
...shared,
|
||||||
},
|
},
|
||||||
]);
|
{
|
||||||
|
format: 'cjs',
|
||||||
|
esbuildPlugins: [ifdefPlugin({ variables: { MODE: 'cjs' }, verbose: true })],
|
||||||
|
splitting: false,
|
||||||
|
target: 'node18',
|
||||||
|
tsconfig: './tsconfig-cjs.json',
|
||||||
|
outDir: './dist/cjs',
|
||||||
|
outExtension() {
|
||||||
|
return {
|
||||||
|
js: '.cjs',
|
||||||
|
};
|
||||||
|
},
|
||||||
|
async onSuccess() {
|
||||||
|
console.log('writing json commonjs');
|
||||||
|
await writeFile('./dist/cjs/package.json', JSON.stringify({ type: 'commonjs' }));
|
||||||
|
},
|
||||||
|
...shared,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
dts: {
|
||||||
|
only: true,
|
||||||
|
},
|
||||||
|
entry: ['src/index.ts'],
|
||||||
|
outDir: 'dist',
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|||||||
Reference in New Issue
Block a user