mirror of
https://github.com/sern-handler/handler
synced 2026-06-06 01:16:55 +00:00
Compare commits
60 Commits
v3.0.0-rc1
...
v3.2.1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
504cdee7b2 | ||
|
|
c7661f272c | ||
|
|
daac37c288 | ||
|
|
a579e272d0 | ||
|
|
2051aa1ac0 | ||
|
|
237c8537c6 | ||
|
|
77fb00d386 | ||
|
|
89f6bbb975 | ||
|
|
8ef4ee87e9 | ||
|
|
fd39858636 | ||
|
|
132b625070 | ||
|
|
03439fec43 | ||
|
|
fc87e99ed0 | ||
|
|
a08541a8e7 | ||
|
|
8bd5eb4949 | ||
|
|
e1059f93f7 | ||
|
|
800531453f | ||
|
|
c9f2d75665 | ||
|
|
e59e0b9d40 | ||
|
|
26ccd118ff | ||
|
|
4b97d86908 | ||
|
|
b1c82448bd | ||
|
|
d80081384a | ||
|
|
50253ca322 | ||
|
|
215aca2f46 | ||
|
|
a7f5ea269f | ||
|
|
52d6368440 | ||
|
|
1e723a4154 | ||
|
|
5fe13f43d2 | ||
|
|
ab9d39306a | ||
|
|
d429f3adbf | ||
|
|
5e011b471e | ||
|
|
41344608c6 | ||
|
|
7a72cc4fe3 | ||
|
|
70cca0dbb0 | ||
|
|
7798e36458 | ||
|
|
9144485c39 | ||
|
|
cf15b67ede | ||
|
|
57cc94ff81 | ||
|
|
6a2a5b4565 | ||
|
|
5fdc1eda7f | ||
|
|
e00d1df32e | ||
|
|
31c221bd5e | ||
|
|
0aba4a6606 | ||
|
|
e9c7661804 | ||
|
|
446417bfb9 | ||
|
|
6b58ef731b | ||
|
|
b62129bf04 | ||
|
|
3d121ff01c | ||
|
|
d201087d4f | ||
|
|
1af4a2bed4 | ||
|
|
edcaed083e | ||
|
|
a4fe2c50df | ||
|
|
9ea991626d | ||
|
|
64f20f1cf5 | ||
|
|
41cc72fe63 | ||
|
|
d983f95906 | ||
|
|
c1f690633c | ||
|
|
8544d301ef | ||
|
|
52bcba9cfc |
1
.github/FUNDING.yml
vendored
Normal file
1
.github/FUNDING.yml
vendored
Normal file
@@ -0,0 +1 @@
|
||||
open_collective: sern
|
||||
39
.github/workflows/codeql-analysis.yml
vendored
39
.github/workflows/codeql-analysis.yml
vendored
@@ -1,39 +0,0 @@
|
||||
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:
|
||||
- name: Check out Git repository
|
||||
uses: actions/checkout@8f4b7f84864484a7bf31766abe9204da3cbe65b3 # v3
|
||||
uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3
|
||||
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@64ed1c7eab4cce3362f8c340dee64e5eaeef8f7c # v3
|
||||
@@ -39,7 +39,7 @@ jobs:
|
||||
|
||||
- name: Create Pull Request
|
||||
id: cpr
|
||||
uses: peter-evans/create-pull-request@v4
|
||||
uses: peter-evans/create-pull-request@38e0b6e68b4c852a5500a94740f0e535e0d7ba54 # v4
|
||||
with:
|
||||
commit-message: "style: pretty please"
|
||||
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
|
||||
steps:
|
||||
- name: 'Checkout Repository'
|
||||
uses: actions/checkout@v3
|
||||
uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3
|
||||
- name: 'Dependency Review'
|
||||
uses: actions/dependency-review-action@v2
|
||||
uses: actions/dependency-review-action@0efb1d1d84fc9633afcdaad14c485cbbc90ef46c # v2
|
||||
|
||||
10
.github/workflows/npm-publish.yml
vendored
10
.github/workflows/npm-publish.yml
vendored
@@ -2,17 +2,21 @@ name: NPM / Publish
|
||||
|
||||
on:
|
||||
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:
|
||||
test-and-publish:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/setup-node@v3
|
||||
- uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3
|
||||
- uses: actions/setup-node@5e21ff4d9bc1a8cf6de233a3057d20ec6b3fb69d # v3
|
||||
with:
|
||||
node-version: 17
|
||||
- run: yarn --immutable
|
||||
- run: yarn build:prod
|
||||
- uses: JS-DevTools/npm-publish@v1
|
||||
- uses: JS-DevTools/npm-publish@0f451a94170d1699fd50710966d48fb26194d939 # v1
|
||||
with:
|
||||
token: ${{ secrets.NPM_TOKEN }}
|
||||
access: "public"
|
||||
|
||||
2
.github/workflows/release-please.yml
vendored
2
.github/workflows/release-please.yml
vendored
@@ -6,7 +6,7 @@ jobs:
|
||||
release-please:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: google-github-actions/release-please-action@v3
|
||||
- uses: google-github-actions/release-please-action@db8f2c60ee802b3748b512940dde88eabd7b7e01 # v3
|
||||
with:
|
||||
release-type: node
|
||||
package-name: release-please-action
|
||||
|
||||
29
.github/workflows/test.yml
vendored
Normal file
29
.github/workflows/test.yml
vendored
Normal file
@@ -0,0 +1,29 @@
|
||||
# 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,3 +91,9 @@ dist
|
||||
# Yarn files
|
||||
.yarn/install-state.gz
|
||||
.yarn/build-state.yml
|
||||
|
||||
.yalc
|
||||
|
||||
yalc.lock
|
||||
|
||||
*.svg
|
||||
|
||||
@@ -8,6 +8,7 @@ logs
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
.yarn
|
||||
# Runtime data
|
||||
pids
|
||||
*.pid
|
||||
@@ -80,9 +81,7 @@ typings/
|
||||
# FuseBox cache
|
||||
.fusebox/
|
||||
|
||||
# TypeScript build output
|
||||
dist
|
||||
|
||||
test
|
||||
# VisualStudio Config file
|
||||
.vs
|
||||
|
||||
|
||||
532
.yarn/releases/yarn-3.5.0.cjs → .yarn/releases/yarn-3.5.1.cjs
vendored
Normal file → Executable file
532
.yarn/releases/yarn-3.5.0.cjs → .yarn/releases/yarn-3.5.1.cjs
vendored
Normal file → Executable file
File diff suppressed because one or more lines are too long
@@ -2,4 +2,4 @@ enableGlobalCache: true
|
||||
|
||||
nodeLinker: node-modules
|
||||
|
||||
yarnPath: .yarn/releases/yarn-3.5.0.cjs
|
||||
yarnPath: .yarn/releases/yarn-3.5.1.cjs
|
||||
|
||||
74
CHANGELOG.md
74
CHANGELOG.md
@@ -1,5 +1,79 @@
|
||||
# Changelog
|
||||
|
||||
## [3.2.1](https://github.com/sern-handler/handler/compare/v3.2.0...v3.2.1) (2023-12-21)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* logger swap failing ([daac37c](https://github.com/sern-handler/handler/commit/daac37c28858c42b21042bdcb8141239db634e7d))
|
||||
|
||||
## [3.2.0](https://github.com/sern-handler/handler/compare/v3.1.1...v3.2.0) (2023-12-15)
|
||||
|
||||
|
||||
### Miscellaneous Chores
|
||||
|
||||
* release 3.2.0 ([237c853](https://github.com/sern-handler/handler/commit/237c8537c66052309d7e13a7e6e0a4f7995c2558))
|
||||
|
||||
## [3.1.1](https://github.com/sern-handler/handler/compare/v3.1.0...v3.1.1) (2023-11-06)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* queuing events ([fd39858](https://github.com/sern-handler/handler/commit/fd39858636d3038abb6d91021b65c99c488a3d6e))
|
||||
* queuing events ([#332](https://github.com/sern-handler/handler/issues/332)) @Benzo-Fury ([#333](https://github.com/sern-handler/handler/issues/333)) ([fd39858](https://github.com/sern-handler/handler/commit/fd39858636d3038abb6d91021b65c99c488a3d6e))
|
||||
|
||||
## [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)
|
||||
|
||||
|
||||
|
||||
38
README.md
38
README.md
@@ -15,19 +15,15 @@
|
||||
</div>
|
||||
|
||||
## Why?
|
||||
- Most handlers don't support discord.js 14.7+
|
||||
- Customizable, composable commands
|
||||
- Plug and play or customize to your liking
|
||||
- Embraces reactive programming for consistent and reliable backend
|
||||
- Customizable logger, error handling, and more
|
||||
- Active development and growing [community](https://sern.dev/discord)
|
||||
## 👀 Quick Look
|
||||
|
||||
* 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
|
||||
- For you. A framework that's tailored to your exact needs.
|
||||
- Lightweight. Does a lot while being small.
|
||||
- Latest features. Support for discord.js v14 and all of its interactions.
|
||||
- Start quickly. Plug and play or customize to your liking.
|
||||
- Switch and customize how errors are handled, logging, and more.
|
||||
- works with [bun](https://bun.sh/) and [node](https://nodejs.org/en) out the box!
|
||||
- Use it with TypeScript or JavaScript. CommonJS and ESM supported.
|
||||
- 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.
|
||||
|
||||
## 📜 Installation
|
||||
|
||||
@@ -80,16 +76,14 @@ export default commandModule({
|
||||
</details>
|
||||
<details open><summary>index.ts</summary>
|
||||
|
||||
```ts
|
||||
|
||||
```ts
|
||||
import { Client, GatewayIntentBits } from 'discord.js';
|
||||
import { Sern, single, type Dependencies } from '@sern/handler';
|
||||
import { Sern, single } from '@sern/handler';
|
||||
|
||||
//client has been declared previously
|
||||
|
||||
interface MyDependencies extends Dependencies {
|
||||
'@sern/client': Singleton<Client>;
|
||||
}
|
||||
export const useContainer = Sern.makeDependencies<MyDependencies>({
|
||||
//Version 3
|
||||
await makeDependencies({
|
||||
build: root => root
|
||||
.add({ '@sern/client': single(() => client) })
|
||||
});
|
||||
@@ -99,9 +93,6 @@ Sern.init({
|
||||
defaultPrefix: '!', // removing defaultPrefix will shut down text commands
|
||||
commands: 'src/commands',
|
||||
// events: 'src/events' (optional),
|
||||
containerConfig : {
|
||||
get: useContainer
|
||||
}
|
||||
});
|
||||
|
||||
client.login("YOUR_BOT_TOKEN_HERE");
|
||||
@@ -115,6 +106,7 @@ client.login("YOUR_BOT_TOKEN_HERE");
|
||||
- [ava](https://github.com/SrIzan10/ava), A discord bot that plays KNGI and Gensokyo Radio.
|
||||
- [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.
|
||||
- [SmokinWeed 💨](https://github.com/Peter-MJ-Parker/sern-bud), A fun bot for a small - but growing - server.
|
||||
|
||||
## 💻 CLI
|
||||
|
||||
|
||||
32
package.json
32
package.json
@@ -1,29 +1,29 @@
|
||||
{
|
||||
"name": "@sern/handler",
|
||||
"packageManager": "yarn@3.5.0",
|
||||
"version": "3.0.0-rc1",
|
||||
"version": "3.2.1",
|
||||
"description": "A complete, customizable, typesafe, & reactive framework for discord bots.",
|
||||
"main": "./dist/esm/index.mjs",
|
||||
"module": "./dist/cjs/index.cjs",
|
||||
"types": "dist/index.d.ts",
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.mjs",
|
||||
"types": "./dist/index.d.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"import": "./dist/esm/index.mjs",
|
||||
"require": "./dist/cjs/index.cjs",
|
||||
"import": "./dist/index.mjs",
|
||||
"require": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"watch": "tsup --watch",
|
||||
"clean-modules": "rimraf node_modules/ && npm install",
|
||||
"lint": "eslint src/**/*.ts",
|
||||
"format": "eslint src/**/*.ts --fix",
|
||||
"build:dev": "tsup --metafile",
|
||||
"build:prod": "tsup --minify",
|
||||
"publish": "npm run build:prod",
|
||||
"build:prod": "tsup ",
|
||||
"prepare": "npm run build:prod",
|
||||
"pretty": "prettier --write .",
|
||||
"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": [
|
||||
"sern-handler",
|
||||
@@ -39,17 +39,17 @@
|
||||
"dependencies": {
|
||||
"iti": "^0.6.0",
|
||||
"rxjs": "^7.8.0",
|
||||
"ts-results-es": "^3.6.0"
|
||||
"ts-results-es": "^4.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@faker-js/faker": "^8.0.1",
|
||||
"@types/node": "^18.15.11",
|
||||
"@typescript-eslint/eslint-plugin": "5.58.0",
|
||||
"@typescript-eslint/parser": "5.58.0",
|
||||
"discord.js": "14.11.0",
|
||||
"esbuild-ifdef": "^0.2.0",
|
||||
"eslint": "8.38.0",
|
||||
"prettier": "2.8.7",
|
||||
"@typescript-eslint/parser": "5.59.1",
|
||||
"discord.js": "^14.11.0",
|
||||
"esbuild": "^0.17.0",
|
||||
"eslint": "8.39.0",
|
||||
"prettier": "2.8.8",
|
||||
"tsup": "^6.7.0",
|
||||
"typescript": "5.0.2",
|
||||
"vitest": "latest"
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
{
|
||||
"extends": [
|
||||
"config:base",
|
||||
"helpers:pinGitHubActionDigests",
|
||||
"group:allNonMajor"
|
||||
],
|
||||
"major": {
|
||||
"dependencyDashboardApproval": true,
|
||||
"reviewers": ["EvolutionX-10", "jacoobes", "Murtatrxx"]
|
||||
|
||||
10
src/core/_internal.ts
Normal file
10
src/core/_internal.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
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'
|
||||
9
src/core/contracts/disposable.ts
Normal file
9
src/core/contracts/disposable.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import type { Awaitable } from '../../types/utility';
|
||||
|
||||
/**
|
||||
* Represents a Disposable contract.
|
||||
* Let dependencies implement this to dispose and cleanup.
|
||||
*/
|
||||
export interface Disposable {
|
||||
dispose(): Awaitable<unknown>;
|
||||
}
|
||||
7
src/core/contracts/emitter.ts
Normal file
7
src/core/contracts/emitter.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
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,21 +1,18 @@
|
||||
import type { CommandModule,Processed, EventModule } from "../../types/core-modules";
|
||||
|
||||
/**
|
||||
* @since 2.0.0
|
||||
*/
|
||||
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
|
||||
*/
|
||||
crash(err :Error) : never
|
||||
crash(err: Error): never;
|
||||
/**
|
||||
* A function that is called on every crash. Updates keepAlive.
|
||||
* If keepAlive is 0, the process crashes.
|
||||
* A function that is called on every throw.
|
||||
* @param error
|
||||
*/
|
||||
updateAlive(error: Error): void;
|
||||
|
||||
}
|
||||
|
||||
@@ -3,3 +3,5 @@ export * from './logging';
|
||||
export * from './module-manager';
|
||||
export * from './module-store';
|
||||
export * from './init';
|
||||
export * from './emitter';
|
||||
export * from './disposable'
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Awaitable } from '../../shared';
|
||||
import type { Awaitable } from '../../types/utility';
|
||||
|
||||
/**
|
||||
* Represents an initialization contract.
|
||||
|
||||
@@ -1,14 +1,27 @@
|
||||
import type {
|
||||
CommandMeta,
|
||||
CommandModule,
|
||||
CommandModuleDefs,
|
||||
Module,
|
||||
} from '../../types/core-modules';
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* @since 2.0.0
|
||||
* @internal - direct access to the module manager will be removed in version 4
|
||||
*/
|
||||
export interface ModuleManager {
|
||||
export interface ModuleManager extends MetadataAccess {
|
||||
get(id: string): string | undefined;
|
||||
getMetadata(m: Module): CommandMeta|undefined;
|
||||
setMetadata(m: Module, c: CommandMeta): void;
|
||||
|
||||
set(id: string, path: string): void;
|
||||
getPublishableCommands(): Promise<CommandModule[]>;
|
||||
getByNameCommandType<T extends CommandType>(name: string, commandType: T): Promise<CommandModuleDefs[T]>|undefined;
|
||||
getByNameCommandType<T extends CommandType>(
|
||||
name: string,
|
||||
commandType: T,
|
||||
): Promise<CommandModuleDefs[T]> | undefined;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { CommandMeta, Module } from '../types/modules';
|
||||
import type { CommandMeta, Module } from '../../types/core-modules';
|
||||
|
||||
/**
|
||||
* Represents a core module store that stores IDs mapped to file paths.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { CommandType, EventType, PluginType } from './structures';
|
||||
import type { Plugin, PluginResult, EventArgs, CommandArgs } from './types/plugins';
|
||||
import type { Plugin, PluginResult, EventArgs, CommandArgs } from '../types/core-plugin';
|
||||
import type { ClientEvents } from 'discord.js';
|
||||
|
||||
export function makePlugin<V extends unknown[]>(
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { Err, Ok } from 'ts-results-es';
|
||||
import { ApplicationCommandOptionType, AutocompleteInteraction } from 'discord.js';
|
||||
import type { SernAutocompleteData, SernOptionsData } from './types/modules';
|
||||
import { AnyCommandPlugin, AnyEventPlugin, Plugin } from './types/plugins';
|
||||
import type { SernAutocompleteData, SernOptionsData } from '../types/core-modules';
|
||||
import type { AnyCommandPlugin, AnyEventPlugin, Plugin } from '../types/core-plugin';
|
||||
import { PluginType } from './structures';
|
||||
import assert from 'assert';
|
||||
|
||||
//function wrappers for empty ok / err
|
||||
export const ok = /* @__PURE__*/ () => Ok.EMPTY;
|
||||
@@ -13,6 +14,7 @@ export function partitionPlugins(
|
||||
): [Plugin[], Plugin[]] {
|
||||
const controlPlugins = [];
|
||||
const initPlugins = [];
|
||||
|
||||
for (const el of arr) {
|
||||
switch (el.type) {
|
||||
case PluginType.Control:
|
||||
@@ -34,33 +36,48 @@ export function partitionPlugins(
|
||||
export function treeSearch(
|
||||
iAutocomplete: AutocompleteInteraction,
|
||||
options: SernOptionsData[] | undefined,
|
||||
): SernAutocompleteData | undefined {
|
||||
): SernAutocompleteData & { parent?: string } | undefined {
|
||||
if (options === undefined) return undefined;
|
||||
const _options = options.slice(); // required to prevent direct mutation of options
|
||||
let autocompleteData: SernAutocompleteData | undefined;
|
||||
|
||||
//clone to prevent mutation of original command module
|
||||
const _options = options.map(a => ({ ...a }));
|
||||
let subcommands = new Set();
|
||||
while (_options.length > 0) {
|
||||
const cur = _options.pop()!;
|
||||
switch (cur.type) {
|
||||
case ApplicationCommandOptionType.Subcommand:
|
||||
{
|
||||
subcommands.add(cur.name);
|
||||
for (const option of cur.options ?? []) _options.push(option);
|
||||
}
|
||||
break;
|
||||
case ApplicationCommandOptionType.SubcommandGroup:
|
||||
{
|
||||
for (const option of cur.options ?? []) {
|
||||
_options.push(option);
|
||||
}
|
||||
for (const command of cur.options ?? []) _options.push(command);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
{
|
||||
if (cur.autocomplete) {
|
||||
if ('autocomplete' in cur && cur.autocomplete) {
|
||||
const choice = iAutocomplete.options.getFocused(true);
|
||||
if (cur.name === choice.name && cur.autocomplete) {
|
||||
autocompleteData = cur;
|
||||
assert(
|
||||
'command' in 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;
|
||||
}
|
||||
}
|
||||
return autocompleteData;
|
||||
}
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { Interaction, InteractionType } from 'discord.js';
|
||||
import { CommandType, EventType } from '../core';
|
||||
import { ApplicationCommandType, ComponentType, Interaction, InteractionType } from 'discord.js';
|
||||
import { CommandType, EventType } from './structures';
|
||||
|
||||
/**
|
||||
* Construct unique ID for a given interaction object.
|
||||
* @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.
|
||||
*/
|
||||
export function reconstructId<T extends Interaction>(event: T) {
|
||||
export function reconstruct<T extends Interaction>(event: T) {
|
||||
switch (event.type) {
|
||||
case InteractionType.MessageComponent: {
|
||||
return `${event.customId}_C${event.componentType}`;
|
||||
@@ -21,8 +21,27 @@ export function reconstructId<T extends Interaction>(event: T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
*
|
||||
* A magic number to represent any commandtype that is an ApplicationCommand.
|
||||
*/
|
||||
const appBitField = 0b000000001111;
|
||||
|
||||
const appBitField = 0b000000011111;
|
||||
// Each index represents the exponent of a CommandType.
|
||||
// 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.
|
||||
* This corresponds to an ApplicationCommandType or ComponentType
|
||||
@@ -30,21 +49,15 @@ const appBitField = 0b000000011111;
|
||||
*/
|
||||
function apiType(t: CommandType | EventType) {
|
||||
if (t === CommandType.Both || t === CommandType.Modal) return 1;
|
||||
const log = Math.log2(t);
|
||||
return (appBitField & t) !== 0 ? log : log - 2;
|
||||
return CommandTypeDiscordApi[Math.log2(t)];
|
||||
}
|
||||
|
||||
/*
|
||||
* Generates an id based on CommandType.
|
||||
* Generates an id based on name and CommandType.
|
||||
* A is for any ApplicationCommand. C is for any ComponentCommand
|
||||
* Then, another number generated by apiType function is appended
|
||||
*/
|
||||
function uniqueSuffix(t: CommandType | EventType) {
|
||||
const am = (appBitField & t) !== 0 ? 'A' : 'C';
|
||||
return am + apiType(t);
|
||||
}
|
||||
|
||||
|
||||
export function createId(name: string, type: CommandType | EventType) {
|
||||
return name+"_"+uniqueSuffix(type)
|
||||
export function create(name: string, type: CommandType | EventType) {
|
||||
const am = (appBitField & type) !== 0 ? 'A' : 'C';
|
||||
return name + '_' + am + apiType(type);
|
||||
}
|
||||
@@ -2,27 +2,3 @@ export * from './contracts';
|
||||
export * from './create-plugins';
|
||||
export * from './structures';
|
||||
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,14 +1,18 @@
|
||||
import * as assert from 'assert';
|
||||
import { composeRoot, useContainer } from './dependency-injection';
|
||||
import { DependencyConfiguration } from './types';
|
||||
import { CoreContainer } from '../structures/container';
|
||||
|
||||
import type { DependencyConfiguration } from '../../types/ioc';
|
||||
import { CoreContainer } from './container';
|
||||
import { Result } from 'ts-results-es'
|
||||
import { DefaultServices } from '../_internal';
|
||||
import { AnyFunction } from '../../types/utility';
|
||||
//SIDE EFFECT: GLOBAL DI
|
||||
let containerSubject: CoreContainer<Partial<Dependencies>>;
|
||||
|
||||
/**
|
||||
* @deprecated
|
||||
* Returns the underlying data structure holding all dependencies.
|
||||
* Exposes methods from iti
|
||||
* Use the Service API. The container should be readonly
|
||||
*/
|
||||
export function useContainerRaw() {
|
||||
assert.ok(
|
||||
@@ -18,17 +22,83 @@ export function useContainerRaw() {
|
||||
return containerSubject;
|
||||
}
|
||||
|
||||
/**
|
||||
* @since 2.0.0
|
||||
* @param conf a configuration for creating your project dependencies
|
||||
*/
|
||||
export async function makeDependencies<const T extends Dependencies>(
|
||||
conf: DependencyConfiguration,
|
||||
) {
|
||||
const dependencyBuilder = (container: any, excluded: string[]) => {
|
||||
type Insertable =
|
||||
| ((container: CoreContainer<Dependencies>) => unknown )
|
||||
| Record<PropertyKey, unknown>
|
||||
return {
|
||||
/**
|
||||
* Insert a dependency into your container.
|
||||
* Supply the correct key and dependency
|
||||
*/
|
||||
add(key: keyof Dependencies, v: Insertable) {
|
||||
Result
|
||||
.wrap(() => container.add({ [key]: v}))
|
||||
.expect("Failed to add " + key);
|
||||
},
|
||||
/**
|
||||
* Exclude any dependencies from being added.
|
||||
* Warning: this could lead to bad errors if not used correctly
|
||||
*/
|
||||
exclude(...keys: (keyof Dependencies)[]) {
|
||||
keys.forEach(key => excluded.push(key));
|
||||
},
|
||||
/**
|
||||
* @param key the key of the dependency
|
||||
* @param v The dependency to swap out.
|
||||
* Swap out a preexisting dependency.
|
||||
*/
|
||||
swap(key: keyof Dependencies, v: Insertable) {
|
||||
Result
|
||||
.wrap(() => container.upsert({ [key]: v }))
|
||||
.expect("Failed to update " + key);
|
||||
},
|
||||
/**
|
||||
* @param key the key of the dependency
|
||||
* @param cleanup Provide cleanup for the dependency at key. First parameter is the dependency itself
|
||||
* @example
|
||||
* ```ts
|
||||
* addDisposer('dbConnection', (dbConnection) => dbConnection.end())
|
||||
* ```
|
||||
* Swap out a preexisting dependency.
|
||||
*/
|
||||
addDisposer(key: keyof Dependencies, cleanup: AnyFunction) {
|
||||
Result
|
||||
.wrap(() => container.addDisposer({ [key] : cleanup }))
|
||||
.expect("Failed to addDisposer for" + key);
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
type CallbackBuilder = (c: ReturnType<typeof dependencyBuilder>) => any
|
||||
|
||||
type ValidDependencyConfig =
|
||||
| CallbackBuilder
|
||||
| DependencyConfiguration;
|
||||
|
||||
export const insertLogger = (containerSubject: CoreContainer<any>) => {
|
||||
containerSubject
|
||||
.upsert({'@sern/logger': () => new DefaultServices.DefaultLogging});
|
||||
}
|
||||
export async function makeDependencies<const T extends Dependencies>
|
||||
(conf: ValidDependencyConfig) {
|
||||
//Until there are more optional dependencies, just check if the logger exists
|
||||
//SIDE EFFECT
|
||||
containerSubject = new CoreContainer();
|
||||
await composeRoot(containerSubject, conf);
|
||||
if(typeof conf === 'function') {
|
||||
const excluded: string[] = [];
|
||||
conf(dependencyBuilder(containerSubject, excluded));
|
||||
if(!excluded.includes('@sern/logger')
|
||||
&& !containerSubject.getTokens()['@sern/logger']) {
|
||||
insertLogger(containerSubject);
|
||||
}
|
||||
containerSubject.ready();
|
||||
} else {
|
||||
composeRoot(containerSubject, conf);
|
||||
}
|
||||
|
||||
return useContainer<T>();
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
54
src/core/ioc/container.ts
Normal file
54
src/core/ioc/container.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,6 @@
|
||||
import type {
|
||||
CoreDependencies,
|
||||
DependencyConfiguration,
|
||||
IntoDependencies,
|
||||
} from './types';
|
||||
import { DefaultLogging } from '../structures';
|
||||
import { SernError } from '../structures/errors';
|
||||
import { useContainerRaw } from './base';
|
||||
import { CoreContainer } from '../structures/container';
|
||||
import type { CoreDependencies, DependencyConfiguration, IntoDependencies } from '../../types/ioc';
|
||||
import { insertLogger, useContainerRaw } from './base';
|
||||
import { CoreContainer } from './container';
|
||||
|
||||
/**
|
||||
* @__PURE__
|
||||
@@ -27,11 +21,26 @@ export function single<T>(cb: () => T) {
|
||||
export function transient<T>(cb: () => () => T) {
|
||||
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) {
|
||||
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]) {
|
||||
const container = useContainerRaw();
|
||||
return keys.map(k => container.get(k)!) as IntoDependencies<T>;
|
||||
@@ -43,25 +52,18 @@ export function Services<const T extends (keyof Dependencies)[]>(...keys: [...T]
|
||||
* Finally, update the containerSubject with the new container state
|
||||
* @param conf
|
||||
*/
|
||||
export async function composeRoot(
|
||||
export function composeRoot(
|
||||
container: CoreContainer<Partial<Dependencies>>,
|
||||
conf: DependencyConfiguration,
|
||||
) {
|
||||
//container should have no client or logger yet.
|
||||
const hasLogger = conf.exclude?.has('@sern/logger');
|
||||
if (!hasLogger) {
|
||||
container.upsert({
|
||||
'@sern/logger': () => new DefaultLogging(),
|
||||
});
|
||||
insertLogger(container);
|
||||
}
|
||||
//Build the container based on the callback provided by the user
|
||||
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) {
|
||||
container.get('@sern/logger')?.info({ message: 'All dependencies loaded successfully.' });
|
||||
}
|
||||
@@ -70,11 +72,6 @@ export async function composeRoot(
|
||||
}
|
||||
|
||||
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]) =>
|
||||
keys.map(key => useContainerRaw().get(key as keyof Dependencies)) as IntoDependencies<V>;
|
||||
}
|
||||
|
||||
40
src/core/ioc/hooks.ts
Normal file
40
src/core/ioc/hooks.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
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,3 +1,2 @@
|
||||
export { useContainerRaw, makeDependencies } from './base';
|
||||
export { makeDependencies } from './base';
|
||||
export { Service, Services, single, transient } from './dependency-injection';
|
||||
export type { Singleton, Transient, CoreDependencies } from './types';
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
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,38 +1,48 @@
|
||||
import { SernError } from './structures/errors';
|
||||
import { Result, Err, Ok } from 'ts-results-es';
|
||||
import { Module } from './types/modules';
|
||||
import { Result } from 'ts-results-es';
|
||||
import { type Observable, from, mergeMap, ObservableInput } from 'rxjs';
|
||||
import { readdir, stat } from 'fs/promises';
|
||||
import { basename, extname, join, resolve } from 'path';
|
||||
import { ImportPayload } from '../handler/types';
|
||||
|
||||
export type ModuleResult<T> = Promise<Result<ImportPayload<T>, SernError>>;
|
||||
import { basename, extname, join, resolve, parse } from 'path';
|
||||
import assert from 'assert';
|
||||
import { createRequire } from 'node:module';
|
||||
import type { ImportPayload, Wrapper } from '../types/core';
|
||||
import type { Module } 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) {
|
||||
// prettier-ignore
|
||||
let module =
|
||||
/// #if MODE === 'esm'
|
||||
import(absPath).then(i => i.default); // eslint-disable-line
|
||||
/// #elif MODE === 'cjs'
|
||||
require(absPath).default; // eslint-disable-line
|
||||
/// #endif
|
||||
return module.then(m =>
|
||||
Result
|
||||
.wrap(() => m.getInstance())
|
||||
.unwrapOr(m)
|
||||
) as T;
|
||||
}
|
||||
export async function defaultModuleLoader<T extends Module>(absPath: string): ModuleResult<T> {
|
||||
let module = await importModule<T>(absPath);
|
||||
if (module === undefined) {
|
||||
return Err(SernError.UndefinedModule);
|
||||
let fileModule = await import(absPath);
|
||||
|
||||
let commandModule = fileModule.default;
|
||||
|
||||
assert(commandModule , `Found no export @ ${absPath}. Forgot to ignore with "!"? (!${basename(absPath)})?`);
|
||||
if ('default' in commandModule ) {
|
||||
commandModule = commandModule.default;
|
||||
}
|
||||
//todo readd class modules
|
||||
return Ok({ module, absPath });
|
||||
return Result
|
||||
.wrap(() => ({ module: commandModule.getInstance() }))
|
||||
.unwrapOr({ module: commandModule }) as T;
|
||||
}
|
||||
|
||||
export const fmtFileName = (n: string) => n.substring(0, n.length - 3);
|
||||
export async function defaultModuleLoader<T extends Module>(absPath: string): ModuleResult<T> {
|
||||
let { module } = await importModule<{ module: T }>(absPath);
|
||||
assert(module, `Found an undefined module: ${absPath}`);
|
||||
return { module, absPath };
|
||||
}
|
||||
|
||||
export const fmtFileName = (fileName: string) => parse(fileName).name;
|
||||
|
||||
/**
|
||||
* a directory string is converted into a stream of modules.
|
||||
@@ -42,58 +52,41 @@ export const fmtFileName = (n: string) => n.substring(0, n.length - 3);
|
||||
*/
|
||||
export function buildModuleStream<T extends Module>(
|
||||
input: ObservableInput<string>,
|
||||
): Observable<Result<ImportPayload<T>, SernError>> {
|
||||
return from(input).pipe(mergeMap(defaultModuleLoader<T>));
|
||||
): Observable<ImportPayload<T>> {
|
||||
return from(input)
|
||||
.pipe(mergeMap(defaultModuleLoader<T>));
|
||||
}
|
||||
|
||||
export function getFullPathTree(dir: string, mode: boolean) {
|
||||
return readPaths(resolve(dir), mode);
|
||||
}
|
||||
export const getFullPathTree = (dir: string) => readPaths(resolve(dir));
|
||||
|
||||
export function filename(path: string) {
|
||||
return fmtFileName(basename(path));
|
||||
}
|
||||
export const filename = (path: string) => fmtFileName(basename(path));
|
||||
|
||||
function createSkipCondition(base: string) {
|
||||
const validExtensions = ['.js', '.cjs', '.mts', '.mjs', 'cts'];
|
||||
return ( type: 'file' | 'directory') => {
|
||||
if(type === 'file') {
|
||||
return fmtFileName(base)[0] === '!'
|
||||
|| !validExtensions.includes(extname(base));
|
||||
}
|
||||
return base[0] === '!';
|
||||
}
|
||||
}
|
||||
const isSkippable = (filename: string) => {
|
||||
//empty string is for non extension files (directories)
|
||||
const validExtensions = ['.js', '.cjs', '.mts', '.mjs', '.cts', '.ts', ''];
|
||||
return filename[0] === '!' || !validExtensions.includes(extname(filename));
|
||||
};
|
||||
async function deriveFileInfo(dir: string, file: string) {
|
||||
const fullPath = join(dir, file);
|
||||
return {
|
||||
fullPath,
|
||||
fileStats: await stat(fullPath),
|
||||
base: basename(file)
|
||||
}
|
||||
const fullPath = join(dir, file);
|
||||
return {
|
||||
fullPath,
|
||||
fileStats: await stat(fullPath),
|
||||
base: basename(file),
|
||||
};
|
||||
}
|
||||
async function* readPaths(dir: string, shouldDebug: boolean): AsyncGenerator<string> {
|
||||
async function* readPaths(dir: string): AsyncGenerator<string> {
|
||||
try {
|
||||
const files = await readdir(dir);
|
||||
for (const file of files) {
|
||||
const { fullPath, fileStats, base } = await deriveFileInfo(dir, file);
|
||||
const isSkippable = createSkipCondition(base);
|
||||
if (fileStats.isDirectory()) {
|
||||
//Todo: refactor so that i dont repeat myself for files (line 71)
|
||||
if (isSkippable('directory')) {
|
||||
if (shouldDebug) console.info(`ignored directory: ${fullPath}`);
|
||||
} else {
|
||||
yield* readPaths(fullPath, shouldDebug);
|
||||
if (!isSkippable(base)) {
|
||||
yield* readPaths(fullPath);
|
||||
}
|
||||
} else {
|
||||
if (isSkippable('file')) {
|
||||
if (shouldDebug) console.info(`ignored: ${fullPath}`);
|
||||
} else {
|
||||
/// #if MODE === 'esm'
|
||||
if (!isSkippable(base)) {
|
||||
yield 'file:///' + fullPath;
|
||||
/// #elif MODE === 'cjs'
|
||||
yield fullPath;
|
||||
/// #endif
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -101,3 +94,34 @@ async function* readPaths(dir: string, shouldDebug: boolean): AsyncGenerator<str
|
||||
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,
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
@@ -1,22 +1,22 @@
|
||||
import { ClientEvents } from 'discord.js';
|
||||
import { CommandType, EventType, PluginType } from '../core/structures';
|
||||
import {
|
||||
import type {
|
||||
AnyCommandPlugin,
|
||||
AnyEventPlugin,
|
||||
CommandArgs,
|
||||
ControlPlugin,
|
||||
EventArgs,
|
||||
InitPlugin,
|
||||
} from '../core/types/plugins';
|
||||
import {
|
||||
} from '../types/core-plugin';
|
||||
import type {
|
||||
CommandModule,
|
||||
EventModule,
|
||||
InputCommand,
|
||||
InputEvent,
|
||||
Module,
|
||||
} from '../core/types/modules';
|
||||
import { partitionPlugins } from '../core/functions';
|
||||
import { Awaitable } from '../shared';
|
||||
} from '../types/core-modules';
|
||||
import { partitionPlugins } from './_internal';
|
||||
import type { Awaitable } from '../types/utility';
|
||||
|
||||
/**
|
||||
* @since 1.0.0 The wrapper function to define command modules for sern
|
||||
@@ -15,14 +15,11 @@ import {
|
||||
OperatorFunction,
|
||||
pipe,
|
||||
share,
|
||||
switchMap,
|
||||
} from 'rxjs';
|
||||
import { Result } from 'ts-results-es';
|
||||
import { EventEmitter } from 'node:events';
|
||||
import { ErrorHandling, Logging } from './contracts';
|
||||
import { Emitter, ErrorHandling, Logging } from './contracts';
|
||||
import util from 'node:util';
|
||||
import { Awaitable } from '../shared';
|
||||
import { PluginResult, VoidResult } from './types/plugins';
|
||||
import type { PluginResult, VoidResult } from '../types/core-plugin';
|
||||
import type { Result } from 'ts-results-es'
|
||||
/**
|
||||
* if {src} is true, mapTo V, else ignore
|
||||
* @param item
|
||||
@@ -31,20 +28,6 @@ export function filterMapTo<V>(item: () => V): OperatorFunction<boolean, V> {
|
||||
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}.
|
||||
* @param args if an array, its spread and plugin called.
|
||||
@@ -65,32 +48,15 @@ export function callPlugin(args: unknown): OperatorFunction<
|
||||
|
||||
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.
|
||||
*/
|
||||
export const everyPluginOk: OperatorFunction<VoidResult, boolean> = pipe(
|
||||
every(result => result.ok),
|
||||
every(result => result.isOk()),
|
||||
defaultIfEmpty(true),
|
||||
);
|
||||
|
||||
export const sharedObservable = <T>(e: EventEmitter, eventName: string) => {
|
||||
export const sharedEventStream = <T>(e: Emitter, eventName: string) => {
|
||||
return (fromEvent(e, eventName) as Observable<T>).pipe(share());
|
||||
};
|
||||
|
||||
@@ -104,3 +70,17 @@ export function handleError<C>(crashHandler: ErrorHandling, logging?: Logging) {
|
||||
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 {
|
||||
import type {
|
||||
AnySelectMenuInteraction,
|
||||
AutocompleteInteraction,
|
||||
ButtonInteraction,
|
||||
|
||||
41
src/core/structures/command-error.ts
Normal file
41
src/core/structures/command-error.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
import type { ReplyOptions } from "../../types/utility";
|
||||
import type { Logging } from "../contracts";
|
||||
|
||||
export interface Response {
|
||||
type: 'fail' | 'continue';
|
||||
body?: ReplyOptions;
|
||||
log?: { type: keyof Logging; message: unknown }
|
||||
}
|
||||
|
||||
export const of = () => {
|
||||
const payload = {
|
||||
type: 'fail',
|
||||
body: undefined,
|
||||
log : undefined
|
||||
} as Record<PropertyKey, unknown>
|
||||
|
||||
return {
|
||||
/**
|
||||
* @param {'fail' | 'continue'} p a status to determine if the error will
|
||||
* terminate your application or continue. Warning and
|
||||
*/
|
||||
status: (p: 'fail' | 'continue') => {
|
||||
payload.type = p;
|
||||
return payload;
|
||||
},
|
||||
/**
|
||||
* @param {keyof Logging} type Determine to log to logger[type].
|
||||
* @param {T} message the message to log
|
||||
*
|
||||
* Log this error with the logger.
|
||||
*/
|
||||
log: <T=string>(type: keyof Logging, message: T) => {
|
||||
payload.log = { type, message };
|
||||
return payload;
|
||||
},
|
||||
reply: (bodyContent: ReplyOptions) => {
|
||||
payload.body = bodyContent;
|
||||
return payload;
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
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,10 +8,11 @@ import {
|
||||
Snowflake,
|
||||
User,
|
||||
} from 'discord.js';
|
||||
import { CoreContext } from './core-context';
|
||||
import { CoreContext } from '../structures/core-context';
|
||||
import { Result, Ok, Err } from 'ts-results-es';
|
||||
import * as assert from 'assert';
|
||||
import { ReplyOptions } from '../../shared';
|
||||
import { ReplyOptions } from '../../types/utility';
|
||||
|
||||
|
||||
/**
|
||||
* @since 1.0.0
|
||||
@@ -30,52 +31,81 @@ export class Context extends CoreContext<Message, ChatInputCommandInteraction> {
|
||||
}
|
||||
|
||||
public get id(): Snowflake {
|
||||
return this.ctx.val.id;
|
||||
return safeUnwrap(this.ctx
|
||||
.map(m => m.id)
|
||||
.mapErr(i => i.id));
|
||||
}
|
||||
|
||||
public get channel() {
|
||||
return this.ctx.val.channel;
|
||||
return safeUnwrap(this.ctx
|
||||
.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
|
||||
* else, interaction.user
|
||||
*/
|
||||
public get user(): User {
|
||||
return safeUnwrap(this.ctx.map(m => m.author).mapErr(i => i.user));
|
||||
return safeUnwrap(this.ctx
|
||||
.map(m => m.author)
|
||||
.mapErr(i => i.user));
|
||||
}
|
||||
|
||||
public get userId(): Snowflake {
|
||||
return this.user.id;
|
||||
}
|
||||
|
||||
public get createdTimestamp(): number {
|
||||
return this.ctx.val.createdTimestamp;
|
||||
return safeUnwrap(this.ctx
|
||||
.map(m => m.createdTimestamp)
|
||||
.mapErr(i => i.createdTimestamp));
|
||||
}
|
||||
|
||||
public get guild() {
|
||||
return this.ctx.val.guild;
|
||||
return safeUnwrap(this.ctx
|
||||
.map(m => m.guild)
|
||||
.mapErr(i => i.guild));
|
||||
}
|
||||
|
||||
public get guildId() {
|
||||
return this.ctx.val.guildId;
|
||||
return safeUnwrap(this.ctx
|
||||
.map(m => m.guildId)
|
||||
.mapErr(i => i.guildId));
|
||||
}
|
||||
/*
|
||||
* interactions can return APIGuildMember if the guild it is emitted from is not cached
|
||||
*/
|
||||
public get member() {
|
||||
return this.ctx.val.member;
|
||||
return safeUnwrap(this.ctx
|
||||
.map(m => m.member)
|
||||
.mapErr(i => i.member));
|
||||
}
|
||||
|
||||
public get client(): Client {
|
||||
return this.ctx.val.client;
|
||||
return safeUnwrap(this.ctx
|
||||
.map(m => m.client)
|
||||
.mapErr(i => i.client));
|
||||
}
|
||||
|
||||
public get inGuild(): boolean {
|
||||
return this.ctx.val.inGuild();
|
||||
return safeUnwrap(this.ctx
|
||||
.map(m => m.inGuild())
|
||||
.mapErr(i => i.inGuild()));
|
||||
}
|
||||
|
||||
public async reply(content: ReplyOptions) {
|
||||
return safeUnwrap(
|
||||
this.ctx
|
||||
.map(m => m.reply(content as string | MessageReplyOptions))
|
||||
.map(m => m.reply(content as MessageReplyOptions))
|
||||
.mapErr(i =>
|
||||
i.reply(content as string | InteractionReplyOptions).then(() => i.fetchReply()),
|
||||
i.reply(content as InteractionReplyOptions).then(() => i.fetchReply()),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -90,5 +120,8 @@ export class Context extends CoreContext<Message, ChatInputCommandInteraction> {
|
||||
}
|
||||
|
||||
function safeUnwrap<T>(res: Result<T, T>) {
|
||||
return res.val;
|
||||
if(res.isOk()) {
|
||||
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 { SernError } from './errors';
|
||||
import { SernError } from '../_internal';
|
||||
import * as assert from 'node:assert';
|
||||
|
||||
/**
|
||||
@@ -7,7 +7,7 @@ import * as assert from 'node:assert';
|
||||
*/
|
||||
export abstract class CoreContext<M, I> {
|
||||
protected constructor(protected ctx: Either<M, I>) {
|
||||
assert.ok(typeof ctx.val === 'object' && ctx.val != null);
|
||||
assert.ok(typeof ctx === 'object' && ctx != null);
|
||||
}
|
||||
get message(): M {
|
||||
return this.ctx.expect(SernError.MismatchEvent);
|
||||
@@ -17,7 +17,7 @@ export abstract class CoreContext<M, I> {
|
||||
}
|
||||
|
||||
public isMessage(): this is CoreContext<M, never> {
|
||||
return this.ctx.ok;
|
||||
return this.ctx.isOk();
|
||||
}
|
||||
|
||||
public isSlash(): this is CoreContext<never, I> {
|
||||
@@ -26,8 +26,6 @@ export abstract class CoreContext<M, I> {
|
||||
//todo: add agnostic options resolver for Context
|
||||
abstract get options(): unknown;
|
||||
|
||||
abstract get id(): string;
|
||||
|
||||
static wrap(_: unknown): unknown {
|
||||
throw Error('You need to override this method; cannot wrap an abstract class');
|
||||
}
|
||||
|
||||
@@ -23,10 +23,10 @@ export enum CommandType {
|
||||
Button = 1 << 4,
|
||||
StringSelect = 1 << 5,
|
||||
Modal = 1 << 6,
|
||||
ChannelSelect = 1 << 7,
|
||||
MentionableSelect = 1 << 8,
|
||||
RoleSelect = 1 << 9,
|
||||
UserSelect = 1 << 10,
|
||||
UserSelect = 1 << 7,
|
||||
RoleSelect = 1 << 8,
|
||||
MentionableSelect = 1 << 9,
|
||||
ChannelSelect = 1 << 10,
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -101,3 +101,42 @@ export enum PayloadType {
|
||||
*/
|
||||
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`,
|
||||
}
|
||||
|
||||
@@ -1,38 +0,0 @@
|
||||
/**
|
||||
* @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,5 +1,6 @@
|
||||
export * from './enums';
|
||||
export { CommandType, PluginType, PayloadType, EventType } from './enums';
|
||||
export * from './context';
|
||||
export * from './sern-emitter';
|
||||
export * from './services';
|
||||
export * from './module-store';
|
||||
export * as CommandError from './command-error';
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { CommandMeta, Module } from '../../types/core-modules';
|
||||
import { CoreModuleStore } from '../contracts';
|
||||
import { Module, CommandMeta } from '../types/modules';
|
||||
|
||||
/*
|
||||
* @internal
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { EventEmitter } from 'node:events';
|
||||
import { PayloadType } from '../../core/structures';
|
||||
import { Payload, SernEventsMapping } from '../../shared';
|
||||
import { Module } from '../types/modules';
|
||||
import { Module } from '../../types/core-modules';
|
||||
import { SernEventsMapping, Payload } from '../../types/utility';
|
||||
|
||||
/**
|
||||
* @since 1.0.0
|
||||
|
||||
@@ -3,20 +3,19 @@ import { ErrorHandling } from '../../contracts';
|
||||
/**
|
||||
* @internal
|
||||
* @since 2.0.0
|
||||
* Version 4.0.0 will internalize this api. Please refrain from using ModuleStore!
|
||||
* Version 4.0.0 will internalize this api. Please refrain from using the defaults!
|
||||
*/
|
||||
export class DefaultErrorHandling implements ErrorHandling {
|
||||
|
||||
crash(err: Error): never {
|
||||
throw err;
|
||||
throw err;
|
||||
}
|
||||
|
||||
keepAlive = 5;
|
||||
#keepAlive = 5;
|
||||
|
||||
updateAlive(err: Error) {
|
||||
this.keepAlive--;
|
||||
if(this.keepAlive === 0) {
|
||||
throw err;
|
||||
this.#keepAlive--;
|
||||
if (this.#keepAlive === 0) {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { createId } from '../../../handler/id';
|
||||
import * as Id from '../../../core/id';
|
||||
import { CoreModuleStore, ModuleManager } from '../../contracts';
|
||||
import { importModule } from '../../module-loading';
|
||||
import { CommandMeta, CommandModule, CommandModuleDefs, Module } from '../../types/modules';
|
||||
import { Files } from '../../_internal';
|
||||
import { CommandMeta, CommandModule, CommandModuleDefs, Module } from '../../../types/core-modules';
|
||||
import { CommandType } from '../enums';
|
||||
/**
|
||||
* @internal
|
||||
@@ -11,12 +11,13 @@ import { CommandType } from '../enums';
|
||||
export class DefaultModuleManager implements ModuleManager {
|
||||
constructor(private moduleStore: CoreModuleStore) {}
|
||||
|
||||
|
||||
getByNameCommandType<T extends CommandType>(name: string, commandType: T) {
|
||||
const id = this.get(createId(name, commandType));
|
||||
if(!id) {
|
||||
const id = this.get(Id.create(name, commandType));
|
||||
if (!id) {
|
||||
return undefined;
|
||||
}
|
||||
return importModule<CommandModuleDefs[T]>(id);
|
||||
return Files.importModule<CommandModuleDefs[T]>(id);
|
||||
}
|
||||
|
||||
setMetadata(m: Module, c: CommandMeta): void {
|
||||
@@ -26,12 +27,11 @@ export class DefaultModuleManager implements ModuleManager {
|
||||
getMetadata(m: Module): CommandMeta {
|
||||
const maybeModule = this.moduleStore.metadata.get(m);
|
||||
if (!maybeModule) {
|
||||
throw Error('Could not find metadata in store for ' + maybeModule);
|
||||
throw Error('Could not find metadata in store for ' + m);
|
||||
}
|
||||
return maybeModule;
|
||||
}
|
||||
|
||||
|
||||
get(id: string) {
|
||||
return this.moduleStore.commands.get(id);
|
||||
}
|
||||
@@ -45,7 +45,7 @@ export class DefaultModuleManager implements ModuleManager {
|
||||
return Promise.all(
|
||||
Array.from(entries)
|
||||
.filter(([id]) => !(Number.parseInt(id.at(-1)!) & publishable))
|
||||
.map(([, path]) => importModule<CommandModule>(path)),
|
||||
.map(([, path]) => Files.importModule<CommandModule>(path)),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,119 +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 } 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);
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
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)),
|
||||
);
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
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)),
|
||||
);
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
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));
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
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,89 +0,0 @@
|
||||
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,
|
||||
};
|
||||
@@ -1,24 +0,0 @@
|
||||
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;
|
||||
}
|
||||
2
src/handlers/_internal.ts
Normal file
2
src/handlers/_internal.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export * from './dispatchers';
|
||||
export * from './event-utils';
|
||||
100
src/handlers/dispatchers.ts
Normal file
100
src/handlers/dispatchers.ts
Normal file
@@ -0,0 +1,100 @@
|
||||
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, 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 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;
|
||||
}) {
|
||||
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, name, parent } = option;
|
||||
|
||||
return {
|
||||
...payload,
|
||||
module: command as Processed<Module>, //autocomplete is not a true "module" warning cast!
|
||||
args: [payload.event],
|
||||
};
|
||||
}
|
||||
return {
|
||||
module: payload.module,
|
||||
args: contextArgs(payload.event),
|
||||
};
|
||||
}
|
||||
default: return {
|
||||
module: payload.module,
|
||||
args: [payload.event],
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -12,29 +12,51 @@ import {
|
||||
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';
|
||||
import {
|
||||
Files,
|
||||
Id,
|
||||
callPlugin,
|
||||
everyPluginOk,
|
||||
filterMapTo,
|
||||
handleError,
|
||||
SernError,
|
||||
VoidResult,
|
||||
useContainerRaw,
|
||||
} from '../core/_internal';
|
||||
import { 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, Processed } from '../types/core-modules';
|
||||
import type { ImportPayload } from '../types/core';
|
||||
|
||||
function createGenericHandler<Source, Narrowed extends Source, Output>(
|
||||
source: Observable<Source>,
|
||||
makeModule: (event: Narrowed) => Awaitable<Result<Output, unknown>>,
|
||||
makeModule: (event: Narrowed) => Promise<Output>,
|
||||
) {
|
||||
return (pred: (i: Source) => i is Narrowed) => source.pipe(filter(pred), filterMap(makeModule));
|
||||
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.
|
||||
@@ -46,15 +68,20 @@ export function createInteractionHandler<T extends Interaction>(
|
||||
source: Observable<Interaction>,
|
||||
mg: ModuleManager,
|
||||
) {
|
||||
return createGenericHandler<Interaction, T, ReturnType<typeof createDispatcher>>(
|
||||
return createGenericHandler<Interaction, T, Result<ReturnType<typeof createDispatcher>, void>>(
|
||||
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 })),
|
||||
);
|
||||
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,
|
||||
event,
|
||||
})));
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -64,16 +91,20 @@ export function createMessageHandler(
|
||||
defaultPrefix: string,
|
||||
mg: ModuleManager,
|
||||
) {
|
||||
return createGenericHandler(source, event => {
|
||||
return createGenericHandler(source, async 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');
|
||||
const fullPath = mg.get(`${prefix}_A1`);
|
||||
|
||||
if(!fullPath) {
|
||||
return Err('Possibly undefined behavior: could not find a static id to resolve')
|
||||
}
|
||||
return defaultModuleLoader<Processed<CommandModule>>(fullPath).then(result => {
|
||||
const args = contextArgs(event, rest);
|
||||
return result.map(payload => dispatchMessage(payload.module, args));
|
||||
});
|
||||
return Files
|
||||
.defaultModuleLoader<Processed<CommandModule>>(fullPath)
|
||||
.then((payload)=> {
|
||||
const args = contextArgs(event, rest);
|
||||
return Ok({ args, ...payload });
|
||||
|
||||
});
|
||||
});
|
||||
}
|
||||
/**
|
||||
@@ -89,38 +120,26 @@ function assignDefaults<T extends Module>(
|
||||
moduleManager.setMetadata(module, {
|
||||
isClass: module.constructor.name === 'Function',
|
||||
fullPath: absPath,
|
||||
id: createId(module.name, module.type),
|
||||
id: Id.create(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),
|
||||
);
|
||||
return Files
|
||||
.buildModuleStream<Processed<T>>(input)
|
||||
.pipe(assignDefaults(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);
|
||||
interface ExecutePayload {
|
||||
module: Processed<Module>;
|
||||
task: () => Awaitable<unknown>;
|
||||
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
|
||||
@@ -130,25 +149,25 @@ export function isNonBot(prefix: string) {
|
||||
* @param task the deferred execution which will be called
|
||||
*/
|
||||
export function executeModule(
|
||||
emitter: SernEmitter,
|
||||
emitter: Emitter,
|
||||
logger: Logging|undefined,
|
||||
errHandler: ErrorHandling,
|
||||
{
|
||||
module,
|
||||
task,
|
||||
}: {
|
||||
module: Processed<Module>;
|
||||
task: () => Awaitable<unknown>;
|
||||
},
|
||||
args
|
||||
}: ExecutePayload,
|
||||
) {
|
||||
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) {
|
||||
if (result.isOk()) {
|
||||
emitter.emit('module.activate', SernEmitter.success(module));
|
||||
return EMPTY;
|
||||
} else {
|
||||
return throwError(() => SernEmitter.failure(module, result.val));
|
||||
}
|
||||
}
|
||||
return throwError(() => SernEmitter.failure(module, result.error));
|
||||
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -175,7 +194,7 @@ export function createResultResolver<
|
||||
const task$ = config.createStream(args);
|
||||
return task$.pipe(
|
||||
tap(result => {
|
||||
result.err && config.onStop?.(args.module);
|
||||
result.isErr() && config.onStop?.(args.module);
|
||||
}),
|
||||
everyPluginOk,
|
||||
filterMapTo(() => config.onNext(args)),
|
||||
@@ -187,14 +206,20 @@ export function createResultResolver<
|
||||
* 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 }) {
|
||||
export function callInitPlugins<T extends Processed<AnyModule>>(sernEmitter: Emitter) {
|
||||
return concatMap(
|
||||
createResultResolver({
|
||||
createStream: args => from(args.module.plugins).pipe(callPlugin(args)),
|
||||
...config,
|
||||
onStop: (module: T) => {
|
||||
sernEmitter.emit(
|
||||
'module.register',
|
||||
SernEmitter.failure(module, SernError.PluginFailure),
|
||||
);
|
||||
},
|
||||
onNext: ({ module }) => {
|
||||
sernEmitter.emit('module.register', SernEmitter.success(module));
|
||||
return { module };
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -205,28 +230,36 @@ export function callInitPlugins<
|
||||
*/
|
||||
export function makeModuleExecutor<
|
||||
M extends Processed<Module>,
|
||||
Args extends { module: M; args: unknown[] },
|
||||
Args extends {
|
||||
module: M;
|
||||
args: unknown[];
|
||||
},
|
||||
>(onStop: (m: M) => unknown) {
|
||||
const onNext = ({ args, module }: Args) => ({ task: () => module.execute(...args), module });
|
||||
const onNext = ({ args, module }: Args) => ({
|
||||
task: () => module.execute(...args),
|
||||
module,
|
||||
args
|
||||
});
|
||||
return concatMap(
|
||||
createResultResolver({
|
||||
onStop,
|
||||
createStream: ({ args, module }) => from(module.onEvent).pipe(callPlugin(args)),
|
||||
createStream: ({ args, module }) =>
|
||||
from(module.onEvent)
|
||||
.pipe(callPlugin(args)),
|
||||
onNext,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export function handleCrash(
|
||||
errorHandler: ErrorHandling,
|
||||
logger?: Logging,
|
||||
) {
|
||||
return pipe(
|
||||
catchError(handleError(errorHandler, logger)),
|
||||
export const handleCrash = (err: ErrorHandling, log?: Logging) =>
|
||||
pipe(
|
||||
catchError(handleError(err, log)),
|
||||
finalize(() => {
|
||||
logger?.info({ message: 'A stream closed or reached end of lifetime' });
|
||||
useContainerRaw()?.disposeAll()
|
||||
.then(() => logger?.info({ message: 'Cleaning container and crashing' }));
|
||||
})
|
||||
log?.info({
|
||||
message: 'A stream closed or reached end of lifetime',
|
||||
});
|
||||
useContainerRaw()
|
||||
?.disposeAll()
|
||||
.then(() => log?.info({ message: 'Cleaning container and crashing' }));
|
||||
}),
|
||||
);
|
||||
}
|
||||
33
src/handlers/interaction-event.ts
Normal file
33
src/handlers/interaction-event.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import { Interaction } from 'discord.js';
|
||||
import { mergeMap, 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))),
|
||||
mergeMap(payload => executeModule(emitter, log, err, payload)),
|
||||
);
|
||||
}
|
||||
47
src/handlers/message-event.ts
Normal file
47
src/handlers/message-event.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
import { mergeMap, 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));
|
||||
}),
|
||||
mergeMap(payload => executeModule(emitter, log, err, payload)),
|
||||
);
|
||||
}
|
||||
47
src/handlers/ready-event.ts
Normal file
47
src/handlers/ready-event.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
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));
|
||||
}
|
||||
36
src/handlers/user-defined-events.ts
Normal file
36
src/handlers/user-defined-events.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
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, 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> }) => {
|
||||
switch (e.module.type) {
|
||||
case EventType.Sern:
|
||||
return eventDispatcher(e.module, emitter);
|
||||
case EventType.Discord:
|
||||
return eventDispatcher(e.module, client);
|
||||
case EventType.External:
|
||||
return eventDispatcher(e.module, 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,11 +1,56 @@
|
||||
export * as Sern from './handler/sern';
|
||||
export * as Sern from './sern';
|
||||
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 {
|
||||
commandModule,
|
||||
eventModule,
|
||||
discordEvent,
|
||||
EventExecutable,
|
||||
CommandExecutable,
|
||||
} from './handler/commands';
|
||||
export { controller } from './handler/sern';
|
||||
export type { Wrapper, Args } from './shared';
|
||||
} from './core/modules';
|
||||
|
||||
export {
|
||||
useContainerRaw
|
||||
} from './core/_internal'
|
||||
export { controller } from './sern';
|
||||
|
||||
66
src/sern.ts
Normal file
66
src/sern.ts
Normal file
@@ -0,0 +1,66 @@
|
||||
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,
|
||||
};
|
||||
@@ -3,8 +3,6 @@ import type {
|
||||
APIApplicationCommandOptionBase,
|
||||
ApplicationCommandOptionType,
|
||||
BaseApplicationCommandOptionsData,
|
||||
} from 'discord.js';
|
||||
import {
|
||||
AutocompleteInteraction,
|
||||
ButtonInteraction,
|
||||
ChannelSelectMenuInteraction,
|
||||
@@ -17,19 +15,19 @@ import {
|
||||
UserContextMenuCommandInteraction,
|
||||
UserSelectMenuInteraction,
|
||||
} from 'discord.js';
|
||||
import { CommandType, Context, EventType } from '../structures';
|
||||
import { AnyCommandPlugin, AnyEventPlugin, ControlPlugin, InitPlugin } from './plugins';
|
||||
import { Awaitable, SernEventsMapping } from '../../shared';
|
||||
import { Processed } from '../../handler/types';
|
||||
import { Args, SlashOptions } from '../../shared';
|
||||
import { CommandType, Context, EventType } from '../../src/core';
|
||||
import { AnyCommandPlugin, AnyEventPlugin, ControlPlugin, InitPlugin } from './core-plugin';
|
||||
import { Awaitable, Args, SlashOptions, SernEventsMapping } from './utility';
|
||||
|
||||
|
||||
|
||||
export interface CommandMeta {
|
||||
fullPath: string;
|
||||
id: string;
|
||||
isClass: boolean
|
||||
isClass: boolean;
|
||||
}
|
||||
|
||||
export type AnyDefinedModule = Processed<CommandModule | EventModule>;
|
||||
export type Processed<T> = T & { name: string; description: string };
|
||||
|
||||
export interface Module {
|
||||
type: CommandType | EventType;
|
||||
@@ -37,7 +35,7 @@ export interface Module {
|
||||
onEvent: ControlPlugin[];
|
||||
plugins: InitPlugin[];
|
||||
description?: string;
|
||||
execute: (...args: any[]) => Awaitable<any>;
|
||||
execute(...args: any[]): Awaitable<any>;
|
||||
}
|
||||
|
||||
export interface SernEventCommand<T extends keyof SernEventsMapping = keyof SernEventsMapping>
|
||||
@@ -147,7 +145,6 @@ export type CommandModule =
|
||||
| ModalSubmitCommand;
|
||||
|
||||
export type AnyModule = CommandModule | EventModule;
|
||||
|
||||
//https://stackoverflow.com/questions/64092736/alternative-to-switch-statement-for-typescript-discriminated-union
|
||||
// Explicit Module Definitions for mapping
|
||||
export interface CommandModuleDefs {
|
||||
@@ -193,10 +190,11 @@ export type InputEvent = {
|
||||
}[EventType];
|
||||
|
||||
export type InputCommand = {
|
||||
[T in CommandType]: CommandModuleNoPlugins[T] & { plugins?: AnyCommandPlugin[] };
|
||||
[T in CommandType]: CommandModuleNoPlugins[T] & {
|
||||
plugins?: AnyCommandPlugin[];
|
||||
};
|
||||
}[CommandType];
|
||||
|
||||
|
||||
/**
|
||||
* Type that replaces autocomplete with {@link SernAutocompleteData}
|
||||
*/
|
||||
@@ -206,7 +204,8 @@ export type SernOptionsData =
|
||||
| APIApplicationCommandBasicOption
|
||||
| SernAutocompleteData;
|
||||
|
||||
export interface SernSubCommandData extends APIApplicationCommandOptionBase<ApplicationCommandOptionType.Subcommand> {
|
||||
export interface SernSubCommandData
|
||||
extends APIApplicationCommandOptionBase<ApplicationCommandOptionType.Subcommand> {
|
||||
type: ApplicationCommandOptionType.Subcommand;
|
||||
options?: SernOptionsData[];
|
||||
}
|
||||
@@ -24,16 +24,17 @@ import type {
|
||||
ExternalEventCommand,
|
||||
MentionableSelectCommand,
|
||||
ModalSubmitCommand,
|
||||
Module,
|
||||
Processed,
|
||||
RoleSelectCommand,
|
||||
SernEventCommand,
|
||||
SlashCommand,
|
||||
StringSelectCommand,
|
||||
TextCommand,
|
||||
UserSelectCommand,
|
||||
} from './modules';
|
||||
import { Args, Awaitable, Payload, SlashOptions } from '../../shared';
|
||||
import { CommandType, Context, EventType, PluginType } from '../structures';
|
||||
import { InitArgs, Processed } from '../../handler/types';
|
||||
} from './core-modules';
|
||||
import { Args, Awaitable, Payload, SlashOptions } from './utility';
|
||||
import { CommandType, Context, EventType, PluginType } from '../core';
|
||||
import {
|
||||
ButtonInteraction,
|
||||
ChannelSelectMenuInteraction,
|
||||
@@ -50,6 +51,10 @@ import {
|
||||
export type PluginResult = Awaitable<VoidResult>;
|
||||
export type VoidResult = Result<void, void>;
|
||||
|
||||
export interface InitArgs<T extends Processed<Module>> {
|
||||
module: T;
|
||||
absPath: string;
|
||||
}
|
||||
export interface Controller {
|
||||
next: () => Ok<void>;
|
||||
stop: () => Err<void>;
|
||||
23
src/types/core.ts
Normal file
23
src/types/core.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
|
||||
export interface ImportPayload<T> {
|
||||
module: T;
|
||||
absPath: string;
|
||||
[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,16 +1,12 @@
|
||||
// This file serves an the interface for developers to augment the Dependencies interface
|
||||
// Developers will have to create a new file dependencies.d.ts in the root directory, augmenting
|
||||
// Developers will have to create a new file dependencies.d.ts in the root directory, augmenting
|
||||
// this type
|
||||
|
||||
/* eslint-disable @typescript-eslint/consistent-type-imports */
|
||||
|
||||
import { CoreDependencies } from './types'
|
||||
import { CoreDependencies } from './ioc';
|
||||
|
||||
declare global {
|
||||
|
||||
interface Dependencies extends CoreDependencies {}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
48
src/types/ioc.ts
Normal file
48
src/types/ioc.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
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,52 +1,33 @@
|
||||
import type {
|
||||
CommandInteractionOptionResolver,
|
||||
InteractionReplyOptions,
|
||||
MessageReplyOptions,
|
||||
} from 'discord.js';
|
||||
import { PayloadType } from './core';
|
||||
import { AnyModule } from './core/types/modules';
|
||||
|
||||
export type ReplyOptions =
|
||||
| string
|
||||
| Omit<InteractionReplyOptions, 'fetchReply'>
|
||||
| MessageReplyOptions;
|
||||
|
||||
export type Payload =
|
||||
| { type: PayloadType.Success; module: AnyModule }
|
||||
| { type: PayloadType.Failure; module?: AnyModule; reason: string | Error }
|
||||
| { type: PayloadType.Warning; reason: string };
|
||||
|
||||
export interface SernEventsMapping {
|
||||
'module.register': [Payload];
|
||||
'module.activate': [Payload];
|
||||
error: [Payload];
|
||||
warning: [Payload];
|
||||
'modulesLoaded': [never?];
|
||||
}
|
||||
import type { CommandInteractionOptionResolver, InteractionReplyOptions, MessageReplyOptions } from 'discord.js';
|
||||
import type { PayloadType } from '../core';
|
||||
import type { AnyModule } from './core-modules';
|
||||
|
||||
export type Awaitable<T> = PromiseLike<T> | T;
|
||||
|
||||
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[];
|
||||
};
|
||||
}
|
||||
export type AnyFunction = (...args: unknown[]) => 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 SlashOptions = Omit<CommandInteractionOptionResolver, 'getMessage' | 'getFocused'>;
|
||||
|
||||
export type Args = ParseType<{ text: string[]; slash: SlashOptions }>;
|
||||
|
||||
export type SlashOptions = Omit<CommandInteractionOptionResolver, 'getMessage' | 'getFocused'>;
|
||||
export interface SernEventsMapping {
|
||||
'module.register': [Payload];
|
||||
'module.activate': [Payload];
|
||||
error: [Payload];
|
||||
warning: [Payload];
|
||||
modulesLoaded: [never?];
|
||||
}
|
||||
|
||||
export type Payload =
|
||||
| { type: PayloadType.Success; module: AnyModule }
|
||||
| { type: PayloadType.Failure; module?: AnyModule; reason: string | Error }
|
||||
| { type: PayloadType.Warning; reason: string };
|
||||
|
||||
|
||||
|
||||
export type ReplyOptions = string | Omit<InteractionReplyOptions, 'fetchReply'> | MessageReplyOptions;
|
||||
85
test/core/context.test.ts
Normal file
85
test/core/context.test.ts
Normal file
@@ -0,0 +1,85 @@
|
||||
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,14 +1,16 @@
|
||||
import { assertType, describe, it, vi } from "vitest";
|
||||
import * as DefaultContracts from '../../src/core/structures/services'
|
||||
import * as Contracts from '../../src/core/contracts/index.js'
|
||||
import { ModuleStore } from "../../src/core";
|
||||
import { assertType, describe, it } from 'vitest';
|
||||
|
||||
import { ModuleStore } from '../../src';
|
||||
import * as DefaultContracts from '../../src/core/structures/services';
|
||||
import * as Contracts from '../../src/core/contracts/index.js';
|
||||
|
||||
describe('default contracts', () => {
|
||||
it('should satisfy contracts', () => {
|
||||
assertType<Contracts.Logging>(new DefaultContracts.DefaultLogging())
|
||||
assertType<Contracts.ErrorHandling>(new DefaultContracts.DefaultErrorHandling())
|
||||
assertType<Contracts.ModuleManager>(new DefaultContracts.DefaultModuleManager(new ModuleStore()))
|
||||
assertType<Contracts.CoreModuleStore>(new ModuleStore())
|
||||
})
|
||||
|
||||
})
|
||||
assertType<Contracts.Logging>(new DefaultContracts.DefaultLogging());
|
||||
assertType<Contracts.ErrorHandling>(new DefaultContracts.DefaultErrorHandling());
|
||||
assertType<Contracts.ModuleManager>(
|
||||
new DefaultContracts.DefaultModuleManager(new ModuleStore()),
|
||||
);
|
||||
assertType<Contracts.CoreModuleStore>(new ModuleStore());
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,35 +1,32 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { CommandControlPlugin, CommandInitPlugin, EventControlPlugin, EventInitPlugin } from '../../src/core/create-plugins'
|
||||
import { PluginType, controller } from '../../src/index'
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import {
|
||||
CommandControlPlugin,
|
||||
CommandInitPlugin,
|
||||
EventControlPlugin,
|
||||
EventInitPlugin,
|
||||
} from '../../src/core/create-plugins';
|
||||
import { PluginType, controller } from '../../src';
|
||||
|
||||
describe('create-plugins', () => {
|
||||
it('should make proper control plugins', () => {
|
||||
const pl = EventControlPlugin(() => controller.next())
|
||||
expect(pl)
|
||||
.to.have.all.keys(['type', 'execute'])
|
||||
expect(pl.type).toBe(PluginType.Control)
|
||||
expect(pl.execute).an('function')
|
||||
const pl2 = CommandControlPlugin(() => controller.next())
|
||||
expect(pl2)
|
||||
.to.have.all.keys(['type', 'execute'])
|
||||
expect(pl2.type).toBe(PluginType.Control)
|
||||
expect(pl2.execute).an('function')
|
||||
|
||||
})
|
||||
const pl = EventControlPlugin(() => controller.next());
|
||||
expect(pl).to.have.all.keys(['type', 'execute']);
|
||||
expect(pl.type).toBe(PluginType.Control);
|
||||
expect(pl.execute).an('function');
|
||||
const pl2 = CommandControlPlugin(() => controller.next());
|
||||
expect(pl2).to.have.all.keys(['type', 'execute']);
|
||||
expect(pl2.type).toBe(PluginType.Control);
|
||||
expect(pl2.execute).an('function');
|
||||
});
|
||||
it('should make proper init plugins', () => {
|
||||
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 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');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,208 +1,404 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { PluginType, SernOptionsData, controller } from '../../src/index'
|
||||
import { partitionPlugins, treeSearch } from "../../src/core/functions";
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { PluginType, SernOptionsData, controller } from '../../src/index';
|
||||
import { partitionPlugins, treeSearch } from '../../src/core/functions';
|
||||
import { faker } from '@faker-js/faker';
|
||||
import { ApplicationCommandOptionType, AutocompleteInteraction } from "discord.js";
|
||||
import { ApplicationCommandOptionType, AutocompleteInteraction } from 'discord.js';
|
||||
|
||||
vi.mock('discord.js', () => {
|
||||
|
||||
const Collection = Map
|
||||
const ModalSubmitInteraction = class {
|
||||
customId
|
||||
type = 5
|
||||
isModalSubmit = vi.fn()
|
||||
constructor(customId) {
|
||||
this.customId = customId
|
||||
}
|
||||
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 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()
|
||||
}
|
||||
};
|
||||
const AutocompleteInteraction = class {
|
||||
type = 4;
|
||||
option: string;
|
||||
constructor(s: string) {
|
||||
this.option = s;
|
||||
}
|
||||
|
||||
return {
|
||||
Collection,
|
||||
ComponentType: {
|
||||
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
|
||||
options = {
|
||||
getFocused: vi.fn(),
|
||||
getSubcommand: vi.fn(),
|
||||
};
|
||||
})
|
||||
};
|
||||
|
||||
describe('functions', () => {
|
||||
afterEach(() => { vi.clearAllMocks() })
|
||||
return {
|
||||
Collection,
|
||||
ComponentType: {
|
||||
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,
|
||||
},
|
||||
ApplicationCommandType: {
|
||||
ChatInput: 1,
|
||||
User: 2,
|
||||
Message: 3,
|
||||
},
|
||||
ModalSubmitInteraction,
|
||||
ButtonInteraction,
|
||||
AutocompleteInteraction,
|
||||
};
|
||||
});
|
||||
|
||||
describe('functions', () => {
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
function createRandomPlugins(len: number) {
|
||||
const random = () => Math.floor(Math.random()*2)+1; // 1 or 2, plugin enum
|
||||
return Array.from({ length: len }, () => ({ type: random(), execute: () => random() === 1 ? controller.next():controller.stop() }))
|
||||
const random = () => Math.floor(Math.random() * 2) + 1; // 1 or 2, plugin enum
|
||||
return Array.from({ length: len }, () => ({
|
||||
type: random(),
|
||||
execute: () => (random() === 1 ? controller.next() : controller.stop()),
|
||||
}));
|
||||
}
|
||||
function createRandomChoice() {
|
||||
return {
|
||||
type: faker.number.int({ min: 1, max: 11}),
|
||||
type: faker.number.int({ min: 1, max: 11 }),
|
||||
name: faker.word.noun(),
|
||||
description: faker.word.adjective(),
|
||||
}
|
||||
};
|
||||
}
|
||||
it('should partition plugins correctly', () => {
|
||||
const plugins = createRandomPlugins(100);
|
||||
const [ onEvent, init ] = partitionPlugins(plugins)
|
||||
for(const el of onEvent)
|
||||
expect(el.type).to.equal(PluginType.Control)
|
||||
|
||||
for(const el of init)
|
||||
expect(el.type).to.equal(PluginType.Init)
|
||||
})
|
||||
|
||||
const plugins = createRandomPlugins(100);
|
||||
const [onEvent, init] = partitionPlugins(plugins);
|
||||
for (const el of onEvent) expect(el.type).to.equal(PluginType.Control);
|
||||
|
||||
for (const el of init) expect(el.type).to.equal(PluginType.Init);
|
||||
});
|
||||
|
||||
it('should tree search options tree depth 1', () => {
|
||||
//@ts-expect-error mocking
|
||||
let autocmpInteraction = new AutocompleteInteraction('autocomplete');
|
||||
const options : SernOptionsData[] = [
|
||||
const options: SernOptionsData[] = [
|
||||
createRandomChoice(),
|
||||
createRandomChoice(),
|
||||
createRandomChoice(),
|
||||
{
|
||||
type: ApplicationCommandOptionType.String,
|
||||
name: 'autocomplete',
|
||||
description: 'here',
|
||||
autocomplete: true,
|
||||
command : { onEvent: [], execute:(a) => {} }
|
||||
}
|
||||
];
|
||||
autocmpInteraction.options.getFocused.mockReturnValue(
|
||||
{
|
||||
type: ApplicationCommandOptionType.String,
|
||||
name: 'autocomplete',
|
||||
value: faker.string.alpha(),
|
||||
focused: true
|
||||
description: 'here',
|
||||
autocomplete: true,
|
||||
command: { onEvent: [], execute: vi.fn() },
|
||||
},
|
||||
);
|
||||
];
|
||||
autocmpInteraction.options.getFocused.mockReturnValue({
|
||||
name: 'autocomplete',
|
||||
value: faker.string.alpha(),
|
||||
focused: true,
|
||||
});
|
||||
const result = treeSearch(autocmpInteraction, options);
|
||||
expect(result == undefined).to.be.false;
|
||||
expect(result.name).to.be.eq('autocomplete');
|
||||
expect(result.command).to.be.not.undefined;
|
||||
|
||||
}),
|
||||
it('should tree search depth 2', () => {
|
||||
//@ts-expect-error mocking
|
||||
let autocmpInteraction = new AutocompleteInteraction('nested');
|
||||
const options : SernOptionsData[] = [
|
||||
{
|
||||
type: ApplicationCommandOptionType.Subcommand,
|
||||
name: faker.string.alpha(),
|
||||
description: faker.string.alpha(),
|
||||
options: [
|
||||
createRandomChoice(),
|
||||
createRandomChoice(),
|
||||
createRandomChoice(),
|
||||
{
|
||||
type: ApplicationCommandOptionType.String,
|
||||
name: 'nested',
|
||||
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(),
|
||||
autocomplete: true,
|
||||
command: {
|
||||
onEvent: [],
|
||||
execute:() => {}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
];
|
||||
autocmpInteraction.options.getFocused.mockReturnValue(
|
||||
{
|
||||
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;
|
||||
|
||||
})
|
||||
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', () => {
|
||||
//@ts-expect-error mocking
|
||||
let autocmpInteraction = new AutocompleteInteraction('nested');
|
||||
const options : SernOptionsData[] = [
|
||||
const subcommandName = faker.string.alpha();
|
||||
const options: SernOptionsData[] = [
|
||||
{
|
||||
|
||||
type: ApplicationCommandOptionType.SubcommandGroup,
|
||||
name: faker.string.alpha(),
|
||||
description: faker.string.alpha(),
|
||||
options: [
|
||||
{
|
||||
type: ApplicationCommandOptionType.Subcommand,
|
||||
name: faker.string.alpha(),
|
||||
description: faker.string.alpha(),
|
||||
options: [
|
||||
createRandomChoice(),
|
||||
createRandomChoice(),
|
||||
createRandomChoice(),
|
||||
{
|
||||
type: ApplicationCommandOptionType.String,
|
||||
name: 'nested',
|
||||
{
|
||||
type: ApplicationCommandOptionType.Subcommand,
|
||||
name: subcommandName,
|
||||
description: faker.string.alpha(),
|
||||
autocomplete: true,
|
||||
command: {
|
||||
onEvent: [],
|
||||
execute:() => {}
|
||||
}
|
||||
}
|
||||
]
|
||||
}]
|
||||
options: [
|
||||
createRandomChoice(),
|
||||
createRandomChoice(),
|
||||
{
|
||||
type: ApplicationCommandOptionType.String,
|
||||
name: 'nested',
|
||||
description: faker.string.alpha(),
|
||||
autocomplete: true,
|
||||
command: {
|
||||
onEvent: [],
|
||||
execute: () => {},
|
||||
},
|
||||
},
|
||||
createRandomChoice(),
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
autocmpInteraction.options.getFocused.mockReturnValue(
|
||||
{
|
||||
name: 'nested',
|
||||
value: faker.string.alpha(),
|
||||
focused: true
|
||||
}
|
||||
);
|
||||
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 correctly resolve suboption of the same name given two subcommands ', () => {
|
||||
let autocmpInteraction = new AutocompleteInteraction('nested');
|
||||
const subcommandName = faker.string.alpha();
|
||||
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: '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;
|
||||
});
|
||||
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: 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(),
|
||||
focused: true,
|
||||
});
|
||||
result = treeSearch(autocomplete, options);
|
||||
}
|
||||
expect(result).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,52 +1,86 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { CoreContainer } from '../../src/core/structures/container'
|
||||
import { CoreDependencies } from "../../src/core/ioc";
|
||||
import { EventEmitter } from "events";
|
||||
import { DefaultLogging, Init, Logging } from "../../src/core";
|
||||
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { CoreContainer } from '../../src/core/ioc/container';
|
||||
import { EventEmitter } from 'events';
|
||||
import { DefaultLogging, Disposable, Init, Logging } from '../../src/core';
|
||||
import { CoreDependencies } from '../../src/types/ioc';
|
||||
|
||||
describe('ioc container', () => {
|
||||
let container: CoreContainer<{}>;
|
||||
let initDependency: Logging & Init;
|
||||
let container: CoreContainer<{}> = new CoreContainer();
|
||||
let dependency: Logging & Init & Disposable;
|
||||
beforeEach(() => {
|
||||
initDependency = {
|
||||
dependency = {
|
||||
init: vi.fn(),
|
||||
error(): void {},
|
||||
warning(): void {},
|
||||
info(): void {},
|
||||
debug(): void {},
|
||||
}
|
||||
container = new CoreContainer()
|
||||
|
||||
})
|
||||
|
||||
dispose: vi.fn()
|
||||
};
|
||||
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()', () => {
|
||||
container.ready()
|
||||
expect(container.isReady()).toBe(true)
|
||||
})
|
||||
it('should container all core dependencies', async () => {
|
||||
const keys = ['@sern/modules', '@sern/emitter', '@sern/logger', '@sern/errors'] satisfies (keyof CoreDependencies)[]
|
||||
container.ready();
|
||||
expect(container.isReady()).toBe(true);
|
||||
});
|
||||
it('should container all core dependencies', async () => {
|
||||
const keys = [
|
||||
'@sern/modules',
|
||||
'@sern/emitter',
|
||||
'@sern/logger',
|
||||
'@sern/errors',
|
||||
] satisfies (keyof CoreDependencies)[];
|
||||
container.add({
|
||||
'@sern/logger': () => new DefaultLogging(),
|
||||
'@sern/client': () => new EventEmitter(),
|
||||
})
|
||||
for(const k of keys) {
|
||||
});
|
||||
for (const k of keys) {
|
||||
//@ts-expect-error typings for iti are strict
|
||||
expect(() => container.get(k)).not.toThrow();
|
||||
}
|
||||
})
|
||||
});
|
||||
it('should init modules', () => {
|
||||
container.upsert({ '@sern/logger': initDependency })
|
||||
container.upsert({ '@sern/logger': dependency });
|
||||
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()
|
||||
expect(initDependency.init).to.toHaveBeenCalledOnce()
|
||||
const db = container.get('db' as never) as DB
|
||||
expect(db.connected).toBeTruthy()
|
||||
|
||||
await container.disposeAll();
|
||||
|
||||
expect(db.connected).toBeFalsy()
|
||||
})
|
||||
|
||||
it('should not lazy module', () => {
|
||||
container.upsert({ '@sern/logger': () => initDependency })
|
||||
container.ready()
|
||||
expect(initDependency.init).toHaveBeenCalledTimes(0);
|
||||
})
|
||||
|
||||
|
||||
|
||||
})
|
||||
container.upsert({ '@sern/logger': () => dependency });
|
||||
container.ready();
|
||||
expect(dependency.init).toHaveBeenCalledTimes(0);
|
||||
});
|
||||
});
|
||||
|
||||
22
test/core/module-loading.test.ts
Normal file
22
test/core/module-loading.test.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
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,80 +1,77 @@
|
||||
import { SpyInstance, afterAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { CoreContainer } from '../../src/core/structures/container'
|
||||
import { DefaultLogging } from "../../src/core";
|
||||
import { faker } from '@faker-js/faker'
|
||||
import { commandModule } from "../../src";
|
||||
import { createId } from '../../src/handler/id'
|
||||
import { CommandMeta } from "../../src/core/types/modules";
|
||||
import { SpyInstance, afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { CoreContainer } from '../../src/core/ioc/container';
|
||||
import { DefaultLogging } from '../../src/core';
|
||||
import { faker } from '@faker-js/faker';
|
||||
import { commandModule } from '../../src';
|
||||
import * as Id from '../../src/core/id';
|
||||
import { CommandMeta } from '../../src/types/core-modules';
|
||||
|
||||
describe('services', () => {
|
||||
//@ts-ignore
|
||||
let container: CoreContainer<Dependencies>;
|
||||
let consoleMock : SpyInstance;
|
||||
let container: CoreContainer<Dependencies>;
|
||||
let consoleMock: SpyInstance;
|
||||
beforeEach(() => {
|
||||
container = new CoreContainer()
|
||||
container.add({ '@sern/logger': () => new DefaultLogging() })
|
||||
container.ready()
|
||||
consoleMock = vi.spyOn(container.get('@sern/logger'), 'error').mockImplementation(() => {})
|
||||
})
|
||||
|
||||
container = new CoreContainer();
|
||||
container.add({ '@sern/logger': () => new DefaultLogging() });
|
||||
container.ready();
|
||||
consoleMock = vi.spyOn(container.get('@sern/logger'), 'error').mockImplementation(() => {});
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
consoleMock.mockReset()
|
||||
consoleMock.mockReset();
|
||||
});
|
||||
it('module-store.ts', async () => {
|
||||
function createRandomCommandModules() {
|
||||
function createRandomCommandModules() {
|
||||
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(),
|
||||
name: faker.string.alpha(),
|
||||
execute: ()=>{}
|
||||
})
|
||||
}
|
||||
execute: () => {},
|
||||
});
|
||||
}
|
||||
|
||||
const modules = faker.helpers.multiple(createRandomCommandModules, { count: 40 })
|
||||
|
||||
const paths = faker.helpers.multiple(faker.system.directoryPath, { count: 40 })
|
||||
.map((path,i) => `${path}/${modules[i]}.js`);
|
||||
const modules = faker.helpers.multiple(createRandomCommandModules, {
|
||||
count: 40,
|
||||
});
|
||||
|
||||
const metadata: CommandMeta[] = modules.map((cm, i) => ({
|
||||
id: createId(cm.name, cm.type),
|
||||
isClass: false,
|
||||
fullPath: `${paths[i]}/${cm.name}.js`
|
||||
}));
|
||||
const moduleManager = container.get('@sern/modules');
|
||||
let i =0;
|
||||
for(const m of modules) {
|
||||
moduleManager.set(createId(m.name,m.type), paths[i]);
|
||||
moduleManager.setMetadata(m, metadata[i]);
|
||||
i++
|
||||
}
|
||||
for(const m of modules) {
|
||||
expect(moduleManager.getMetadata(m), "module references do not exist").toBeDefined()
|
||||
}
|
||||
|
||||
})
|
||||
const paths = faker.helpers
|
||||
.multiple(faker.system.directoryPath, { count: 40 })
|
||||
.map((path, i) => `${path}/${modules[i]}.js`);
|
||||
|
||||
const metadata: CommandMeta[] = modules.map((cm, i) => ({
|
||||
id: Id.create(cm.name!, cm.type),
|
||||
isClass: false,
|
||||
fullPath: `${paths[i]}/${cm.name}.js`,
|
||||
}));
|
||||
const moduleManager = container.get('@sern/modules');
|
||||
let i = 0;
|
||||
for (const m of modules) {
|
||||
moduleManager.set(Id.create(m.name!, m.type), paths[i]);
|
||||
moduleManager.setMetadata(m, metadata[i]);
|
||||
i++;
|
||||
}
|
||||
for (const m of modules) {
|
||||
expect(moduleManager.getMetadata(m), 'module references do not exist').toBeDefined();
|
||||
}
|
||||
});
|
||||
|
||||
//todo add more
|
||||
it('error-handling', () => {
|
||||
const errorHandler = container.get('@sern/errors');
|
||||
const lifetime = errorHandler.keepAlive;
|
||||
for(let i = 0; i< lifetime; i++) {
|
||||
if(i == lifetime-1) {
|
||||
expect(() => errorHandler.updateAlive(new Error("poo"))).toThrowError();
|
||||
for (let i = 0; i < lifetime; i++) {
|
||||
if (i == lifetime - 1) {
|
||||
expect(() => errorHandler.updateAlive(new Error('poo'))).toThrowError();
|
||||
} else {
|
||||
expect(() => errorHandler.updateAlive(new Error("poo"))).not.toThrowError();
|
||||
expect(() => errorHandler.updateAlive(new Error('poo'))).not.toThrowError();
|
||||
}
|
||||
}
|
||||
|
||||
})
|
||||
});
|
||||
//todo add more, spy on every instance?
|
||||
it('logger', () => {
|
||||
|
||||
container.get('@sern/logger').error({ message: 'error' })
|
||||
container.get('@sern/logger').error({ message: 'error' });
|
||||
|
||||
expect(consoleMock).toHaveBeenCalledOnce();
|
||||
expect(consoleMock).toHaveBeenLastCalledWith({ message: 'error' })
|
||||
})
|
||||
|
||||
|
||||
|
||||
})
|
||||
expect(consoleMock).toHaveBeenLastCalledWith({ message: 'error' });
|
||||
});
|
||||
});
|
||||
|
||||
45
test/handlers/dispatchers.test.ts
Normal file
45
test/handlers/dispatchers.test.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
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();
|
||||
});
|
||||
});
|
||||
72
test/handlers/id.test.ts
Normal file
72
test/handlers/id.test.ts
Normal file
@@ -0,0 +1,72 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -1,19 +0,0 @@
|
||||
{
|
||||
"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"]
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
{
|
||||
"extends": "./tsconfig-base.json",
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
"outDir": "dist/cjs",
|
||||
"target": "esnext"
|
||||
}
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
{
|
||||
"extends": "./tsconfig-base.json",
|
||||
"compilerOptions": {
|
||||
"module": "esnext",
|
||||
"outDir": "dist/esm",
|
||||
"target": "esnext"
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,19 @@
|
||||
{
|
||||
"extends": "./tsconfig-esm.json"
|
||||
"compilerOptions": {
|
||||
"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,61 +1,24 @@
|
||||
import { defineConfig } from 'tsup';
|
||||
import { writeFile } from 'fs/promises';
|
||||
import ifdefPlugin from 'esbuild-ifdef';
|
||||
const shared = {
|
||||
entry: ['src/index.ts'],
|
||||
external: ['discord.js', 'iti'],
|
||||
platform: 'node',
|
||||
clean: true,
|
||||
sourcemap: false,
|
||||
sourcemap: true,
|
||||
treeshake: {
|
||||
moduleSideEffects: false,
|
||||
correctVarValueBeforeDeclaration: true, //need this to treeshake esm discord.js empty import
|
||||
annotations: true,
|
||||
},
|
||||
dts: false,
|
||||
};
|
||||
export default defineConfig([
|
||||
{
|
||||
format: 'esm',
|
||||
format: ['esm', 'cjs'],
|
||||
target: 'node18',
|
||||
tsconfig: './tsconfig-esm.json',
|
||||
outDir: './dist/esm',
|
||||
splitting: 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' }));
|
||||
},
|
||||
tsconfig: './tsconfig.json',
|
||||
outDir: './dist',
|
||||
minify: false,
|
||||
dts: true,
|
||||
...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