chore: revert multi and clean up code

This commit is contained in:
Jacob Nguyen
2023-05-05 23:31:51 -05:00
parent 29499457bb
commit ff478123a8
17 changed files with 107 additions and 296 deletions

View File

@@ -1,11 +1,10 @@
import type { Container } from 'iti';
import type { AnyDependencies, DependencyConfiguration, MapDeps, ServerlessDependencies, WebsocketDependencies } from '../types/core';
import { SernEmitter } from './sernEmitter';
import { DefaultErrorHandling, DefaultLogging, DefaultModuleManager } from './contracts';
import { Result } from 'ts-results-es';
import { BehaviorSubject } from 'rxjs';
import { createContainer } from 'iti';
import { ModuleStore } from './structures';
import { ModuleStore, SernEmitter } from './structures';
import { AnyWrapper, ServerlessWrapper, WebsocketWrapper } from './structures/wrapper';
export const containerSubject = new BehaviorSubject(defaultContainer());
@@ -124,3 +123,12 @@ export function makeFetcher<Dep extends AnyDependencies>(containerConfig : AnyWr
>;
}
/**
* @since 2.0.0
* @param conf a configuration for creating your project dependencies
*/
export function makeDependencies<const T extends AnyDependencies>(conf: DependencyConfiguration<T>) {
//Until there are more optional dependencies, just check if the logger exists
composeRoot(conf);
return useContainer<T>();
}

View File

@@ -4,8 +4,8 @@ import type { SernAutocompleteData, SernOptionsData } from '../types/module';
//function wrappers for empty ok / err
export const ok = () => Ok.EMPTY;
export const err = () => Err.EMPTY;
export const ok = /* @__PURE__*/ () => Ok.EMPTY;
export const err =/* @__PURE__*/ () => Err.EMPTY;
export function partition<T, V>(arr: (T & V)[], condition: (e: T & V) => boolean): [T[], V[]] {
const t: T[] = [];

View File

@@ -1,6 +1,5 @@
export * from './sernEmitter';
export * from './contracts';
export * from './platform';
export * from './plugins';
export * from './structures/';
export { single, transient, useContainerRaw } from './dependencies'
export * from './structures';
export { single, transient, useContainerRaw, makeDependencies } from './dependencies'

View File

@@ -1,67 +0,0 @@
import { Module } from "../types/module";
import { Result } from "ts-results-es";
import { Processed } from "../types/core";
import { SernError } from "./structures/errors";
import { readdir, stat } from 'fs/promises';
import { join, resolve } from 'path';
import { type Observable, from, mergeMap, ObservableInput } from 'rxjs';
import { defaultModuleLoader } from "./module-loading";
export const fmtFileName = (n: string) => n.substring(0, n.length - 3);
/**
* a directory string is converted into a stream of modules.
* starts the stream of modules that sern needs to process on init
* @returns {Observable<{ mod: Module; absPath: string; }[]>} data from command files
* @param commandDir
*/
export function buildModuleStream<T extends Module>(
input: ObservableInput<string>
): Observable<Result<Processed<T>, SernError>> {
return from(input).pipe(mergeMap(defaultModuleLoader<T>));
}
export function getCommands(dir: string) {
return readPath(resolve(dir));
}
export function filename(path: string) {
const i = path.lastIndexOf('/')
return fmtFileName(path.substring(i))
}
async function* readPath(dir: string): AsyncGenerator<string> {
try {
const files = await readdir(dir);
for (const file of files) {
const fullPath = join(dir, file);
const fileStats = await stat(fullPath);
if (fileStats.isDirectory()) {
yield* readPath(fullPath);
} else {
/// #if MODE === 'esm'
yield 'file:///'+fullPath;
/// #elif MODE === 'cjs'
yield fullPath;
/// #endif
}
}
} catch (err) {
throw err;
}
}
//https://stackoverflow.com/questions/16697791/nodejs-get-filename-of-caller-function
export function filePath() {
const err = new Error();
Error.prepareStackTrace = (_, stack) => stack;
const stack = err.stack as unknown as NodeJS.CallSite[];
Error.prepareStackTrace = undefined;
const path = stack[2].getFileName();
if(path === null) {
throw Error("Could not get the name of commandModule.")
}
return path;
}

View File

@@ -1,12 +1,61 @@
import { readdir, stat } from 'fs/promises';
import { join, basename, resolve } from 'path';
import { type Observable, from, mergeMap } from 'rxjs';
import { SernError } from './structures/errors';
import { type Result, Err, Ok } from 'ts-results-es';
import { Processed } from '../types/core';
import { Module } from '../types/module';
import * as assert from 'node:assert'
import * as util from 'node:util'
import { type Observable, from, mergeMap, ObservableInput } from 'rxjs';
import { readdir, stat } from 'fs/promises';
import { basename, join, resolve } from 'path';
type ModuleResult<T> = Promise<Result<Processed<T>, SernError>>
export type Loader<T> = (absPath: string) => ModuleResult<T>
export async function defaultModuleLoader<T extends Module>(
absPath: string,
): ModuleResult<T> {
// prettier-ignore
let module: T | undefined
/// #if MODE === 'esm'
= (await import(absPath)).default
/// #elif MODE === 'cjs'
= require(absPath).default; // eslint-disable-line
/// #endif
if (module === undefined) {
return Err(SernError.UndefinedModule);
}
try {
module = new (module as unknown as new () => T)();
} catch {}
checkIsProcessed(module)
return Ok(module);
}
function checkIsProcessed<T extends Module>(m: T): asserts m is Processed<T> {
assert.ok(m.name !== undefined, `name is not defined for ${util.format(m)}`)
}
export const fmtFileName = (n: string) => n.substring(0, n.length - 3);
/**
* a directory string is converted into a stream of modules.
* starts the stream of modules that sern needs to process on init
* @returns {Observable<{ mod: Module; absPath: string; }[]>} data from command files
* @param commandDir
*/
export function buildModuleStream<T extends Module>(
input: ObservableInput<string>
): Observable<Result<Processed<T>, SernError>> {
return from(input).pipe(mergeMap(defaultModuleLoader<T>));
}
export function getCommands(dir: string) {
return readPath(resolve(dir));
}
export function filename(path: string) {
return fmtFileName(basename(path))
}
async function* readPath(dir: string): AsyncGenerator<string> {
try {
@@ -29,53 +78,6 @@ async function* readPath(dir: string): AsyncGenerator<string> {
}
}
export const fmtFileName = (n: string) => n.substring(0, n.length - 3);
export async function defaultModuleLoader<T extends Module>(
absPath: string,
): Promise<Result< Processed<T>, SernError>> {
// prettier-ignore
let module: T | undefined
/// #if MODE === 'esm'
= (await import(absPath)).default
/// #elif MODE === 'cjs'
= require(absPath).default; // eslint-disable-line
/// #endif
if (module === undefined) {
return Err(SernError.UndefinedModule);
}
try {
module = new (module as unknown as new () => T)();
} catch {}
checkIsProcessed(module)
return Ok(module);
}
function checkIsProcessed<T extends Module>(m: T): asserts m is Processed<T> {
assert.ok(m.name !== undefined, `name is not defined for ${util.format(m)}`)
}
/**
* a directory string is converted into a stream of modules.
* starts the stream of modules that sern needs to process on init
* @returns {Observable<{ mod: Module; absPath: string; }[]>} data from command files
* @param commandDir
*/
export function buildModuleStream<T extends Module >(
commandDir: string,
): Observable<Result<Processed<T>, SernError>> {
const commands = getCommands(commandDir);
return from(commands).pipe(mergeMap(defaultModuleLoader<T>));
}
export function getCommands(dir: string) {
return readPath(resolve(dir));
}
export function filename(path: string) {
return fmtFileName(basename(path))
}
//https://stackoverflow.com/questions/16697791/nodejs-get-filename-of-caller-function
export function filePath() {
const err = new Error();
@@ -89,5 +91,4 @@ export function filePath() {
if(path === null) {
throw Error("Could not get the name of commandModule.")
}
return path;
}
return path; }

View File

@@ -28,10 +28,9 @@ export function makeWebsocketAdapter(
};
}
export function makeServerlessAdapter(i : { endpoint: string }): ServerlessStrategy {
export function makeServerlessAdapter(): ServerlessStrategy {
return {
type: DispatchType.Serverless ,
...i
type: DispatchType.Serverless,
};
}

View File

@@ -1,2 +1,2 @@
export { type EventArgs, type InitArgs, type CommandArgs } from './args';
export * from './args';
export * from './createPlugin';

View File

@@ -1,87 +0,0 @@
import { EventEmitter } from 'events';
import type { Payload, SernEventsMapping } from '../types/handler';
import { PayloadType } from '../core/structures';
import type { Module } from '../types/module';
/**
* @since 1.0.0
*/
export class SernEmitter extends EventEmitter {
/**
* Listening to sern events with on. This event stays on until a crash or a normal exit
* @param eventName
* @param listener what to do with the data
*/
public override on<T extends keyof SernEventsMapping>(
eventName: T,
listener: (...args: SernEventsMapping[T][]) => void,
): this {
return super.on(eventName, listener);
}
/**
* Listening to sern events with on. This event stays on until a crash or a normal exit
* @param eventName
* @param listener what to do with the data
*/
public override once<T extends keyof SernEventsMapping>(
eventName: T,
listener: (...args: SernEventsMapping[T][]) => void,
): this {
return super.once(eventName, listener);
}
/**
* Listening to sern events with on. This event stays on until a crash or a normal exit
* @param eventName
* @param args the arguments for emitting the eventName
*/
public override emit<T extends keyof SernEventsMapping>(
eventName: T,
...args: SernEventsMapping[T]
): boolean {
return super.emit(eventName, ...args);
}
private static payload<T extends Payload>(
type: PayloadType,
module?: Module,
reason?: unknown,
) {
return { type, module, reason } as T;
}
/**
* Creates a compliant SernEmitter failure payload
* @param module
* @param reason
*/
static failure(module?: Module, reason?: unknown) {
//The generic cast Payload & { type : PayloadType.* } coerces the type to be a failure payload
// same goes to the other methods below
return SernEmitter.payload<Payload & { type: PayloadType.Failure }>(
PayloadType.Failure,
module,
reason,
);
}
/**
* Creates a compliant SernEmitter module success payload
* @param module
*/
static success(module: Module) {
return SernEmitter.payload<Payload & { type: PayloadType.Success }>(
PayloadType.Success,
module,
);
}
/**
* Creates a compliant SernEmitter module warning payload
* @param reason
*/
static warning(reason: unknown) {
return SernEmitter.payload<Payload & { type: PayloadType.Warning }>(
PayloadType.Warning,
undefined,
reason,
);
}
}

View File

@@ -1,7 +1,7 @@
import { EventEmitter } from 'node:events';
import type { Payload, SernEventsMapping } from '../types/handler';
import { PayloadType } from '../core/structures';
import type { Module } from '../types/module';
import type { Payload, SernEventsMapping } from '../../types/handler';
import { PayloadType } from '../../core/structures';
import type { Module } from '../../types/module';
/**
* @since 1.0.0