Skip to content

Commit

Permalink
Merge branch 'main' into renovate/actions-checkout-digest
Browse files Browse the repository at this point in the history
  • Loading branch information
jacoobes authored Mar 19, 2024
2 parents abde1cc + a19edaf commit 264c27d
Show file tree
Hide file tree
Showing 24 changed files with 178 additions and 203 deletions.
16 changes: 16 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,21 @@
# 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)


Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@sern/handler",
"packageManager": "[email protected]",
"version": "3.3.2",
"version": "3.3.4",
"description": "A complete, customizable, typesafe, & reactive framework for discord bots.",
"main": "./dist/index.js",
"module": "./dist/index.mjs",
Expand Down
4 changes: 2 additions & 2 deletions src/core/_internal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,6 @@ export * from './functions';
export type { VoidResult } from '../types/core-plugin';
export { SernError } from './structures/enums';
export { ModuleStore } from './structures/module-store';
export * as DefaultServices from './structures/services';
export { useContainerRaw } from './ioc/base'
export * as __Services from './structures/services';
export { useContainerRaw } from './ioc/base';

15 changes: 11 additions & 4 deletions src/core/contracts/module-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,19 @@ interface MetadataAccess {
* @internal - direct access to the module manager will be removed in version 4
*/
export interface ModuleManager extends MetadataAccess {
get(id: string): string | undefined;
get(id: string): Module | undefined;

set(id: string, path: string): void;
getPublishableCommands(): Promise<CommandModule[]>;
set(id: string, path: Module): void;
/**
* @deprecated
*/
getPublishableCommands(): CommandModule[];

/*
* @deprecated
*/
getByNameCommandType<T extends CommandType>(
name: string,
commandType: T,
): Promise<CommandModuleDefs[T]> | undefined;
): CommandModuleDefs[T] | undefined;
}
2 changes: 1 addition & 1 deletion src/core/contracts/module-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@ import type { CommandMeta, Module } from '../../types/core-modules';
* Represents a core module store that stores IDs mapped to file paths.
*/
export interface CoreModuleStore {
commands: Map<string, string>;
commands: Map<string, Module>;
metadata: WeakMap<Module, CommandMeta>;
}
6 changes: 3 additions & 3 deletions src/core/functions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@ import type {
UserContextMenuCommandInteraction,
AutocompleteInteraction
} from 'discord.js';
import { ApplicationCommandOptionType, InteractionType } from 'discord.js'
import { ApplicationCommandOptionType, InteractionType } from 'discord.js';
import { PayloadType, PluginType } from './structures';
import assert from 'assert';
import { Payload } from '../types/utility';
import type { Payload } from '../types/utility';

//function wrappers for empty ok / err
export const ok = /* @__PURE__*/ () => Ok.EMPTY;
Expand Down Expand Up @@ -50,7 +50,7 @@ export function treeSearch(
if (options === undefined) return undefined;
//clone to prevent mutation of original command module
const _options = options.map(a => ({ ...a }));
let subcommands = new Set();
const subcommands = new Set();
while (_options.length > 0) {
const cur = _options.pop()!;
switch (cur.type) {
Expand Down
13 changes: 2 additions & 11 deletions src/core/id.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,19 +42,10 @@ const TypeMap = new Map<number, number>([
[CommandType.RoleSelect, ComponentType.RoleSelect],
[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.
* 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) {
if(type == CommandType.Text) {
Expand All @@ -67,7 +58,7 @@ export function create(name: string, type: CommandType | EventType) {
return `${name}_M`;
}
const am = (appBitField & type) !== 0 ? 'A' : 'C';
return `${name}_${am}${apiType(type)}`
return `${name}_${am}${TypeMap.get(type)!}`
}


Expand Down
74 changes: 51 additions & 23 deletions src/core/ioc/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,38 @@ import { useContainer } from './dependency-injection';
import type { CoreDependencies, DependencyConfiguration } from '../../types/ioc';
import { CoreContainer } from './container';
import { Result } from 'ts-results-es';
import { DefaultServices } from '../_internal';
import { __Services } from '../_internal';
import { AnyFunction } from '../../types/utility';
import type { Logging } from '../contracts/logging';

import type { UnpackFunction } from 'iti';
//SIDE EFFECT: GLOBAL DI
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.
* 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() {
assert.ok(
Expand All @@ -29,19 +49,27 @@ export function disposeAll(logger: Logging|undefined) {
?.disposeAll()
.then(() => logger?.info({ message: 'Cleaning container and crashing' }));
}

const dependencyBuilder = (container: any, excluded: string[] ) => {
type Insertable =
| ((container: CoreContainer<Dependencies>) => unknown )
type UnpackedDependencies = {
[K in keyof Dependencies]: UnpackFunction<Dependencies[K]>
}
type Insertable =
| ((container: UnpackedDependencies) => unknown)
| object
const dependencyBuilder = (container: any, excluded: string[] ) => {
return {
/**
* Insert a dependency into your container.
* Supply the correct key and dependency
*/
add(key: keyof Dependencies, v: Insertable) {
Result.wrap(() => container.add({ [key]: v}))
.expect("Failed to add " + key);
if(typeof v !== 'function') {
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.
Expand All @@ -57,8 +85,14 @@ const dependencyBuilder = (container: any, excluded: string[] ) => {
* Swap out a preexisting dependency.
*/
swap(key: keyof Dependencies, v: Insertable) {
Result.wrap(() => container.upsert({ [key]: v }))
.expect("Failed to update " + key);
if(typeof v !== 'function') {
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
Expand All @@ -76,17 +110,11 @@ const dependencyBuilder = (container: any, excluded: string[] ) => {
};
};

type CallbackBuilder = (c: ReturnType<typeof dependencyBuilder>) => any

type ValidDependencyConfig =
| CallbackBuilder
| ((c: ReturnType<typeof dependencyBuilder>) => any)
| 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.
Expand All @@ -101,7 +129,7 @@ function composeRoot(
//container should have no client or logger yet.
const hasLogger = conf.exclude?.has('@sern/logger');
if (!hasLogger) {
insertLogger(container);
__add_container('@sern/logger', new __Services.DefaultLogging);
}
//Build the container based on the callback provided by the user
conf.build(container as CoreContainer<Omit<CoreDependencies, '@sern/client'>>);
Expand All @@ -119,13 +147,13 @@ export async function makeDependencies<const T extends Dependencies>
if(typeof conf === 'function') {
const excluded: string[] = [];
conf(dependencyBuilder(containerSubject, excluded));

//We only include logger if it does not exist
const includeLogger =
!excluded.includes('@sern/logger')
&& !containerSubject.getTokens()['@sern/logger'];
&& !containerSubject.hasKey('@sern/logger');

if(includeLogger) {
insertLogger(containerSubject);
__add_container('@sern/logger', new __Services.DefaultLogging);
}

containerSubject.ready();
Expand Down
9 changes: 3 additions & 6 deletions src/core/ioc/container.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Container } from 'iti';
import { Disposable } from '../';
import * as assert from 'node:assert';
import { Subject } from 'rxjs';
import { DefaultServices, ModuleStore } from '../_internal';
import { __Services, ModuleStore } from '../_internal';
import * as Hooks from './hooks';
import { EventEmitter } from 'node:events';

Expand All @@ -23,12 +23,11 @@ export class CoreContainer<T extends Partial<Dependencies>> extends Container<T,
.subscribe({ complete: unsubscribe });

(this as Container<{}, {}>)
.add({ '@sern/errors': () => new DefaultServices.DefaultErrorHandling,
.add({ '@sern/errors': () => new __Services.DefaultErrorHandling,
'@sern/emitter': () => new EventEmitter({ captureRejections: true }),
'@sern/store': () => new ModuleStore })
.add(ctx => {
return { '@sern/modules': () =>
new DefaultServices.DefaultModuleManager(ctx['@sern/store']) };
return { '@sern/modules': new __Services.DefaultModuleManager(ctx['@sern/store'])};
});
}

Expand All @@ -52,8 +51,6 @@ export class CoreContainer<T extends Partial<Dependencies>> extends Container<T,
await super.disposeAll();
}



ready() {
this.ready$.complete();
this.ready$.unsubscribe();
Expand Down
7 changes: 2 additions & 5 deletions src/core/module-loading.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { Result } from 'ts-results-es';
import { type Observable, from, mergeMap, ObservableInput } from 'rxjs';
import { readdir, stat } from 'fs/promises';
import { basename, extname, join, resolve, parse, dirname } from 'path';
Expand Down Expand Up @@ -42,9 +41,7 @@ export async function importModule<T>(absPath: string) {
if ('default' in commandModule ) {
commandModule = commandModule.default;
}
return Result
.wrap(() => ({ module: commandModule.getInstance() }))
.unwrapOr({ module: commandModule }) as T;
return { module: commandModule } as T;
}

export async function defaultModuleLoader<T extends Module>(absPath: string): ModuleResult<T> {
Expand Down Expand Up @@ -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 {
if (wrapper !== 'file') {
Expand Down
58 changes: 1 addition & 57 deletions src/core/modules.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,13 @@
import { ClientEvents } from 'discord.js';
import { CommandType, EventType, PluginType } from '../core/structures';
import { EventType } from '../core/structures';
import type {
AnyCommandPlugin,
AnyEventPlugin,
CommandArgs,
ControlPlugin,
EventArgs,
InitPlugin,
} from '../types/core-plugin';
import type {
CommandModule,
EventModule,
InputCommand,
InputEvent,
Module,
} from '../types/core-modules';
import { partitionPlugins } from './_internal';
import type { Awaitable } from '../types/utility';
Expand Down Expand Up @@ -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>;
}
Loading

0 comments on commit 264c27d

Please sign in to comment.