Merge branch 'main' into renovate/actions-checkout-digest

This commit is contained in:
Jacob Nguyen
2024-03-19 10:21:40 -05:00
committed by GitHub
24 changed files with 178 additions and 203 deletions

View File

@@ -1,5 +1,21 @@
# Changelog # Changelog
## [3.3.4](https://github.com/sern-handler/handler/compare/v3.3.3...v3.3.4) (2024-03-18)
### Bug Fixes
* sern emitter err ([#358](https://github.com/sern-handler/handler/issues/358)) ([90e55df](https://github.com/sern-handler/handler/commit/90e55dfa1466c91e5da48922251309331921b1ef))
## [3.3.3](https://github.com/sern-handler/handler/compare/v3.3.2...v3.3.3) (2024-02-25)
### Bug Fixes
* rm deprecated class modules, clean up, rm indirection ([#355](https://github.com/sern-handler/handler/issues/355)) ([48f9f6e](https://github.com/sern-handler/handler/commit/48f9f6ec16e650d574bd24dcbb0ed176933bfe17))
* singleton init not being fired when inserting function ([07b11b3](https://github.com/sern-handler/handler/commit/07b11b357baac0c3c7055c022bc353995c80f766))
* typings and cleanup ([#356](https://github.com/sern-handler/handler/issues/356)) ([ce8c4bf](https://github.com/sern-handler/handler/commit/ce8c4bf6492b9680fb1c1a530d3e0028f214ad2f))
## [3.3.2](https://github.com/sern-handler/handler/compare/v3.3.1...v3.3.2) (2024-01-08) ## [3.3.2](https://github.com/sern-handler/handler/compare/v3.3.1...v3.3.2) (2024-01-08)

View File

@@ -1,7 +1,7 @@
{ {
"name": "@sern/handler", "name": "@sern/handler",
"packageManager": "yarn@3.5.0", "packageManager": "yarn@3.5.0",
"version": "3.3.2", "version": "3.3.4",
"description": "A complete, customizable, typesafe, & reactive framework for discord bots.", "description": "A complete, customizable, typesafe, & reactive framework for discord bots.",
"main": "./dist/index.js", "main": "./dist/index.js",
"module": "./dist/index.mjs", "module": "./dist/index.mjs",

View File

@@ -5,6 +5,6 @@ export * from './functions';
export type { VoidResult } from '../types/core-plugin'; export type { VoidResult } from '../types/core-plugin';
export { SernError } from './structures/enums'; export { SernError } from './structures/enums';
export { ModuleStore } from './structures/module-store'; export { ModuleStore } from './structures/module-store';
export * as DefaultServices from './structures/services'; export * as __Services from './structures/services';
export { useContainerRaw } from './ioc/base' export { useContainerRaw } from './ioc/base';

View File

@@ -16,12 +16,19 @@ interface MetadataAccess {
* @internal - direct access to the module manager will be removed in version 4 * @internal - direct access to the module manager will be removed in version 4
*/ */
export interface ModuleManager extends MetadataAccess { export interface ModuleManager extends MetadataAccess {
get(id: string): string | undefined; get(id: string): Module | undefined;
set(id: string, path: string): void; set(id: string, path: Module): void;
getPublishableCommands(): Promise<CommandModule[]>; /**
* @deprecated
*/
getPublishableCommands(): CommandModule[];
/*
* @deprecated
*/
getByNameCommandType<T extends CommandType>( getByNameCommandType<T extends CommandType>(
name: string, name: string,
commandType: T, commandType: T,
): Promise<CommandModuleDefs[T]> | undefined; ): CommandModuleDefs[T] | undefined;
} }

View File

@@ -4,6 +4,6 @@ import type { CommandMeta, Module } from '../../types/core-modules';
* Represents a core module store that stores IDs mapped to file paths. * Represents a core module store that stores IDs mapped to file paths.
*/ */
export interface CoreModuleStore { export interface CoreModuleStore {
commands: Map<string, string>; commands: Map<string, Module>;
metadata: WeakMap<Module, CommandMeta>; metadata: WeakMap<Module, CommandMeta>;
} }

View File

@@ -10,10 +10,10 @@ import type {
UserContextMenuCommandInteraction, UserContextMenuCommandInteraction,
AutocompleteInteraction AutocompleteInteraction
} from 'discord.js'; } from 'discord.js';
import { ApplicationCommandOptionType, InteractionType } from 'discord.js' import { ApplicationCommandOptionType, InteractionType } from 'discord.js';
import { PayloadType, PluginType } from './structures'; import { PayloadType, PluginType } from './structures';
import assert from 'assert'; import assert from 'assert';
import { Payload } from '../types/utility'; import type { Payload } from '../types/utility';
//function wrappers for empty ok / err //function wrappers for empty ok / err
export const ok = /* @__PURE__*/ () => Ok.EMPTY; export const ok = /* @__PURE__*/ () => Ok.EMPTY;
@@ -50,7 +50,7 @@ export function treeSearch(
if (options === undefined) return undefined; if (options === undefined) return undefined;
//clone to prevent mutation of original command module //clone to prevent mutation of original command module
const _options = options.map(a => ({ ...a })); const _options = options.map(a => ({ ...a }));
let subcommands = new Set(); const subcommands = new Set();
while (_options.length > 0) { while (_options.length > 0) {
const cur = _options.pop()!; const cur = _options.pop()!;
switch (cur.type) { switch (cur.type) {

View File

@@ -42,19 +42,10 @@ const TypeMap = new Map<number, number>([
[CommandType.RoleSelect, ComponentType.RoleSelect], [CommandType.RoleSelect, ComponentType.RoleSelect],
[CommandType.ChannelSelect, ComponentType.ChannelSelect]]); [CommandType.ChannelSelect, ComponentType.ChannelSelect]]);
/*
* Generates a number based on CommandType.
* This corresponds to an ApplicationCommandType or ComponentType
* TextCommands are 0 as they aren't either or.
*/
function apiType(t: CommandType | EventType) {
return TypeMap.get(t)!;
}
/* /*
* Generates an id based on name and CommandType. * Generates an id based on name and CommandType.
* A is for any ApplicationCommand. C is for any ComponentCommand * A is for any ApplicationCommand. C is for any ComponentCommand
* Then, another number generated by apiType function is appended * Then, another number fetched from TypeMap
*/ */
export function create(name: string, type: CommandType | EventType) { export function create(name: string, type: CommandType | EventType) {
if(type == CommandType.Text) { if(type == CommandType.Text) {
@@ -67,7 +58,7 @@ export function create(name: string, type: CommandType | EventType) {
return `${name}_M`; return `${name}_M`;
} }
const am = (appBitField & type) !== 0 ? 'A' : 'C'; const am = (appBitField & type) !== 0 ? 'A' : 'C';
return `${name}_${am}${apiType(type)}` return `${name}_${am}${TypeMap.get(type)!}`
} }

View File

@@ -3,18 +3,38 @@ import { useContainer } from './dependency-injection';
import type { CoreDependencies, DependencyConfiguration } from '../../types/ioc'; import type { CoreDependencies, DependencyConfiguration } from '../../types/ioc';
import { CoreContainer } from './container'; import { CoreContainer } from './container';
import { Result } from 'ts-results-es'; import { Result } from 'ts-results-es';
import { DefaultServices } from '../_internal'; import { __Services } from '../_internal';
import { AnyFunction } from '../../types/utility'; import { AnyFunction } from '../../types/utility';
import type { Logging } from '../contracts/logging'; import type { Logging } from '../contracts/logging';
import type { UnpackFunction } from 'iti';
//SIDE EFFECT: GLOBAL DI //SIDE EFFECT: GLOBAL DI
let containerSubject: CoreContainer<Partial<Dependencies>>; let containerSubject: CoreContainer<Partial<Dependencies>>;
/** /**
* @deprecated * @internal
* Don't use this unless you know what you're doing. Destroys old containerSubject if it exists and disposes everything
* then it will swap
*/
export async function __swap_container(c: CoreContainer<Partial<Dependencies>>) {
if(containerSubject) {
await containerSubject.disposeAll()
}
containerSubject = c;
}
/**
* @internal
* Don't use this unless you know what you're doing. Destroys old containerSubject if it exists and disposes everything
* then it will swap
*/
export function __add_container(key: string,v : Insertable) {
containerSubject.add({ [key]: v });
}
/**
* Returns the underlying data structure holding all dependencies. * Returns the underlying data structure holding all dependencies.
* Exposes methods from iti * Exposes methods from iti
* Use the Service API. The container should be readonly * Use the Service API. The container should be readonly from the consumer side
*/ */
export function useContainerRaw() { export function useContainerRaw() {
assert.ok( assert.ok(
@@ -29,19 +49,27 @@ export function disposeAll(logger: Logging|undefined) {
?.disposeAll() ?.disposeAll()
.then(() => logger?.info({ message: 'Cleaning container and crashing' })); .then(() => logger?.info({ message: 'Cleaning container and crashing' }));
} }
type UnpackedDependencies = {
const dependencyBuilder = (container: any, excluded: string[] ) => { [K in keyof Dependencies]: UnpackFunction<Dependencies[K]>
type Insertable = }
| ((container: CoreContainer<Dependencies>) => unknown ) type Insertable =
| ((container: UnpackedDependencies) => unknown)
| object | object
const dependencyBuilder = (container: any, excluded: string[] ) => {
return { return {
/** /**
* Insert a dependency into your container. * Insert a dependency into your container.
* Supply the correct key and dependency * Supply the correct key and dependency
*/ */
add(key: keyof Dependencies, v: Insertable) { add(key: keyof Dependencies, v: Insertable) {
Result.wrap(() => container.add({ [key]: v})) if(typeof v !== 'function') {
.expect("Failed to add " + key); Result.wrap(() => container.add({ [key]: v}))
.expect("Failed to add " + key);
} else {
Result.wrap(() =>
container.add((cntr: UnpackedDependencies) => ({ [key]: v(cntr)} )))
.expect("Failed to add " + key);
}
}, },
/** /**
* Exclude any dependencies from being added. * Exclude any dependencies from being added.
@@ -57,8 +85,14 @@ const dependencyBuilder = (container: any, excluded: string[] ) => {
* Swap out a preexisting dependency. * Swap out a preexisting dependency.
*/ */
swap(key: keyof Dependencies, v: Insertable) { swap(key: keyof Dependencies, v: Insertable) {
Result.wrap(() => container.upsert({ [key]: v })) if(typeof v !== 'function') {
.expect("Failed to update " + key); Result.wrap(() => container.upsert({ [key]: v}))
.expect("Failed to update " + key);
} else {
Result.wrap(() =>
container.upsert((cntr: UnpackedDependencies) => ({ [key]: v(cntr)})))
.expect("Failed to update " + key);
}
}, },
/** /**
* @param key the key of the dependency * @param key the key of the dependency
@@ -76,17 +110,11 @@ const dependencyBuilder = (container: any, excluded: string[] ) => {
}; };
}; };
type CallbackBuilder = (c: ReturnType<typeof dependencyBuilder>) => any
type ValidDependencyConfig = type ValidDependencyConfig =
| CallbackBuilder | ((c: ReturnType<typeof dependencyBuilder>) => any)
| DependencyConfiguration; | DependencyConfiguration;
export const insertLogger = (containerSubject: CoreContainer<any>) => {
containerSubject
.upsert({'@sern/logger': () => new DefaultServices.DefaultLogging});
}
/** /**
* Given the user's conf, check for any excluded/included dependency keys. * Given the user's conf, check for any excluded/included dependency keys.
@@ -101,7 +129,7 @@ function composeRoot(
//container should have no client or logger yet. //container should have no client or logger yet.
const hasLogger = conf.exclude?.has('@sern/logger'); const hasLogger = conf.exclude?.has('@sern/logger');
if (!hasLogger) { if (!hasLogger) {
insertLogger(container); __add_container('@sern/logger', new __Services.DefaultLogging);
} }
//Build the container based on the callback provided by the user //Build the container based on the callback provided by the user
conf.build(container as CoreContainer<Omit<CoreDependencies, '@sern/client'>>); conf.build(container as CoreContainer<Omit<CoreDependencies, '@sern/client'>>);
@@ -119,13 +147,13 @@ export async function makeDependencies<const T extends Dependencies>
if(typeof conf === 'function') { if(typeof conf === 'function') {
const excluded: string[] = []; const excluded: string[] = [];
conf(dependencyBuilder(containerSubject, excluded)); conf(dependencyBuilder(containerSubject, excluded));
//We only include logger if it does not exist
const includeLogger = const includeLogger =
!excluded.includes('@sern/logger') !excluded.includes('@sern/logger')
&& !containerSubject.getTokens()['@sern/logger']; && !containerSubject.hasKey('@sern/logger');
if(includeLogger) { if(includeLogger) {
insertLogger(containerSubject); __add_container('@sern/logger', new __Services.DefaultLogging);
} }
containerSubject.ready(); containerSubject.ready();

View File

@@ -2,7 +2,7 @@ import { Container } from 'iti';
import { Disposable } from '../'; import { Disposable } from '../';
import * as assert from 'node:assert'; import * as assert from 'node:assert';
import { Subject } from 'rxjs'; import { Subject } from 'rxjs';
import { DefaultServices, ModuleStore } from '../_internal'; import { __Services, ModuleStore } from '../_internal';
import * as Hooks from './hooks'; import * as Hooks from './hooks';
import { EventEmitter } from 'node:events'; import { EventEmitter } from 'node:events';
@@ -23,12 +23,11 @@ export class CoreContainer<T extends Partial<Dependencies>> extends Container<T,
.subscribe({ complete: unsubscribe }); .subscribe({ complete: unsubscribe });
(this as Container<{}, {}>) (this as Container<{}, {}>)
.add({ '@sern/errors': () => new DefaultServices.DefaultErrorHandling, .add({ '@sern/errors': () => new __Services.DefaultErrorHandling,
'@sern/emitter': () => new EventEmitter({ captureRejections: true }), '@sern/emitter': () => new EventEmitter({ captureRejections: true }),
'@sern/store': () => new ModuleStore }) '@sern/store': () => new ModuleStore })
.add(ctx => { .add(ctx => {
return { '@sern/modules': () => return { '@sern/modules': new __Services.DefaultModuleManager(ctx['@sern/store'])};
new DefaultServices.DefaultModuleManager(ctx['@sern/store']) };
}); });
} }
@@ -52,8 +51,6 @@ export class CoreContainer<T extends Partial<Dependencies>> extends Container<T,
await super.disposeAll(); await super.disposeAll();
} }
ready() { ready() {
this.ready$.complete(); this.ready$.complete();
this.ready$.unsubscribe(); this.ready$.unsubscribe();

View File

@@ -1,4 +1,3 @@
import { Result } from 'ts-results-es';
import { type Observable, from, mergeMap, ObservableInput } from 'rxjs'; import { type Observable, from, mergeMap, ObservableInput } from 'rxjs';
import { readdir, stat } from 'fs/promises'; import { readdir, stat } from 'fs/promises';
import { basename, extname, join, resolve, parse, dirname } from 'path'; import { basename, extname, join, resolve, parse, dirname } from 'path';
@@ -42,9 +41,7 @@ export async function importModule<T>(absPath: string) {
if ('default' in commandModule ) { if ('default' in commandModule ) {
commandModule = commandModule.default; commandModule = commandModule.default;
} }
return Result return { module: commandModule } as T;
.wrap(() => ({ module: commandModule.getInstance() }))
.unwrapOr({ module: commandModule }) as T;
} }
export async function defaultModuleLoader<T extends Module>(absPath: string): ModuleResult<T> { export async function defaultModuleLoader<T extends Module>(absPath: string): ModuleResult<T> {
@@ -106,7 +103,7 @@ async function* readPaths(dir: string): AsyncGenerator<string> {
} }
} }
export const requir = createRequire(import.meta.url); const requir = createRequire(import.meta.url);
export function loadConfig(wrapper: Wrapper | 'file', log: Logging | undefined): Wrapper { export function loadConfig(wrapper: Wrapper | 'file', log: Logging | undefined): Wrapper {
if (wrapper !== 'file') { if (wrapper !== 'file') {

View File

@@ -1,19 +1,13 @@
import { ClientEvents } from 'discord.js'; import { ClientEvents } from 'discord.js';
import { CommandType, EventType, PluginType } from '../core/structures'; import { EventType } from '../core/structures';
import type { import type {
AnyCommandPlugin,
AnyEventPlugin, AnyEventPlugin,
CommandArgs,
ControlPlugin,
EventArgs,
InitPlugin,
} from '../types/core-plugin'; } from '../types/core-plugin';
import type { import type {
CommandModule, CommandModule,
EventModule, EventModule,
InputCommand, InputCommand,
InputEvent, InputEvent,
Module,
} from '../types/core-modules'; } from '../types/core-modules';
import { partitionPlugins } from './_internal'; import { partitionPlugins } from './_internal';
import type { Awaitable } from '../types/utility'; import type { Awaitable } from '../types/utility';
@@ -61,53 +55,3 @@ export function discordEvent<T extends keyof ClientEvents>(mod: {
}); });
} }
/**
* @deprecated
*/
function prepareClassPlugins(c: Module) {
const [onEvent, initPlugins] = partitionPlugins(c.plugins);
c.plugins = initPlugins as InitPlugin[];
c.onEvent = onEvent as ControlPlugin[];
}
/**
* @deprecated
* Will be removed in future
*/
export abstract class CommandExecutable<const Type extends CommandType = CommandType> {
abstract type: Type;
plugins: AnyCommandPlugin[] = [];
private static _instance: CommandModule;
static getInstance() {
if (!CommandExecutable._instance) {
//@ts-ignore
CommandExecutable._instance = new this();
prepareClassPlugins(CommandExecutable._instance);
}
return CommandExecutable._instance;
}
abstract execute(...args: CommandArgs<Type, PluginType.Control>): Awaitable<unknown>;
}
/**
* @deprecated
* Will be removed in future
*/
export abstract class EventExecutable<Type extends EventType> {
abstract type: Type;
plugins: AnyEventPlugin[] = [];
private static _instance: EventModule;
static getInstance() {
if (!EventExecutable._instance) {
//@ts-ignore
EventExecutable._instance = new this();
prepareClassPlugins(EventExecutable._instance);
}
return EventExecutable._instance;
}
abstract execute(...args: EventArgs<Type, PluginType.Control>): Awaitable<unknown>;
}

View File

@@ -59,13 +59,14 @@ export const sharedEventStream = <T>(e: Emitter, eventName: string) => {
return (fromEvent(e, eventName) as Observable<T>).pipe(share()); return (fromEvent(e, eventName) as Observable<T>).pipe(share());
}; };
export function handleError<C>(crashHandler: ErrorHandling, logging?: Logging) { export function handleError<C>(crashHandler: ErrorHandling, emitter: Emitter, 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.inspect(pload, { colors: true })); if(!emitter.emit('error', pload)) {
//formatted payload const err = pload instanceof Error ? pload : Error(util.inspect(pload, { colors: true }));
logging?.error({ message: util.inspect(pload) }); logging?.error({ message: util.inspect(pload) });
crashHandler.updateAlive(err); crashHandler.updateAlive(err);
}
return caught; return caught;
}; };
} }

View File

@@ -25,10 +25,8 @@ export type Config <T extends (keyof Dependencies)[]> =
* Create a Presence module which **MUST** be put in a file called presence.(language-extension) * Create a Presence module which **MUST** be put in a file called presence.(language-extension)
* adjacent to the file where **Sern.init** is CALLED. * adjacent to the file where **Sern.init** is CALLED.
*/ */
export function module<T extends (keyof Dependencies)[]> export function module<T extends (keyof Dependencies)[]>(conf: Config<T>)
(conf: Config<T>) { { return conf; }
return conf;
}
/** /**

View File

@@ -7,5 +7,5 @@ import { CommandMeta, Module } from '../../types/core-modules';
*/ */
export class ModuleStore { export class ModuleStore {
metadata = new WeakMap<Module, CommandMeta>(); metadata = new WeakMap<Module, CommandMeta>();
commands = new Map<string, string>(); commands = new Map<string, Module>();
} }

View File

@@ -10,7 +10,7 @@ export class DefaultErrorHandling implements ErrorHandling {
throw err; throw err;
} }
#keepAlive = 5; #keepAlive = 1;
updateAlive(err: Error) { updateAlive(err: Error) {
this.#keepAlive--; this.#keepAlive--;

View File

@@ -1,6 +1,5 @@
import * as Id from '../../../core/id'; import * as Id from '../../../core/id';
import { CoreModuleStore, ModuleManager } from '../../contracts'; import { CoreModuleStore, ModuleManager } from '../../contracts';
import { Files } from '../../_internal';
import { CommandMeta, CommandModule, CommandModuleDefs, Module } from '../../../types/core-modules'; import { CommandMeta, CommandModule, CommandModuleDefs, Module } from '../../../types/core-modules';
import { CommandType } from '../enums'; import { CommandType } from '../enums';
/** /**
@@ -13,11 +12,11 @@ export class DefaultModuleManager implements ModuleManager {
getByNameCommandType<T extends CommandType>(name: string, commandType: T) { getByNameCommandType<T extends CommandType>(name: string, commandType: T) {
const id = this.get(Id.create(name, commandType)); const module = this.get(Id.create(name, commandType));
if (!id) { if (!module) {
return undefined; return undefined;
} }
return Files.importModule<CommandModuleDefs[T]>(id); return module as CommandModuleDefs[T];
} }
setMetadata(m: Module, c: CommandMeta): void { setMetadata(m: Module, c: CommandMeta): void {
@@ -35,20 +34,18 @@ export class DefaultModuleManager implements ModuleManager {
get(id: string) { get(id: string) {
return this.moduleStore.commands.get(id); return this.moduleStore.commands.get(id);
} }
set(id: string, path: string): void { set(id: string, path: CommandModule): void {
this.moduleStore.commands.set(id, path); this.moduleStore.commands.set(id, path);
} }
//not tested //not tested
getPublishableCommands(): Promise<CommandModule[]> { getPublishableCommands(): CommandModule[] {
const entries = this.moduleStore.commands.entries(); const entries = this.moduleStore.commands.entries();
const publishable = 0b000000110; const publishable = 0b000000110;
return Promise.all( return Array.from(entries)
Array.from(entries)
.filter(([id]) => { .filter(([id]) => {
const last_entry = id.at(-1); const last_entry = id.at(-1);
return last_entry == 'B' || !(publishable & Number.parseInt(last_entry!)); return last_entry == 'B' || !(publishable & Number.parseInt(last_entry!));
}) })
.map(([, path]) => Files.importModule<CommandModule>(path)), .map(([, path]) => path as CommandModule);
);
} }
} }

View File

@@ -17,10 +17,7 @@ import type { CommandModule, Module, Processed } from '../types/core-modules';
//TODO: refactor dispatchers so that it implements a strategy for each different type of payload? //TODO: refactor dispatchers so that it implements a strategy for each different type of payload?
export function dispatchMessage(module: Processed<CommandModule>, args: [Context, Args]) { export function dispatchMessage(module: Processed<CommandModule>, args: [Context, Args]) {
return { return { module, args };
module,
args,
};
} }
export function contextArgs(wrappable: Message | BaseInteraction, messageArgs?: string[]) { export function contextArgs(wrappable: Message | BaseInteraction, messageArgs?: string[]) {
@@ -87,9 +84,6 @@ export function createDispatcher(payload: {
} }
return { module: payload.module, args: contextArgs(payload.event) }; return { module: payload.module, args: contextArgs(payload.event) };
} }
default: return { default: return { module: payload.module, args: [payload.event] };
module: payload.module,
args: [payload.event],
};
} }
} }

View File

@@ -8,9 +8,9 @@ import {
of, of,
throwError, throwError,
tap, tap,
MonoTypeOperatorFunction,
catchError, catchError,
finalize, finalize,
map,
} from 'rxjs'; } from 'rxjs';
import { import {
Files, Files,
@@ -29,8 +29,7 @@ import { ObservableInput, pipe } from 'rxjs';
import { Err, Ok, Result } from 'ts-results-es'; import { Err, Ok, Result } from 'ts-results-es';
import type { Awaitable } from '../types/utility'; import type { Awaitable } from '../types/utility';
import type { ControlPlugin } from '../types/core-plugin'; import type { ControlPlugin } from '../types/core-plugin';
import type { AnyModule, CommandModule, Module, Processed } from '../types/core-modules'; import type { AnyModule, CommandMeta, CommandModule, Module, Processed } from '../types/core-modules';
import type { ImportPayload } from '../types/core';
import { disposeAll } from '../core/ioc/base'; import { disposeAll } from '../core/ioc/base';
function createGenericHandler<Source, Narrowed extends Source, Output>( function createGenericHandler<Source, Narrowed extends Source, Output>(
@@ -74,18 +73,13 @@ export function createInteractionHandler<T extends Interaction>(
const possibleIds = Id.reconstruct(event); const possibleIds = Id.reconstruct(event);
let fullPaths= possibleIds let fullPaths= possibleIds
.map(id => mg.get(id)) .map(id => mg.get(id))
.filter((id): id is string => id !== undefined); .filter((id): id is Module => id !== undefined);
if(fullPaths.length == 0) { if(fullPaths.length == 0) {
return Err.EMPTY; return Err.EMPTY;
} }
const [ path ] = fullPaths; const [ path ] = fullPaths;
return Files return Ok(createDispatcher({ module: path as Processed<CommandModule>, event }));
.defaultModuleLoader<Processed<CommandModule>>(path)
.then(payload => Ok(createDispatcher({
module: payload.module,
event,
})));
}); });
} }
@@ -103,39 +97,37 @@ export function createMessageHandler(
return Err('Possibly undefined behavior: could not find a static id to resolve'); return Err('Possibly undefined behavior: could not find a static id to resolve');
} }
} }
return Files return Ok({ args: contextArgs(event, rest), module: fullPath as Processed<CommandModule> })
.defaultModuleLoader<Processed<CommandModule>>(fullPath)
.then(payload => {
const args = contextArgs(event, rest);
return Ok({ args, ...payload });
});
}); });
} }
/** /**
* IMPURE SIDE EFFECT
* This function assigns remaining, incomplete data to each imported module. * This function assigns remaining, incomplete data to each imported module.
*/ */
function assignDefaults<T extends Module>( function assignDefaults() {
moduleManager: ModuleManager, return map(({ module, absPath }) => {
): MonoTypeOperatorFunction<ImportPayload<T>> { const processed = {
return tap(({ module, absPath }) => { name: module.name ?? Files.filename(absPath),
module.name ??= Files.filename(absPath); description: module.description ?? '...',
module.description ??= '...'; ...module
moduleManager.setMetadata(module, { }
isClass: module.constructor.name === 'Function', return {
fullPath: absPath, module: processed,
id: Id.create(module.name, module.type), absPath,
}); metadata: {
isClass: module.constructor.name === 'Function',
fullPath: absPath,
id: Id.create(processed.name, module.type),
}
}
}); });
} }
export function buildModules<T extends AnyModule>( export function buildModules<T extends AnyModule>(
input: ObservableInput<string>, input: ObservableInput<string>,
moduleManager: ModuleManager,
) { ) {
return Files return Files
.buildModuleStream<Processed<T>>(input) .buildModuleStream<Processed<T>>(input)
.pipe(assignDefaults(moduleManager)); .pipe(assignDefaults());
} }
@@ -219,9 +211,9 @@ export function callInitPlugins<T extends Processed<AnyModule>>(sernEmitter: Emi
onStop: (module: T) => { onStop: (module: T) => {
sernEmitter.emit('module.register', resultPayload(PayloadType.Failure, module, SernError.PluginFailure)); sernEmitter.emit('module.register', resultPayload(PayloadType.Failure, module, SernError.PluginFailure));
}, },
onNext: ({ module }) => { onNext: (payload) => {
sernEmitter.emit('module.register', resultPayload(PayloadType.Success, module)); sernEmitter.emit('module.register', resultPayload(PayloadType.Success, payload.module));
return { module }; return payload as { module: T; metadata: CommandMeta };
}, },
}), }),
); );
@@ -254,9 +246,9 @@ export function makeModuleExecutor<
); );
} }
export const handleCrash = (err: ErrorHandling, log?: Logging) => export const handleCrash = (err: ErrorHandling,sernemitter: Emitter, log?: Logging) =>
pipe( pipe(
catchError(handleError(err, log)), catchError(handleError(err, sernemitter, log)),
finalize(() => { finalize(() => {
log?.info({ log?.info({
message: 'A stream closed or reached end of lifetime', message: 'A stream closed or reached end of lifetime',

View File

@@ -1,29 +1,31 @@
import { ObservableInput, concat, first, fromEvent, ignoreElements, pipe } from 'rxjs'; import { ObservableInput, concat, first, fromEvent, ignoreElements, pipe, tap } from 'rxjs';
import { CommandType } from '../core/structures'; import { CommandType } from '../core/structures';
import { SernError } from '../core/_internal'; import { SernError } from '../core/_internal';
import { Result } from 'ts-results-es'; import { Result } from 'ts-results-es';
import { ModuleManager } from '../core/contracts'; import { Logging, ModuleManager } from '../core/contracts';
import { buildModules, callInitPlugins } from './_internal'; import { buildModules, callInitPlugins } from './_internal';
import * as assert from 'node:assert'; import * as assert from 'node:assert';
import * as util from 'node:util'; import * as util from 'node:util';
import type { DependencyList } from '../types/ioc'; import type { DependencyList } from '../types/ioc';
import type { AnyModule, Processed } from '../types/core-modules'; import type { AnyModule, CommandMeta, Processed } from '../types/core-modules';
export function readyHandler( export function readyHandler(
[sEmitter, , , moduleManager, client]: DependencyList, [sEmitter, , log , moduleManager, client]: DependencyList,
allPaths: ObservableInput<string>, allPaths: ObservableInput<string>,
) { ) {
const ready$ = fromEvent(client!, 'ready').pipe(once()); //Todo: add module manager on on ready
const ready$ = fromEvent(client!, 'ready').pipe(once(log));
return concat(ready$, buildModules<AnyModule>(allPaths, moduleManager))
return concat(ready$, buildModules<AnyModule>(allPaths))
.pipe(callInitPlugins(sEmitter)) .pipe(callInitPlugins(sEmitter))
.subscribe(({ module }) => { .subscribe(({ module, metadata }) => {
register(moduleManager, module) register(moduleManager, module, metadata)
.expect(SernError.InvalidModuleType + ' ' + util.inspect(module)); .expect(SernError.InvalidModuleType + ' ' + util.inspect(module));
}); });
} }
const once = () => pipe( const once = (log: Logging | undefined) => pipe(
tap(() => { log?.info({ message: "Waiting on discord client to be ready..." }) }),
first(), first(),
ignoreElements()) ignoreElements())
@@ -31,20 +33,22 @@ const once = () => pipe(
function register<T extends Processed<AnyModule>>( function register<T extends Processed<AnyModule>>(
manager: ModuleManager, manager: ModuleManager,
module: T, module: T,
metadata:CommandMeta
): Result<void, void> { ): Result<void, void> {
const { id, fullPath } = manager.getMetadata(module)!; manager.setMetadata(module, metadata)!;
const validModuleType = module.type >= 0 && module.type <= 1 << 10; const validModuleType = module.type >= 0 && module.type <= 1 << 10;
assert.ok( assert.ok(
validModuleType, validModuleType,
`Found ${module.name} at ${fullPath}, which does not have a valid type`, //@ts-ignore
`Found ${module.name} at ${metadata.fullPath}, which does not have a valid type`,
); );
if (module.type === CommandType.Both) { if (module.type === CommandType.Both) {
module.alias?.forEach(a => manager.set(`${a}_B`, fullPath)); module.alias?.forEach(a => manager.set(`${a}_B`, module));
} else { } else {
if(module.type === CommandType.Text){ if(module.type === CommandType.Text){
module.alias?.forEach(a => manager.set(`${a}_T`, fullPath)); module.alias?.forEach(a => manager.set(`${a}_T`, module));
} }
} }
return Result.wrap(() => manager.set(id, fullPath)); return Result.wrap(() => manager.set(metadata.id, module));
} }

View File

@@ -23,7 +23,7 @@ export function eventsHandler(
throw Error(SernError.InvalidModuleType + ' while creating event handler'); throw Error(SernError.InvalidModuleType + ' while creating event handler');
} }
}; };
buildModules<EventModule>(allPaths, moduleManager) buildModules<EventModule>(allPaths)
.pipe( .pipe(
callInitPlugins(emitter), callInitPlugins(emitter),
map(intoDispatcher), map(intoDispatcher),
@@ -31,6 +31,6 @@ export function eventsHandler(
* Where all events are turned on * Where all events are turned on
*/ */
mergeAll(), mergeAll(),
handleCrash(err, log)) handleCrash(err, emitter, log))
.subscribe(); .subscribe();
} }

View File

@@ -46,12 +46,8 @@ export {
commandModule, commandModule,
eventModule, eventModule,
discordEvent, discordEvent,
EventExecutable,
CommandExecutable,
} from './core/modules'; } from './core/modules';
export * as Presence from './core/presences' export * as Presence from './core/presences'
export {
useContainerRaw
} from './core/_internal'

View File

@@ -43,9 +43,10 @@ export function init(maybeWrapper: Wrapper | 'file') {
//Ready event: load all modules and when finished, time should be taken and logged //Ready event: load all modules and when finished, time should be taken and logged
readyHandler(dependencies, Files.getFullPathTree(wrapper.commands)) readyHandler(dependencies, Files.getFullPathTree(wrapper.commands))
.add(() => { .add(() => {
logger?.info({ message: "Client signaled ready, registering modules" });
const time = ((performance.now() - startTime) / 1000).toFixed(2); const time = ((performance.now() - startTime) / 1000).toFixed(2);
dependencies[0].emit('modulesLoaded'); dependencies[0].emit('modulesLoaded');
logger?.info({ message: `sern: registered all modules in ${time} s`, }); logger?.info({ message: `sern: registered in ${time} s`, });
if(presencePath.exists) { if(presencePath.exists) {
const setPresence = async (p: any) => { const setPresence = async (p: any) => {
return (dependencies[4] as Client).user?.setPresence(p); return (dependencies[4] as Client).user?.setPresence(p);
@@ -57,5 +58,5 @@ export function init(maybeWrapper: Wrapper | 'file') {
const messages$ = messageHandler(dependencies, wrapper.defaultPrefix); const messages$ = messageHandler(dependencies, wrapper.defaultPrefix);
const interactions$ = interactionHandler(dependencies); const interactions$ = interactionHandler(dependencies);
// listening to the message stream and interaction stream // listening to the message stream and interaction stream
merge(messages$, interactions$).pipe(handleCrash(errorHandler, logger)).subscribe(); merge(messages$, interactions$).pipe(handleCrash(errorHandler, dependencies[0], logger)).subscribe();
} }

View File

@@ -18,7 +18,7 @@ export type Args = ParseType<{ text: string[]; slash: SlashOptions }>;
export interface SernEventsMapping { export interface SernEventsMapping {
'module.register': [Payload]; 'module.register': [Payload];
'module.activate': [Payload]; 'module.activate': [Payload];
error: [Payload]; error: [{ type: PayloadType.Failure; module?: AnyModule; reason: string | Error }];
warning: [Payload]; warning: [Payload];
modulesLoaded: [never?]; modulesLoaded: [never?];
} }
@@ -26,7 +26,7 @@ export interface SernEventsMapping {
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; module: undefined; reason: string };
export type ReplyOptions = string | Omit<InteractionReplyOptions, 'fetchReply'> | MessageReplyOptions; export type ReplyOptions = string | Omit<InteractionReplyOptions, 'fetchReply'> | MessageReplyOptions;

View File

@@ -98,4 +98,16 @@ describe('ioc container', () => {
container.ready(); container.ready();
expect(dependency.init).toHaveBeenCalledTimes(1); expect(dependency.init).toHaveBeenCalledTimes(1);
}) })
it('should detect a key already exists', () => {
container.add({ '@sern/client': dependency2 });
expect(container.hasKey('@sern/client')).toBeTruthy()
})
it('should detect a key already exists', () => {
container.add({ '@sern/client': () => dependency2 });
expect(container.hasKey('@sern/client')).toBeTruthy()
})
}); });