Skip to content

Commit

Permalink
fix: singleton init not being fired when inserting function
Browse files Browse the repository at this point in the history
  • Loading branch information
jacoobes committed Feb 14, 2024
1 parent ac7f47c commit 07b11b3
Show file tree
Hide file tree
Showing 8 changed files with 36 additions and 40 deletions.
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
21 changes: 16 additions & 5 deletions src/core/ioc/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ export async function __swap_container(c: CoreContainer<Partial<Dependencies>>)
containerSubject = c;
}
/**
* @deprecated
* Returns the underlying data structure holding all dependencies.
* Exposes methods from iti
* Use the Service API. The container should be readonly
Expand Down Expand Up @@ -51,8 +50,14 @@ const dependencyBuilder = (container: any, excluded: string[] ) => {
* 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: CoreContainer<Dependencies>) => ({ [key]: v(cntr)} )))
.expect("Failed to add " + key);
}
},
/**
* Exclude any dependencies from being added.
Expand All @@ -68,8 +73,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: CoreContainer<Dependencies>) => ({ [key]: v(cntr)})))
.expect("Failed to update " + key);
}
},
/**
* @param key the key of the dependency
Expand Down
2 changes: 0 additions & 2 deletions src/core/ioc/container.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,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
8 changes: 1 addition & 7 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
7 changes: 3 additions & 4 deletions src/handlers/event-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ import { ObservableInput, pipe } from 'rxjs';
import { Err, Ok, Result } from 'ts-results-es';
import type { Awaitable } from '../types/utility';
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';

Expand Down Expand Up @@ -105,7 +105,7 @@ export function createMessageHandler(
/**
* This function assigns remaining, incomplete data to each imported module.
*/
function assignDefaults<T extends Module>() {
function assignDefaults() {
return map(({ module, absPath }) => {
const processed = {
name: module.name ?? Files.filename(absPath),
Expand All @@ -126,7 +126,6 @@ function assignDefaults<T extends Module>() {

export function buildModules<T extends AnyModule>(
input: ObservableInput<string>,
moduleManager: ModuleManager,
) {
return Files
.buildModuleStream<Processed<T>>(input)
Expand Down Expand Up @@ -216,7 +215,7 @@ export function callInitPlugins<T extends Processed<AnyModule>>(sernEmitter: Emi
},
onNext: (payload) => {
sernEmitter.emit('module.register', resultPayload(PayloadType.Success, payload.module));
return payload;
return payload as { module: T; metadata: CommandMeta };
},
}),
);
Expand Down
20 changes: 11 additions & 9 deletions src/handlers/ready-event.ts
Original file line number Diff line number Diff line change
@@ -1,39 +1,42 @@
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 { SernError } from '../core/_internal';
import { Result } from 'ts-results-es';
import { ModuleManager } from '../core/contracts';
import { Logging, ModuleManager } from '../core/contracts';
import { buildModules, callInitPlugins } from './_internal';
import * as assert from 'node:assert';
import * as util from 'node:util';
import type { DependencyList } from '../types/ioc';
import type { AnyModule, CommandMeta, Processed } from '../types/core-modules';

export function readyHandler(
[sEmitter, , , moduleManager, client]: DependencyList,
[sEmitter, , log , moduleManager, client]: DependencyList,
allPaths: ObservableInput<string>,
) {
const ready$ = fromEvent(client!, 'ready').pipe(once());
const ready$ = fromEvent(client!, 'ready').pipe(once(log));

return concat(ready$, buildModules<AnyModule>(allPaths, moduleManager))
return concat(ready$, buildModules<AnyModule>(allPaths))
.pipe(callInitPlugins(sEmitter))
.subscribe(({ module, metadata }) => {
register(moduleManager, module, metadata)
.expect(SernError.InvalidModuleType + ' ' + util.inspect(module));
//TODO: TEST ALL MODULES AGAIN
console.log(module)
});
}

const once = () => pipe(
const once = (log: Logging | undefined) => pipe(
tap(() => { log?.info({ message: "Waiting on discord client to be ready..." }) }),
first(),
ignoreElements())


function register<T extends Processed<AnyModule>>(
manager: ModuleManager,
module: T,
metadata: unknown
metadata:CommandMeta
): Result<void, void> {
manager.setMetadata(module, metadata as CommandMeta)!;
manager.setMetadata(module, metadata)!;

const validModuleType = module.type >= 0 && module.type <= 1 << 10;
assert.ok(
Expand All @@ -48,6 +51,5 @@ function register<T extends Processed<AnyModule>>(
module.alias?.forEach(a => manager.set(`${a}_T`, module));
}
}
//@ts-ignore
return Result.wrap(() => manager.set(metadata.id, module));
}
2 changes: 1 addition & 1 deletion src/handlers/user-defined-events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export function eventsHandler(
throw Error(SernError.InvalidModuleType + ' while creating event handler');
}
};
buildModules<EventModule>(allPaths, moduleManager)
buildModules<EventModule>(allPaths)
.pipe(
callInitPlugins(emitter),
map(intoDispatcher),
Expand Down
3 changes: 2 additions & 1 deletion src/sern.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,10 @@ export function init(maybeWrapper: Wrapper | 'file') {
//Ready event: load all modules and when finished, time should be taken and logged
readyHandler(dependencies, Files.getFullPathTree(wrapper.commands))
.add(() => {
logger?.info({ message: "Client signaled ready, registering modules" });
const time = ((performance.now() - startTime) / 1000).toFixed(2);
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) {
const setPresence = async (p: any) => {
return (dependencies[4] as Client).user?.setPresence(p);
Expand Down

0 comments on commit 07b11b3

Please sign in to comment.