mirror of
https://github.com/sern-handler/handler
synced 2026-06-06 01:16:55 +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 }],
|
||||
"semi": ["error", "always"],
|
||||
"@typescript-eslint/no-empty-interface": 0,
|
||||
"@typescript-eslint/ban-types" : 0,
|
||||
"@typescript-eslint/ban-types": 0,
|
||||
"@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:
|
||||
- name: Check out Git repository
|
||||
uses: actions/checkout@93ea575cb5d8a053eaa0ac8fa3b40d7e05a33cc8 # tag=v3
|
||||
uses: actions/checkout@755da8c3cf115ac066823e79a1e1788f8940201b # v3
|
||||
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@8c91899e586c5b171469028077307d293428b516 # tag=v3
|
||||
|
||||
12
CHANGELOG.md
12
CHANGELOG.md
@@ -1,5 +1,17 @@
|
||||
# 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)
|
||||
|
||||
|
||||
|
||||
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",
|
||||
"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.",
|
||||
"main": "dist/cjs/index.cjs",
|
||||
"module": "dist/esm/index.mjs",
|
||||
@@ -39,14 +39,12 @@
|
||||
"ts-results-es": "^3.5.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@typescript-eslint/eslint-plugin": "5.44.0",
|
||||
"@typescript-eslint/parser": "5.44.0",
|
||||
"eslint": "8.25.0",
|
||||
"prettier": "2.7.1",
|
||||
"@typescript-eslint/eslint-plugin": "5.47.1",
|
||||
"@typescript-eslint/parser": "5.47.1",
|
||||
"eslint": "8.30.0",
|
||||
"prettier": "2.8.1",
|
||||
"tsup": "^6.1.3",
|
||||
"typescript": "4.9.4"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"typescript": "4.9.4",
|
||||
"discord.js": ">= ^14.7.x"
|
||||
},
|
||||
"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
|
||||
*/
|
||||
keepAlive : number
|
||||
keepAlive: number;
|
||||
|
||||
/**
|
||||
* Utility function to crash
|
||||
* @param error
|
||||
*/
|
||||
crash(error : Error) : never
|
||||
crash(error: Error): never;
|
||||
|
||||
/**
|
||||
* A function that is called on every crash. Updates keepAlive
|
||||
* @param error
|
||||
*/
|
||||
updateAlive(error: Error): void
|
||||
updateAlive(error: Error): void;
|
||||
}
|
||||
|
||||
export class DefaultErrorHandling implements ErrorHandling {
|
||||
@@ -35,10 +35,12 @@ export function handleError<C>(crashHandler: ErrorHandling, logging?: Logging) {
|
||||
return (pload: unknown, caught: Observable<C>) => {
|
||||
// This is done to fit the ErrorHandling contract
|
||||
const err = pload instanceof Error ? pload : Error(util.format(pload));
|
||||
if(crashHandler.keepAlive == 0) {
|
||||
useContainerRaw()?.disposeAll().then(() => {
|
||||
logging?.info({ message: 'Cleaning container and crashing' });
|
||||
});
|
||||
if (crashHandler.keepAlive == 0) {
|
||||
useContainerRaw()
|
||||
?.disposeAll()
|
||||
.then(() => {
|
||||
logging?.info({ message: 'Cleaning container and crashing' });
|
||||
});
|
||||
crashHandler.crash(err);
|
||||
}
|
||||
//formatted payload
|
||||
@@ -46,4 +48,4 @@ export function handleError<C>(crashHandler: ErrorHandling, logging?: Logging) {
|
||||
crashHandler.updateAlive(err);
|
||||
return caught;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
export { ErrorHandling, DefaultErrorHandling } from './errorHandling';
|
||||
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';
|
||||
|
||||
export interface Logging<T = unknown> {
|
||||
error(payload : LogPayload<T>) : void;
|
||||
warning(payload : LogPayload<T>) : void;
|
||||
info(payload : LogPayload<T>) : void
|
||||
debug(payload : LogPayload<T>) : void
|
||||
error(payload: LogPayload<T>): void;
|
||||
warning(payload: LogPayload<T>): void;
|
||||
info(payload: LogPayload<T>): void;
|
||||
debug(payload: LogPayload<T>): void;
|
||||
}
|
||||
|
||||
export class DefaultLogging implements Logging {
|
||||
@@ -24,5 +24,4 @@ export class DefaultLogging implements Logging {
|
||||
warning(payload: LogPayload): void {
|
||||
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 { ModuleStore } from '../structures/moduleStore';
|
||||
|
||||
|
||||
export interface ModuleManager {
|
||||
get<T extends CommandType>(strat : (ms: ModuleStore) => CommandModuleDefs[T] | undefined) : CommandModuleDefs[T] | undefined
|
||||
set(strat: (ms: ModuleStore) => void) : void
|
||||
get<T extends CommandType>(
|
||||
strat: (ms: ModuleStore) => CommandModuleDefs[T] | undefined,
|
||||
): CommandModuleDefs[T] | undefined;
|
||||
set(strat: (ms: ModuleStore) => void): void;
|
||||
}
|
||||
|
||||
export class DefaultModuleManager implements ModuleManager {
|
||||
|
||||
@@ -1,3 +1 @@
|
||||
export {
|
||||
useContainer
|
||||
} from './provider';
|
||||
export { useContainer } from './provider';
|
||||
|
||||
@@ -10,62 +10,69 @@ import { ModuleStore } from '../structures/moduleStore';
|
||||
import { Ok, Result } from 'ts-results-es';
|
||||
import { DefaultLogging } from '../contracts';
|
||||
|
||||
export const containerSubject = new BehaviorSubject<Container<Dependencies, Partial<Dependencies>> | null>(null);
|
||||
export function composeRoot<T extends Dependencies>(root: Container<Partial<T>, Partial<Dependencies>>, exclusion: Set<keyof Dependencies>) {
|
||||
export const containerSubject = new BehaviorSubject<Container<
|
||||
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');
|
||||
assert.ok(client !== undefined, SernError.MissingRequired);
|
||||
//A utility function checking if a dependency has been declared excluded
|
||||
const excluded = (key: keyof Dependencies) => exclusion.has(key);
|
||||
//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) => {
|
||||
//Gets dependency but if an Err, map to a function that upserts.
|
||||
const dep = get(key).mapErr(() => elseAction);
|
||||
if(dep.err) {
|
||||
if (dep.err) {
|
||||
//Defers upsert until final check here
|
||||
return dep.val();
|
||||
}
|
||||
};
|
||||
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
|
||||
.andThen(() => Ok(root.delete(key)))
|
||||
.unwrapOr(ok());
|
||||
} else {
|
||||
getOr(key, action);
|
||||
}
|
||||
|
||||
};
|
||||
xGetOr('@sern/emitter', () => root.upsert({
|
||||
'@sern/emitter' : _const(new SernEmitter())
|
||||
})
|
||||
xGetOr('@sern/emitter', () =>
|
||||
root.upsert({
|
||||
'@sern/emitter': _const(new SernEmitter()),
|
||||
}),
|
||||
);
|
||||
//An "optional" dependency
|
||||
xGetOr('@sern/logger', () => {
|
||||
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({
|
||||
'@sern/store' : _const(new ModuleStore())
|
||||
})
|
||||
xGetOr('@sern/modules', () =>
|
||||
root.upsert(ctx => ({
|
||||
'@sern/modules': _const(new DefaultModuleManager(ctx['@sern/store'] as ModuleStore)),
|
||||
})),
|
||||
);
|
||||
xGetOr('@sern/modules', () => root.upsert((ctx) => ({
|
||||
'@sern/modules' : _const(new DefaultModuleManager(ctx['@sern/store'] as ModuleStore))
|
||||
}))
|
||||
);
|
||||
xGetOr('@sern/errors', () => 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.
|
||||
get<Logging>('@sern/logger')
|
||||
.map((logger => logger.info({ message: 'All dependencies loaded successfully' })))
|
||||
.map(logger => logger.info({ message: 'All dependencies loaded successfully' }))
|
||||
.unwrapOr(ok());
|
||||
}
|
||||
|
||||
|
||||
export function useContainer<T extends Dependencies>() {
|
||||
const container = containerSubject.getValue()! as unknown as Container<T, {}>;
|
||||
assert.ok(container !== null, 'useContainer was called before Sern#init');
|
||||
@@ -80,4 +87,4 @@ export function useContainer<T extends Dependencies>() {
|
||||
*/
|
||||
export function useContainerRaw() {
|
||||
return containerSubject.getValue();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,15 +15,24 @@ import { SernError } from '../structures/errors';
|
||||
import treeSearch from '../utilities/treeSearch';
|
||||
import type {
|
||||
BothCommand,
|
||||
ButtonCommand, ContextMenuMsg,
|
||||
ButtonCommand,
|
||||
ContextMenuMsg,
|
||||
ContextMenuUser,
|
||||
ModalSubmitCommand,
|
||||
StringSelectCommand,
|
||||
SlashCommand, UserSelectCommand, ChannelSelectCommand, MentionableSelectCommand, RoleSelectCommand,
|
||||
SlashCommand,
|
||||
UserSelectCommand,
|
||||
ChannelSelectCommand,
|
||||
MentionableSelectCommand,
|
||||
RoleSelectCommand,
|
||||
} from '../../types/module';
|
||||
import type SernEmitter from '../sernEmitter';
|
||||
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 { reducePlugins } from '../utilities/functions';
|
||||
import { concatMap, from, fromEvent, map, of } from 'rxjs';
|
||||
@@ -85,7 +94,14 @@ export function buttonCommandDispatcher(interaction: ButtonInteraction) {
|
||||
|
||||
export function selectMenuCommandDispatcher(interaction: MessageComponentInteraction) {
|
||||
//safe casts because command type runtime check
|
||||
return (mod: StringSelectCommand | UserSelectCommand | ChannelSelectCommand | MentionableSelectCommand | RoleSelectCommand) => ({
|
||||
return (
|
||||
mod:
|
||||
| StringSelectCommand
|
||||
| UserSelectCommand
|
||||
| ChannelSelectCommand
|
||||
| MentionableSelectCommand
|
||||
| RoleSelectCommand,
|
||||
) => ({
|
||||
mod,
|
||||
execute: () => mod.execute(interaction as never),
|
||||
eventPluginRes: arrAsync(
|
||||
@@ -115,19 +131,27 @@ export function ctxMenuMsgDispatcher(interaction: MessageContextMenuCommandInter
|
||||
}
|
||||
|
||||
export function sernEmitterDispatcher(e: SernEmitter) {
|
||||
return(cmd: SernEventCommand & { name: string }) => ({
|
||||
return (cmd: SernEventCommand & { name: string }) => ({
|
||||
source: e,
|
||||
cmd,
|
||||
execute: fromEvent(e, cmd.name)
|
||||
.pipe( map( event => ({
|
||||
execute: fromEvent(e, cmd.name).pipe(
|
||||
map(event => ({
|
||||
event,
|
||||
executeEvent: of(event).pipe(concatMap(event =>
|
||||
reducePlugins(from(
|
||||
arrAsync(
|
||||
cmd.onEvent.map(plug => plug.execute([event as Payload], controller))
|
||||
))
|
||||
)))
|
||||
})))
|
||||
executeEvent: of(event).pipe(
|
||||
concatMap(event =>
|
||||
reducePlugins(
|
||||
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 }) => ({
|
||||
source: e,
|
||||
cmd,
|
||||
execute: fromEvent(e, cmd.name)
|
||||
.pipe( map( event => ({
|
||||
event,
|
||||
executeEvent: of(event).pipe(concatMap( event =>
|
||||
reducePlugins(from(
|
||||
arrAsync(
|
||||
// god forbid I use any!!!
|
||||
cmd.onEvent.map(plug => plug.execute([event as any], controller))
|
||||
))
|
||||
)))
|
||||
})))
|
||||
execute: fromEvent(e, cmd.name).pipe(
|
||||
map(event => ({
|
||||
event,
|
||||
executeEvent: of(event).pipe(
|
||||
concatMap(event =>
|
||||
reducePlugins(
|
||||
from(
|
||||
arrAsync(
|
||||
// god forbid I use any!!!
|
||||
cmd.onEvent.map(plug =>
|
||||
plug.execute([event as any], controller),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
})),
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
export function externalEventDispatcher(e: (e:ExternalEventCommand) => unknown) {
|
||||
return (cmd: ExternalEventCommand & { name: string}) => {
|
||||
export function externalEventDispatcher(e: (e: ExternalEventCommand) => unknown) {
|
||||
return (cmd: ExternalEventCommand & { name: string }) => {
|
||||
const external = e(cmd);
|
||||
assert.ok(external instanceof EventEmitter, `${e} is not an EventEmitter`);
|
||||
return {
|
||||
source: external,
|
||||
cmd,
|
||||
execute: fromEvent(external, cmd.name)
|
||||
.pipe(map(event => ({
|
||||
event,
|
||||
executeEvent : of(event).pipe(concatMap(event =>
|
||||
reducePlugins(from(arrAsync(
|
||||
cmd.onEvent.map(plug => plug.execute([event], controller))
|
||||
)))
|
||||
)),
|
||||
})))
|
||||
execute: fromEvent(external, cmd.name).pipe(
|
||||
map(event => ({
|
||||
event,
|
||||
executeEvent: of(event).pipe(
|
||||
concatMap(event =>
|
||||
reducePlugins(
|
||||
from(
|
||||
arrAsync(
|
||||
cmd.onEvent.map(plug => plug.execute([event], controller)),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
})),
|
||||
),
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
@@ -13,14 +13,14 @@ export abstract class EventsHandler<T> {
|
||||
protected logger?: Logging;
|
||||
protected modules: ModuleManager;
|
||||
protected constructor({ containerConfig }: Wrapper) {
|
||||
const [
|
||||
client,
|
||||
emitter,
|
||||
crash,
|
||||
modules,
|
||||
logger,
|
||||
] = containerConfig.get('@sern/client', '@sern/emitter', '@sern/errors', '@sern/modules', '@sern/logger');
|
||||
this.logger = logger as Logging|undefined;
|
||||
const [client, emitter, crash, modules, logger] = containerConfig.get(
|
||||
'@sern/client',
|
||||
'@sern/emitter',
|
||||
'@sern/errors',
|
||||
'@sern/modules',
|
||||
'@sern/logger',
|
||||
);
|
||||
this.logger = logger as Logging | undefined;
|
||||
this.modules = modules as ModuleManager;
|
||||
this.client = client as EventEmitter;
|
||||
this.emitter = emitter as SernEmitter;
|
||||
|
||||
@@ -38,8 +38,9 @@ export default class InteractionHandler extends EventsHandler<{
|
||||
this.payloadSubject
|
||||
.pipe(
|
||||
map(this.processModules),
|
||||
concatMap(({ mod, execute, eventPluginRes }) =>
|
||||
from(eventPluginRes).pipe(map(res => ({ mod, res, execute }))) //resolve all the Results from event plugins
|
||||
concatMap(
|
||||
({ mod, execute, eventPluginRes }) =>
|
||||
from(eventPluginRes).pipe(map(res => ({ mod, res, execute }))), //resolve all the Results from event plugins
|
||||
),
|
||||
concatMap(payload => executeModule(wrapper, payload)),
|
||||
catchError(handleError(this.crashHandler, this.logger)),
|
||||
@@ -48,23 +49,25 @@ export default class InteractionHandler extends EventsHandler<{
|
||||
}
|
||||
|
||||
override init() {
|
||||
const get = (cb: (ms: ModuleStore) => CommandModule|undefined) => {
|
||||
return this.modules.get(cb);
|
||||
const get = (cb: (ms: ModuleStore) => CommandModule | undefined) => {
|
||||
return this.modules.get(cb);
|
||||
};
|
||||
this.discordEvent.subscribe({
|
||||
next: event => {
|
||||
if (event.isMessageComponent()) {
|
||||
const mod = get(ms =>
|
||||
ms.InteractionHandlers[event.componentType].get(event.customId));
|
||||
const mod = get(ms =>
|
||||
ms.InteractionHandlers[event.componentType].get(event.customId),
|
||||
);
|
||||
this.setState({ event, mod });
|
||||
} else if (event.isCommand() || event.isAutocomplete()) {
|
||||
const mod = get(ms =>
|
||||
ms.ApplicationCommands[event.commandType].get(event.commandName) ??
|
||||
ms.BothCommands.get(event.commandName)
|
||||
const mod = get(
|
||||
ms =>
|
||||
ms.ApplicationCommands[event.commandType].get(event.commandName) ??
|
||||
ms.BothCommands.get(event.commandName),
|
||||
);
|
||||
this.setState({ event, mod });
|
||||
} 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 });
|
||||
} else {
|
||||
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 {
|
||||
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 {
|
||||
//if statement above checks already, safe cast
|
||||
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: P.union(
|
||||
{
|
||||
type: P.union(
|
||||
CommandType.RoleSelect,
|
||||
CommandType.StringSelect,
|
||||
CommandType.UserSelect,
|
||||
CommandType.MentionableSelect,
|
||||
CommandType.ChannelSelect
|
||||
) },
|
||||
CommandType.ChannelSelect,
|
||||
),
|
||||
},
|
||||
selectMenuCommandDispatcher(event as MessageComponentInteraction),
|
||||
)
|
||||
.with(
|
||||
|
||||
@@ -26,7 +26,7 @@ export default class MessageHandler extends EventsHandler<{
|
||||
.pipe(
|
||||
switchMap(({ mod, ctx, args }) => {
|
||||
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);
|
||||
//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
|
||||
const { defaultPrefix } = this.wrapper;
|
||||
const get = (cb: (ms: ModuleStore) => CommandModule | undefined) => {
|
||||
return this.modules.get(cb);
|
||||
return this.modules.get(cb);
|
||||
};
|
||||
this.discordEvent
|
||||
.pipe(
|
||||
@@ -52,10 +52,7 @@ export default class MessageHandler extends EventsHandler<{
|
||||
return {
|
||||
ctx: Context.wrap(message),
|
||||
args: <['text', string[]]>['text', rest],
|
||||
mod: get(ms =>
|
||||
ms.TextCommands.get(prefix) ??
|
||||
ms.BothCommands.get(prefix)
|
||||
),
|
||||
mod: get(ms => ms.TextCommands.get(prefix) ?? ms.BothCommands.get(prefix)),
|
||||
};
|
||||
}),
|
||||
concatMap(element =>
|
||||
@@ -67,8 +64,7 @@ export default class MessageHandler extends EventsHandler<{
|
||||
)
|
||||
.subscribe({
|
||||
next: value => this.setState(value),
|
||||
error: reason =>
|
||||
this.emitter.emit('error', { type: PayloadType.Failure, reason }),
|
||||
error: 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;
|
||||
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(
|
||||
concatMap(res => {
|
||||
if (res.err) {
|
||||
@@ -115,7 +117,10 @@ export function executeModule(
|
||||
}
|
||||
}
|
||||
|
||||
export function resolvePlugins({ mod, cmdPluginRes }: {
|
||||
export function resolvePlugins({
|
||||
mod,
|
||||
cmdPluginRes,
|
||||
}: {
|
||||
mod: DefinedCommandModule | DefinedEventModule;
|
||||
cmdPluginRes: {
|
||||
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);
|
||||
return of({ mod: payload.mod, cmdPluginRes });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,10 +37,8 @@ export default class ReadyHandler extends EventsHandler<{
|
||||
);
|
||||
this.init();
|
||||
this.payloadSubject
|
||||
.pipe(
|
||||
concatMap(processPlugins),
|
||||
concatMap(resolvePlugins),
|
||||
).subscribe(payload => {
|
||||
.pipe(concatMap(processPlugins), concatMap(resolvePlugins))
|
||||
.subscribe(payload => {
|
||||
const allPluginsSuccessful = payload.pluginRes.every(({ execute }) => execute.ok);
|
||||
if (allPluginsSuccessful) {
|
||||
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 insert = (cb: (ms: ModuleStore) => void) => {
|
||||
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));
|
||||
})
|
||||
.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 => {
|
||||
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 =>
|
||||
insert(ms => ms.ApplicationCommands[ApplicationCommandType.User].set(name, mod))
|
||||
insert(ms => ms.ApplicationCommands[ApplicationCommandType.User].set(name, 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 =>
|
||||
insert(ms => ms.InteractionHandlers[ComponentType.Button].set(name, mod))
|
||||
insert(ms => ms.InteractionHandlers[ComponentType.Button].set(name, 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 =>
|
||||
insert (ms => ms.InteractionHandlers[ComponentType.MentionableSelect].set(name, mod))
|
||||
.with({ type: CommandType.MentionableSelect }, mod =>
|
||||
insert(ms => ms.InteractionHandlers[ComponentType.MentionableSelect].set(name, mod)),
|
||||
)
|
||||
.with( { type: CommandType.ChannelSelect }, mod =>
|
||||
insert ( ms => ms.InteractionHandlers[ComponentType.ChannelSelect].set(name, mod))
|
||||
.with({ type: CommandType.ChannelSelect }, mod =>
|
||||
insert(ms => ms.InteractionHandlers[ComponentType.ChannelSelect].set(name, mod)),
|
||||
)
|
||||
.with( { type: CommandType.UserSelect }, mod =>
|
||||
insert ( ms => ms.InteractionHandlers[ComponentType.UserSelect].set(name, mod))
|
||||
.with({ type: CommandType.UserSelect }, mod =>
|
||||
insert(ms => ms.InteractionHandlers[ComponentType.UserSelect].set(name, mod)),
|
||||
)
|
||||
.with( { type: CommandType.RoleSelect}, 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.RoleSelect }, mod =>
|
||||
insert(ms => ms.InteractionHandlers[ComponentType.RoleSelect].set(name, mod)),
|
||||
)
|
||||
.with({ type: CommandType.Modal }, mod => insert(ms => ms.ModalSubmit.set(name, mod)))
|
||||
.otherwise(err);
|
||||
}
|
||||
|
||||
@@ -11,7 +11,11 @@ import type { EventEmitter } from 'events';
|
||||
import type SernEmitter from '../sernEmitter';
|
||||
import { nameOrFilename, reducePlugins } from '../utilities/functions';
|
||||
import { match } from 'ts-pattern';
|
||||
import { discordEventDispatcher, externalEventDispatcher, sernEmitterDispatcher } from './dispatchers';
|
||||
import {
|
||||
discordEventDispatcher,
|
||||
externalEventDispatcher,
|
||||
sernEmitterDispatcher,
|
||||
} from './dispatchers';
|
||||
import type { ErrorHandling, Logging } from '../contracts';
|
||||
import { SernError } from '../structures/errors';
|
||||
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
|
||||
* @param payload
|
||||
*/
|
||||
export function processCommandPlugins<T extends DefinedCommandModule | DefinedEventModule>(
|
||||
payload: { mod: T; absPath: string },
|
||||
): {type: PluginType.Command, execute: Awaitable<Result<void,void>>}[] {
|
||||
export function processCommandPlugins<
|
||||
T extends DefinedCommandModule | DefinedEventModule,
|
||||
>(payload: {
|
||||
mod: T;
|
||||
absPath: string;
|
||||
}): { type: PluginType.Command; execute: Awaitable<Result<void, void>> }[] {
|
||||
return payload.mod.plugins.map(plug => ({
|
||||
type: plug.type,
|
||||
execute: plug.execute(payload as any, controller),
|
||||
@@ -32,77 +39,86 @@ export function processCommandPlugins<T extends DefinedCommandModule | DefinedEv
|
||||
}
|
||||
|
||||
export function processEvents({ containerConfig, events }: Wrapper) {
|
||||
const [
|
||||
client,
|
||||
error,
|
||||
sernEmitter,
|
||||
logging
|
||||
] = containerConfig.get('@sern/client', '@sern/errors', '@sern/emitter', '@sern/logger') as [EventEmitter, ErrorHandling, SernEmitter, Logging?];
|
||||
const [client, error, sernEmitter, logging] = containerConfig.get(
|
||||
'@sern/client',
|
||||
'@sern/errors',
|
||||
'@sern/emitter',
|
||||
'@sern/logger',
|
||||
) as [EventEmitter, ErrorHandling, SernEmitter, Logging?];
|
||||
const lazy = (k: string) => containerConfig.get(k as keyof Dependencies)[0];
|
||||
const eventStream$ = eventObservable$(events!, sernEmitter);
|
||||
const emitSuccess$ = (mod: AnyModule) =>
|
||||
of({ type: PayloadType.Failure, module: mod, reason: SernError.PluginFailure })
|
||||
.pipe(tap( it => sernEmitter.emit('module.register', it)));
|
||||
of({ type: PayloadType.Failure, module: mod, reason: SernError.PluginFailure }).pipe(
|
||||
tap(it => sernEmitter.emit('module.register', it)),
|
||||
);
|
||||
const emitFailure$ = (mod: AnyModule) =>
|
||||
of({ type: PayloadType.Success, module: mod, } as const)
|
||||
.pipe(tap(it => sernEmitter.emit('module.register', it)));
|
||||
of({ type: PayloadType.Success, module: mod } as const).pipe(
|
||||
tap(it => sernEmitter.emit('module.register', it)),
|
||||
);
|
||||
const eventCreation$ = eventStream$.pipe(
|
||||
map(({ mod, absPath }) => ({
|
||||
mod : {
|
||||
mod: {
|
||||
name: nameOrFilename(mod.name, absPath),
|
||||
...mod,
|
||||
} as DefinedEventModule,
|
||||
absPath
|
||||
absPath,
|
||||
})),
|
||||
concatMap(processPlugins),
|
||||
concatMap(resolvePlugins),
|
||||
//Reduces pluginRes (generated from above) into a single boolean
|
||||
concatMap(({pluginRes, mod}) => from(pluginRes)
|
||||
.pipe(
|
||||
concatMap(({ pluginRes, mod }) =>
|
||||
from(pluginRes).pipe(
|
||||
map(pl => pl.execute),
|
||||
toArray(),
|
||||
reducePlugins,
|
||||
map(success => ({ success, mod }))
|
||||
)),
|
||||
map(success => ({ success, mod })),
|
||||
),
|
||||
),
|
||||
concatMap(({ success, mod }) =>
|
||||
iif(() => success,
|
||||
emitFailure$(mod),
|
||||
emitSuccess$(mod)
|
||||
).pipe(
|
||||
iif(() => success, emitFailure$(mod), emitSuccess$(mod)).pipe(
|
||||
filter(res => res.type === PayloadType.Success),
|
||||
map(() => mod)
|
||||
)
|
||||
map(() => mod),
|
||||
),
|
||||
),
|
||||
);
|
||||
eventCreation$.subscribe(e => {
|
||||
const payload = match(e)
|
||||
.when(isSernEvent, sernEmitterDispatcher(sernEmitter))
|
||||
.when(isDiscordEvent, discordEventDispatcher(client))
|
||||
.when(isExternalEvent, externalEventDispatcher(e => lazy(e.emitter)))
|
||||
.when(
|
||||
isExternalEvent,
|
||||
externalEventDispatcher(e => lazy(e.emitter)),
|
||||
)
|
||||
.otherwise(() => error.crash(Error(SernError.InvalidModuleType)));
|
||||
payload
|
||||
.execute
|
||||
payload.execute
|
||||
.pipe(
|
||||
concatMap(({event, executeEvent}) =>
|
||||
executeEvent
|
||||
.pipe( tap(success => {
|
||||
if(success)
|
||||
payload.cmd.execute(event as never);
|
||||
}), catchError(handleError(error, logging)))
|
||||
concatMap(({ event, executeEvent }) =>
|
||||
executeEvent.pipe(
|
||||
tap(success => {
|
||||
if (success) {
|
||||
if (Array.isArray(event)) {
|
||||
payload.cmd.execute(...event);
|
||||
} else {
|
||||
payload.cmd.execute(event as never);
|
||||
}
|
||||
}
|
||||
}),
|
||||
catchError(handleError(error, logging)),
|
||||
),
|
||||
),
|
||||
).subscribe();
|
||||
)
|
||||
.subscribe();
|
||||
});
|
||||
}
|
||||
|
||||
function eventObservable$(events: string, emitter: SernEmitter) {
|
||||
return buildData<EventModule>(events)
|
||||
.pipe(
|
||||
errTap(reason =>
|
||||
emitter.emit('module.register', {
|
||||
type: PayloadType.Failure,
|
||||
module: undefined,
|
||||
reason,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return buildData<EventModule>(events).pipe(
|
||||
errTap(reason =>
|
||||
emitter.emit('module.register', {
|
||||
type: PayloadType.Failure,
|
||||
module: undefined,
|
||||
reason,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -31,31 +31,32 @@ export interface Plugin {
|
||||
name?: string;
|
||||
/** @deprecated will be removed in the next update */
|
||||
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;
|
||||
execute: (
|
||||
payload: {
|
||||
mod: CommandModuleDefs[T] & { name : string; description : string };
|
||||
mod: CommandModuleDefs[T] & { name: string; description: string };
|
||||
absPath: string;
|
||||
},
|
||||
controller: Controller,
|
||||
) => Awaitable<Result<void, void>>;
|
||||
}
|
||||
export interface DiscordEmitterPlugin extends Plugin {
|
||||
type: PluginType.Command;
|
||||
execute: (
|
||||
payload: { mod: DiscordEventCommand & { name: string }; absPath: string },
|
||||
controller: Controller,
|
||||
) => Awaitable<Result<void, void>>;
|
||||
type: PluginType.Command;
|
||||
execute: (
|
||||
payload: { mod: DiscordEventCommand & { name: string }; absPath: string },
|
||||
controller: Controller,
|
||||
) => Awaitable<Result<void, void>>;
|
||||
}
|
||||
|
||||
export interface ExternalEmitterPlugin extends Plugin {
|
||||
type: PluginType.Command;
|
||||
execute: (
|
||||
payload: { mod: ExternalEventCommand & { name : string }; absPath: string } ,
|
||||
payload: { mod: ExternalEventCommand & { name: string }; absPath: string },
|
||||
controller: Controller,
|
||||
) => Awaitable<Result<void, void>>;
|
||||
}
|
||||
@@ -63,7 +64,7 @@ export interface ExternalEmitterPlugin extends Plugin {
|
||||
export interface SernEmitterPlugin extends Plugin {
|
||||
type: PluginType.Command;
|
||||
execute: (
|
||||
payload: { mod : SernEventCommand & { name : string }; absPath: string },
|
||||
payload: { mod: SernEventCommand & { name: string }; absPath: string },
|
||||
controller: Controller,
|
||||
) => Awaitable<Result<void, void>>;
|
||||
}
|
||||
@@ -76,8 +77,8 @@ export interface AutocompletePlugin extends Plugin {
|
||||
) => Awaitable<Result<void, void>>;
|
||||
}
|
||||
|
||||
|
||||
export interface EventPlugin<K extends keyof CommandModuleDefs = keyof CommandModuleDefs> extends Plugin {
|
||||
export interface EventPlugin<K extends keyof CommandModuleDefs = keyof CommandModuleDefs>
|
||||
extends Plugin {
|
||||
type: PluginType.Event;
|
||||
execute: (
|
||||
event: Parameters<CommandModuleDefs[K]['execute']>,
|
||||
@@ -85,13 +86,11 @@ export interface EventPlugin<K extends keyof CommandModuleDefs = keyof CommandMo
|
||||
) => 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;
|
||||
type: PluginType.Event;
|
||||
execute: (
|
||||
args: SernEventsMapping[T],
|
||||
controller: Controller,
|
||||
) => Awaitable<Result<void, void>>;
|
||||
execute: (args: SernEventsMapping[T], controller: Controller) => Awaitable<Result<void, void>>;
|
||||
}
|
||||
|
||||
export interface ExternalEventPlugin extends Plugin {
|
||||
@@ -99,7 +98,8 @@ export interface ExternalEventPlugin extends Plugin {
|
||||
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;
|
||||
type: PluginType.Event;
|
||||
execute: (args: ClientEvents[T], controller: Controller) => Awaitable<Result<void, void>>;
|
||||
|
||||
@@ -13,7 +13,12 @@ import type {
|
||||
import InteractionHandler from './events/interactionHandler';
|
||||
import ReadyHandler from './events/readyHandler';
|
||||
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 type { Dependencies, OptionalDependencies } from '../types/handler';
|
||||
import { composeRoot, containerSubject, useContainer } from './dependencies/provider';
|
||||
@@ -46,7 +51,7 @@ export function init(wrapper: Wrapper) {
|
||||
new MessageHandler(wrapper);
|
||||
new InteractionHandler(wrapper);
|
||||
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
|
||||
*/
|
||||
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 {
|
||||
...mod,
|
||||
onEvent,
|
||||
@@ -74,8 +82,11 @@ export function commandModule(mod: InputCommandModule): CommandModule {
|
||||
* @param mod
|
||||
*/
|
||||
export function eventModule(mod: InputEventModule): EventModule {
|
||||
const [onEvent, plugins] = partition(mod.plugins ?? [], el => (el as Plugin).type === PluginType.Event);
|
||||
return {
|
||||
const [onEvent, plugins] = partition(
|
||||
mod.plugins ?? [],
|
||||
el => (el as Plugin).type === PluginType.Event,
|
||||
);
|
||||
return {
|
||||
...mod,
|
||||
onEvent,
|
||||
plugins,
|
||||
@@ -85,8 +96,8 @@ export function eventModule(mod: InputEventModule): EventModule {
|
||||
* @param conf a configuration for creating your project dependencies
|
||||
*/
|
||||
export function makeDependencies<T extends Dependencies>(conf: {
|
||||
exclude?: Set<OptionalDependencies>,
|
||||
build: (root: Container<Record<string,any>, {}>) => Container<Partial<T>, T>,
|
||||
exclude?: Set<OptionalDependencies>;
|
||||
build: (root: Container<Record<string, any>, {}>) => Container<Partial<T>, T>;
|
||||
}) {
|
||||
const container = conf.build(createContainer());
|
||||
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 { SernError } from './errors';
|
||||
|
||||
|
||||
function safeUnwrap<T>(res: Either<T, T>) {
|
||||
return res.val;
|
||||
}
|
||||
@@ -20,16 +19,14 @@ function safeUnwrap<T>(res: Either<T, T>) {
|
||||
* Message and ChatInputCommandInteraction
|
||||
*/
|
||||
export default class Context {
|
||||
private constructor(
|
||||
private ctx: Either<Message, ChatInputCommandInteraction>,
|
||||
) {}
|
||||
private constructor(private ctx: Either<Message, ChatInputCommandInteraction>) {}
|
||||
|
||||
/**
|
||||
* Getting the Message object. Crashes if module type is
|
||||
* CommandType.Slash or the event fired in a Both command was
|
||||
* ChatInputCommandInteraction
|
||||
*/
|
||||
public get message() {
|
||||
public get message() {
|
||||
return this.ctx.expect(SernError.MismatchEvent);
|
||||
}
|
||||
/**
|
||||
@@ -42,71 +39,45 @@ export default class Context {
|
||||
}
|
||||
|
||||
public get id(): Snowflake {
|
||||
return safeUnwrap(
|
||||
this.ctx
|
||||
.map(m => m.id)
|
||||
.mapErr(i => i.id));
|
||||
return safeUnwrap(this.ctx.map(m => m.id).mapErr(i => i.id));
|
||||
}
|
||||
|
||||
public get channel() {
|
||||
return safeUnwrap(this.ctx
|
||||
.map(m => m.channel)
|
||||
.mapErr(i => i.channel));
|
||||
return safeUnwrap(this.ctx.map(m => m.channel).mapErr(i => i.channel));
|
||||
}
|
||||
/**
|
||||
* 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 createdTimestamp(): number {
|
||||
return safeUnwrap(this.ctx
|
||||
.map(m => m.createdTimestamp)
|
||||
.mapErr(i => i.createdTimestamp)
|
||||
);
|
||||
return safeUnwrap(this.ctx.map(m => m.createdTimestamp).mapErr(i => i.createdTimestamp));
|
||||
}
|
||||
|
||||
public get guild() {
|
||||
return safeUnwrap(this.ctx
|
||||
.map(m => m.guild)
|
||||
.mapErr(i => i.guild)
|
||||
);
|
||||
return safeUnwrap(this.ctx.map(m => m.guild).mapErr(i => i.guild));
|
||||
}
|
||||
|
||||
public get guildId() {
|
||||
return safeUnwrap(this.ctx
|
||||
.map(m => m.guildId)
|
||||
.mapErr(i => i.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 safeUnwrap(this.ctx
|
||||
.map(m => m.member)
|
||||
.mapErr(i => i.member)
|
||||
);
|
||||
return safeUnwrap(this.ctx.map(m => m.member).mapErr(i => i.member));
|
||||
}
|
||||
|
||||
public get client(): Client {
|
||||
return safeUnwrap(this.ctx
|
||||
.map(m => m.client)
|
||||
.mapErr(i => i.client)
|
||||
);
|
||||
return safeUnwrap(this.ctx.map(m => m.client).mapErr(i => i.client));
|
||||
}
|
||||
|
||||
public get inGuild(): boolean {
|
||||
return safeUnwrap(this.ctx
|
||||
.map(m=>m.inGuild())
|
||||
.mapErr(i => i.inGuild())
|
||||
);
|
||||
return safeUnwrap(this.ctx.map(m => m.inGuild()).mapErr(i => i.inGuild()));
|
||||
}
|
||||
public isMessage() {
|
||||
return this.ctx.map(() => true).unwrapOr(false);
|
||||
@@ -124,9 +95,12 @@ export default class Context {
|
||||
}
|
||||
|
||||
public reply(content: ReplyOptions) {
|
||||
return safeUnwrap(this.ctx
|
||||
.map( m => m.reply(content as string | MessageReplyOptions))
|
||||
.mapErr(i => i.reply(content as string | InteractionReplyOptions).then(() => i.fetchReply()))
|
||||
return safeUnwrap(
|
||||
this.ctx
|
||||
.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,
|
||||
MentionableSelect = 512,
|
||||
RoleSelect= 1024,
|
||||
UserSelect= 2048
|
||||
RoleSelect = 1024,
|
||||
UserSelect = 2048,
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -34,5 +34,5 @@ export enum SernError {
|
||||
/**
|
||||
* 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 { Module } from '../../types/module';
|
||||
|
||||
|
||||
export interface SernEventCommand<T extends keyof SernEventsMapping = keyof SernEventsMapping> extends Module {
|
||||
export interface SernEventCommand<T extends keyof SernEventsMapping = keyof SernEventsMapping>
|
||||
extends Module {
|
||||
name?: T;
|
||||
type: EventType.Sern;
|
||||
onEvent: SernEventPlugin[];
|
||||
@@ -20,7 +20,8 @@ export interface SernEventCommand<T extends keyof SernEventsMapping = keyof Sern
|
||||
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;
|
||||
type: EventType.Discord;
|
||||
onEvent: DiscordEventPlugin[];
|
||||
@@ -29,7 +30,7 @@ export interface DiscordEventCommand<T extends keyof ClientEvents = keyof Client
|
||||
}
|
||||
|
||||
export interface ExternalEventCommand extends Module {
|
||||
name?: string
|
||||
name?: string;
|
||||
emitter: string;
|
||||
type: EventType.External;
|
||||
onEvent: ExternalEventPlugin[];
|
||||
|
||||
@@ -6,8 +6,8 @@ import { ApplicationCommandType, ComponentType } from 'discord.js';
|
||||
* This dependency is usually injected into ModuleManager
|
||||
*/
|
||||
export class ModuleStore {
|
||||
readonly BothCommands = new Map<string, CommandModule>();
|
||||
readonly ApplicationCommands = {
|
||||
readonly BothCommands = new Map<string, CommandModule>();
|
||||
readonly ApplicationCommands = {
|
||||
[ApplicationCommandType.User]: new Map<string, CommandModule>(),
|
||||
[ApplicationCommandType.Message]: new Map<string, CommandModule>(),
|
||||
[ApplicationCommandType.ChatInput]: new Map<string, CommandModule>(),
|
||||
@@ -17,10 +17,9 @@ export class ModuleStore {
|
||||
readonly InteractionHandlers = {
|
||||
[ComponentType.Button]: new Map<string, CommandModule>(),
|
||||
[ComponentType.StringSelect]: new Map<string, CommandModule>(),
|
||||
[ComponentType.ChannelSelect] : new Map<string, CommandModule>(),
|
||||
[ComponentType.MentionableSelect] : new Map<string, CommandModule>(),
|
||||
[ComponentType.RoleSelect] : new Map<string, CommandModule>(),
|
||||
[ComponentType.UserSelect] : new Map<string, CommandModule>(),
|
||||
[ComponentType.ChannelSelect]: new Map<string, CommandModule>(),
|
||||
[ComponentType.MentionableSelect]: new Map<string, CommandModule>(),
|
||||
[ComponentType.RoleSelect]: new Map<string, CommandModule>(),
|
||||
[ComponentType.UserSelect]: new Map<string, CommandModule>(),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -3,8 +3,4 @@ import type Wrapper from './wrapper';
|
||||
import { ModuleStore } from './moduleStore';
|
||||
|
||||
export * from './enums';
|
||||
export {
|
||||
Context,
|
||||
Wrapper,
|
||||
ModuleStore
|
||||
};
|
||||
export { Context, Wrapper, ModuleStore };
|
||||
|
||||
@@ -8,8 +8,8 @@ interface Wrapper {
|
||||
readonly defaultPrefix?: string;
|
||||
readonly commands: string;
|
||||
readonly events?: string;
|
||||
readonly containerConfig : {
|
||||
readonly containerConfig: {
|
||||
get: (...keys: (keyof Dependencies)[]) => unknown[];
|
||||
}
|
||||
};
|
||||
}
|
||||
export default Wrapper;
|
||||
|
||||
@@ -7,13 +7,19 @@ import { Observable, of, switchMap } from 'rxjs';
|
||||
* Used for singleton in iti
|
||||
* @param value
|
||||
*/
|
||||
export const _const = <T>(value: T) => () => value;
|
||||
export const _const =
|
||||
<T>(value: T) =>
|
||||
() =>
|
||||
value;
|
||||
/**
|
||||
* A function that returns another function
|
||||
* Used for transient in iti
|
||||
* @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) {
|
||||
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 err = _const(Err.EMPTY);
|
||||
|
||||
|
||||
export function partition<T, V>(arr: (T & V)[], condition: (e: (T & V)) => boolean) : [T[], V[]] {
|
||||
const t : T[] = [];
|
||||
const v : V[] = [];
|
||||
for(const el of arr) {
|
||||
if(condition(el)) {
|
||||
export function partition<T, V>(arr: (T & V)[], condition: (e: T & V) => boolean): [T[], V[]] {
|
||||
const t: T[] = [];
|
||||
const v: V[] = [];
|
||||
for (const el of arr) {
|
||||
if (condition(el)) {
|
||||
t.push(el as T);
|
||||
} else {
|
||||
v.push(el as V);
|
||||
}
|
||||
}
|
||||
return [ t, v ];
|
||||
return [t, v];
|
||||
}
|
||||
|
||||
export function reducePlugins(src: Observable<Result<void, void>[]>) : Observable<boolean> {
|
||||
return src.pipe(switchMap(s => of(s.every((a) => a.ok))));
|
||||
}
|
||||
export function reducePlugins(src: Observable<Result<void, void>[]>): Observable<boolean> {
|
||||
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 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;
|
||||
}
|
||||
|
||||
|
||||
export function isDiscordEvent(el: EventModule | CommandModule): el is DiscordEventCommand {
|
||||
return el.type === EventType.Discord;
|
||||
}
|
||||
|
||||
@@ -4,7 +4,6 @@ import { type Observable, from, concatAll } from 'rxjs';
|
||||
import { SernError } from '../structures/errors';
|
||||
import { type Result, Err, Ok } from 'ts-results-es';
|
||||
|
||||
|
||||
// Courtesy @Townsy45
|
||||
function readPath(dir: string, arrayOfFiles: string[] = []): string[] {
|
||||
try {
|
||||
|
||||
@@ -13,30 +13,30 @@ export default function treeSearch(
|
||||
const cur = _options.pop()!;
|
||||
switch (cur.type) {
|
||||
case ApplicationCommandOptionType.Subcommand:
|
||||
{
|
||||
for (const option of cur.options ?? []) {
|
||||
_options.push(option);
|
||||
}
|
||||
}
|
||||
break;
|
||||
case ApplicationCommandOptionType.SubcommandGroup:
|
||||
{
|
||||
for (const command of cur.options ?? []) {
|
||||
_options.push(command);
|
||||
}
|
||||
}
|
||||
break;
|
||||
default:
|
||||
{
|
||||
if (cur.autocomplete) {
|
||||
const choice = iAutocomplete.options.getFocused(true);
|
||||
if (cur.name === choice.name && cur.autocomplete) {
|
||||
autocompleteData = cur;
|
||||
{
|
||||
for (const option of cur.options ?? []) {
|
||||
_options.push(option);
|
||||
}
|
||||
}
|
||||
break;
|
||||
case ApplicationCommandOptionType.SubcommandGroup:
|
||||
{
|
||||
for (const command of cur.options ?? []) {
|
||||
_options.push(command);
|
||||
}
|
||||
}
|
||||
break;
|
||||
default:
|
||||
{
|
||||
if (cur.autocomplete) {
|
||||
const choice = iAutocomplete.options.getFocused(true);
|
||||
if (cur.name === choice.name && cur.autocomplete) {
|
||||
autocompleteData = cur;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
return autocompleteData;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,4 +8,4 @@ export * from './handler/plugins/plugin';
|
||||
export * from './handler/contracts/index';
|
||||
export { SernEmitter };
|
||||
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 DefinedEventModule = EventModule & { name: string };
|
||||
export type AnyDefinedModule = DefinedCommandModule | DefinedEventModule
|
||||
export type AnyDefinedModule = DefinedCommandModule | DefinedEventModule;
|
||||
export type Payload =
|
||||
| { type: PayloadType.Success; module: AnyModule }
|
||||
| { type: PayloadType.Failure; module?: AnyModule; reason: string | Error }
|
||||
| { type: PayloadType.Warning; reason: string};
|
||||
| { type: PayloadType.Warning; reason: string };
|
||||
export type SernEventsMapping = {
|
||||
'module.register': [Payload];
|
||||
'module.activate': [Payload];
|
||||
'error': [Payload];
|
||||
'warning': [Payload];
|
||||
error: [Payload];
|
||||
warning: [Payload];
|
||||
};
|
||||
export type LogPayload<T = unknown> = { message: T }
|
||||
export type Singleton<T> = () => T
|
||||
export type LogPayload<T = unknown> = { message: T };
|
||||
export type Singleton<T> = () => T;
|
||||
export type Transient<T> = () => () => T;
|
||||
|
||||
export interface Dependencies {
|
||||
'@sern/client': Singleton<EventEmitter>;
|
||||
'@sern/logger'?: Singleton<Logging>;
|
||||
'@sern/emitter': Singleton<SernEmitter>;
|
||||
'@sern/store' : Singleton<ModuleStore>;
|
||||
'@sern/modules' : Singleton<ModuleManager>;
|
||||
'@sern/store': Singleton<ModuleStore>;
|
||||
'@sern/modules': Singleton<ModuleManager>;
|
||||
'@sern/errors': Singleton<ErrorHandling>;
|
||||
}
|
||||
|
||||
export type ReplyOptions = string | Omit<InteractionReplyOptions, 'fetchReply'> | MessageReplyOptions;
|
||||
export type ReplyOptions =
|
||||
| string
|
||||
| Omit<InteractionReplyOptions, 'fetchReply'>
|
||||
| MessageReplyOptions;
|
||||
|
||||
export type MapDeps<
|
||||
Deps extends Dependencies,
|
||||
T 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]
|
||||
export type MapDeps<Deps extends Dependencies, T 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];
|
||||
//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,
|
||||
MentionableSelectMenuInteraction,
|
||||
RoleSelectMenuInteraction,
|
||||
StringSelectMenuInteraction
|
||||
StringSelectMenuInteraction,
|
||||
} from 'discord.js';
|
||||
import type {
|
||||
DiscordEventCommand,
|
||||
@@ -36,7 +36,7 @@ export interface Module {
|
||||
type?: CommandType | EventType;
|
||||
name?: string;
|
||||
description?: string;
|
||||
execute: (...args: any[]) => any
|
||||
execute: (...args: any[]) => any;
|
||||
}
|
||||
|
||||
export interface TextCommand extends Module {
|
||||
@@ -162,10 +162,10 @@ export type CommandModuleDefs = {
|
||||
[CommandType.CtxUser]: ContextMenuUser;
|
||||
[CommandType.Button]: ButtonCommand;
|
||||
[CommandType.StringSelect]: StringSelectCommand;
|
||||
[CommandType.RoleSelect] : RoleSelectCommand;
|
||||
[CommandType.ChannelSelect] : ChannelSelectCommand;
|
||||
[CommandType.MentionableSelect] : MentionableSelectCommand;
|
||||
[CommandType.UserSelect] : UserSelectCommand;
|
||||
[CommandType.RoleSelect]: RoleSelectCommand;
|
||||
[CommandType.ChannelSelect]: ChannelSelectCommand;
|
||||
[CommandType.MentionableSelect]: MentionableSelectCommand;
|
||||
[CommandType.UserSelect]: UserSelectCommand;
|
||||
[CommandType.Modal]: ModalSubmitCommand;
|
||||
};
|
||||
|
||||
@@ -175,7 +175,8 @@ export type EventModuleDefs = {
|
||||
[EventType.External]: ExternalEventCommand;
|
||||
};
|
||||
|
||||
export interface SernAutocompleteData extends Omit<BaseApplicationCommandOptionsData, 'autocomplete'> {
|
||||
export interface SernAutocompleteData
|
||||
extends Omit<BaseApplicationCommandOptionsData, 'autocomplete'> {
|
||||
autocomplete: true;
|
||||
type:
|
||||
| ApplicationCommandOptionType.String
|
||||
@@ -212,4 +213,4 @@ export type SernOptionsData<U extends ApplicationCommandOptionData = Application
|
||||
? SernSubCommandData
|
||||
: U extends ApplicationCommandSubGroupData
|
||||
? SernSubCommandGroupData
|
||||
: BaseOptions;
|
||||
: BaseOptions;
|
||||
|
||||
@@ -1,20 +1,20 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "esnext",
|
||||
"module": "commonjs",
|
||||
"outDir": "dist",
|
||||
"rootDir": "src",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"noImplicitAny": true,
|
||||
"strictNullChecks": true,
|
||||
"importsNotUsedAsValues": "error",
|
||||
"baseUrl": ".",
|
||||
"resolveJsonModule": true,
|
||||
"moduleResolution": "node",
|
||||
"skipLibCheck": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"forceConsistentCasingInFileNames": true
|
||||
},
|
||||
"include": ["src/secrets.json", "src"]
|
||||
}
|
||||
"compilerOptions": {
|
||||
"target": "esnext",
|
||||
"module": "commonjs",
|
||||
"outDir": "dist",
|
||||
"rootDir": "src",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"noImplicitAny": true,
|
||||
"strictNullChecks": true,
|
||||
"importsNotUsedAsValues": "error",
|
||||
"baseUrl": ".",
|
||||
"resolveJsonModule": true,
|
||||
"moduleResolution": "node",
|
||||
"skipLibCheck": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"forceConsistentCasingInFileNames": true
|
||||
},
|
||||
"include": ["src/secrets.json", "src"]
|
||||
}
|
||||
|
||||
@@ -1,20 +1,20 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "esnext",
|
||||
"module": "esnext",
|
||||
"outDir": "dist",
|
||||
"rootDir": "src",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"noImplicitAny": true,
|
||||
"strictNullChecks": true,
|
||||
"importsNotUsedAsValues": "error",
|
||||
"baseUrl": ".",
|
||||
"resolveJsonModule": true,
|
||||
"moduleResolution": "node",
|
||||
"skipLibCheck": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"forceConsistentCasingInFileNames": true
|
||||
},
|
||||
"include": ["src/secrets.json", "src"]
|
||||
}
|
||||
"compilerOptions": {
|
||||
"target": "esnext",
|
||||
"module": "esnext",
|
||||
"outDir": "dist",
|
||||
"rootDir": "src",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"noImplicitAny": true,
|
||||
"strictNullChecks": true,
|
||||
"importsNotUsedAsValues": "error",
|
||||
"baseUrl": ".",
|
||||
"resolveJsonModule": true,
|
||||
"moduleResolution": "node",
|
||||
"skipLibCheck": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"forceConsistentCasingInFileNames": true
|
||||
},
|
||||
"include": ["src/secrets.json", "src"]
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ const shared = {
|
||||
external: ['discord.js'],
|
||||
platform: 'node',
|
||||
clean: true,
|
||||
sourcemap: false
|
||||
sourcemap: false,
|
||||
};
|
||||
export default defineConfig([
|
||||
{
|
||||
@@ -19,7 +19,7 @@ export default defineConfig([
|
||||
js: '.mjs',
|
||||
};
|
||||
},
|
||||
...shared
|
||||
...shared,
|
||||
},
|
||||
{
|
||||
format: 'cjs',
|
||||
@@ -33,6 +33,6 @@ export default defineConfig([
|
||||
js: '.cjs',
|
||||
};
|
||||
},
|
||||
...shared
|
||||
...shared,
|
||||
},
|
||||
]);
|
||||
|
||||
Reference in New Issue
Block a user