mirror of
https://github.com/sern-handler/handler
synced 2026-06-26 17:52:14 +00:00
Compare commits
12 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
49e4ba623f | ||
|
|
1b6c413fc2 | ||
|
|
e986535935 | ||
|
|
c30aac476c | ||
|
|
f9622d3788 | ||
|
|
f286a24686 | ||
|
|
166934d749 | ||
|
|
01d79177e8 | ||
|
|
50dac7fb46 | ||
|
|
714d23d401 | ||
|
|
565c4fc35a | ||
|
|
8d18c4b182 |
@@ -7,7 +7,7 @@
|
|||||||
"quotes": [2, "single", { "avoidEscape": true, "allowTemplateLiterals": true }],
|
"quotes": [2, "single", { "avoidEscape": true, "allowTemplateLiterals": true }],
|
||||||
"semi": ["error", "always"],
|
"semi": ["error", "always"],
|
||||||
"@typescript-eslint/no-empty-interface": 0,
|
"@typescript-eslint/no-empty-interface": 0,
|
||||||
"@typescript-eslint/ban-types" : 0,
|
"@typescript-eslint/ban-types": 0,
|
||||||
"@typescript-eslint/no-explicit-any": "off"
|
"@typescript-eslint/no-explicit-any": "off"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
2
.github/workflows/continuous-integration.yml
vendored
2
.github/workflows/continuous-integration.yml
vendored
@@ -17,7 +17,7 @@ jobs:
|
|||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Check out Git repository
|
- name: Check out Git repository
|
||||||
uses: actions/checkout@93ea575cb5d8a053eaa0ac8fa3b40d7e05a33cc8 # tag=v3
|
uses: actions/checkout@755da8c3cf115ac066823e79a1e1788f8940201b # v3
|
||||||
|
|
||||||
- name: Set up Node.js
|
- name: Set up Node.js
|
||||||
uses: actions/setup-node@8c91899e586c5b171469028077307d293428b516 # tag=v3
|
uses: actions/setup-node@8c91899e586c5b171469028077307d293428b516 # tag=v3
|
||||||
|
|||||||
12
CHANGELOG.md
12
CHANGELOG.md
@@ -1,5 +1,17 @@
|
|||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
|
## [2.1.0](https://github.com/sern-handler/handler/compare/v2.0.0...v2.1.0) (2022-12-30)
|
||||||
|
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
* grammar ([c30aac4](https://github.com/sern-handler/handler/commit/c30aac476cdc2094de34f9f67b5805204cc5e4dd))
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* multi parameter events ([e986535](https://github.com/sern-handler/handler/commit/e98653593566ef4635493e0c997bd107a7a3a2a2))
|
||||||
|
|
||||||
## [2.0.0](https://github.com/sern-handler/handler/compare/v1.2.1...v2.0.0) (2022-12-28)
|
## [2.0.0](https://github.com/sern-handler/handler/compare/v1.2.1...v2.0.0) (2022-12-28)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
4935
package-lock.json
generated
Normal file
4935
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
14
package.json
14
package.json
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "@sern/handler",
|
"name": "@sern/handler",
|
||||||
"packageManager": "pnpm@7.18.2",
|
"packageManager": "pnpm@7.18.2",
|
||||||
"version": "2.0.0",
|
"version": "2.1.0",
|
||||||
"description": "A customizable, batteries-included, powerful discord.js framework to automate and streamline bot development.",
|
"description": "A customizable, batteries-included, powerful discord.js framework to automate and streamline bot development.",
|
||||||
"main": "dist/cjs/index.cjs",
|
"main": "dist/cjs/index.cjs",
|
||||||
"module": "dist/esm/index.mjs",
|
"module": "dist/esm/index.mjs",
|
||||||
@@ -39,14 +39,12 @@
|
|||||||
"ts-results-es": "^3.5.0"
|
"ts-results-es": "^3.5.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@typescript-eslint/eslint-plugin": "5.44.0",
|
"@typescript-eslint/eslint-plugin": "5.47.1",
|
||||||
"@typescript-eslint/parser": "5.44.0",
|
"@typescript-eslint/parser": "5.47.1",
|
||||||
"eslint": "8.25.0",
|
"eslint": "8.30.0",
|
||||||
"prettier": "2.7.1",
|
"prettier": "2.8.1",
|
||||||
"tsup": "^6.1.3",
|
"tsup": "^6.1.3",
|
||||||
"typescript": "4.9.4"
|
"typescript": "4.9.4",
|
||||||
},
|
|
||||||
"peerDependencies": {
|
|
||||||
"discord.js": ">= ^14.7.x"
|
"discord.js": ">= ^14.7.x"
|
||||||
},
|
},
|
||||||
"repository": {
|
"repository": {
|
||||||
|
|||||||
4109
pnpm-lock.yaml
generated
4109
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
@@ -6,19 +6,19 @@ export interface ErrorHandling {
|
|||||||
/**
|
/**
|
||||||
* Number of times the process should throw an error until crashing and exiting
|
* Number of times the process should throw an error until crashing and exiting
|
||||||
*/
|
*/
|
||||||
keepAlive : number
|
keepAlive: number;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Utility function to crash
|
* Utility function to crash
|
||||||
* @param error
|
* @param error
|
||||||
*/
|
*/
|
||||||
crash(error : Error) : never
|
crash(error: Error): never;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A function that is called on every crash. Updates keepAlive
|
* A function that is called on every crash. Updates keepAlive
|
||||||
* @param error
|
* @param error
|
||||||
*/
|
*/
|
||||||
updateAlive(error: Error): void
|
updateAlive(error: Error): void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export class DefaultErrorHandling implements ErrorHandling {
|
export class DefaultErrorHandling implements ErrorHandling {
|
||||||
@@ -35,10 +35,12 @@ export function handleError<C>(crashHandler: ErrorHandling, logging?: Logging) {
|
|||||||
return (pload: unknown, caught: Observable<C>) => {
|
return (pload: unknown, caught: Observable<C>) => {
|
||||||
// This is done to fit the ErrorHandling contract
|
// This is done to fit the ErrorHandling contract
|
||||||
const err = pload instanceof Error ? pload : Error(util.format(pload));
|
const err = pload instanceof Error ? pload : Error(util.format(pload));
|
||||||
if(crashHandler.keepAlive == 0) {
|
if (crashHandler.keepAlive == 0) {
|
||||||
useContainerRaw()?.disposeAll().then(() => {
|
useContainerRaw()
|
||||||
logging?.info({ message: 'Cleaning container and crashing' });
|
?.disposeAll()
|
||||||
});
|
.then(() => {
|
||||||
|
logging?.info({ message: 'Cleaning container and crashing' });
|
||||||
|
});
|
||||||
crashHandler.crash(err);
|
crashHandler.crash(err);
|
||||||
}
|
}
|
||||||
//formatted payload
|
//formatted payload
|
||||||
@@ -46,4 +48,4 @@ export function handleError<C>(crashHandler: ErrorHandling, logging?: Logging) {
|
|||||||
crashHandler.updateAlive(err);
|
crashHandler.updateAlive(err);
|
||||||
return caught;
|
return caught;
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,3 @@
|
|||||||
export { ErrorHandling, DefaultErrorHandling } from './errorHandling';
|
export { ErrorHandling, DefaultErrorHandling } from './errorHandling';
|
||||||
export { Logging, DefaultLogging } from './logging';
|
export { Logging, DefaultLogging } from './logging';
|
||||||
export { ModuleManager, DefaultModuleManager } from './moduleManager';
|
export { ModuleManager, DefaultModuleManager } from './moduleManager';
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
import type { LogPayload } from '../../types/handler';
|
import type { LogPayload } from '../../types/handler';
|
||||||
|
|
||||||
export interface Logging<T = unknown> {
|
export interface Logging<T = unknown> {
|
||||||
error(payload : LogPayload<T>) : void;
|
error(payload: LogPayload<T>): void;
|
||||||
warning(payload : LogPayload<T>) : void;
|
warning(payload: LogPayload<T>): void;
|
||||||
info(payload : LogPayload<T>) : void
|
info(payload: LogPayload<T>): void;
|
||||||
debug(payload : LogPayload<T>) : void
|
debug(payload: LogPayload<T>): void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export class DefaultLogging implements Logging {
|
export class DefaultLogging implements Logging {
|
||||||
@@ -24,5 +24,4 @@ export class DefaultLogging implements Logging {
|
|||||||
warning(payload: LogPayload): void {
|
warning(payload: LogPayload): void {
|
||||||
console.warn(`WARN: ${this.date().toISOString()} -> ${payload.message}`);
|
console.warn(`WARN: ${this.date().toISOString()} -> ${payload.message}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,10 +2,11 @@ import type { CommandModuleDefs } from '../../types/module';
|
|||||||
import type { CommandType } from '../structures/enums';
|
import type { CommandType } from '../structures/enums';
|
||||||
import type { ModuleStore } from '../structures/moduleStore';
|
import type { ModuleStore } from '../structures/moduleStore';
|
||||||
|
|
||||||
|
|
||||||
export interface ModuleManager {
|
export interface ModuleManager {
|
||||||
get<T extends CommandType>(strat : (ms: ModuleStore) => CommandModuleDefs[T] | undefined) : CommandModuleDefs[T] | undefined
|
get<T extends CommandType>(
|
||||||
set(strat: (ms: ModuleStore) => void) : void
|
strat: (ms: ModuleStore) => CommandModuleDefs[T] | undefined,
|
||||||
|
): CommandModuleDefs[T] | undefined;
|
||||||
|
set(strat: (ms: ModuleStore) => void): void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export class DefaultModuleManager implements ModuleManager {
|
export class DefaultModuleManager implements ModuleManager {
|
||||||
|
|||||||
@@ -1,3 +1 @@
|
|||||||
export {
|
export { useContainer } from './provider';
|
||||||
useContainer
|
|
||||||
} from './provider';
|
|
||||||
|
|||||||
@@ -10,62 +10,69 @@ import { ModuleStore } from '../structures/moduleStore';
|
|||||||
import { Ok, Result } from 'ts-results-es';
|
import { Ok, Result } from 'ts-results-es';
|
||||||
import { DefaultLogging } from '../contracts';
|
import { DefaultLogging } from '../contracts';
|
||||||
|
|
||||||
export const containerSubject = new BehaviorSubject<Container<Dependencies, Partial<Dependencies>> | null>(null);
|
export const containerSubject = new BehaviorSubject<Container<
|
||||||
export function composeRoot<T extends Dependencies>(root: Container<Partial<T>, Partial<Dependencies>>, exclusion: Set<keyof Dependencies>) {
|
Dependencies,
|
||||||
|
Partial<Dependencies>
|
||||||
|
> | null>(null);
|
||||||
|
export function composeRoot<T extends Dependencies>(
|
||||||
|
root: Container<Partial<T>, Partial<Dependencies>>,
|
||||||
|
exclusion: Set<keyof Dependencies>,
|
||||||
|
) {
|
||||||
const client = root.get('@sern/client');
|
const client = root.get('@sern/client');
|
||||||
assert.ok(client !== undefined, SernError.MissingRequired);
|
assert.ok(client !== undefined, SernError.MissingRequired);
|
||||||
//A utility function checking if a dependency has been declared excluded
|
//A utility function checking if a dependency has been declared excluded
|
||||||
const excluded = (key: keyof Dependencies) => exclusion.has(key);
|
const excluded = (key: keyof Dependencies) => exclusion.has(key);
|
||||||
//Wraps a fetch to the container in a Result, deferring the action
|
//Wraps a fetch to the container in a Result, deferring the action
|
||||||
const get = <T>(key : keyof Dependencies) => Result.wrap(() => root.get(key) as T);
|
const get = <T>(key: keyof Dependencies) => Result.wrap(() => root.get(key) as T);
|
||||||
const getOr = (key: keyof Dependencies, elseAction: () => unknown) => {
|
const getOr = (key: keyof Dependencies, elseAction: () => unknown) => {
|
||||||
//Gets dependency but if an Err, map to a function that upserts.
|
//Gets dependency but if an Err, map to a function that upserts.
|
||||||
const dep = get(key).mapErr(() => elseAction);
|
const dep = get(key).mapErr(() => elseAction);
|
||||||
if(dep.err) {
|
if (dep.err) {
|
||||||
//Defers upsert until final check here
|
//Defers upsert until final check here
|
||||||
return dep.val();
|
return dep.val();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
const xGetOr = (key: keyof Dependencies, action: () => unknown) => {
|
const xGetOr = (key: keyof Dependencies, action: () => unknown) => {
|
||||||
if(excluded(key)) {
|
if (excluded(key)) {
|
||||||
get(key) //if dev created a dependency but excluded, deletes on root composition
|
get(key) //if dev created a dependency but excluded, deletes on root composition
|
||||||
.andThen(() => Ok(root.delete(key)))
|
.andThen(() => Ok(root.delete(key)))
|
||||||
.unwrapOr(ok());
|
.unwrapOr(ok());
|
||||||
} else {
|
} else {
|
||||||
getOr(key, action);
|
getOr(key, action);
|
||||||
}
|
}
|
||||||
|
|
||||||
};
|
};
|
||||||
xGetOr('@sern/emitter', () => root.upsert({
|
xGetOr('@sern/emitter', () =>
|
||||||
'@sern/emitter' : _const(new SernEmitter())
|
root.upsert({
|
||||||
})
|
'@sern/emitter': _const(new SernEmitter()),
|
||||||
|
}),
|
||||||
);
|
);
|
||||||
//An "optional" dependency
|
//An "optional" dependency
|
||||||
xGetOr('@sern/logger', () => {
|
xGetOr('@sern/logger', () => {
|
||||||
root.upsert({
|
root.upsert({
|
||||||
'@sern/logger' : _const(new DefaultLogging())
|
'@sern/logger': _const(new DefaultLogging()),
|
||||||
});
|
});
|
||||||
}
|
});
|
||||||
|
xGetOr('@sern/store', () =>
|
||||||
|
root.upsert({
|
||||||
|
'@sern/store': _const(new ModuleStore()),
|
||||||
|
}),
|
||||||
);
|
);
|
||||||
xGetOr('@sern/store', () => root.upsert({
|
xGetOr('@sern/modules', () =>
|
||||||
'@sern/store' : _const(new ModuleStore())
|
root.upsert(ctx => ({
|
||||||
})
|
'@sern/modules': _const(new DefaultModuleManager(ctx['@sern/store'] as ModuleStore)),
|
||||||
|
})),
|
||||||
);
|
);
|
||||||
xGetOr('@sern/modules', () => root.upsert((ctx) => ({
|
xGetOr('@sern/errors', () =>
|
||||||
'@sern/modules' : _const(new DefaultModuleManager(ctx['@sern/store'] as ModuleStore))
|
root.upsert({
|
||||||
}))
|
'@sern/errors': _const(new DefaultErrorHandling()),
|
||||||
);
|
}),
|
||||||
xGetOr('@sern/errors', () => root.upsert({
|
|
||||||
'@sern/errors': _const(new DefaultErrorHandling())
|
|
||||||
})
|
|
||||||
);
|
);
|
||||||
//If logger exists, log info, else do nothing.
|
//If logger exists, log info, else do nothing.
|
||||||
get<Logging>('@sern/logger')
|
get<Logging>('@sern/logger')
|
||||||
.map((logger => logger.info({ message: 'All dependencies loaded successfully' })))
|
.map(logger => logger.info({ message: 'All dependencies loaded successfully' }))
|
||||||
.unwrapOr(ok());
|
.unwrapOr(ok());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
export function useContainer<T extends Dependencies>() {
|
export function useContainer<T extends Dependencies>() {
|
||||||
const container = containerSubject.getValue()! as unknown as Container<T, {}>;
|
const container = containerSubject.getValue()! as unknown as Container<T, {}>;
|
||||||
assert.ok(container !== null, 'useContainer was called before Sern#init');
|
assert.ok(container !== null, 'useContainer was called before Sern#init');
|
||||||
@@ -80,4 +87,4 @@ export function useContainer<T extends Dependencies>() {
|
|||||||
*/
|
*/
|
||||||
export function useContainerRaw() {
|
export function useContainerRaw() {
|
||||||
return containerSubject.getValue();
|
return containerSubject.getValue();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,15 +15,24 @@ import { SernError } from '../structures/errors';
|
|||||||
import treeSearch from '../utilities/treeSearch';
|
import treeSearch from '../utilities/treeSearch';
|
||||||
import type {
|
import type {
|
||||||
BothCommand,
|
BothCommand,
|
||||||
ButtonCommand, ContextMenuMsg,
|
ButtonCommand,
|
||||||
|
ContextMenuMsg,
|
||||||
ContextMenuUser,
|
ContextMenuUser,
|
||||||
ModalSubmitCommand,
|
ModalSubmitCommand,
|
||||||
StringSelectCommand,
|
StringSelectCommand,
|
||||||
SlashCommand, UserSelectCommand, ChannelSelectCommand, MentionableSelectCommand, RoleSelectCommand,
|
SlashCommand,
|
||||||
|
UserSelectCommand,
|
||||||
|
ChannelSelectCommand,
|
||||||
|
MentionableSelectCommand,
|
||||||
|
RoleSelectCommand,
|
||||||
} from '../../types/module';
|
} from '../../types/module';
|
||||||
import type SernEmitter from '../sernEmitter';
|
import type SernEmitter from '../sernEmitter';
|
||||||
import { EventEmitter } from 'events';
|
import { EventEmitter } from 'events';
|
||||||
import type { DiscordEventCommand, ExternalEventCommand, SernEventCommand } from '../structures/events';
|
import type {
|
||||||
|
DiscordEventCommand,
|
||||||
|
ExternalEventCommand,
|
||||||
|
SernEventCommand,
|
||||||
|
} from '../structures/events';
|
||||||
import * as assert from 'assert';
|
import * as assert from 'assert';
|
||||||
import { reducePlugins } from '../utilities/functions';
|
import { reducePlugins } from '../utilities/functions';
|
||||||
import { concatMap, from, fromEvent, map, of } from 'rxjs';
|
import { concatMap, from, fromEvent, map, of } from 'rxjs';
|
||||||
@@ -85,7 +94,14 @@ export function buttonCommandDispatcher(interaction: ButtonInteraction) {
|
|||||||
|
|
||||||
export function selectMenuCommandDispatcher(interaction: MessageComponentInteraction) {
|
export function selectMenuCommandDispatcher(interaction: MessageComponentInteraction) {
|
||||||
//safe casts because command type runtime check
|
//safe casts because command type runtime check
|
||||||
return (mod: StringSelectCommand | UserSelectCommand | ChannelSelectCommand | MentionableSelectCommand | RoleSelectCommand) => ({
|
return (
|
||||||
|
mod:
|
||||||
|
| StringSelectCommand
|
||||||
|
| UserSelectCommand
|
||||||
|
| ChannelSelectCommand
|
||||||
|
| MentionableSelectCommand
|
||||||
|
| RoleSelectCommand,
|
||||||
|
) => ({
|
||||||
mod,
|
mod,
|
||||||
execute: () => mod.execute(interaction as never),
|
execute: () => mod.execute(interaction as never),
|
||||||
eventPluginRes: arrAsync(
|
eventPluginRes: arrAsync(
|
||||||
@@ -115,19 +131,27 @@ export function ctxMenuMsgDispatcher(interaction: MessageContextMenuCommandInter
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function sernEmitterDispatcher(e: SernEmitter) {
|
export function sernEmitterDispatcher(e: SernEmitter) {
|
||||||
return(cmd: SernEventCommand & { name: string }) => ({
|
return (cmd: SernEventCommand & { name: string }) => ({
|
||||||
source: e,
|
source: e,
|
||||||
cmd,
|
cmd,
|
||||||
execute: fromEvent(e, cmd.name)
|
execute: fromEvent(e, cmd.name).pipe(
|
||||||
.pipe( map( event => ({
|
map(event => ({
|
||||||
event,
|
event,
|
||||||
executeEvent: of(event).pipe(concatMap(event =>
|
executeEvent: of(event).pipe(
|
||||||
reducePlugins(from(
|
concatMap(event =>
|
||||||
arrAsync(
|
reducePlugins(
|
||||||
cmd.onEvent.map(plug => plug.execute([event as Payload], controller))
|
from(
|
||||||
))
|
arrAsync(
|
||||||
)))
|
cmd.onEvent.map(plug =>
|
||||||
})))
|
plug.execute([event as Payload], controller),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
})),
|
||||||
|
),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -135,36 +159,51 @@ export function discordEventDispatcher(e: EventEmitter) {
|
|||||||
return (cmd: DiscordEventCommand & { name: string }) => ({
|
return (cmd: DiscordEventCommand & { name: string }) => ({
|
||||||
source: e,
|
source: e,
|
||||||
cmd,
|
cmd,
|
||||||
execute: fromEvent(e, cmd.name)
|
execute: fromEvent(e, cmd.name).pipe(
|
||||||
.pipe( map( event => ({
|
map(event => ({
|
||||||
event,
|
event,
|
||||||
executeEvent: of(event).pipe(concatMap( event =>
|
executeEvent: of(event).pipe(
|
||||||
reducePlugins(from(
|
concatMap(event =>
|
||||||
arrAsync(
|
reducePlugins(
|
||||||
// god forbid I use any!!!
|
from(
|
||||||
cmd.onEvent.map(plug => plug.execute([event as any], controller))
|
arrAsync(
|
||||||
))
|
// god forbid I use any!!!
|
||||||
)))
|
cmd.onEvent.map(plug =>
|
||||||
})))
|
plug.execute([event as any], controller),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
})),
|
||||||
|
),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function externalEventDispatcher(e: (e:ExternalEventCommand) => unknown) {
|
export function externalEventDispatcher(e: (e: ExternalEventCommand) => unknown) {
|
||||||
return (cmd: ExternalEventCommand & { name: string}) => {
|
return (cmd: ExternalEventCommand & { name: string }) => {
|
||||||
const external = e(cmd);
|
const external = e(cmd);
|
||||||
assert.ok(external instanceof EventEmitter, `${e} is not an EventEmitter`);
|
assert.ok(external instanceof EventEmitter, `${e} is not an EventEmitter`);
|
||||||
return {
|
return {
|
||||||
source: external,
|
source: external,
|
||||||
cmd,
|
cmd,
|
||||||
execute: fromEvent(external, cmd.name)
|
execute: fromEvent(external, cmd.name).pipe(
|
||||||
.pipe(map(event => ({
|
map(event => ({
|
||||||
event,
|
event,
|
||||||
executeEvent : of(event).pipe(concatMap(event =>
|
executeEvent: of(event).pipe(
|
||||||
reducePlugins(from(arrAsync(
|
concatMap(event =>
|
||||||
cmd.onEvent.map(plug => plug.execute([event], controller))
|
reducePlugins(
|
||||||
)))
|
from(
|
||||||
)),
|
arrAsync(
|
||||||
})))
|
cmd.onEvent.map(plug => plug.execute([event], controller)),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
})),
|
||||||
|
),
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,14 +13,14 @@ export abstract class EventsHandler<T> {
|
|||||||
protected logger?: Logging;
|
protected logger?: Logging;
|
||||||
protected modules: ModuleManager;
|
protected modules: ModuleManager;
|
||||||
protected constructor({ containerConfig }: Wrapper) {
|
protected constructor({ containerConfig }: Wrapper) {
|
||||||
const [
|
const [client, emitter, crash, modules, logger] = containerConfig.get(
|
||||||
client,
|
'@sern/client',
|
||||||
emitter,
|
'@sern/emitter',
|
||||||
crash,
|
'@sern/errors',
|
||||||
modules,
|
'@sern/modules',
|
||||||
logger,
|
'@sern/logger',
|
||||||
] = containerConfig.get('@sern/client', '@sern/emitter', '@sern/errors', '@sern/modules', '@sern/logger');
|
);
|
||||||
this.logger = logger as Logging|undefined;
|
this.logger = logger as Logging | undefined;
|
||||||
this.modules = modules as ModuleManager;
|
this.modules = modules as ModuleManager;
|
||||||
this.client = client as EventEmitter;
|
this.client = client as EventEmitter;
|
||||||
this.emitter = emitter as SernEmitter;
|
this.emitter = emitter as SernEmitter;
|
||||||
|
|||||||
@@ -38,8 +38,9 @@ export default class InteractionHandler extends EventsHandler<{
|
|||||||
this.payloadSubject
|
this.payloadSubject
|
||||||
.pipe(
|
.pipe(
|
||||||
map(this.processModules),
|
map(this.processModules),
|
||||||
concatMap(({ mod, execute, eventPluginRes }) =>
|
concatMap(
|
||||||
from(eventPluginRes).pipe(map(res => ({ mod, res, execute }))) //resolve all the Results from event plugins
|
({ mod, execute, eventPluginRes }) =>
|
||||||
|
from(eventPluginRes).pipe(map(res => ({ mod, res, execute }))), //resolve all the Results from event plugins
|
||||||
),
|
),
|
||||||
concatMap(payload => executeModule(wrapper, payload)),
|
concatMap(payload => executeModule(wrapper, payload)),
|
||||||
catchError(handleError(this.crashHandler, this.logger)),
|
catchError(handleError(this.crashHandler, this.logger)),
|
||||||
@@ -48,23 +49,25 @@ export default class InteractionHandler extends EventsHandler<{
|
|||||||
}
|
}
|
||||||
|
|
||||||
override init() {
|
override init() {
|
||||||
const get = (cb: (ms: ModuleStore) => CommandModule|undefined) => {
|
const get = (cb: (ms: ModuleStore) => CommandModule | undefined) => {
|
||||||
return this.modules.get(cb);
|
return this.modules.get(cb);
|
||||||
};
|
};
|
||||||
this.discordEvent.subscribe({
|
this.discordEvent.subscribe({
|
||||||
next: event => {
|
next: event => {
|
||||||
if (event.isMessageComponent()) {
|
if (event.isMessageComponent()) {
|
||||||
const mod = get(ms =>
|
const mod = get(ms =>
|
||||||
ms.InteractionHandlers[event.componentType].get(event.customId));
|
ms.InteractionHandlers[event.componentType].get(event.customId),
|
||||||
|
);
|
||||||
this.setState({ event, mod });
|
this.setState({ event, mod });
|
||||||
} else if (event.isCommand() || event.isAutocomplete()) {
|
} else if (event.isCommand() || event.isAutocomplete()) {
|
||||||
const mod = get(ms =>
|
const mod = get(
|
||||||
ms.ApplicationCommands[event.commandType].get(event.commandName) ??
|
ms =>
|
||||||
ms.BothCommands.get(event.commandName)
|
ms.ApplicationCommands[event.commandType].get(event.commandName) ??
|
||||||
|
ms.BothCommands.get(event.commandName),
|
||||||
);
|
);
|
||||||
this.setState({ event, mod });
|
this.setState({ event, mod });
|
||||||
} else if (event.isModalSubmit()) {
|
} else if (event.isModalSubmit()) {
|
||||||
const mod = get((ms) => ms.InteractionHandlers[5].get(event.customId));
|
const mod = get(ms => ms.InteractionHandlers[5].get(event.customId));
|
||||||
this.setState({ event, mod });
|
this.setState({ event, mod });
|
||||||
} else {
|
} else {
|
||||||
throw Error('This interaction is not supported yet');
|
throw Error('This interaction is not supported yet');
|
||||||
@@ -78,7 +81,10 @@ export default class InteractionHandler extends EventsHandler<{
|
|||||||
|
|
||||||
protected setState(state: { event: Interaction; mod: CommandModule | undefined }): void {
|
protected setState(state: { event: Interaction; mod: CommandModule | undefined }): void {
|
||||||
if (state.mod === undefined) {
|
if (state.mod === undefined) {
|
||||||
this.emitter.emit('warning',{ type: PayloadType.Warning, reason: 'Found no module for this interaction' });
|
this.emitter.emit('warning', {
|
||||||
|
type: PayloadType.Warning,
|
||||||
|
reason: 'Found no module for this interaction',
|
||||||
|
});
|
||||||
} else {
|
} else {
|
||||||
//if statement above checks already, safe cast
|
//if statement above checks already, safe cast
|
||||||
this.payloadSubject.next(state as { event: Interaction; mod: CommandModule });
|
this.payloadSubject.next(state as { event: Interaction; mod: CommandModule });
|
||||||
@@ -97,13 +103,15 @@ export default class InteractionHandler extends EventsHandler<{
|
|||||||
)
|
)
|
||||||
.with({ type: CommandType.Button }, buttonCommandDispatcher(event as ButtonInteraction))
|
.with({ type: CommandType.Button }, buttonCommandDispatcher(event as ButtonInteraction))
|
||||||
.with(
|
.with(
|
||||||
{ type: P.union(
|
{
|
||||||
|
type: P.union(
|
||||||
CommandType.RoleSelect,
|
CommandType.RoleSelect,
|
||||||
CommandType.StringSelect,
|
CommandType.StringSelect,
|
||||||
CommandType.UserSelect,
|
CommandType.UserSelect,
|
||||||
CommandType.MentionableSelect,
|
CommandType.MentionableSelect,
|
||||||
CommandType.ChannelSelect
|
CommandType.ChannelSelect,
|
||||||
) },
|
),
|
||||||
|
},
|
||||||
selectMenuCommandDispatcher(event as MessageComponentInteraction),
|
selectMenuCommandDispatcher(event as MessageComponentInteraction),
|
||||||
)
|
)
|
||||||
.with(
|
.with(
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ export default class MessageHandler extends EventsHandler<{
|
|||||||
.pipe(
|
.pipe(
|
||||||
switchMap(({ mod, ctx, args }) => {
|
switchMap(({ mod, ctx, args }) => {
|
||||||
const res = arrAsync(
|
const res = arrAsync(
|
||||||
mod.onEvent.map(ep => ep.execute([ctx, args], controller)),
|
mod.onEvent.map(ep => ep.execute([ctx, args], controller)),
|
||||||
);
|
);
|
||||||
const execute = () => mod.execute(ctx, args);
|
const execute = () => mod.execute(ctx, args);
|
||||||
//resolves the promise and re-emits it back into source
|
//resolves the promise and re-emits it back into source
|
||||||
@@ -42,7 +42,7 @@ export default class MessageHandler extends EventsHandler<{
|
|||||||
if (this.wrapper.defaultPrefix === undefined) return; //for now, just ignore if prefix doesn't exist
|
if (this.wrapper.defaultPrefix === undefined) return; //for now, just ignore if prefix doesn't exist
|
||||||
const { defaultPrefix } = this.wrapper;
|
const { defaultPrefix } = this.wrapper;
|
||||||
const get = (cb: (ms: ModuleStore) => CommandModule | undefined) => {
|
const get = (cb: (ms: ModuleStore) => CommandModule | undefined) => {
|
||||||
return this.modules.get(cb);
|
return this.modules.get(cb);
|
||||||
};
|
};
|
||||||
this.discordEvent
|
this.discordEvent
|
||||||
.pipe(
|
.pipe(
|
||||||
@@ -52,10 +52,7 @@ export default class MessageHandler extends EventsHandler<{
|
|||||||
return {
|
return {
|
||||||
ctx: Context.wrap(message),
|
ctx: Context.wrap(message),
|
||||||
args: <['text', string[]]>['text', rest],
|
args: <['text', string[]]>['text', rest],
|
||||||
mod: get(ms =>
|
mod: get(ms => ms.TextCommands.get(prefix) ?? ms.BothCommands.get(prefix)),
|
||||||
ms.TextCommands.get(prefix) ??
|
|
||||||
ms.BothCommands.get(prefix)
|
|
||||||
),
|
|
||||||
};
|
};
|
||||||
}),
|
}),
|
||||||
concatMap(element =>
|
concatMap(element =>
|
||||||
@@ -67,8 +64,7 @@ export default class MessageHandler extends EventsHandler<{
|
|||||||
)
|
)
|
||||||
.subscribe({
|
.subscribe({
|
||||||
next: value => this.setState(value),
|
next: value => this.setState(value),
|
||||||
error: reason =>
|
error: reason => this.emitter.emit('error', { type: PayloadType.Failure, reason }),
|
||||||
this.emitter.emit('error', { type: PayloadType.Failure, reason }),
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -85,7 +85,9 @@ export function executeModule(
|
|||||||
) {
|
) {
|
||||||
const emitter = wrapper.containerConfig.get('@sern/emitter')[0] as SernEmitter;
|
const emitter = wrapper.containerConfig.get('@sern/emitter')[0] as SernEmitter;
|
||||||
if (payload.res.every(el => el.ok)) {
|
if (payload.res.every(el => el.ok)) {
|
||||||
const executeFn = Result.wrapAsync<unknown, Error | string>(() => Promise.resolve(payload.execute()));
|
const executeFn = Result.wrapAsync<unknown, Error | string>(() =>
|
||||||
|
Promise.resolve(payload.execute()),
|
||||||
|
);
|
||||||
return from(executeFn).pipe(
|
return from(executeFn).pipe(
|
||||||
concatMap(res => {
|
concatMap(res => {
|
||||||
if (res.err) {
|
if (res.err) {
|
||||||
@@ -115,7 +117,10 @@ export function executeModule(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function resolvePlugins({ mod, cmdPluginRes }: {
|
export function resolvePlugins({
|
||||||
|
mod,
|
||||||
|
cmdPluginRes,
|
||||||
|
}: {
|
||||||
mod: DefinedCommandModule | DefinedEventModule;
|
mod: DefinedCommandModule | DefinedEventModule;
|
||||||
cmdPluginRes: {
|
cmdPluginRes: {
|
||||||
execute: Awaitable<Result<void, void>>;
|
execute: Awaitable<Result<void, void>>;
|
||||||
@@ -137,7 +142,10 @@ export function resolvePlugins({ mod, cmdPluginRes }: {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function processPlugins(payload: { mod: DefinedCommandModule | DefinedEventModule; absPath: string }) {
|
export function processPlugins(payload: {
|
||||||
|
mod: DefinedCommandModule | DefinedEventModule;
|
||||||
|
absPath: string;
|
||||||
|
}) {
|
||||||
const cmdPluginRes = processCommandPlugins(payload);
|
const cmdPluginRes = processCommandPlugins(payload);
|
||||||
return of({ mod: payload.mod, cmdPluginRes });
|
return of({ mod: payload.mod, cmdPluginRes });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -37,10 +37,8 @@ export default class ReadyHandler extends EventsHandler<{
|
|||||||
);
|
);
|
||||||
this.init();
|
this.init();
|
||||||
this.payloadSubject
|
this.payloadSubject
|
||||||
.pipe(
|
.pipe(concatMap(processPlugins), concatMap(resolvePlugins))
|
||||||
concatMap(processPlugins),
|
.subscribe(payload => {
|
||||||
concatMap(resolvePlugins),
|
|
||||||
).subscribe(payload => {
|
|
||||||
const allPluginsSuccessful = payload.pluginRes.every(({ execute }) => execute.ok);
|
const allPluginsSuccessful = payload.pluginRes.every(({ execute }) => execute.ok);
|
||||||
if (allPluginsSuccessful) {
|
if (allPluginsSuccessful) {
|
||||||
const res = registerModule(this.modules, payload.mod);
|
const res = registerModule(this.modules, payload.mod);
|
||||||
@@ -85,7 +83,10 @@ export default class ReadyHandler extends EventsHandler<{
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function registerModule(manager: ModuleManager, mod: DefinedCommandModule | DefinedEventModule): Result<void, void> {
|
function registerModule(
|
||||||
|
manager: ModuleManager,
|
||||||
|
mod: DefinedCommandModule | DefinedEventModule,
|
||||||
|
): Result<void, void> {
|
||||||
const name = mod.name;
|
const name = mod.name;
|
||||||
const insert = (cb: (ms: ModuleStore) => void) => {
|
const insert = (cb: (ms: ModuleStore) => void) => {
|
||||||
const set = Result.wrap(_const(manager.set(cb)));
|
const set = Result.wrap(_const(manager.set(cb)));
|
||||||
@@ -97,38 +98,36 @@ function registerModule(manager: ModuleManager, mod: DefinedCommandModule | Defi
|
|||||||
return insert(ms => ms.TextCommands.set(name, mod));
|
return insert(ms => ms.TextCommands.set(name, mod));
|
||||||
})
|
})
|
||||||
.with({ type: CommandType.Slash }, mod =>
|
.with({ type: CommandType.Slash }, mod =>
|
||||||
insert(ms => ms.ApplicationCommands[ApplicationCommandType.ChatInput].set(name, mod))
|
insert(ms => ms.ApplicationCommands[ApplicationCommandType.ChatInput].set(name, mod)),
|
||||||
)
|
)
|
||||||
.with({ type: CommandType.Both }, mod => {
|
.with({ type: CommandType.Both }, mod => {
|
||||||
mod.alias?.forEach(a => insert(ms => ms.TextCommands.set(a, mod)));
|
mod.alias?.forEach(a => insert(ms => ms.TextCommands.set(a, mod)));
|
||||||
return insert( ms => ms.BothCommands.set(name, mod));
|
return insert(ms => ms.BothCommands.set(name, mod));
|
||||||
})
|
})
|
||||||
.with({ type: CommandType.CtxUser }, mod =>
|
.with({ type: CommandType.CtxUser }, mod =>
|
||||||
insert(ms => ms.ApplicationCommands[ApplicationCommandType.User].set(name, mod))
|
insert(ms => ms.ApplicationCommands[ApplicationCommandType.User].set(name, mod)),
|
||||||
)
|
)
|
||||||
.with({ type: CommandType.CtxMsg }, mod =>
|
.with({ type: CommandType.CtxMsg }, mod =>
|
||||||
insert(ms => ms.ApplicationCommands[ApplicationCommandType.Message].set(name, mod))
|
insert(ms => ms.ApplicationCommands[ApplicationCommandType.Message].set(name, mod)),
|
||||||
)
|
)
|
||||||
.with({ type: CommandType.Button }, mod =>
|
.with({ type: CommandType.Button }, mod =>
|
||||||
insert(ms => ms.InteractionHandlers[ComponentType.Button].set(name, mod))
|
insert(ms => ms.InteractionHandlers[ComponentType.Button].set(name, mod)),
|
||||||
)
|
)
|
||||||
.with({ type: CommandType.StringSelect }, mod =>
|
.with({ type: CommandType.StringSelect }, mod =>
|
||||||
insert(ms => ms.InteractionHandlers[ComponentType.StringSelect].set(name, mod))
|
insert(ms => ms.InteractionHandlers[ComponentType.StringSelect].set(name, mod)),
|
||||||
)
|
)
|
||||||
.with( { type: CommandType.MentionableSelect }, mod =>
|
.with({ type: CommandType.MentionableSelect }, mod =>
|
||||||
insert (ms => ms.InteractionHandlers[ComponentType.MentionableSelect].set(name, mod))
|
insert(ms => ms.InteractionHandlers[ComponentType.MentionableSelect].set(name, mod)),
|
||||||
)
|
)
|
||||||
.with( { type: CommandType.ChannelSelect }, mod =>
|
.with({ type: CommandType.ChannelSelect }, mod =>
|
||||||
insert ( ms => ms.InteractionHandlers[ComponentType.ChannelSelect].set(name, mod))
|
insert(ms => ms.InteractionHandlers[ComponentType.ChannelSelect].set(name, mod)),
|
||||||
)
|
)
|
||||||
.with( { type: CommandType.UserSelect }, mod =>
|
.with({ type: CommandType.UserSelect }, mod =>
|
||||||
insert ( ms => ms.InteractionHandlers[ComponentType.UserSelect].set(name, mod))
|
insert(ms => ms.InteractionHandlers[ComponentType.UserSelect].set(name, mod)),
|
||||||
)
|
)
|
||||||
.with( { type: CommandType.RoleSelect}, mod =>
|
.with({ type: CommandType.RoleSelect }, mod =>
|
||||||
insert ( ms => ms.InteractionHandlers[ComponentType.RoleSelect].set(name, mod))
|
insert(ms => ms.InteractionHandlers[ComponentType.RoleSelect].set(name, mod)),
|
||||||
)
|
|
||||||
.with({ type: CommandType.Modal }, mod =>
|
|
||||||
insert(ms => ms.ModalSubmit.set(name, mod))
|
|
||||||
)
|
)
|
||||||
|
.with({ type: CommandType.Modal }, mod => insert(ms => ms.ModalSubmit.set(name, mod)))
|
||||||
.otherwise(err);
|
.otherwise(err);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,7 +11,11 @@ import type { EventEmitter } from 'events';
|
|||||||
import type SernEmitter from '../sernEmitter';
|
import type SernEmitter from '../sernEmitter';
|
||||||
import { nameOrFilename, reducePlugins } from '../utilities/functions';
|
import { nameOrFilename, reducePlugins } from '../utilities/functions';
|
||||||
import { match } from 'ts-pattern';
|
import { match } from 'ts-pattern';
|
||||||
import { discordEventDispatcher, externalEventDispatcher, sernEmitterDispatcher } from './dispatchers';
|
import {
|
||||||
|
discordEventDispatcher,
|
||||||
|
externalEventDispatcher,
|
||||||
|
sernEmitterDispatcher,
|
||||||
|
} from './dispatchers';
|
||||||
import type { ErrorHandling, Logging } from '../contracts';
|
import type { ErrorHandling, Logging } from '../contracts';
|
||||||
import { SernError } from '../structures/errors';
|
import { SernError } from '../structures/errors';
|
||||||
import { handleError } from '../contracts/errorHandling';
|
import { handleError } from '../contracts/errorHandling';
|
||||||
@@ -22,9 +26,12 @@ import type { Result } from 'ts-results-es';
|
|||||||
* Utility function to process command plugins for all Modules
|
* Utility function to process command plugins for all Modules
|
||||||
* @param payload
|
* @param payload
|
||||||
*/
|
*/
|
||||||
export function processCommandPlugins<T extends DefinedCommandModule | DefinedEventModule>(
|
export function processCommandPlugins<
|
||||||
payload: { mod: T; absPath: string },
|
T extends DefinedCommandModule | DefinedEventModule,
|
||||||
): {type: PluginType.Command, execute: Awaitable<Result<void,void>>}[] {
|
>(payload: {
|
||||||
|
mod: T;
|
||||||
|
absPath: string;
|
||||||
|
}): { type: PluginType.Command; execute: Awaitable<Result<void, void>> }[] {
|
||||||
return payload.mod.plugins.map(plug => ({
|
return payload.mod.plugins.map(plug => ({
|
||||||
type: plug.type,
|
type: plug.type,
|
||||||
execute: plug.execute(payload as any, controller),
|
execute: plug.execute(payload as any, controller),
|
||||||
@@ -32,77 +39,86 @@ export function processCommandPlugins<T extends DefinedCommandModule | DefinedEv
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function processEvents({ containerConfig, events }: Wrapper) {
|
export function processEvents({ containerConfig, events }: Wrapper) {
|
||||||
const [
|
const [client, error, sernEmitter, logging] = containerConfig.get(
|
||||||
client,
|
'@sern/client',
|
||||||
error,
|
'@sern/errors',
|
||||||
sernEmitter,
|
'@sern/emitter',
|
||||||
logging
|
'@sern/logger',
|
||||||
] = containerConfig.get('@sern/client', '@sern/errors', '@sern/emitter', '@sern/logger') as [EventEmitter, ErrorHandling, SernEmitter, Logging?];
|
) as [EventEmitter, ErrorHandling, SernEmitter, Logging?];
|
||||||
const lazy = (k: string) => containerConfig.get(k as keyof Dependencies)[0];
|
const lazy = (k: string) => containerConfig.get(k as keyof Dependencies)[0];
|
||||||
const eventStream$ = eventObservable$(events!, sernEmitter);
|
const eventStream$ = eventObservable$(events!, sernEmitter);
|
||||||
const emitSuccess$ = (mod: AnyModule) =>
|
const emitSuccess$ = (mod: AnyModule) =>
|
||||||
of({ type: PayloadType.Failure, module: mod, reason: SernError.PluginFailure })
|
of({ type: PayloadType.Failure, module: mod, reason: SernError.PluginFailure }).pipe(
|
||||||
.pipe(tap( it => sernEmitter.emit('module.register', it)));
|
tap(it => sernEmitter.emit('module.register', it)),
|
||||||
|
);
|
||||||
const emitFailure$ = (mod: AnyModule) =>
|
const emitFailure$ = (mod: AnyModule) =>
|
||||||
of({ type: PayloadType.Success, module: mod, } as const)
|
of({ type: PayloadType.Success, module: mod } as const).pipe(
|
||||||
.pipe(tap(it => sernEmitter.emit('module.register', it)));
|
tap(it => sernEmitter.emit('module.register', it)),
|
||||||
|
);
|
||||||
const eventCreation$ = eventStream$.pipe(
|
const eventCreation$ = eventStream$.pipe(
|
||||||
map(({ mod, absPath }) => ({
|
map(({ mod, absPath }) => ({
|
||||||
mod : {
|
mod: {
|
||||||
name: nameOrFilename(mod.name, absPath),
|
name: nameOrFilename(mod.name, absPath),
|
||||||
...mod,
|
...mod,
|
||||||
} as DefinedEventModule,
|
} as DefinedEventModule,
|
||||||
absPath
|
absPath,
|
||||||
})),
|
})),
|
||||||
concatMap(processPlugins),
|
concatMap(processPlugins),
|
||||||
concatMap(resolvePlugins),
|
concatMap(resolvePlugins),
|
||||||
//Reduces pluginRes (generated from above) into a single boolean
|
//Reduces pluginRes (generated from above) into a single boolean
|
||||||
concatMap(({pluginRes, mod}) => from(pluginRes)
|
concatMap(({ pluginRes, mod }) =>
|
||||||
.pipe(
|
from(pluginRes).pipe(
|
||||||
map(pl => pl.execute),
|
map(pl => pl.execute),
|
||||||
toArray(),
|
toArray(),
|
||||||
reducePlugins,
|
reducePlugins,
|
||||||
map(success => ({ success, mod }))
|
map(success => ({ success, mod })),
|
||||||
)),
|
),
|
||||||
|
),
|
||||||
concatMap(({ success, mod }) =>
|
concatMap(({ success, mod }) =>
|
||||||
iif(() => success,
|
iif(() => success, emitFailure$(mod), emitSuccess$(mod)).pipe(
|
||||||
emitFailure$(mod),
|
|
||||||
emitSuccess$(mod)
|
|
||||||
).pipe(
|
|
||||||
filter(res => res.type === PayloadType.Success),
|
filter(res => res.type === PayloadType.Success),
|
||||||
map(() => mod)
|
map(() => mod),
|
||||||
)
|
),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
eventCreation$.subscribe(e => {
|
eventCreation$.subscribe(e => {
|
||||||
const payload = match(e)
|
const payload = match(e)
|
||||||
.when(isSernEvent, sernEmitterDispatcher(sernEmitter))
|
.when(isSernEvent, sernEmitterDispatcher(sernEmitter))
|
||||||
.when(isDiscordEvent, discordEventDispatcher(client))
|
.when(isDiscordEvent, discordEventDispatcher(client))
|
||||||
.when(isExternalEvent, externalEventDispatcher(e => lazy(e.emitter)))
|
.when(
|
||||||
|
isExternalEvent,
|
||||||
|
externalEventDispatcher(e => lazy(e.emitter)),
|
||||||
|
)
|
||||||
.otherwise(() => error.crash(Error(SernError.InvalidModuleType)));
|
.otherwise(() => error.crash(Error(SernError.InvalidModuleType)));
|
||||||
payload
|
payload.execute
|
||||||
.execute
|
|
||||||
.pipe(
|
.pipe(
|
||||||
concatMap(({event, executeEvent}) =>
|
concatMap(({ event, executeEvent }) =>
|
||||||
executeEvent
|
executeEvent.pipe(
|
||||||
.pipe( tap(success => {
|
tap(success => {
|
||||||
if(success)
|
if (success) {
|
||||||
payload.cmd.execute(event as never);
|
if (Array.isArray(event)) {
|
||||||
}), catchError(handleError(error, logging)))
|
payload.cmd.execute(...event);
|
||||||
|
} else {
|
||||||
|
payload.cmd.execute(event as never);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
catchError(handleError(error, logging)),
|
||||||
|
),
|
||||||
),
|
),
|
||||||
).subscribe();
|
)
|
||||||
|
.subscribe();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function eventObservable$(events: string, emitter: SernEmitter) {
|
function eventObservable$(events: string, emitter: SernEmitter) {
|
||||||
return buildData<EventModule>(events)
|
return buildData<EventModule>(events).pipe(
|
||||||
.pipe(
|
errTap(reason =>
|
||||||
errTap(reason =>
|
emitter.emit('module.register', {
|
||||||
emitter.emit('module.register', {
|
type: PayloadType.Failure,
|
||||||
type: PayloadType.Failure,
|
module: undefined,
|
||||||
module: undefined,
|
reason,
|
||||||
reason,
|
}),
|
||||||
}),
|
),
|
||||||
),
|
);
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -31,31 +31,32 @@ export interface Plugin {
|
|||||||
name?: string;
|
name?: string;
|
||||||
/** @deprecated will be removed in the next update */
|
/** @deprecated will be removed in the next update */
|
||||||
description?: string;
|
description?: string;
|
||||||
type: PluginType
|
type: PluginType;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface CommandPlugin<T extends keyof CommandModuleDefs = keyof CommandModuleDefs> extends Plugin {
|
export interface CommandPlugin<T extends keyof CommandModuleDefs = keyof CommandModuleDefs>
|
||||||
|
extends Plugin {
|
||||||
type: PluginType.Command;
|
type: PluginType.Command;
|
||||||
execute: (
|
execute: (
|
||||||
payload: {
|
payload: {
|
||||||
mod: CommandModuleDefs[T] & { name : string; description : string };
|
mod: CommandModuleDefs[T] & { name: string; description: string };
|
||||||
absPath: string;
|
absPath: string;
|
||||||
},
|
},
|
||||||
controller: Controller,
|
controller: Controller,
|
||||||
) => Awaitable<Result<void, void>>;
|
) => Awaitable<Result<void, void>>;
|
||||||
}
|
}
|
||||||
export interface DiscordEmitterPlugin extends Plugin {
|
export interface DiscordEmitterPlugin extends Plugin {
|
||||||
type: PluginType.Command;
|
type: PluginType.Command;
|
||||||
execute: (
|
execute: (
|
||||||
payload: { mod: DiscordEventCommand & { name: string }; absPath: string },
|
payload: { mod: DiscordEventCommand & { name: string }; absPath: string },
|
||||||
controller: Controller,
|
controller: Controller,
|
||||||
) => Awaitable<Result<void, void>>;
|
) => Awaitable<Result<void, void>>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ExternalEmitterPlugin extends Plugin {
|
export interface ExternalEmitterPlugin extends Plugin {
|
||||||
type: PluginType.Command;
|
type: PluginType.Command;
|
||||||
execute: (
|
execute: (
|
||||||
payload: { mod: ExternalEventCommand & { name : string }; absPath: string } ,
|
payload: { mod: ExternalEventCommand & { name: string }; absPath: string },
|
||||||
controller: Controller,
|
controller: Controller,
|
||||||
) => Awaitable<Result<void, void>>;
|
) => Awaitable<Result<void, void>>;
|
||||||
}
|
}
|
||||||
@@ -63,7 +64,7 @@ export interface ExternalEmitterPlugin extends Plugin {
|
|||||||
export interface SernEmitterPlugin extends Plugin {
|
export interface SernEmitterPlugin extends Plugin {
|
||||||
type: PluginType.Command;
|
type: PluginType.Command;
|
||||||
execute: (
|
execute: (
|
||||||
payload: { mod : SernEventCommand & { name : string }; absPath: string },
|
payload: { mod: SernEventCommand & { name: string }; absPath: string },
|
||||||
controller: Controller,
|
controller: Controller,
|
||||||
) => Awaitable<Result<void, void>>;
|
) => Awaitable<Result<void, void>>;
|
||||||
}
|
}
|
||||||
@@ -76,8 +77,8 @@ export interface AutocompletePlugin extends Plugin {
|
|||||||
) => Awaitable<Result<void, void>>;
|
) => Awaitable<Result<void, void>>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface EventPlugin<K extends keyof CommandModuleDefs = keyof CommandModuleDefs>
|
||||||
export interface EventPlugin<K extends keyof CommandModuleDefs = keyof CommandModuleDefs> extends Plugin {
|
extends Plugin {
|
||||||
type: PluginType.Event;
|
type: PluginType.Event;
|
||||||
execute: (
|
execute: (
|
||||||
event: Parameters<CommandModuleDefs[K]['execute']>,
|
event: Parameters<CommandModuleDefs[K]['execute']>,
|
||||||
@@ -85,13 +86,11 @@ export interface EventPlugin<K extends keyof CommandModuleDefs = keyof CommandMo
|
|||||||
) => Awaitable<Result<void, void>>;
|
) => Awaitable<Result<void, void>>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface SernEventPlugin<T extends keyof SernEventsMapping = keyof SernEventsMapping> extends Plugin {
|
export interface SernEventPlugin<T extends keyof SernEventsMapping = keyof SernEventsMapping>
|
||||||
|
extends Plugin {
|
||||||
name?: T;
|
name?: T;
|
||||||
type: PluginType.Event;
|
type: PluginType.Event;
|
||||||
execute: (
|
execute: (args: SernEventsMapping[T], controller: Controller) => Awaitable<Result<void, void>>;
|
||||||
args: SernEventsMapping[T],
|
|
||||||
controller: Controller,
|
|
||||||
) => Awaitable<Result<void, void>>;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ExternalEventPlugin extends Plugin {
|
export interface ExternalEventPlugin extends Plugin {
|
||||||
@@ -99,7 +98,8 @@ export interface ExternalEventPlugin extends Plugin {
|
|||||||
execute: (args: unknown[], controller: Controller) => Awaitable<Result<void, void>>;
|
execute: (args: unknown[], controller: Controller) => Awaitable<Result<void, void>>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface DiscordEventPlugin<T extends keyof ClientEvents = keyof ClientEvents> extends Plugin {
|
export interface DiscordEventPlugin<T extends keyof ClientEvents = keyof ClientEvents>
|
||||||
|
extends Plugin {
|
||||||
name?: T;
|
name?: T;
|
||||||
type: PluginType.Event;
|
type: PluginType.Event;
|
||||||
execute: (args: ClientEvents[T], controller: Controller) => Awaitable<Result<void, void>>;
|
execute: (args: ClientEvents[T], controller: Controller) => Awaitable<Result<void, void>>;
|
||||||
|
|||||||
@@ -13,7 +13,12 @@ import type {
|
|||||||
import InteractionHandler from './events/interactionHandler';
|
import InteractionHandler from './events/interactionHandler';
|
||||||
import ReadyHandler from './events/readyHandler';
|
import ReadyHandler from './events/readyHandler';
|
||||||
import MessageHandler from './events/messageHandler';
|
import MessageHandler from './events/messageHandler';
|
||||||
import type { CommandModule, CommandModuleDefs, EventModule, EventModuleDefs } from '../types/module';
|
import type {
|
||||||
|
CommandModule,
|
||||||
|
CommandModuleDefs,
|
||||||
|
EventModule,
|
||||||
|
EventModuleDefs,
|
||||||
|
} from '../types/module';
|
||||||
import { Container, createContainer } from 'iti';
|
import { Container, createContainer } from 'iti';
|
||||||
import type { Dependencies, OptionalDependencies } from '../types/handler';
|
import type { Dependencies, OptionalDependencies } from '../types/handler';
|
||||||
import { composeRoot, containerSubject, useContainer } from './dependencies/provider';
|
import { composeRoot, containerSubject, useContainer } from './dependencies/provider';
|
||||||
@@ -46,7 +51,7 @@ export function init(wrapper: Wrapper) {
|
|||||||
new MessageHandler(wrapper);
|
new MessageHandler(wrapper);
|
||||||
new InteractionHandler(wrapper);
|
new InteractionHandler(wrapper);
|
||||||
const endTime = performance.now();
|
const endTime = performance.now();
|
||||||
logger?.info({ message: `sern : ${(endTime-startTime).toFixed(2)} ms` });
|
logger?.info({ message: `sern : ${(endTime - startTime).toFixed(2)} ms` });
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -62,7 +67,10 @@ export const controller = {
|
|||||||
* @param mod
|
* @param mod
|
||||||
*/
|
*/
|
||||||
export function commandModule(mod: InputCommandModule): CommandModule {
|
export function commandModule(mod: InputCommandModule): CommandModule {
|
||||||
const [onEvent, plugins] = partition(mod.plugins ?? [], el => (el as Plugin).type === PluginType.Event);
|
const [onEvent, plugins] = partition(
|
||||||
|
mod.plugins ?? [],
|
||||||
|
el => (el as Plugin).type === PluginType.Event,
|
||||||
|
);
|
||||||
return {
|
return {
|
||||||
...mod,
|
...mod,
|
||||||
onEvent,
|
onEvent,
|
||||||
@@ -74,8 +82,11 @@ export function commandModule(mod: InputCommandModule): CommandModule {
|
|||||||
* @param mod
|
* @param mod
|
||||||
*/
|
*/
|
||||||
export function eventModule(mod: InputEventModule): EventModule {
|
export function eventModule(mod: InputEventModule): EventModule {
|
||||||
const [onEvent, plugins] = partition(mod.plugins ?? [], el => (el as Plugin).type === PluginType.Event);
|
const [onEvent, plugins] = partition(
|
||||||
return {
|
mod.plugins ?? [],
|
||||||
|
el => (el as Plugin).type === PluginType.Event,
|
||||||
|
);
|
||||||
|
return {
|
||||||
...mod,
|
...mod,
|
||||||
onEvent,
|
onEvent,
|
||||||
plugins,
|
plugins,
|
||||||
@@ -85,8 +96,8 @@ export function eventModule(mod: InputEventModule): EventModule {
|
|||||||
* @param conf a configuration for creating your project dependencies
|
* @param conf a configuration for creating your project dependencies
|
||||||
*/
|
*/
|
||||||
export function makeDependencies<T extends Dependencies>(conf: {
|
export function makeDependencies<T extends Dependencies>(conf: {
|
||||||
exclude?: Set<OptionalDependencies>,
|
exclude?: Set<OptionalDependencies>;
|
||||||
build: (root: Container<Record<string,any>, {}>) => Container<Partial<T>, T>,
|
build: (root: Container<Record<string, any>, {}>) => Container<Partial<T>, T>;
|
||||||
}) {
|
}) {
|
||||||
const container = conf.build(createContainer());
|
const container = conf.build(createContainer());
|
||||||
composeRoot(container, conf.exclude ?? new Set());
|
composeRoot(container, conf.exclude ?? new Set());
|
||||||
|
|||||||
@@ -11,7 +11,6 @@ import { Result as Either, Ok as Left, Err as Right } from 'ts-results-es';
|
|||||||
import type { ReplyOptions } from '../../types/handler';
|
import type { ReplyOptions } from '../../types/handler';
|
||||||
import { SernError } from './errors';
|
import { SernError } from './errors';
|
||||||
|
|
||||||
|
|
||||||
function safeUnwrap<T>(res: Either<T, T>) {
|
function safeUnwrap<T>(res: Either<T, T>) {
|
||||||
return res.val;
|
return res.val;
|
||||||
}
|
}
|
||||||
@@ -20,16 +19,14 @@ function safeUnwrap<T>(res: Either<T, T>) {
|
|||||||
* Message and ChatInputCommandInteraction
|
* Message and ChatInputCommandInteraction
|
||||||
*/
|
*/
|
||||||
export default class Context {
|
export default class Context {
|
||||||
private constructor(
|
private constructor(private ctx: Either<Message, ChatInputCommandInteraction>) {}
|
||||||
private ctx: Either<Message, ChatInputCommandInteraction>,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Getting the Message object. Crashes if module type is
|
* Getting the Message object. Crashes if module type is
|
||||||
* CommandType.Slash or the event fired in a Both command was
|
* CommandType.Slash or the event fired in a Both command was
|
||||||
* ChatInputCommandInteraction
|
* ChatInputCommandInteraction
|
||||||
*/
|
*/
|
||||||
public get message() {
|
public get message() {
|
||||||
return this.ctx.expect(SernError.MismatchEvent);
|
return this.ctx.expect(SernError.MismatchEvent);
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
@@ -42,71 +39,45 @@ export default class Context {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public get id(): Snowflake {
|
public get id(): Snowflake {
|
||||||
return safeUnwrap(
|
return safeUnwrap(this.ctx.map(m => m.id).mapErr(i => i.id));
|
||||||
this.ctx
|
|
||||||
.map(m => m.id)
|
|
||||||
.mapErr(i => i.id));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public get channel() {
|
public get channel() {
|
||||||
return safeUnwrap(this.ctx
|
return safeUnwrap(this.ctx.map(m => m.channel).mapErr(i => i.channel));
|
||||||
.map(m => m.channel)
|
|
||||||
.mapErr(i => i.channel));
|
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* If context is holding a message, message.author
|
* If context is holding a message, message.author
|
||||||
* else, interaction.user
|
* else, interaction.user
|
||||||
*/
|
*/
|
||||||
public get user(): User {
|
public get user(): User {
|
||||||
return safeUnwrap(this.ctx
|
return safeUnwrap(this.ctx.map(m => m.author).mapErr(i => i.user));
|
||||||
.map(m => m.author)
|
|
||||||
.mapErr(i => i.user)
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public get createdTimestamp(): number {
|
public get createdTimestamp(): number {
|
||||||
return safeUnwrap(this.ctx
|
return safeUnwrap(this.ctx.map(m => m.createdTimestamp).mapErr(i => i.createdTimestamp));
|
||||||
.map(m => m.createdTimestamp)
|
|
||||||
.mapErr(i => i.createdTimestamp)
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public get guild() {
|
public get guild() {
|
||||||
return safeUnwrap(this.ctx
|
return safeUnwrap(this.ctx.map(m => m.guild).mapErr(i => i.guild));
|
||||||
.map(m => m.guild)
|
|
||||||
.mapErr(i => i.guild)
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public get guildId() {
|
public get guildId() {
|
||||||
return safeUnwrap(this.ctx
|
return safeUnwrap(this.ctx.map(m => m.guildId).mapErr(i => i.guildId));
|
||||||
.map(m => m.guildId)
|
|
||||||
.mapErr(i => i.guildId)
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* interactions can return APIGuildMember if the guild it is emitted from is not cached
|
* interactions can return APIGuildMember if the guild it is emitted from is not cached
|
||||||
*/
|
*/
|
||||||
public get member() {
|
public get member() {
|
||||||
return safeUnwrap(this.ctx
|
return safeUnwrap(this.ctx.map(m => m.member).mapErr(i => i.member));
|
||||||
.map(m => m.member)
|
|
||||||
.mapErr(i => i.member)
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public get client(): Client {
|
public get client(): Client {
|
||||||
return safeUnwrap(this.ctx
|
return safeUnwrap(this.ctx.map(m => m.client).mapErr(i => i.client));
|
||||||
.map(m => m.client)
|
|
||||||
.mapErr(i => i.client)
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public get inGuild(): boolean {
|
public get inGuild(): boolean {
|
||||||
return safeUnwrap(this.ctx
|
return safeUnwrap(this.ctx.map(m => m.inGuild()).mapErr(i => i.inGuild()));
|
||||||
.map(m=>m.inGuild())
|
|
||||||
.mapErr(i => i.inGuild())
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
public isMessage() {
|
public isMessage() {
|
||||||
return this.ctx.map(() => true).unwrapOr(false);
|
return this.ctx.map(() => true).unwrapOr(false);
|
||||||
@@ -124,9 +95,12 @@ export default class Context {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public reply(content: ReplyOptions) {
|
public reply(content: ReplyOptions) {
|
||||||
return safeUnwrap(this.ctx
|
return safeUnwrap(
|
||||||
.map( m => m.reply(content as string | MessageReplyOptions))
|
this.ctx
|
||||||
.mapErr(i => i.reply(content as string | InteractionReplyOptions).then(() => i.fetchReply()))
|
.map(m => m.reply(content as string | MessageReplyOptions))
|
||||||
|
.mapErr(i =>
|
||||||
|
i.reply(content as string | InteractionReplyOptions).then(() => i.fetchReply()),
|
||||||
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -51,8 +51,8 @@ export enum CommandType {
|
|||||||
*/
|
*/
|
||||||
ChannelSelect = 256,
|
ChannelSelect = 256,
|
||||||
MentionableSelect = 512,
|
MentionableSelect = 512,
|
||||||
RoleSelect= 1024,
|
RoleSelect = 1024,
|
||||||
UserSelect= 2048
|
UserSelect = 2048,
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -34,5 +34,5 @@ export enum SernError {
|
|||||||
/**
|
/**
|
||||||
* Required Dependency not found
|
* Required Dependency not found
|
||||||
*/
|
*/
|
||||||
MissingRequired = `@sern/client is required but was not found`
|
MissingRequired = `@sern/client is required but was not found`,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,8 +11,8 @@ import type { Awaitable, ClientEvents } from 'discord.js';
|
|||||||
import type { EventType } from './enums';
|
import type { EventType } from './enums';
|
||||||
import type { Module } from '../../types/module';
|
import type { Module } from '../../types/module';
|
||||||
|
|
||||||
|
export interface SernEventCommand<T extends keyof SernEventsMapping = keyof SernEventsMapping>
|
||||||
export interface SernEventCommand<T extends keyof SernEventsMapping = keyof SernEventsMapping> extends Module {
|
extends Module {
|
||||||
name?: T;
|
name?: T;
|
||||||
type: EventType.Sern;
|
type: EventType.Sern;
|
||||||
onEvent: SernEventPlugin[];
|
onEvent: SernEventPlugin[];
|
||||||
@@ -20,7 +20,8 @@ export interface SernEventCommand<T extends keyof SernEventsMapping = keyof Sern
|
|||||||
execute(...args: SernEventsMapping[T]): Awaitable<unknown>;
|
execute(...args: SernEventsMapping[T]): Awaitable<unknown>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface DiscordEventCommand<T extends keyof ClientEvents = keyof ClientEvents> extends Module {
|
export interface DiscordEventCommand<T extends keyof ClientEvents = keyof ClientEvents>
|
||||||
|
extends Module {
|
||||||
name?: T;
|
name?: T;
|
||||||
type: EventType.Discord;
|
type: EventType.Discord;
|
||||||
onEvent: DiscordEventPlugin[];
|
onEvent: DiscordEventPlugin[];
|
||||||
@@ -29,7 +30,7 @@ export interface DiscordEventCommand<T extends keyof ClientEvents = keyof Client
|
|||||||
}
|
}
|
||||||
|
|
||||||
export interface ExternalEventCommand extends Module {
|
export interface ExternalEventCommand extends Module {
|
||||||
name?: string
|
name?: string;
|
||||||
emitter: string;
|
emitter: string;
|
||||||
type: EventType.External;
|
type: EventType.External;
|
||||||
onEvent: ExternalEventPlugin[];
|
onEvent: ExternalEventPlugin[];
|
||||||
|
|||||||
@@ -6,8 +6,8 @@ import { ApplicationCommandType, ComponentType } from 'discord.js';
|
|||||||
* This dependency is usually injected into ModuleManager
|
* This dependency is usually injected into ModuleManager
|
||||||
*/
|
*/
|
||||||
export class ModuleStore {
|
export class ModuleStore {
|
||||||
readonly BothCommands = new Map<string, CommandModule>();
|
readonly BothCommands = new Map<string, CommandModule>();
|
||||||
readonly ApplicationCommands = {
|
readonly ApplicationCommands = {
|
||||||
[ApplicationCommandType.User]: new Map<string, CommandModule>(),
|
[ApplicationCommandType.User]: new Map<string, CommandModule>(),
|
||||||
[ApplicationCommandType.Message]: new Map<string, CommandModule>(),
|
[ApplicationCommandType.Message]: new Map<string, CommandModule>(),
|
||||||
[ApplicationCommandType.ChatInput]: new Map<string, CommandModule>(),
|
[ApplicationCommandType.ChatInput]: new Map<string, CommandModule>(),
|
||||||
@@ -17,10 +17,9 @@ export class ModuleStore {
|
|||||||
readonly InteractionHandlers = {
|
readonly InteractionHandlers = {
|
||||||
[ComponentType.Button]: new Map<string, CommandModule>(),
|
[ComponentType.Button]: new Map<string, CommandModule>(),
|
||||||
[ComponentType.StringSelect]: new Map<string, CommandModule>(),
|
[ComponentType.StringSelect]: new Map<string, CommandModule>(),
|
||||||
[ComponentType.ChannelSelect] : new Map<string, CommandModule>(),
|
[ComponentType.ChannelSelect]: new Map<string, CommandModule>(),
|
||||||
[ComponentType.MentionableSelect] : new Map<string, CommandModule>(),
|
[ComponentType.MentionableSelect]: new Map<string, CommandModule>(),
|
||||||
[ComponentType.RoleSelect] : new Map<string, CommandModule>(),
|
[ComponentType.RoleSelect]: new Map<string, CommandModule>(),
|
||||||
[ComponentType.UserSelect] : new Map<string, CommandModule>(),
|
[ComponentType.UserSelect]: new Map<string, CommandModule>(),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,8 +3,4 @@ import type Wrapper from './wrapper';
|
|||||||
import { ModuleStore } from './moduleStore';
|
import { ModuleStore } from './moduleStore';
|
||||||
|
|
||||||
export * from './enums';
|
export * from './enums';
|
||||||
export {
|
export { Context, Wrapper, ModuleStore };
|
||||||
Context,
|
|
||||||
Wrapper,
|
|
||||||
ModuleStore
|
|
||||||
};
|
|
||||||
|
|||||||
@@ -8,8 +8,8 @@ interface Wrapper {
|
|||||||
readonly defaultPrefix?: string;
|
readonly defaultPrefix?: string;
|
||||||
readonly commands: string;
|
readonly commands: string;
|
||||||
readonly events?: string;
|
readonly events?: string;
|
||||||
readonly containerConfig : {
|
readonly containerConfig: {
|
||||||
get: (...keys: (keyof Dependencies)[]) => unknown[];
|
get: (...keys: (keyof Dependencies)[]) => unknown[];
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
export default Wrapper;
|
export default Wrapper;
|
||||||
|
|||||||
@@ -7,13 +7,19 @@ import { Observable, of, switchMap } from 'rxjs';
|
|||||||
* Used for singleton in iti
|
* Used for singleton in iti
|
||||||
* @param value
|
* @param value
|
||||||
*/
|
*/
|
||||||
export const _const = <T>(value: T) => () => value;
|
export const _const =
|
||||||
|
<T>(value: T) =>
|
||||||
|
() =>
|
||||||
|
value;
|
||||||
/**
|
/**
|
||||||
* A function that returns another function
|
* A function that returns another function
|
||||||
* Used for transient in iti
|
* Used for transient in iti
|
||||||
* @param value
|
* @param value
|
||||||
*/
|
*/
|
||||||
export const transient = <T>( value : T) => () => _const(value);
|
export const transient =
|
||||||
|
<T>(value: T) =>
|
||||||
|
() =>
|
||||||
|
_const(value);
|
||||||
|
|
||||||
export function nameOrFilename(modName: string | undefined, absPath: string) {
|
export function nameOrFilename(modName: string | undefined, absPath: string) {
|
||||||
return modName ?? Files.fmtFileName(basename(absPath));
|
return modName ?? Files.fmtFileName(basename(absPath));
|
||||||
@@ -23,20 +29,19 @@ export function nameOrFilename(modName: string | undefined, absPath: string) {
|
|||||||
export const ok = _const(Ok.EMPTY);
|
export const ok = _const(Ok.EMPTY);
|
||||||
export const err = _const(Err.EMPTY);
|
export const err = _const(Err.EMPTY);
|
||||||
|
|
||||||
|
export function partition<T, V>(arr: (T & V)[], condition: (e: T & V) => boolean): [T[], V[]] {
|
||||||
export function partition<T, V>(arr: (T & V)[], condition: (e: (T & V)) => boolean) : [T[], V[]] {
|
const t: T[] = [];
|
||||||
const t : T[] = [];
|
const v: V[] = [];
|
||||||
const v : V[] = [];
|
for (const el of arr) {
|
||||||
for(const el of arr) {
|
if (condition(el)) {
|
||||||
if(condition(el)) {
|
|
||||||
t.push(el as T);
|
t.push(el as T);
|
||||||
} else {
|
} else {
|
||||||
v.push(el as V);
|
v.push(el as V);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return [ t, v ];
|
return [t, v];
|
||||||
}
|
}
|
||||||
|
|
||||||
export function reducePlugins(src: Observable<Result<void, void>[]>) : Observable<boolean> {
|
export function reducePlugins(src: Observable<Result<void, void>[]>): Observable<boolean> {
|
||||||
return src.pipe(switchMap(s => of(s.every((a) => a.ok))));
|
return src.pipe(switchMap(s => of(s.every(a => a.ok))));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,8 @@
|
|||||||
import type { DiscordEventCommand, ExternalEventCommand, SernEventCommand } from '../structures/events';
|
import type {
|
||||||
|
DiscordEventCommand,
|
||||||
|
ExternalEventCommand,
|
||||||
|
SernEventCommand,
|
||||||
|
} from '../structures/events';
|
||||||
import { CommandModule, EventType } from '../..';
|
import { CommandModule, EventType } from '../..';
|
||||||
import type { AnyModule, CommandModuleDefs, EventModule } from '../../types/module';
|
import type { AnyModule, CommandModuleDefs, EventModule } from '../../types/module';
|
||||||
|
|
||||||
@@ -11,7 +15,6 @@ export function correctModuleType<T extends keyof CommandModuleDefs>(
|
|||||||
return plug !== undefined && (plug.type & type) !== 0;
|
return plug !== undefined && (plug.type & type) !== 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
export function isDiscordEvent(el: EventModule | CommandModule): el is DiscordEventCommand {
|
export function isDiscordEvent(el: EventModule | CommandModule): el is DiscordEventCommand {
|
||||||
return el.type === EventType.Discord;
|
return el.type === EventType.Discord;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ import { type Observable, from, concatAll } from 'rxjs';
|
|||||||
import { SernError } from '../structures/errors';
|
import { SernError } from '../structures/errors';
|
||||||
import { type Result, Err, Ok } from 'ts-results-es';
|
import { type Result, Err, Ok } from 'ts-results-es';
|
||||||
|
|
||||||
|
|
||||||
// Courtesy @Townsy45
|
// Courtesy @Townsy45
|
||||||
function readPath(dir: string, arrayOfFiles: string[] = []): string[] {
|
function readPath(dir: string, arrayOfFiles: string[] = []): string[] {
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -13,30 +13,30 @@ export default function treeSearch(
|
|||||||
const cur = _options.pop()!;
|
const cur = _options.pop()!;
|
||||||
switch (cur.type) {
|
switch (cur.type) {
|
||||||
case ApplicationCommandOptionType.Subcommand:
|
case ApplicationCommandOptionType.Subcommand:
|
||||||
{
|
{
|
||||||
for (const option of cur.options ?? []) {
|
for (const option of cur.options ?? []) {
|
||||||
_options.push(option);
|
_options.push(option);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case ApplicationCommandOptionType.SubcommandGroup:
|
case ApplicationCommandOptionType.SubcommandGroup:
|
||||||
{
|
{
|
||||||
for (const command of cur.options ?? []) {
|
for (const command of cur.options ?? []) {
|
||||||
_options.push(command);
|
_options.push(command);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
{
|
{
|
||||||
if (cur.autocomplete) {
|
if (cur.autocomplete) {
|
||||||
const choice = iAutocomplete.options.getFocused(true);
|
const choice = iAutocomplete.options.getFocused(true);
|
||||||
if (cur.name === choice.name && cur.autocomplete) {
|
if (cur.name === choice.name && cur.autocomplete) {
|
||||||
autocompleteData = cur;
|
autocompleteData = cur;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return autocompleteData;
|
return autocompleteData;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,4 +8,4 @@ export * from './handler/plugins/plugin';
|
|||||||
export * from './handler/contracts/index';
|
export * from './handler/contracts/index';
|
||||||
export { SernEmitter };
|
export { SernEmitter };
|
||||||
export { _const as single, transient as many } from './handler/utilities/functions';
|
export { _const as single, transient as many } from './handler/utilities/functions';
|
||||||
export { useContainerRaw } from './handler/dependencies/provider';
|
export { useContainerRaw } from './handler/dependencies/provider';
|
||||||
|
|||||||
@@ -22,36 +22,43 @@ export type SlashOptions = Omit<CommandInteractionOptionResolver, 'getMessage' |
|
|||||||
*/
|
*/
|
||||||
export type DefinedCommandModule = CommandModule & { name: string; description: string };
|
export type DefinedCommandModule = CommandModule & { name: string; description: string };
|
||||||
export type DefinedEventModule = EventModule & { name: string };
|
export type DefinedEventModule = EventModule & { name: string };
|
||||||
export type AnyDefinedModule = DefinedCommandModule | DefinedEventModule
|
export type AnyDefinedModule = DefinedCommandModule | DefinedEventModule;
|
||||||
export type Payload =
|
export type Payload =
|
||||||
| { type: PayloadType.Success; module: AnyModule }
|
| { type: PayloadType.Success; module: AnyModule }
|
||||||
| { type: PayloadType.Failure; module?: AnyModule; reason: string | Error }
|
| { type: PayloadType.Failure; module?: AnyModule; reason: string | Error }
|
||||||
| { type: PayloadType.Warning; reason: string};
|
| { type: PayloadType.Warning; reason: string };
|
||||||
export type SernEventsMapping = {
|
export type SernEventsMapping = {
|
||||||
'module.register': [Payload];
|
'module.register': [Payload];
|
||||||
'module.activate': [Payload];
|
'module.activate': [Payload];
|
||||||
'error': [Payload];
|
error: [Payload];
|
||||||
'warning': [Payload];
|
warning: [Payload];
|
||||||
};
|
};
|
||||||
export type LogPayload<T = unknown> = { message: T }
|
export type LogPayload<T = unknown> = { message: T };
|
||||||
export type Singleton<T> = () => T
|
export type Singleton<T> = () => T;
|
||||||
export type Transient<T> = () => () => T;
|
export type Transient<T> = () => () => T;
|
||||||
|
|
||||||
export interface Dependencies {
|
export interface Dependencies {
|
||||||
'@sern/client': Singleton<EventEmitter>;
|
'@sern/client': Singleton<EventEmitter>;
|
||||||
'@sern/logger'?: Singleton<Logging>;
|
'@sern/logger'?: Singleton<Logging>;
|
||||||
'@sern/emitter': Singleton<SernEmitter>;
|
'@sern/emitter': Singleton<SernEmitter>;
|
||||||
'@sern/store' : Singleton<ModuleStore>;
|
'@sern/store': Singleton<ModuleStore>;
|
||||||
'@sern/modules' : Singleton<ModuleManager>;
|
'@sern/modules': Singleton<ModuleManager>;
|
||||||
'@sern/errors': Singleton<ErrorHandling>;
|
'@sern/errors': Singleton<ErrorHandling>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ReplyOptions = string | Omit<InteractionReplyOptions, 'fetchReply'> | MessageReplyOptions;
|
export type ReplyOptions =
|
||||||
|
| string
|
||||||
|
| Omit<InteractionReplyOptions, 'fetchReply'>
|
||||||
|
| MessageReplyOptions;
|
||||||
|
|
||||||
export type MapDeps<
|
export type MapDeps<Deps extends Dependencies, T extends readonly unknown[]> = T extends [
|
||||||
Deps extends Dependencies,
|
infer First extends keyof Deps,
|
||||||
T extends readonly unknown[]
|
...infer Rest extends readonly unknown[],
|
||||||
> = T extends [infer First extends keyof Deps, ...infer Rest extends readonly unknown[]]
|
]
|
||||||
? [ UnpackFunction<Deps[First]>, ...(MapDeps<Deps, Rest> extends [never] ? [] : MapDeps<Deps,Rest>)] : [never]
|
? [
|
||||||
|
UnpackFunction<Deps[First]>,
|
||||||
|
...(MapDeps<Deps, Rest> extends [never] ? [] : MapDeps<Deps, Rest>),
|
||||||
|
]
|
||||||
|
: [never];
|
||||||
//Basically, '@sern/client' | '@sern/store' | '@sern/modules' | '@sern/error' | '@sern/emitter' will be provided defaults, and you can exclude the rest
|
//Basically, '@sern/client' | '@sern/store' | '@sern/modules' | '@sern/error' | '@sern/emitter' will be provided defaults, and you can exclude the rest
|
||||||
export type OptionalDependencies = '@sern/logger';
|
export type OptionalDependencies = '@sern/logger';
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ import type {
|
|||||||
ChannelSelectMenuInteraction,
|
ChannelSelectMenuInteraction,
|
||||||
MentionableSelectMenuInteraction,
|
MentionableSelectMenuInteraction,
|
||||||
RoleSelectMenuInteraction,
|
RoleSelectMenuInteraction,
|
||||||
StringSelectMenuInteraction
|
StringSelectMenuInteraction,
|
||||||
} from 'discord.js';
|
} from 'discord.js';
|
||||||
import type {
|
import type {
|
||||||
DiscordEventCommand,
|
DiscordEventCommand,
|
||||||
@@ -36,7 +36,7 @@ export interface Module {
|
|||||||
type?: CommandType | EventType;
|
type?: CommandType | EventType;
|
||||||
name?: string;
|
name?: string;
|
||||||
description?: string;
|
description?: string;
|
||||||
execute: (...args: any[]) => any
|
execute: (...args: any[]) => any;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface TextCommand extends Module {
|
export interface TextCommand extends Module {
|
||||||
@@ -162,10 +162,10 @@ export type CommandModuleDefs = {
|
|||||||
[CommandType.CtxUser]: ContextMenuUser;
|
[CommandType.CtxUser]: ContextMenuUser;
|
||||||
[CommandType.Button]: ButtonCommand;
|
[CommandType.Button]: ButtonCommand;
|
||||||
[CommandType.StringSelect]: StringSelectCommand;
|
[CommandType.StringSelect]: StringSelectCommand;
|
||||||
[CommandType.RoleSelect] : RoleSelectCommand;
|
[CommandType.RoleSelect]: RoleSelectCommand;
|
||||||
[CommandType.ChannelSelect] : ChannelSelectCommand;
|
[CommandType.ChannelSelect]: ChannelSelectCommand;
|
||||||
[CommandType.MentionableSelect] : MentionableSelectCommand;
|
[CommandType.MentionableSelect]: MentionableSelectCommand;
|
||||||
[CommandType.UserSelect] : UserSelectCommand;
|
[CommandType.UserSelect]: UserSelectCommand;
|
||||||
[CommandType.Modal]: ModalSubmitCommand;
|
[CommandType.Modal]: ModalSubmitCommand;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -175,7 +175,8 @@ export type EventModuleDefs = {
|
|||||||
[EventType.External]: ExternalEventCommand;
|
[EventType.External]: ExternalEventCommand;
|
||||||
};
|
};
|
||||||
|
|
||||||
export interface SernAutocompleteData extends Omit<BaseApplicationCommandOptionsData, 'autocomplete'> {
|
export interface SernAutocompleteData
|
||||||
|
extends Omit<BaseApplicationCommandOptionsData, 'autocomplete'> {
|
||||||
autocomplete: true;
|
autocomplete: true;
|
||||||
type:
|
type:
|
||||||
| ApplicationCommandOptionType.String
|
| ApplicationCommandOptionType.String
|
||||||
@@ -212,4 +213,4 @@ export type SernOptionsData<U extends ApplicationCommandOptionData = Application
|
|||||||
? SernSubCommandData
|
? SernSubCommandData
|
||||||
: U extends ApplicationCommandSubGroupData
|
: U extends ApplicationCommandSubGroupData
|
||||||
? SernSubCommandGroupData
|
? SernSubCommandGroupData
|
||||||
: BaseOptions;
|
: BaseOptions;
|
||||||
|
|||||||
@@ -1,20 +1,20 @@
|
|||||||
{
|
{
|
||||||
"compilerOptions": {
|
"compilerOptions": {
|
||||||
"target": "esnext",
|
"target": "esnext",
|
||||||
"module": "commonjs",
|
"module": "commonjs",
|
||||||
"outDir": "dist",
|
"outDir": "dist",
|
||||||
"rootDir": "src",
|
"rootDir": "src",
|
||||||
"strict": true,
|
"strict": true,
|
||||||
"esModuleInterop": true,
|
"esModuleInterop": true,
|
||||||
"noImplicitAny": true,
|
"noImplicitAny": true,
|
||||||
"strictNullChecks": true,
|
"strictNullChecks": true,
|
||||||
"importsNotUsedAsValues": "error",
|
"importsNotUsedAsValues": "error",
|
||||||
"baseUrl": ".",
|
"baseUrl": ".",
|
||||||
"resolveJsonModule": true,
|
"resolveJsonModule": true,
|
||||||
"moduleResolution": "node",
|
"moduleResolution": "node",
|
||||||
"skipLibCheck": true,
|
"skipLibCheck": true,
|
||||||
"allowSyntheticDefaultImports": true,
|
"allowSyntheticDefaultImports": true,
|
||||||
"forceConsistentCasingInFileNames": true
|
"forceConsistentCasingInFileNames": true
|
||||||
},
|
},
|
||||||
"include": ["src/secrets.json", "src"]
|
"include": ["src/secrets.json", "src"]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,20 +1,20 @@
|
|||||||
{
|
{
|
||||||
"compilerOptions": {
|
"compilerOptions": {
|
||||||
"target": "esnext",
|
"target": "esnext",
|
||||||
"module": "esnext",
|
"module": "esnext",
|
||||||
"outDir": "dist",
|
"outDir": "dist",
|
||||||
"rootDir": "src",
|
"rootDir": "src",
|
||||||
"strict": true,
|
"strict": true,
|
||||||
"esModuleInterop": true,
|
"esModuleInterop": true,
|
||||||
"noImplicitAny": true,
|
"noImplicitAny": true,
|
||||||
"strictNullChecks": true,
|
"strictNullChecks": true,
|
||||||
"importsNotUsedAsValues": "error",
|
"importsNotUsedAsValues": "error",
|
||||||
"baseUrl": ".",
|
"baseUrl": ".",
|
||||||
"resolveJsonModule": true,
|
"resolveJsonModule": true,
|
||||||
"moduleResolution": "node",
|
"moduleResolution": "node",
|
||||||
"skipLibCheck": true,
|
"skipLibCheck": true,
|
||||||
"allowSyntheticDefaultImports": true,
|
"allowSyntheticDefaultImports": true,
|
||||||
"forceConsistentCasingInFileNames": true
|
"forceConsistentCasingInFileNames": true
|
||||||
},
|
},
|
||||||
"include": ["src/secrets.json", "src"]
|
"include": ["src/secrets.json", "src"]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ const shared = {
|
|||||||
external: ['discord.js'],
|
external: ['discord.js'],
|
||||||
platform: 'node',
|
platform: 'node',
|
||||||
clean: true,
|
clean: true,
|
||||||
sourcemap: false
|
sourcemap: false,
|
||||||
};
|
};
|
||||||
export default defineConfig([
|
export default defineConfig([
|
||||||
{
|
{
|
||||||
@@ -19,7 +19,7 @@ export default defineConfig([
|
|||||||
js: '.mjs',
|
js: '.mjs',
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
...shared
|
...shared,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
format: 'cjs',
|
format: 'cjs',
|
||||||
@@ -33,6 +33,6 @@ export default defineConfig([
|
|||||||
js: '.cjs',
|
js: '.cjs',
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
...shared
|
...shared,
|
||||||
},
|
},
|
||||||
]);
|
]);
|
||||||
|
|||||||
Reference in New Issue
Block a user