Compare commits

..

17 Commits

Author SHA1 Message Date
jacob
922567ff7b simplify, remove reply option 2023-11-02 15:16:12 -05:00
jacob
17eb701b5f decide not to support error handling for autocomplete 2023-11-02 14:19:43 -05:00
jacob
2b07bcc661 extract & refactor 2023-10-12 12:52:50 -05:00
jacob
a2b7158d24 Merge branch 'main' into feat/errors 2023-10-12 12:35:49 -05:00
Jacob Nguyen
56a74ab32a naive onError handling, not tested 2023-10-04 00:38:18 -05:00
Jacob Nguyen
f2218d02d4 progress on error handling 2023-10-02 22:01:15 -05:00
Jacob Nguyen
e954e2a399 fix merge 2023-10-02 11:07:13 -05:00
jacob
f3ed5354eb add command error builder 2023-09-28 19:42:36 -05:00
Jacob Nguyen
b1263c1c05 update error handling contract and wire more 2023-09-10 23:52:31 -05:00
Jacob Nguyen
0fbabea428 seems to work 2023-09-10 00:36:32 -05:00
Jacob Nguyen
fa66ff7471 wiring 2023-09-09 12:27:07 -05:00
Jacob Nguyen
c7ee2736b8 type alias 2023-09-09 11:39:04 -05:00
Jacob Nguyen
4591471e7e update onError to be record 2023-09-09 11:32:11 -05:00
Jacob Nguyen
374a12bb92 fix error callbacks not being stored 2023-09-09 01:08:56 -05:00
Jacob Nguyen
cafca503f9 wiring onError callback through module loader and resolver 2023-09-08 23:11:46 -05:00
Jacob Nguyen
59e7927816 Merge branch 'main' into feat/errors 2023-09-08 14:19:21 -05:00
jacob
a4848743c2 progress on better error handling 2023-08-29 18:09:31 -05:00
59 changed files with 899 additions and 1056 deletions

View File

@@ -23,7 +23,7 @@ jobs:
uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3 uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3
- name: Set up Node.js - name: Set up Node.js
uses: actions/setup-node@1a4442cacd436585916779262731d5b162bc6ec7 # v3 uses: actions/setup-node@64ed1c7eab4cce3362f8c340dee64e5eaeef8f7c # v3
with: with:
node-version: 17 node-version: 17

View File

@@ -1,34 +0,0 @@
name: Continuous Delivery
on:
push:
branches:
- main
paths:
- 'src/**'
- 'package.json'
jobs:
Publish:
name: Publishing Dev
runs-on: ubuntu-latest
steps:
- name: Check out Git repository
uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c # v3
- name: Set up Node.js
uses: actions/setup-node@64ed1c7eab4cce3362f8c340dee64e5eaeef8f7c # v3
with:
node-version: 18
registry-url: 'https://registry.npmjs.org'
- name: Install Node.js dependencies
run: npm i && npm run build:dev
- name: Publish to npm
run: |
npm version premajor --preid "dev.$(git rev-parse --verify --short HEAD)" --git-tag-version=false
npm publish --tag dev
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}

View File

@@ -11,7 +11,7 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3 - uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3
- uses: actions/setup-node@1a4442cacd436585916779262731d5b162bc6ec7 # v3 - uses: actions/setup-node@5e21ff4d9bc1a8cf6de233a3057d20ec6b3fb69d # v3
with: with:
node-version: 17 node-version: 17
- run: yarn --immutable - run: yarn --immutable

View File

@@ -6,7 +6,7 @@ jobs:
release-please: release-please:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: google-github-actions/release-please-action@db8f2c60ee802b3748b512940dde88eabd7b7e01 # v3 - uses: google-github-actions/release-please-action@ca6063f4ed81b55db15b8c42d1b6f7925866342d # v3
with: with:
release-type: node release-type: node
package-name: release-please-action package-name: release-please-action

View File

@@ -20,7 +20,7 @@ jobs:
steps: steps:
- uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3 - uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3
- name: Use Node.js ${{ matrix.node-version }} - name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@1a4442cacd436585916779262731d5b162bc6ec7 # v3 uses: actions/setup-node@5e21ff4d9bc1a8cf6de233a3057d20ec6b3fb69d # v3
with: with:
node-version: ${{ matrix.node-version }} node-version: ${{ matrix.node-version }}
cache: 'npm' cache: 'npm'

View File

@@ -1,69 +1,5 @@
# 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)
### Bug Fixes
* presence feature not working on cjs applications ([#351](https://github.com/sern-handler/handler/issues/351)) ([4f23871](https://github.com/sern-handler/handler/commit/4f2387119acfde036d0d1626553e9050f55627d1))
## [3.3.1](https://github.com/sern-handler/handler/compare/v3.3.0...v3.3.1) (2024-01-07)
### Bug Fixes
* crashing when slash command is used as text command ([#349](https://github.com/sern-handler/handler/issues/349)) ([a359f73](https://github.com/sern-handler/handler/commit/a359f73fa24127a4964d411c8c1c0dfea5edc0f1))
### Reverts
* the last commit ([655bb8d](https://github.com/sern-handler/handler/commit/655bb8d35815fe0ce9797d8b169310a07b284ae0))
## [3.3.0](https://github.com/sern-handler/handler/compare/v3.2.1...v3.3.0) (2023-12-27)
### Features
* presence ([#345](https://github.com/sern-handler/handler/issues/345)) ([7458bef](https://github.com/sern-handler/handler/commit/7458befe8a5900480cd71900df02a8364837dc00))
## [3.2.1](https://github.com/sern-handler/handler/compare/v3.2.0...v3.2.1) (2023-12-21)
### Bug Fixes
* logger swap failing ([daac37c](https://github.com/sern-handler/handler/commit/daac37c28858c42b21042bdcb8141239db634e7d))
## [3.2.0](https://github.com/sern-handler/handler/compare/v3.1.1...v3.2.0) (2023-12-15)
### Miscellaneous Chores
* release 3.2.0 ([237c853](https://github.com/sern-handler/handler/commit/237c8537c66052309d7e13a7e6e0a4f7995c2558))
## [3.1.1](https://github.com/sern-handler/handler/compare/v3.1.0...v3.1.1) (2023-11-06)
### Bug Fixes
* queuing events ([fd39858](https://github.com/sern-handler/handler/commit/fd39858636d3038abb6d91021b65c99c488a3d6e))
* queuing events ([#332](https://github.com/sern-handler/handler/issues/332)) @Benzo-Fury ([#333](https://github.com/sern-handler/handler/issues/333)) ([fd39858](https://github.com/sern-handler/handler/commit/fd39858636d3038abb6d91021b65c99c488a3d6e))
## [3.1.0](https://github.com/sern-handler/handler/compare/v3.0.2...v3.1.0) (2023-09-04) ## [3.1.0](https://github.com/sern-handler/handler/compare/v3.0.2...v3.1.0) (2023-09-04)

View File

@@ -19,16 +19,28 @@
- Lightweight. Does a lot while being small. - Lightweight. Does a lot while being small.
- Latest features. Support for discord.js v14 and all of its interactions. - Latest features. Support for discord.js v14 and all of its interactions.
- Start quickly. Plug and play or customize to your liking. - Start quickly. Plug and play or customize to your liking.
- Switch and customize how errors are handled, logging, and more.
- works with [bun](https://bun.sh/) and [node](https://nodejs.org/en) out the box! - works with [bun](https://bun.sh/) and [node](https://nodejs.org/en) out the box!
- Use it with TypeScript or JavaScript. CommonJS and ESM supported. - Use it with TypeScript or JavaScript. CommonJS and ESM supported.
- Active and growing community, always here to help. [Join us](https://sern.dev/discord) - Active and growing community, always here to help. [Join us](https://sern.dev/discord)
- Unleash its full potential with a powerful CLI and awesome plugins. - Unleash its full potential with a powerful CLI and awesome plugins.
## 📜 Installation ## 📜 Installation
[Start here!!](https://sern.dev/docs/guide/walkthrough/new-project)
```sh
npm install @sern/handler
```
```sh
yarn add @sern/handler
```
```sh
pnpm add @sern/handler
```
## 👶 Basic Usage ## 👶 Basic Usage
<details><summary>ping.ts</summary> <details open><summary>ping.ts</summary>
```ts ```ts
export default commandModule({ export default commandModule({
@@ -42,7 +54,50 @@ export default commandModule({
}); });
``` ```
</details> </details>
<details open><summary>modal.ts</summary>
```ts
export default commandModule({
type: CommandType.Modal,
//Installed a plugin to make sure modal fields pass a validation.
plugins : [
assertFields({
fields: {
name: /^([^0-9]*)$/
},
failure: (errors, modal) => modal.reply('your submission did not pass the validations')
})
],
execute : (modal) => {
modal.reply('thanks for the submission!');
}
})
```
</details>
<details open><summary>index.ts</summary>
```ts
import { Client, GatewayIntentBits } from 'discord.js';
import { Sern, single } from '@sern/handler';
//client has been declared previously
//Version 3
await makeDependencies({
build: root => root
.add({ '@sern/client': single(() => client) })
});
//View docs for all options
Sern.init({
defaultPrefix: '!', // removing defaultPrefix will shut down text commands
commands: 'src/commands',
// events: 'src/events' (optional),
});
client.login("YOUR_BOT_TOKEN_HERE");
```
</details>
## 🤖 Bots Using sern ## 🤖 Bots Using sern
- [Community Bot](https://github.com/sern-handler/sern-community), the community bot for our [discord server](https://sern.dev/discord). - [Community Bot](https://github.com/sern-handler/sern-community), the community bot for our [discord server](https://sern.dev/discord).
@@ -52,8 +107,7 @@ export default commandModule({
- [Murayama](https://github.com/murayamabot/murayama), :pepega: - [Murayama](https://github.com/murayamabot/murayama), :pepega:
- [Protector (WIP)](https://github.com/needhamgary/Protector), Just a simple bot to help enhance a private minecraft server. - [Protector (WIP)](https://github.com/needhamgary/Protector), Just a simple bot to help enhance a private minecraft server.
- [SmokinWeed 💨](https://github.com/Peter-MJ-Parker/sern-bud), A fun bot for a small - but growing - server. - [SmokinWeed 💨](https://github.com/Peter-MJ-Parker/sern-bud), A fun bot for a small - but growing - server.
- [Man Nomic](https://github.com/jacoobes/man-nomic), A simple information bot to provide information to the nomic-ai discord community.
- [Linear-Discord](https://github.com/sern-handler/linear-discord) Display and manage a linear dashboard.
## 💻 CLI ## 💻 CLI
It is **highly encouraged** to use the [command line interface](https://github.com/sern-handler/cli) for your project. Don't forget to view it. It is **highly encouraged** to use the [command line interface](https://github.com/sern-handler/cli) for your project. Don't forget to view it.

View File

@@ -1 +0,0 @@

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.4", "version": "3.1.0",
"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",
@@ -15,6 +15,7 @@
}, },
"scripts": { "scripts": {
"watch": "tsup --watch", "watch": "tsup --watch",
"clean-modules": "rimraf node_modules/ && npm install",
"lint": "eslint src/**/*.ts", "lint": "eslint src/**/*.ts",
"format": "eslint src/**/*.ts --fix", "format": "eslint src/**/*.ts --fix",
"build:dev": "tsup --metafile", "build:dev": "tsup --metafile",
@@ -37,7 +38,6 @@
"author": "SernDevs", "author": "SernDevs",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"callsites": "^3.1.0",
"iti": "^0.6.0", "iti": "^0.6.0",
"rxjs": "^7.8.0", "rxjs": "^7.8.0",
"ts-results-es": "^4.0.0" "ts-results-es": "^4.0.0"
@@ -47,7 +47,8 @@
"@types/node": "^18.15.11", "@types/node": "^18.15.11",
"@typescript-eslint/eslint-plugin": "5.58.0", "@typescript-eslint/eslint-plugin": "5.58.0",
"@typescript-eslint/parser": "5.59.1", "@typescript-eslint/parser": "5.59.1",
"discord.js": "^14.11.0", "discord.js": "14.11.0",
"esbuild": "^0.17.0",
"eslint": "8.39.0", "eslint": "8.39.0",
"prettier": "2.8.8", "prettier": "2.8.8",
"tsup": "^6.7.0", "tsup": "^6.7.0",
@@ -94,8 +95,5 @@
"type": "git", "type": "git",
"url": "git+https://github.com/sern-handler/handler.git" "url": "git+https://github.com/sern-handler/handler.git"
}, },
"engines": {
"node": ">= 18.16.x"
},
"homepage": "https://sern.dev" "homepage": "https://sern.dev"
} }

View File

@@ -1,10 +1,10 @@
export * as Id from './id'; export * as Id from './id';
export * from './operators'; export * from './operators';
export * from './predicates';
export * as Files from './module-loading'; export * as Files from './module-loading';
export * from './functions'; 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 __Services from './structures/services'; export * as DefaultServices from './structures/services';
export { useContainerRaw } from './ioc/base'; export { useContainerRaw } from './ioc/base'

View File

@@ -0,0 +1,9 @@
import type { Awaitable } from '../../types/utility';
/**
* Represents a Disposable contract.
* Let dependencies implement this to dispose and cleanup.
*/
export interface Disposable {
dispose(): Awaitable<unknown>;
}

View File

@@ -1,5 +1,3 @@
//i deleted it, hmm so how should we allow users to enable localization?
// a
import type { AnyFunction } from '../../types/utility'; import type { AnyFunction } from '../../types/utility';
export interface Emitter { export interface Emitter {

View File

@@ -1,3 +1,5 @@
import type { CommandModule,Processed, EventModule } from "../../types/core-modules";
/** /**
* @since 2.0.0 * @since 2.0.0
*/ */
@@ -8,9 +10,17 @@ export interface ErrorHandling {
*/ */
crash(err: Error): never; crash(err: Error): never;
/** /**
* A function that is called on every throw. * A function that is called on every throw,
* If and only if the command is not handled properly
* @param error * @param error
*/ */
updateAlive(error: Error): void; updateAlive(error: Error): void;
/**
* This callback is called if a module
* handles onError with type 'fail'
*
*/
handleError(error: Error): void;
} }

View File

@@ -1,16 +0,0 @@
/**
* Represents an initialization contract.
* Let dependencies implement this to initiate some logic.
*/
export interface Init {
init(): unknown;
}
/**
* Represents a Disposable contract.
* Let dependencies implement this to dispose and cleanup.
*/
export interface Disposable {
dispose(): unknown;
}

View File

@@ -2,5 +2,6 @@ export * from './error-handling';
export * from './logging'; export * from './logging';
export * from './module-manager'; export * from './module-manager';
export * from './module-store'; export * from './module-store';
export * from './hooks'; export * from './init';
export * from './emitter'; export * from './emitter';
export * from './disposable'

View File

@@ -0,0 +1,9 @@
import type { Awaitable } from '../../types/utility';
/**
* Represents an initialization contract.
* Let dependencies implement this to initiate some logic.
*/
export interface Init {
init(): Awaitable<unknown>;
}

View File

@@ -3,6 +3,7 @@ import type {
CommandModule, CommandModule,
CommandModuleDefs, CommandModuleDefs,
Module, Module,
OnError,
} from '../../types/core-modules'; } from '../../types/core-modules';
import { CommandType } from '../structures'; import { CommandType } from '../structures';
@@ -11,24 +12,21 @@ interface MetadataAccess {
setMetadata(m: Module, c: CommandMeta): void; setMetadata(m: Module, c: CommandMeta): void;
} }
interface OnErrorAccess {
getErrorCallback(m: Module): OnError;
setErrorCallback(m: Module, c: NonNullable<OnError>): void;
}
/** /**
* @since 2.0.0 * @since 2.0.0
* @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, OnErrorAccess {
get(id: string): Module | undefined; get(id: string): string | undefined;
set(id: string, path: Module): void; set(id: string, path: string): void;
/** getPublishableCommands(): Promise<CommandModule[]>;
* @deprecated
*/
getPublishableCommands(): CommandModule[];
/*
* @deprecated
*/
getByNameCommandType<T extends CommandType>( getByNameCommandType<T extends CommandType>(
name: string, name: string,
commandType: T, commandType: T,
): CommandModuleDefs[T] | undefined; ): Promise<CommandModuleDefs[T]> | undefined;
} }

View File

@@ -1,9 +1,10 @@
import type { CommandMeta, Module } from '../../types/core-modules'; import type { CommandMeta, Module, OnError } 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, Module>; commands: Map<string, string>;
metadata: WeakMap<Module, CommandMeta>; metadata: WeakMap<Module, CommandMeta>;
onError: WeakMap<Module, NonNullable<OnError>>;
} }

View File

@@ -1,7 +1,6 @@
import { CommandType, EventType, PluginType } from './structures'; import { CommandType, EventType, PluginType } from './structures';
import type { Plugin, PluginResult, EventArgs, CommandArgs } from '../types/core-plugin'; import type { Plugin, PluginResult, EventArgs, CommandArgs } from '../types/core-plugin';
import type { ClientEvents } from 'discord.js'; import type { ClientEvents } from 'discord.js';
import { err, ok } from './functions';
export function makePlugin<V extends unknown[]>( export function makePlugin<V extends unknown[]>(
type: PluginType, type: PluginType,
@@ -61,12 +60,3 @@ export function DiscordEventControlPlugin<T extends keyof ClientEvents>(
) { ) {
return makePlugin(PluginType.Control, execute); return makePlugin(PluginType.Control, execute);
} }
/**
* @since 1.0.0
* The object passed into every plugin to control a command's behavior
*/
export const controller = {
next: ok,
stop: err,
};

View File

@@ -1,19 +1,9 @@
import { Err, Ok } from 'ts-results-es'; import { Err, Ok } from 'ts-results-es';
import type { Module, SernAutocompleteData, SernOptionsData } from '../types/core-modules'; import { ApplicationCommandOptionType, AutocompleteInteraction } from 'discord.js';
import type { SernAutocompleteData, SernOptionsData } from '../types/core-modules';
import type { AnyCommandPlugin, AnyEventPlugin, Plugin } from '../types/core-plugin'; import type { AnyCommandPlugin, AnyEventPlugin, Plugin } from '../types/core-plugin';
import type { import { PluginType } from './structures';
AnySelectMenuInteraction,
ButtonInteraction,
ChatInputCommandInteraction,
MessageContextMenuCommandInteraction,
ModalSubmitInteraction,
UserContextMenuCommandInteraction,
AutocompleteInteraction
} from 'discord.js';
import { ApplicationCommandOptionType, InteractionType } from 'discord.js';
import { PayloadType, PluginType } from './structures';
import assert from 'assert'; import assert from 'assert';
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 +40,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 }));
const subcommands = new Set(); let 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) {
@@ -71,7 +61,7 @@ export function treeSearch(
const choice = iAutocomplete.options.getFocused(true); const choice = iAutocomplete.options.getFocused(true);
assert( assert(
'command' in cur, 'command' in cur,
'No `command` property found for autocomplete option', 'No command property found for autocomplete option',
); );
if (subcommands.size > 0) { if (subcommands.size > 0) {
const parent = iAutocomplete.options.getSubcommand(); const parent = iAutocomplete.options.getSubcommand();
@@ -91,33 +81,3 @@ export function treeSearch(
} }
} }
} }
interface InteractionTypable {
type: InteractionType;
}
//discord.js pls fix ur typings or i will >:(
type AnyMessageComponentInteraction = AnySelectMenuInteraction | ButtonInteraction;
type AnyCommandInteraction =
| ChatInputCommandInteraction
| MessageContextMenuCommandInteraction
| UserContextMenuCommandInteraction;
export function isMessageComponent(i: InteractionTypable): i is AnyMessageComponentInteraction {
return i.type === InteractionType.MessageComponent;
}
export function isCommand(i: InteractionTypable): i is AnyCommandInteraction {
return i.type === InteractionType.ApplicationCommand;
}
export function isAutocomplete(i: InteractionTypable): i is AutocompleteInteraction {
return i.type === InteractionType.ApplicationCommandAutocomplete;
}
export function isModal(i: InteractionTypable): i is ModalSubmitInteraction {
return i.type === InteractionType.ModalSubmit;
}
export function resultPayload<T extends PayloadType>
(type: T, module?: Module, reason?: unknown) {
return { type, module, reason } as Payload & { type : T };
}

View File

@@ -4,20 +4,20 @@ import { CommandType, EventType } from './structures';
/** /**
* Construct unique ID for a given interaction object. * Construct unique ID for a given interaction object.
* @param event The interaction object for which to create an ID. * @param event The interaction object for which to create an ID.
* @returns An array of unique string IDs based on the type and properties of the interaction object. * @returns A unique string ID based on the type and properties of the interaction object.
*/ */
export function reconstruct<T extends Interaction>(event: T) { export function reconstruct<T extends Interaction>(event: T) {
switch (event.type) { switch (event.type) {
case InteractionType.MessageComponent: { case InteractionType.MessageComponent: {
return [`${event.customId}_C${event.componentType}`]; return `${event.customId}_C${event.componentType}`;
} }
case InteractionType.ApplicationCommand: case InteractionType.ApplicationCommand:
case InteractionType.ApplicationCommandAutocomplete: { case InteractionType.ApplicationCommandAutocomplete: {
return [`${event.commandName}_A${event.commandType}`, `${event.commandName}_B`]; return `${event.commandName}_A${event.commandType}`;
} }
//Modal interactions are classified as components for sern //Modal interactions are classified as components for sern
case InteractionType.ModalSubmit: { case InteractionType.ModalSubmit: {
return [`${event.customId}_M`]; return `${event.customId}_C1`;
} }
} }
} }
@@ -27,39 +27,37 @@ export function reconstruct<T extends Interaction>(event: T) {
*/ */
const appBitField = 0b000000001111; const appBitField = 0b000000001111;
// Each index represents the exponent of a CommandType.
const TypeMap = new Map<number, number>([ // Every CommandType is a power of two.
[CommandType.Text, 0], export const CommandTypeDiscordApi = [
[CommandType.Both, 0], 1, // CommandType.Text
[CommandType.Slash, ApplicationCommandType.ChatInput], ApplicationCommandType.ChatInput,
[CommandType.CtxUser, ApplicationCommandType.User], ApplicationCommandType.User,
[CommandType.CtxMsg, ApplicationCommandType.Message], ApplicationCommandType.Message,
[CommandType.Button, ComponentType.Button], ComponentType.Button,
[CommandType.Modal, InteractionType.ModalSubmit], ComponentType.StringSelect,
[CommandType.StringSelect, ComponentType.StringSelect], 1, // CommandType.Modal
[CommandType.UserSelect, ComponentType.UserSelect], ComponentType.UserSelect,
[CommandType.MentionableSelect, ComponentType.MentionableSelect], ComponentType.RoleSelect,
[CommandType.RoleSelect, ComponentType.RoleSelect], ComponentType.MentionableSelect,
[CommandType.ChannelSelect, ComponentType.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) {
if (t === CommandType.Both || t === CommandType.Modal) return 1;
return CommandTypeDiscordApi[Math.log2(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 fetched from TypeMap * Then, another number generated by apiType function is appended
*/ */
export function create(name: string, type: CommandType | EventType) { export function create(name: string, type: CommandType | EventType) {
if(type == CommandType.Text) {
return `${name}_T`;
}
if(type == CommandType.Both) {
return `${name}_B`;
}
if(type == CommandType.Modal) {
return `${name}_M`;
}
const am = (appBitField & type) !== 0 ? 'A' : 'C'; const am = (appBitField & type) !== 0 ? 'A' : 'C';
return `${name}_${am}${TypeMap.get(type)!}` return name + '_' + am + apiType(type);
} }

View File

@@ -1,40 +1,16 @@
import * as assert from 'assert'; import * as assert from 'assert';
import { useContainer } from './dependency-injection'; import { composeRoot, useContainer } from './dependency-injection';
import type { CoreDependencies, DependencyConfiguration } from '../../types/ioc'; import type { DependencyConfiguration } from '../../types/ioc';
import { CoreContainer } from './container'; import { CoreContainer } from './container';
import { Result } from 'ts-results-es';
import { __Services } from '../_internal';
import { AnyFunction } from '../../types/utility';
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>>;
/** /**
* @internal * @deprecated
* 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 from the consumer side * Use the Service API. The container should be readonly
*/ */
export function useContainerRaw() { export function useContainerRaw() {
assert.ok( assert.ok(
@@ -44,123 +20,17 @@ export function useContainerRaw() {
return containerSubject; return containerSubject;
} }
export function disposeAll(logger: Logging|undefined) {
containerSubject
?.disposeAll()
.then(() => logger?.info({ message: 'Cleaning container and crashing' }));
}
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) {
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.
* Warning: this could lead to bad errors if not used correctly
*/
exclude(...keys: (keyof Dependencies)[]) {
keys.forEach(key => excluded.push(key));
},
/**
* @param key the key of the dependency
* @param v The dependency to swap out.
* Swap out a preexisting dependency.
*/
swap(key: keyof Dependencies, v: Insertable) {
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
* @param cleanup Provide cleanup for the dependency at key. First parameter is the dependency itself
* @example
* ```ts
* addDisposer('dbConnection', (dbConnection) => dbConnection.end())
* ```
* Swap out a preexisting dependency.
*/
addDisposer(key: keyof Dependencies, cleanup: AnyFunction) {
Result.wrap(() => container.addDisposer({ [key] : cleanup }))
.expect("Failed to addDisposer for" + key);
}
};
};
type ValidDependencyConfig =
| ((c: ReturnType<typeof dependencyBuilder>) => any)
| DependencyConfiguration;
/** /**
* Given the user's conf, check for any excluded/included dependency keys. * @since 2.0.0
* Then, call conf.build to get the rest of the users' dependencies. * @param conf a configuration for creating your project dependencies
* Finally, update the containerSubject with the new container state
* @param conf
*/ */
function composeRoot( export async function makeDependencies<const T extends Dependencies>(
container: CoreContainer<Partial<Dependencies>>,
conf: DependencyConfiguration, conf: DependencyConfiguration,
) { ) {
//container should have no client or logger yet. //Until there are more optional dependencies, just check if the logger exists
const hasLogger = conf.exclude?.has('@sern/logger'); //SIDE EFFECT
if (!hasLogger) {
__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'>>);
if (!hasLogger) {
container.get('@sern/logger')?.info({ message: 'All dependencies loaded successfully.' });
}
container.ready();
}
export async function makeDependencies<const T extends Dependencies>
(conf: ValidDependencyConfig) {
containerSubject = new CoreContainer(); containerSubject = new CoreContainer();
if(typeof conf === 'function') { await composeRoot(containerSubject, conf);
const excluded: string[] = [];
conf(dependencyBuilder(containerSubject, excluded));
//We only include logger if it does not exist
const includeLogger =
!excluded.includes('@sern/logger')
&& !containerSubject.hasKey('@sern/logger');
if(includeLogger) {
__add_container('@sern/logger', new __Services.DefaultLogging);
}
containerSubject.ready();
} else {
composeRoot(containerSubject, conf);
}
return useContainer<T>(); return useContainer<T>();
} }

View File

@@ -1,10 +1,9 @@
import { Container } from 'iti'; import { Container } from 'iti';
import { Disposable } from '../'; import { Disposable, SernEmitter } from '../';
import * as assert from 'node:assert'; import * as assert from 'node:assert';
import { Subject } from 'rxjs'; import { Subject } from 'rxjs';
import { __Services, ModuleStore } from '../_internal'; import { DefaultServices, ModuleStore } from '../_internal';
import * as Hooks from './hooks'; import * as Hooks from './hooks'
import { EventEmitter } from 'node:events';
/** /**
@@ -18,39 +17,42 @@ export class CoreContainer<T extends Partial<Dependencies>> extends Container<T,
assert.ok(!this.isReady(), 'Listening for dispose & init should occur prior to sern being ready.'); assert.ok(!this.isReady(), 'Listening for dispose & init should occur prior to sern being ready.');
const { unsubscribe } = Hooks.createInitListener(this); const { unsubscribe } = Hooks.createInitListener(this);
this.ready$ this.ready$
.subscribe({ complete: unsubscribe }); .subscribe({ complete: unsubscribe });
(this as Container<{}, {}>) (this as Container<{}, {}>)
.add({ '@sern/errors': () => new __Services.DefaultErrorHandling, .add({
'@sern/emitter': () => new EventEmitter({ captureRejections: true }), '@sern/errors': () => new DefaultServices.DefaultErrorHandling(),
'@sern/store': () => new ModuleStore }) '@sern/emitter': () => new SernEmitter(),
'@sern/store': () => new ModuleStore(),
})
.add(ctx => { .add(ctx => {
return { '@sern/modules': new __Services.DefaultModuleManager(ctx['@sern/store'])}; return {
'@sern/modules': () =>
new DefaultServices.DefaultModuleManager(ctx['@sern/store']),
};
}); });
} }
isReady() { isReady() {
return this.ready$.closed; return this.ready$.closed;
} }
hasKey(key: string): boolean {
return Boolean((this as Container<any,any>)._context[key]);
}
override async disposeAll() { override async disposeAll() {
const otherDisposables = Object const otherDisposables = Object
.entries(this._context) .entries(this._context)
.flatMap(([key, value]) => .flatMap(([key, value]) =>
'dispose' in value ? [key] : []); 'dispose' in value
otherDisposables.forEach(key => { ? [key]
//possible source of bug: dispose is a property. : []);
for(const key of otherDisposables) {
this.addDisposer({ [key]: (dep: Disposable) => dep.dispose() } as never); this.addDisposer({ [key]: (dep: Disposable) => dep.dispose() } as never);
}) }
await super.disposeAll(); await super.disposeAll()
} }
ready() { ready() {
this.ready$.complete(); this.ready$.complete();
this.ready$.unsubscribe(); this.ready$.unsubscribe();

View File

@@ -1,6 +1,7 @@
import assert from 'node:assert'; import type { CoreDependencies, DependencyConfiguration, IntoDependencies } from '../../types/ioc';
import type { IntoDependencies } from '../../types/ioc'; import { DefaultServices } from '../_internal';
import { useContainerRaw } from './base'; import { useContainerRaw } from './base';
import { CoreContainer } from './container';
/** /**
* @__PURE__ * @__PURE__
@@ -25,7 +26,6 @@ export function transient<T>(cb: () => () => T) {
* The new Service api, a cleaner alternative to useContainer * The new Service api, a cleaner alternative to useContainer
* To obtain intellisense, ensure a .d.ts file exists in the root of compilation. * To obtain intellisense, ensure a .d.ts file exists in the root of compilation.
* Usually our scaffolding tool takes care of this. * Usually our scaffolding tool takes care of this.
* Note: this method only works AFTER your container has been initiated
* @since 3.0.0 * @since 3.0.0
* @example * @example
* ```ts * ```ts
@@ -35,9 +35,7 @@ export function transient<T>(cb: () => () => T) {
* *
*/ */
export function Service<const T extends keyof Dependencies>(key: T) { export function Service<const T extends keyof Dependencies>(key: T) {
const dep = useContainerRaw().get(key)!; return useContainerRaw().get(key)!;
assert(dep, "Requested key " + key + " returned undefined");
return dep;
} }
/** /**
* @since 3.0.0 * @since 3.0.0
@@ -49,9 +47,34 @@ export function Services<const T extends (keyof Dependencies)[]>(...keys: [...T]
return keys.map(k => container.get(k)!) as IntoDependencies<T>; return keys.map(k => container.get(k)!) as IntoDependencies<T>;
} }
/**
* Given the user's conf, check for any excluded dependency keys.
* Then, call conf.build to get the rest of the users' dependencies.
* Finally, update the containerSubject with the new container state
* @param conf
*/
export async function composeRoot(
container: CoreContainer<Partial<Dependencies>>,
conf: DependencyConfiguration,
) {
//container should have no client or logger yet.
const hasLogger = conf.exclude?.has('@sern/logger');
if (!hasLogger) {
container.upsert({
'@sern/logger': () => new DefaultServices.DefaultLogging(),
});
}
//Build the container based on the callback provided by the user
conf.build(container as CoreContainer<Omit<CoreDependencies, '@sern/client'>>);
if (!hasLogger) {
container.get('@sern/logger')?.info({ message: 'All dependencies loaded successfully.' });
}
container.ready();
}
export function useContainer<const T extends Dependencies>() { export function useContainer<const T extends Dependencies>() {
return <V extends (keyof T)[]>(...keys: [...V]) => return <V extends (keyof T)[]>(...keys: [...V]) =>
keys.map(key => useContainerRaw().get(key as keyof Dependencies)) as IntoDependencies<V>; keys.map(key => useContainerRaw().get(key as keyof Dependencies)) as IntoDependencies<V>;
} }

View File

@@ -9,7 +9,7 @@ type HookName = 'init';
export const createInitListener = (coreContainer : CoreContainer<any>) => { export const createInitListener = (coreContainer : CoreContainer<any>) => {
const initCalled = new Set<PropertyKey>(); const initCalled = new Set<PropertyKey>();
const hasCallableMethod = createPredicate(initCalled); const hasCallableMethod = createPredicate(initCalled);
const unsubscribe = coreContainer.on('containerUpserted', async event => { const unsubscribe = coreContainer.on('containerUpserted', async (event) => {
if(isNotHookable(event)) { if(isNotHookable(event)) {
return; return;
@@ -21,7 +21,6 @@ export const createInitListener = (coreContainer : CoreContainer<any>) => {
} }
}); });
return { unsubscribe }; return { unsubscribe };
} }

View File

@@ -1,21 +1,11 @@
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 } from 'path';
import assert from 'assert'; import assert from 'assert';
import { createRequire } from 'node:module'; import { createRequire } from 'node:module';
import type { ImportPayload, Wrapper } from '../types/core'; import type { ImportPayload, Wrapper } from '../types/core';
import type { Module } from '../types/core-modules'; import type { Module, OnError } from '../types/core-modules';
import { existsSync } from 'fs';
import type { Logging } from './contracts/logging';
export const shouldHandle = (path: string, fpath: string) => {
const file_name = fpath+extname(path);
let newPath = join(dirname(path), file_name)
.replace(/file:\\?/, "");
return { exists: existsSync(newPath),
path: 'file:///'+newPath };
}
export type ModuleResult<T> = Promise<ImportPayload<T>>; export type ModuleResult<T> = Promise<ImportPayload<T>>;
@@ -35,19 +25,25 @@ export type ModuleResult<T> = Promise<ImportPayload<T>>;
export async function importModule<T>(absPath: string) { export async function importModule<T>(absPath: string) {
let fileModule = await import(absPath); let fileModule = await import(absPath);
let commandModule = fileModule.default; let commandModule = fileModule.default,
onError = fileModule.onError;
assert(commandModule , `Found no export @ ${absPath}. Forgot to ignore with "!"? (!${basename(absPath)})?`); assert(commandModule , `Found no export @ ${absPath}. Forgot to ignore with "!"? (!${basename(absPath)})?`);
if ('default' in commandModule ) { if ('default' in commandModule ) {
commandModule = commandModule.default; commandModule = commandModule.default;
} }
return { module: commandModule } as T; return Result
.wrap(() => ({ module: commandModule.getInstance(), onError }))
.unwrapOr({ module: commandModule, onError }) as T;
}
interface FileExtras {
onError : OnError
} }
export async function defaultModuleLoader<T extends Module>(absPath: string): ModuleResult<T> { export async function defaultModuleLoader<T extends Module>(absPath: string): ModuleResult<T> {
let { module } = await importModule<{ module: T }>(absPath); let { onError, module } = await importModule<{ module: T } & FileExtras>(absPath);
assert(module, `Found an undefined module: ${absPath}`); assert(module, `Found an undefined module: ${absPath}`);
return { module, absPath }; return { module, absPath, onError };
} }
export const fmtFileName = (fileName: string) => parse(fileName).name; export const fmtFileName = (fileName: string) => parse(fileName).name;
@@ -74,14 +70,14 @@ const isSkippable = (filename: string) => {
const validExtensions = ['.js', '.cjs', '.mts', '.mjs', '.cts', '.ts', '']; const validExtensions = ['.js', '.cjs', '.mts', '.mjs', '.cts', '.ts', ''];
return filename[0] === '!' || !validExtensions.includes(extname(filename)); return filename[0] === '!' || !validExtensions.includes(extname(filename));
}; };
async function deriveFileInfo(dir: string, file: string) { async function deriveFileInfo(dir: string, file: string) {
const fullPath = join(dir, file); const fullPath = join(dir, file);
return { fullPath, return {
fileStats: await stat(fullPath), fullPath,
base: basename(file) }; fileStats: await stat(fullPath),
base: basename(file),
};
} }
async function* readPaths(dir: string): AsyncGenerator<string> { async function* readPaths(dir: string): AsyncGenerator<string> {
try { try {
const files = await readdir(dir); const files = await readdir(dir);
@@ -105,11 +101,11 @@ async function* readPaths(dir: string): AsyncGenerator<string> {
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'): Wrapper {
if (wrapper !== 'file') { if (wrapper !== 'file') {
return wrapper; return wrapper;
} }
log?.info({ message: 'Experimental loading of sern.config.json'}); console.log('Experimental loading of sern.config.json');
const config = requir(resolve('sern.config.json')); const config = requir(resolve('sern.config.json'));
const makePath = (dir: PropertyKey) => const makePath = (dir: PropertyKey) =>
@@ -117,18 +113,19 @@ export function loadConfig(wrapper: Wrapper | 'file', log: Logging | undefined):
? join('dist', config.paths[dir]!) ? join('dist', config.paths[dir]!)
: join(config.paths[dir]!); : join(config.paths[dir]!);
log?.info({ message: 'Loading config: ' + JSON.stringify(config, null, 4) }); console.log('Loading config: ', config);
const commandsPath = makePath('commands'); const commandsPath = makePath('commands');
log?.info({ message: `Commands path is set to ${commandsPath}` }); console.log('Commands path is set to', commandsPath);
let eventsPath: string | undefined; let eventsPath: string | undefined;
if (config.paths.events) { if (config.paths.events) {
eventsPath = makePath('events'); eventsPath = makePath('events');
log?.info({ message: `Events path is set to ${eventsPath} `}); console.log('Events path is set to', eventsPath);
} }
return {
return { defaultPrefix: config.defaultPrefix, defaultPrefix: config.defaultPrefix,
commands: commandsPath, commands: commandsPath,
events: eventsPath }; events: eventsPath,
};
} }

View File

@@ -1,13 +1,19 @@
import { ClientEvents } from 'discord.js'; import { ClientEvents } from 'discord.js';
import { EventType } from '../core/structures'; import { CommandType, EventType, PluginType } 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';
@@ -55,3 +61,52 @@ export function discordEvent<T extends keyof ClientEvents>(mod: {
}); });
} }
function prepareClassPlugins(c: Module) {
const [onEvent, initPlugins] = partitionPlugins(c.plugins);
c.plugins = initPlugins as InitPlugin[];
c.onEvent = onEvent as ControlPlugin[];
}
//
// Class modules:
// Can be refactored.
// Both implement singleton, could I make them inherit a singleton parent class?
/**
* @Experimental
* Will be refactored / changed 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>;
}
/**
* @Experimental
* Will be refactored 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

@@ -28,15 +28,16 @@ export function filterMapTo<V>(item: () => V): OperatorFunction<boolean, V> {
return concatMap(shouldKeep => (shouldKeep ? of(item()) : EMPTY)); return concatMap(shouldKeep => (shouldKeep ? of(item()) : EMPTY));
} }
interface PluginExecutable {
execute: (...args: unknown[]) => PluginResult;
};
/** /**
* Calls any plugin with {args}. * Calls any plugin with {args}.
* @param args if an array, its spread and plugin called. * @param args if an array, its spread and plugin called.
*/ */
export function callPlugin(args: unknown): OperatorFunction<PluginExecutable, VoidResult> export function callPlugin(args: unknown): OperatorFunction<
{ {
execute: (...args: unknown[]) => PluginResult;
},
VoidResult
> {
return concatMap(async plugin => { return concatMap(async plugin => {
if (Array.isArray(args)) { if (Array.isArray(args)) {
return plugin.execute(...args); return plugin.execute(...args);
@@ -59,25 +60,27 @@ 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, emitter: Emitter, logging?: Logging) { export function handleError<C>(crashHandler: ErrorHandling, 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
if(!emitter.emit('error', pload)) { const err = pload instanceof Error ? pload : Error(util.inspect(pload, { colors: true }));
const err = pload instanceof Error ? pload : Error(util.inspect(pload, { colors: true })); //formatted payload
logging?.error({ message: util.inspect(pload) }); logging?.error({ message: util.inspect(pload) });
crashHandler.updateAlive(err); crashHandler.updateAlive(err);
}
return caught; return caught;
}; };
} }
// Temporary until i get rxjs operators working on ts-results-es // Temporary until i get rxjs operators working on ts-results-es
export const filterTap = <K, R>(onErr: (e: R) => void): OperatorFunction<Result<K, R>, K> => export const filterTap = <K, R>(onErr: (e: R) => void): OperatorFunction<Result<K, R>, K> =>
pipe(concatMap(result => { pipe(
concatMap(result => {
if(result.isOk()) { if(result.isOk()) {
return of(result.value) return of(result.value)
} }
onErr(result.error); onErr(result.error);
return EMPTY return EMPTY
}))
})
)

34
src/core/predicates.ts Normal file
View File

@@ -0,0 +1,34 @@
import type {
AnySelectMenuInteraction,
AutocompleteInteraction,
ButtonInteraction,
ChatInputCommandInteraction,
MessageContextMenuCommandInteraction,
ModalSubmitInteraction,
UserContextMenuCommandInteraction,
} from 'discord.js';
import { InteractionType } from 'discord.js';
interface InteractionTypable {
type: InteractionType;
}
//discord.js pls fix ur typings or i will >:(
type AnyMessageComponentInteraction = AnySelectMenuInteraction | ButtonInteraction;
type AnyCommandInteraction =
| ChatInputCommandInteraction
| MessageContextMenuCommandInteraction
| UserContextMenuCommandInteraction;
export function isMessageComponent(i: InteractionTypable): i is AnyMessageComponentInteraction {
return i.type === InteractionType.MessageComponent;
}
export function isCommand(i: InteractionTypable): i is AnyCommandInteraction {
return i.type === InteractionType.ApplicationCommand;
}
export function isAutocomplete(i: InteractionTypable): i is AutocompleteInteraction {
return i.type === InteractionType.ApplicationCommandAutocomplete;
}
export function isModal(i: InteractionTypable): i is ModalSubmitInteraction {
return i.type === InteractionType.ModalSubmit;
}

View File

@@ -1,68 +0,0 @@
import type { ActivitiesOptions } from "discord.js";
import type { IntoDependencies } from "../types/ioc";
import type { Emitter } from "./contracts/emitter";
type Status = 'online' | 'idle' | 'invisible' | 'dnd'
type PresenceReduce = (previous: Result) => Result;
export interface Result {
status?: Status;
afk?: boolean;
activities?: ActivitiesOptions[];
shardId?: number[];
repeat?: number | [Emitter, string];
onRepeat?: (previous: Result) => Result;
}
export type Config <T extends (keyof Dependencies)[]> =
{
inject?: [...T]
execute: (...v: IntoDependencies<T>) => Result;
};
/**
* A small wrapper to provide type inference.
* Create a Presence module which **MUST** be put in a file called presence.(language-extension)
* adjacent to the file where **Sern.init** is CALLED.
*/
export function module<T extends (keyof Dependencies)[]>(conf: Config<T>)
{ return conf; }
/**
* Create a Presence body which can be either:
* - once, the presence is activated only once.
* - repeated, per cycle or event, the presence can be changed.
*/
export function of(root: Omit<Result, 'repeat' | 'onRepeat'>) {
return {
/**
* @example
* Presence
* .of({
* activities: [{ name: "deez nuts" }]
* }) //starts the presence with "deez nuts".
* .repeated(prev => {
* return {
* afk: true,
* activities: prev.activities?.map(s => ({ ...s, name: s.name+"s" }))
* };
* }, 10000)) //every 10 s, the callback sets the presence to the returned one.
*/
repeated: (onRepeat: PresenceReduce, repeat: number | [Emitter, string]) => {
return { repeat, onRepeat, ...root }
},
/**
* @example
* Presence
* .of({
* activities: [
* { name: "Chilling out" }
* ]
* })
* .once() // Sets the presence once, with what's provided in '.of()'
*/
once: () => root
};
}

View File

@@ -0,0 +1,6 @@
import type { Logging } from "../contracts";
export interface Response {
type: 'fail' | 'handled';
log?: { type: keyof Logging; message: unknown }
}

View File

@@ -1,4 +1,4 @@
import type { import {
BaseInteraction, BaseInteraction,
ChatInputCommandInteraction, ChatInputCommandInteraction,
Client, Client,
@@ -114,7 +114,7 @@ export class Context extends CoreContext<Message, ChatInputCommandInteraction> {
if ('interaction' in wrappable) { if ('interaction' in wrappable) {
return new Context(Ok(wrappable)); return new Context(Ok(wrappable));
} }
assert.ok(wrappable.isChatInputCommand(), "Context created with bad interaction."); assert.ok(wrappable.isChatInputCommand());
return new Context(Err(wrappable)); return new Context(Err(wrappable));
} }
} }

View File

@@ -7,7 +7,7 @@ import * as assert from 'node:assert';
*/ */
export abstract class CoreContext<M, I> { export abstract class CoreContext<M, I> {
protected constructor(protected ctx: Either<M, I>) { protected constructor(protected ctx: Either<M, I>) {
assert.ok(typeof ctx === 'object' && ctx != null, "Context was nonobject or null"); assert.ok(typeof ctx === 'object' && ctx != null);
} }
get message(): M { get message(): M {
return this.ctx.expect(SernError.MismatchEvent); return this.ctx.expect(SernError.MismatchEvent);

View File

@@ -1,5 +1,6 @@
export { CommandType, PluginType, PayloadType, EventType } from './enums'; export { CommandType, PluginType, PayloadType, EventType } from './enums';
export * from './context'; export * from './context';
export * from './sern-emitter';
export * from './services'; export * from './services';
export * from './module-store'; export * from './module-store';
export * as CommandError from './command-error';

View File

@@ -1,11 +1,13 @@
import { CommandMeta, Module } from '../../types/core-modules'; import { CommandMeta, Module, OnError } from '../../types/core-modules';
import { CoreModuleStore } from '../contracts';
/* /*
* @deprecated * @internal
* Version 4.0.0 will internalize this api. Please refrain from using ModuleStore! * Version 4.0.0 will internalize this api. Please refrain from using ModuleStore!
* For interacting with modules, use the ModuleManager instead. * For interacting with modules, use the ModuleManager instead.
*/ */
export class ModuleStore { export class ModuleStore implements CoreModuleStore {
onError = new WeakMap<Module, NonNullable<OnError>>();
metadata = new WeakMap<Module, CommandMeta>(); metadata = new WeakMap<Module, CommandMeta>();
commands = new Map<string, Module>(); commands = new Map<string, string>();
} }

View File

@@ -0,0 +1,89 @@
import { EventEmitter } from 'node:events';
import { PayloadType } from '../../core/structures';
import { Module } from '../../types/core-modules';
import { SernEventsMapping, Payload } from '../../types/utility';
/**
* @since 1.0.0
*/
export class SernEmitter extends EventEmitter {
constructor() {
super({ captureRejections: true });
}
/**
* 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

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

View File

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

View File

@@ -11,13 +11,15 @@ import {
import { createResultResolver } from './event-utils'; import { createResultResolver } from './event-utils';
import { BaseInteraction, Message } from 'discord.js'; import { BaseInteraction, Message } from 'discord.js';
import { CommandType, Context } from '../core'; import { CommandType, Context } from '../core';
import type { Args } from '../types/utility'; import type { AnyFunction, Args } from '../types/utility';
import { inspect } from 'node:util' import type { CommandModule, Module, OnError, Processed } from '../types/core-modules';
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 { module, args }; return {
module,
args,
};
} }
export function contextArgs(wrappable: Message | BaseInteraction, messageArgs?: string[]) { export function contextArgs(wrappable: Message | BaseInteraction, messageArgs?: string[]) {
@@ -26,17 +28,20 @@ export function contextArgs(wrappable: Message | BaseInteraction, messageArgs?:
return [ctx, args] as [Context, Args]; return [ctx, args] as [Context, Args];
} }
function interactionArg<T extends BaseInteraction>(interaction: T) {
return [interaction] as [T];
}
function intoPayload(module: Processed<Module>, ) { function intoPayload(module: Processed<Module>, onError: AnyFunction|undefined) {
return pipe( return pipe(
arrayifySource, arrayifySource,
map(args => ({ module, args, })), map(args => ({ module, args, onError })),
); );
} }
const createResult = createResultResolver< const createResult = createResultResolver<
Processed<Module>, Processed<Module>,
{ module: Processed<Module>; args: unknown[] }, { module: Processed<Module>; args: unknown[], onError: AnyFunction|undefined },
unknown[] unknown[]
>({ >({
createStream: ({ module, args }) => from(module.onEvent).pipe(callPlugin(args)), createStream: ({ module, args }) => from(module.onEvent).pipe(callPlugin(args)),
@@ -47,14 +52,14 @@ const createResult = createResultResolver<
* @param module * @param module
* @param source * @param source
*/ */
export function eventDispatcher(module: Processed<Module>, source: unknown) { export function eventDispatcher(module: Processed<Module>, onError: OnError, source: unknown) {
assert.ok(source instanceof EventEmitter, `${source} is not an EventEmitter`); assert.ok(source instanceof EventEmitter, `${source} is not an EventEmitter`);
const execute: OperatorFunction<unknown[], unknown> = concatMap(async args => const execute: OperatorFunction<unknown[], unknown> = concatMap(async args =>
module.execute(...args), module.execute(...args),
); );
return fromEvent(source, module.name).pipe( return fromEvent(source, module.name).pipe(
intoPayload(module), intoPayload(module, onError),
concatMap(createResult), concatMap(createResult),
execute, execute,
); );
@@ -63,6 +68,7 @@ export function eventDispatcher(module: Processed<Module>, source: unknown) {
export function createDispatcher(payload: { export function createDispatcher(payload: {
module: Processed<CommandModule>; module: Processed<CommandModule>;
event: BaseInteraction; event: BaseInteraction;
onError: OnError
}) { }) {
assert.ok( assert.ok(
CommandType.Text !== payload.module.type, CommandType.Text !== payload.module.type,
@@ -73,17 +79,29 @@ export function createDispatcher(payload: {
case CommandType.Both: { case CommandType.Both: {
if (isAutocomplete(payload.event)) { if (isAutocomplete(payload.event)) {
const option = treeSearch(payload.event, payload.module.options); const option = treeSearch(payload.event, payload.module.options);
assert.ok(option, SernError.NotSupportedInteraction + ` There is no autocomplete tag for ` + inspect(payload.module)); assert.ok(
option,
Error(SernError.NotSupportedInteraction + ` There is no autocomplete tag for this option`),
);
const { command } = option; const { command } = option;
return { return {
...payload, ...payload,
module: command as Processed<Module>, //autocomplete is not a true "module" warning cast! module: command as Processed<Module>, //autocomplete is not a true "module" warning cast!
args: [payload.event], args: [payload.event],
onError: undefined
}; };
} }
return { module: payload.module, args: contextArgs(payload.event) }; return {
args: contextArgs(payload.event),
...payload,
onError: payload.onError
};
} }
default: return { module: payload.module, args: [payload.event] }; default:
return {
args: interactionArg(payload.event),
...payload,
onError: payload.onError
}
} }
} }

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,
@@ -21,16 +21,18 @@ import {
handleError, handleError,
SernError, SernError,
VoidResult, VoidResult,
resultPayload, useContainerRaw,
} from '../core/_internal'; } from '../core/_internal';
import { Emitter, ErrorHandling, Logging, ModuleManager, PayloadType } from '../core'; import { CommandError, Emitter, ErrorHandling, Logging, ModuleManager } from '../core';
import { contextArgs, createDispatcher } from './dispatchers'; import { contextArgs, createDispatcher } from './dispatchers';
import { ObservableInput, pipe } from 'rxjs'; import { ObservableInput, pipe } from 'rxjs';
import { SernEmitter } from '../core';
import { Err, Ok, Result } from 'ts-results-es'; import { Err, Ok, Result } from 'ts-results-es';
import type { Awaitable } from '../types/utility'; import type { AnyFunction, Awaitable } from '../types/utility';
import type { ControlPlugin } from '../types/core-plugin'; import type { ControlPlugin } from '../types/core-plugin';
import type { AnyModule, CommandMeta, CommandModule, Module, Processed } from '../types/core-modules'; import type { AnyModule, CommandModule, Module, OnError, Processed } from '../types/core-modules';
import { disposeAll } from '../core/ioc/base'; import type { ImportPayload } from '../types/core';
import assert from 'node:assert';
function createGenericHandler<Source, Narrowed extends Source, Output>( function createGenericHandler<Source, Narrowed extends Source, Output>(
source: Observable<Source>, source: Observable<Source>,
@@ -70,17 +72,20 @@ export function createInteractionHandler<T extends Interaction>(
return createGenericHandler<Interaction, T, Result<ReturnType<typeof createDispatcher>, void>>( return createGenericHandler<Interaction, T, Result<ReturnType<typeof createDispatcher>, void>>(
source, source,
async event => { async event => {
const possibleIds = Id.reconstruct(event); const fullPath = mg.get(Id.reconstruct(event));
let fullPaths= possibleIds if(!fullPath) {
.map(id => mg.get(id)) return Err.EMPTY
.filter((id): id is Module => id !== undefined);
if(fullPaths.length == 0) {
return Err.EMPTY;
} }
const [ path ] = fullPaths; return Files
return Ok(createDispatcher({ module: path as Processed<CommandModule>, event })); .defaultModuleLoader<Processed<CommandModule>>(fullPath)
}); .then(payload =>
Ok(createDispatcher({
module: payload.module,
onError: payload.onError,
event,
})));
},
);
} }
export function createMessageHandler( export function createMessageHandler(
@@ -90,50 +95,49 @@ export function createMessageHandler(
) { ) {
return createGenericHandler(source, async event => { return createGenericHandler(source, async event => {
const [prefix, ...rest] = fmt(event.content, defaultPrefix); const [prefix, ...rest] = fmt(event.content, defaultPrefix);
let fullPath = mg.get(`${prefix}_T`); const fullPath = mg.get(`${prefix}_A1`);
if(!fullPath) { if(!fullPath) {
fullPath = mg.get(`${prefix}_B`); return Err('Possibly undefined behavior: could not find a static id to resolve')
if(!fullPath) {
return Err('Possibly undefined behavior: could not find a static id to resolve');
}
} }
return Ok({ args: contextArgs(event, rest), module: fullPath as Processed<CommandModule> }) return Files
.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() { function assignDefaults<T extends Module>(
return map(({ module, absPath }) => { moduleManager: ModuleManager,
const processed = { ): MonoTypeOperatorFunction<ImportPayload<T>> {
name: module.name ?? Files.filename(absPath), return tap(({ module, absPath }) => {
description: module.description ?? '...', module.name ??= Files.filename(absPath);
...module module.description ??= '...';
} moduleManager.setMetadata(module, {
return { isClass: module.constructor.name === 'Function',
module: processed, fullPath: absPath,
absPath, id: Id.create(module.name, module.type),
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).pipe(assignDefaults(moduleManager));
.buildModuleStream<Processed<T>>(input)
.pipe(assignDefaults());
} }
interface ExecutePayload { interface ExecutePayload {
module: Processed<Module>; module: Processed<Module>;
task: () => Awaitable<unknown>; task: () => Awaitable<unknown>;
onError: AnyFunction|undefined
args: unknown[] args: unknown[]
} }
/** /**
@@ -151,25 +155,44 @@ export function executeModule(
{ {
module, module,
task, task,
onError,
args args
}: ExecutePayload, }: ExecutePayload,
) { ) {
const onError$ = (err_msg: unknown) => {
if(!onError) {
return throwError(() => SernEmitter.failure(module, err));
}
//Could be promise
const err = onError(err_msg) as CommandError.Response
if(!err) {
const failure = SernEmitter.failure(module, "onError: returned undefined/null");
return throwError(() => failure);
}
if(err.log) {
const { type, message } = err.log;
logger?.[type]({ message });
};
if(err.type === 'fail') {
} else {
}
return EMPTY;
}
return of(module).pipe( return of(module).pipe(
//converting the task into a promise so rxjs can resolve the Awaitable properly //converting the task into a promise so rxjs can resolve the Awaitable properly
concatMap(() => Result.wrapAsync(async () => task())), concatMap(() => Result.wrapAsync(async () => task())),
concatMap(result => { concatMap(result => {
if (result.isOk()) { if (result.isOk()) {
emitter.emit('module.activate', resultPayload(PayloadType.Success, module)); emitter.emit('module.activate', SernEmitter.success(module));
return EMPTY; return EMPTY;
} }
return throwError(() => resultPayload(PayloadType.Failure, module, result.error)); return onError$(result.error);
}), }),
); );
} }
/** /**
* A higher order function that * A higher order function that
* - creates a stream of {@link VoidResult} { config.createStream } * - creates a stream of {@link VoidResult} { config.createStream }
@@ -181,7 +204,7 @@ export function executeModule(
*/ */
export function createResultResolver< export function createResultResolver<
T extends { execute: (...args: any[]) => any; onEvent: ControlPlugin[] }, T extends { execute: (...args: any[]) => any; onEvent: ControlPlugin[] },
Args extends { module: T; [key: string]: unknown }, Args extends { module: T; onError: unknown, [key: string]: unknown },
Output, Output,
>(config: { >(config: {
onStop?: (module: T) => unknown; onStop?: (module: T) => unknown;
@@ -209,11 +232,14 @@ export function callInitPlugins<T extends Processed<AnyModule>>(sernEmitter: Emi
createResultResolver({ createResultResolver({
createStream: args => from(args.module.plugins).pipe(callPlugin(args)), createStream: args => from(args.module.plugins).pipe(callPlugin(args)),
onStop: (module: T) => { onStop: (module: T) => {
sernEmitter.emit('module.register', resultPayload(PayloadType.Failure, module, SernError.PluginFailure)); sernEmitter.emit(
'module.register',
SernEmitter.failure(module, SernError.PluginFailure),
);
}, },
onNext: (payload) => { onNext: ({ module, onError }) => {
sernEmitter.emit('module.register', resultPayload(PayloadType.Success, payload.module)); sernEmitter.emit('module.register', SernEmitter.success(module));
return payload as { module: T; metadata: CommandMeta }; return { module, onError: onError as OnError };
}, },
}), }),
); );
@@ -228,11 +254,13 @@ export function makeModuleExecutor<
Args extends { Args extends {
module: M; module: M;
args: unknown[]; args: unknown[];
onError: AnyFunction|undefined
}, },
>(onStop: (m: M) => unknown) { >(onStop: (m: M) => unknown) {
const onNext = ({ args, module }: Args) => ({ const onNext = ({ args, module, onError }: Args) => ({
task: () => module.execute(...args), task: () => module.execute(...args),
module, module,
onError,
args args
}); });
return concatMap( return concatMap(
@@ -246,12 +274,15 @@ export function makeModuleExecutor<
); );
} }
export const handleCrash = (err: ErrorHandling,sernemitter: Emitter, log?: Logging) => export const handleCrash = (err: ErrorHandling, log?: Logging) =>
pipe( pipe(
catchError(handleError(err, sernemitter, log)), catchError(handleError(err, 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',
}); });
disposeAll(log); useContainerRaw()
})); ?.disposeAll()
.then(() => log?.info({ message: 'Cleaning container and crashing' }));
}),
);

View File

@@ -1,6 +1,6 @@
import { Interaction } from 'discord.js'; import { Interaction } from 'discord.js';
import { mergeMap, merge } from 'rxjs'; import { concatMap, merge } from 'rxjs';
import { PayloadType } from '../core'; import { SernEmitter } from '../core';
import { import {
isAutocomplete, isAutocomplete,
isCommand, isCommand,
@@ -9,7 +9,6 @@ import {
sharedEventStream, sharedEventStream,
SernError, SernError,
filterTap, filterTap,
resultPayload,
} from '../core/_internal'; } from '../core/_internal';
import { createInteractionHandler, executeModule, makeModuleExecutor } from './_internal'; import { createInteractionHandler, executeModule, makeModuleExecutor } from './_internal';
import type { DependencyList } from '../types/ioc'; import type { DependencyList } from '../types/ioc';
@@ -26,8 +25,9 @@ export function interactionHandler([emitter, err, log, modules, client]: Depende
); );
return interactionHandler$ return interactionHandler$
.pipe( .pipe(
filterTap(e => emitter.emit('warning', resultPayload(PayloadType.Warning, undefined, e))), filterTap(e => emitter.emit('warning', SernEmitter.warning(e))),
makeModuleExecutor(module => makeModuleExecutor(module =>
emitter.emit('module.activate', resultPayload(PayloadType.Failure, module, SernError.PluginFailure))), emitter.emit('module.activate', SernEmitter.failure(module, SernError.PluginFailure))),
mergeMap(payload => executeModule(emitter, log, err, payload))); concatMap(payload => executeModule(emitter, log, err, payload)),
);
} }

View File

@@ -1,7 +1,7 @@
import { mergeMap, EMPTY } from 'rxjs'; import { concatMap, EMPTY } from 'rxjs';
import type { Message } from 'discord.js'; import type { Message } from 'discord.js';
import { PayloadType } from '../core'; import { SernEmitter } from '../core';
import { sharedEventStream, SernError, filterTap, resultPayload } from '../core/_internal'; import { sharedEventStream, SernError, filterTap } from '../core/_internal';
import { createMessageHandler, executeModule, makeModuleExecutor } from './_internal'; import { createMessageHandler, executeModule, makeModuleExecutor } from './_internal';
import type { DependencyList } from '../types/ioc'; import type { DependencyList } from '../types/ioc';
@@ -38,10 +38,10 @@ export function messageHandler(
const msgCommands$ = handle(isNonBot(defaultPrefix)); const msgCommands$ = handle(isNonBot(defaultPrefix));
return msgCommands$.pipe( return msgCommands$.pipe(
filterTap((e) => emitter.emit('warning', resultPayload(PayloadType.Warning, undefined, e))), filterTap((e) => emitter.emit('warning', SernEmitter.warning(e))),
makeModuleExecutor(module => { makeModuleExecutor(module => {
const result = resultPayload(PayloadType.Failure, module, SernError.PluginFailure); emitter.emit('module.activate', SernEmitter.failure(module, SernError.PluginFailure));
emitter.emit('module.activate', result);
}), }),
mergeMap(payload => executeModule(emitter, log, err, payload))); concatMap(payload => executeModule(emitter, log, err, payload)),
);
} }

View File

@@ -1,45 +0,0 @@
import { concatMap, from, interval, of, map, scan, startWith, fromEvent, take } from "rxjs"
import { Files } from "../core/_internal";
import * as Presence from "../core/presences";
import { Services } from "../core/ioc";
import assert from "node:assert";
type SetPresence = (conf: Presence.Result) => Promise<unknown>
const parseConfig = async (conf: Promise<Presence.Result>) => {
return conf.then(s => {
if('repeat' in s) {
const { onRepeat, repeat } = s;
assert(repeat !== undefined, "repeat option is undefined");
assert(onRepeat !== undefined, "onRepeat callback is undefined, but repeat exists");
const src$ = typeof repeat === 'number'
? interval(repeat)
: fromEvent(...repeat);
return src$
.pipe(scan(onRepeat, s),
startWith(s));
}
return of(s).pipe(take(1));
})
};
export const presenceHandler = (path: string, setPresence: SetPresence) => {
interface PresenceModule {
module: Presence.Config<(keyof Dependencies)[]>
}
const presence = Files
.importModule<PresenceModule>(path)
.then(({ module }) => {
//fetch services with the order preserved, passing it to the execute fn
const fetchedServices = Services(...module.inject ?? []);
return async () => module.execute(...fetchedServices);
})
const module$ = from(presence);
return module$.pipe(
//compose:
//call the execute function, passing that result into parseConfig.
//concatMap resolves the promise, and passes it to the next concatMap.
concatMap(fn => parseConfig(fn())),
// subscribe to the observable parseConfig yields, and set the presence.
concatMap(conf => conf.pipe(map(setPresence))));
}

View File

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

View File

@@ -4,26 +4,26 @@ import { SernError } from '../core/_internal';
import { buildModules, callInitPlugins, handleCrash, eventDispatcher } from './_internal'; import { buildModules, callInitPlugins, handleCrash, eventDispatcher } from './_internal';
import { Service } from '../core/ioc'; import { Service } from '../core/ioc';
import type { DependencyList } from '../types/ioc'; import type { DependencyList } from '../types/ioc';
import type { EventModule, Processed } from '../types/core-modules'; import type { EventModule, OnError, Processed } from '../types/core-modules';
export function eventsHandler( export function eventsHandler(
[emitter, err, log, moduleManager, client]: DependencyList, [emitter, err, log, moduleManager, client]: DependencyList,
allPaths: ObservableInput<string>, allPaths: ObservableInput<string>,
) { ) {
//code smell //code smell
const intoDispatcher = (e: { module: Processed<EventModule> }) => { const intoDispatcher = (e: { module: Processed<EventModule>, onError: OnError }) => {
switch (e.module.type) { switch (e.module.type) {
case EventType.Sern: case EventType.Sern:
return eventDispatcher(e.module, emitter); return eventDispatcher(e.module, e.onError, emitter);
case EventType.Discord: case EventType.Discord:
return eventDispatcher(e.module, client); return eventDispatcher(e.module, e.onError, client);
case EventType.External: case EventType.External:
return eventDispatcher(e.module, Service(e.module.emitter)); return eventDispatcher(e.module, e.onError, Service(e.module.emitter));
default: default:
throw Error(SernError.InvalidModuleType + ' while creating event handler'); throw Error(SernError.InvalidModuleType + ' while creating event handler');
} }
}; };
buildModules<EventModule>(allPaths) buildModules<EventModule>(allPaths, moduleManager)
.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, emitter, log)) handleCrash(err, log))
.subscribe(); .subscribe();
} }

View File

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

View File

@@ -1,15 +1,12 @@
import { handleCrash } from './handlers/_internal'; import { handleCrash } from './handlers/_internal';
import callsites from 'callsites'; import { err, ok, Files } from './core/_internal';
import { Files } from './core/_internal';
import { merge } from 'rxjs'; import { merge } from 'rxjs';
import { Services } from './core/ioc'; import { Services } from './core/ioc';
import { Wrapper } from './types/core'; import { Wrapper } from './types/core';
import { eventsHandler } from './handlers/user-defined-events'; import { eventsHandler } from './handlers/user-defined-events';
import { readyHandler } from './handlers/ready-event'; import { startReadyEvent } from './handlers/ready-event';
import { messageHandler } from './handlers/message-event'; import { messageHandler } from './handlers/message-event';
import { interactionHandler } from './handlers/interaction-event'; import { interactionHandler } from './handlers/interaction-event';
import { presenceHandler } from './handlers/presence';
import { Client } from 'discord.js';
/** /**
* @since 1.0.0 * @since 1.0.0
@@ -23,40 +20,47 @@ import { Client } from 'discord.js';
* }) * })
* ``` * ```
*/ */
export function init(maybeWrapper: Wrapper | 'file') { export function init(maybeWrapper: Wrapper | 'file') {
const startTime = performance.now(); const startTime = performance.now();
const dependencies = Services('@sern/emitter', const wrapper = Files.loadConfig(maybeWrapper);
'@sern/errors', const dependencies = useDependencies();
'@sern/logger',
'@sern/modules',
'@sern/client');
const logger = dependencies[2], const logger = dependencies[2],
errorHandler = dependencies[1]; errorHandler = dependencies[1];
const wrapper = Files.loadConfig(maybeWrapper, logger);
if (wrapper.events !== undefined) { if (wrapper.events !== undefined) {
eventsHandler(dependencies, Files.getFullPathTree(wrapper.events)); eventsHandler(dependencies, Files.getFullPathTree(wrapper.events));
} }
const initCallsite = callsites()[1].getFileName();
const presencePath = Files.shouldHandle(initCallsite!, "presence");
//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)) startReadyEvent(dependencies, Files.getFullPathTree(wrapper.commands)).add(() => {
.add(() => { const time = ((performance.now() - startTime) / 1000).toFixed(2);
logger?.info({ message: "Client signaled ready, registering modules" }); dependencies[0].emit('modulesLoaded');
const time = ((performance.now() - startTime) / 1000).toFixed(2); logger?.info({
dependencies[0].emit('modulesLoaded'); 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);
}
presenceHandler(presencePath.path, setPresence).subscribe();
}
}); });
});
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, dependencies[0], logger)).subscribe(); merge(messages$, interactions$).pipe(handleCrash(errorHandler, logger)).subscribe();
} }
function useDependencies() {
return Services(
'@sern/emitter',
'@sern/errors',
'@sern/logger',
'@sern/modules',
'@sern/client',
);
}
/**
* @since 1.0.0
* The object passed into every plugin to control a command's behavior
*/
export const controller = {
next: ok,
stop: err,
};

View File

@@ -17,7 +17,9 @@ import type {
} from 'discord.js'; } from 'discord.js';
import { CommandType, Context, EventType } from '../../src/core'; import { CommandType, Context, EventType } from '../../src/core';
import { AnyCommandPlugin, AnyEventPlugin, ControlPlugin, InitPlugin } from './core-plugin'; import { AnyCommandPlugin, AnyEventPlugin, ControlPlugin, InitPlugin } from './core-plugin';
import { Awaitable, Args, SlashOptions, SernEventsMapping } from './utility'; import { Awaitable, Args, SlashOptions, SernEventsMapping, AnyFunction } from './utility';
export type OnError = AnyFunction|undefined
export interface CommandMeta { export interface CommandMeta {

View File

@@ -33,9 +33,9 @@ import type {
TextCommand, TextCommand,
UserSelectCommand, UserSelectCommand,
} from './core-modules'; } from './core-modules';
import type { Args, Awaitable, Payload, SlashOptions } from './utility'; import { Args, Awaitable, Payload, SlashOptions } from './utility';
import type { CommandType, Context, EventType, PluginType } from '../core'; import { CommandType, Context, EventType, PluginType } from '../core';
import type { import {
ButtonInteraction, ButtonInteraction,
ChannelSelectMenuInteraction, ChannelSelectMenuInteraction,
ClientEvents, ClientEvents,

View File

@@ -1,7 +1,9 @@
import { OnError } from "./core-modules";
export interface ImportPayload<T> { export interface ImportPayload<T> {
module: T; module: T;
absPath: string; absPath: string;
onError: OnError
[key: string]: unknown; [key: string]: unknown;
} }

View File

@@ -26,15 +26,11 @@ export type DependencyList = [
export interface CoreDependencies { export interface CoreDependencies {
'@sern/client': () => Contracts.Emitter; '@sern/client': () => Contracts.Emitter;
'@sern/logger'?: () => Contracts.Logging;
'@sern/emitter': () => Contracts.Emitter; '@sern/emitter': () => Contracts.Emitter;
/**
* @deprecated
* Will be removed and turned internal
*/
'@sern/store': () => Contracts.CoreModuleStore; '@sern/store': () => Contracts.CoreModuleStore;
'@sern/modules': () => Contracts.ModuleManager; '@sern/modules': () => Contracts.ModuleManager;
'@sern/errors': () => Contracts.ErrorHandling; '@sern/errors': () => Contracts.ErrorHandling;
'@sern/logger'?: () => Contracts.Logging;
} }
export type DependencyFromKey<T extends keyof Dependencies> = Dependencies[T]; export type DependencyFromKey<T extends keyof Dependencies> = Dependencies[T];
@@ -43,13 +39,8 @@ export type IntoDependencies<Tuple extends [...any[]]> = {
[Index in keyof Tuple]: UnpackFunction<NonNullable<DependencyFromKey<Tuple[Index]>>>; //Unpack and make NonNullable [Index in keyof Tuple]: UnpackFunction<NonNullable<DependencyFromKey<Tuple[Index]>>>; //Unpack and make NonNullable
} & { length: Tuple['length'] }; } & { length: Tuple['length'] };
/**
* @deprecated This old signature will be incompatible with future versions of sern.
*/
export interface DependencyConfiguration { export interface DependencyConfiguration {
/* //@deprecated. Loggers will always be included in the future
* @deprecated. Loggers will be opt-in the future
*/
exclude?: Set<'@sern/logger'>; exclude?: Set<'@sern/logger'>;
build: ( build: (
root: Container<Omit<CoreDependencies, '@sern/client'>, {}>, root: Container<Omit<CoreDependencies, '@sern/client'>, {}>,

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: [{ type: PayloadType.Failure; module?: AnyModule; reason: string | Error }]; error: [Payload];
warning: [Payload]; warning: [Payload];
modulesLoaded: [never?]; modulesLoaded: [never?];
} }
@@ -26,7 +26,8 @@ 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; module: undefined; reason: string }; | { type: PayloadType.Warning; reason: string };
export type ReplyOptions = string | Omit<InteractionReplyOptions, 'fetchReply'> | MessageReplyOptions; export type ReplyOptions = string | Omit<InteractionReplyOptions, 'fetchReply'> | MessageReplyOptions;

View File

@@ -1,64 +0,0 @@
import { CommandType } from '../../src/core';
import * as Id from '../../src/core/id'
import { expect, test } from 'vitest'
test('id -> Text', () => {
const bothCmdId = Id.create("ping", CommandType.Text)
expect(bothCmdId).toBe("ping_T")
})
test('id -> Both', () => {
const bothCmdId = Id.create("ping", CommandType.Both)
expect(bothCmdId).toBe("ping_B")
})
test('id -> CtxMsg', () => {
const bothCmdId = Id.create("ping", CommandType.CtxMsg)
expect(bothCmdId).toBe("ping_A3")
})
test('id -> CtxUsr', () => {
const bothCmdId = Id.create("ping", CommandType.CtxUser)
expect(bothCmdId).toBe("ping_A2")
})
test('id -> Modal', () => {
const modal = Id.create("my-modal", CommandType.Modal)
expect(modal).toBe("my-modal_M");
})
test('id -> Button', () => {
const modal = Id.create("my-button", CommandType.Button)
expect(modal).toBe("my-button_C2");
})
test('id -> Slash', () => {
const modal = Id.create("myslash", CommandType.Slash)
expect(modal).toBe("myslash_A1");
})
test('id -> StringSelect', () => {
const modal = Id.create("mystringselect", CommandType.StringSelect)
expect(modal).toBe("mystringselect_C3");
})
test('id -> UserSelect', () => {
const modal = Id.create("myuserselect", CommandType.UserSelect)
expect(modal).toBe("myuserselect_C5");
})
test('id -> RoleSelect', () => {
const modal = Id.create("myroleselect", CommandType.RoleSelect)
expect(modal).toBe("myroleselect_C6");
})
test('id -> MentionSelect', () => {
const modal = Id.create("mymentionselect", CommandType.MentionableSelect)
expect(modal).toBe("mymentionselect_C7");
})
test('id -> ChannelSelect', () => {
const modal = Id.create("mychannelselect", CommandType.ChannelSelect)
expect(modal).toBe("mychannelselect_C8");
})

View File

@@ -1,13 +1,12 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'; import { beforeEach, describe, expect, it, vi } from 'vitest';
import { CoreContainer } from '../../src/core/ioc/container'; import { CoreContainer } from '../../src/core/ioc/container';
import { EventEmitter } from 'events'; import { EventEmitter } from 'events';
import { DefaultLogging, Disposable, Emitter, Init, Logging } from '../../src/core'; import { DefaultLogging, Disposable, Init, Logging } from '../../src/core';
import { CoreDependencies } from '../../src/types/ioc'; import { CoreDependencies } from '../../src/types/ioc';
describe('ioc container', () => { describe('ioc container', () => {
let container: CoreContainer<{}> = new CoreContainer(); let container: CoreContainer<{}> = new CoreContainer();
let dependency: Logging & Init & Disposable; let dependency: Logging & Init & Disposable;
let dependency2: Emitter
beforeEach(() => { beforeEach(() => {
dependency = { dependency = {
init: vi.fn(), init: vi.fn(),
@@ -17,11 +16,6 @@ describe('ioc container', () => {
debug(): void {}, debug(): void {},
dispose: vi.fn() dispose: vi.fn()
}; };
dependency2 = {
addListener: vi.fn(),
removeListener: vi.fn(),
emit: vi.fn()
};
container = new CoreContainer(); container = new CoreContainer();
}); });
const wait = (seconds: number) => new Promise((resolve) => setTimeout(resolve, seconds)); const wait = (seconds: number) => new Promise((resolve) => setTimeout(resolve, seconds));
@@ -89,25 +83,4 @@ describe('ioc container', () => {
container.ready(); container.ready();
expect(dependency.init).toHaveBeenCalledTimes(0); expect(dependency.init).toHaveBeenCalledTimes(0);
}); });
it('should init dependency depending on something else', () => {
container.add({ '@sern/client': dependency2 });
container.upsert((cntr) => ({
'@sern/logger': dependency
}));
container.ready();
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()
})
}); });

View File

@@ -1,57 +0,0 @@
import { describe, expect, it, vi } from 'vitest';
import { Presence } from '../../src';
// Example test suite for the module function
describe('module function', () => {
it('should return a valid configuration', () => {
const config: Presence.Config<['dependency1', 'dependency2']> = Presence.module({
inject: ['dependency1', 'dependency2'],
execute: vi.fn(),
});
expect(config).toBeDefined();
expect(config.inject).toEqual(['dependency1', 'dependency2']);
expect(typeof config.execute).toBe('function');
});
});
describe('of function', () => {
it('should return a valid presence configuration without repeat and onRepeat', () => {
const presenceConfig = Presence.of({
status: 'online',
afk: false,
activities: [{ name: 'Test Activity' }],
shardId: [1, 2, 3],
}).once();
expect(presenceConfig).toBeDefined();
//@ts-ignore Maybe fix?
expect(presenceConfig.repeat).toBeUndefined();
//@ts-ignore Maybe fix?
expect(presenceConfig.onRepeat).toBeUndefined();
expect(presenceConfig).toMatchObject({
status: 'online',
afk: false,
activities: [{ name: 'Test Activity' }],
shardId: [1, 2, 3],
});
});
it('should return a valid presence configuration with repeat and onRepeat', () => {
const onRepeatCallback = vi.fn();
const presenceConfig = Presence.of({
status: 'idle',
activities: [{ name: 'Another Test Activity' }],
}).repeated(onRepeatCallback, 5000);
expect(presenceConfig).toBeDefined();
expect(presenceConfig.repeat).toBe(5000);
expect(presenceConfig.onRepeat).toBe(onRepeatCallback);
expect(presenceConfig).toMatchObject({
status: 'idle',
activities: [{ name: 'Another Test Activity' }],
});
});
})

View File

@@ -74,7 +74,4 @@ describe('services', () => {
expect(consoleMock).toHaveBeenCalledOnce(); expect(consoleMock).toHaveBeenCalledOnce();
expect(consoleMock).toHaveBeenLastCalledWith({ message: 'error' }); expect(consoleMock).toHaveBeenLastCalledWith({ message: 'error' });
}); });
}); });

View File

@@ -29,14 +29,14 @@ describe('eventDispatcher standard', () => {
}); });
it('should throw', () => { it('should throw', () => {
expect(() => eventDispatcher(m, 'not event emitter')).toThrowError(); expect(() => eventDispatcher(m, 'not event emitter')).toThrowError();
}); });
it("Shouldn't throw", () => { it("Shouldn't throw", () => {
expect(() => eventDispatcher(m, ee)).not.toThrowError(); expect(() => eventDispatcher(m, ee)).not.toThrowError();
}); });
it('Should be called once', () => { it('Should be called once', () => {
const s = eventDispatcher(m, ee); const s = eventDispatcher(m, ee);
s.subscribe(); s.subscribe();
ee.emit(m.name, faker.string.alpha()); ee.emit(m.name, faker.string.alpha());

View File

@@ -2,6 +2,7 @@ import { describe, expect, it, vi } from 'vitest';
import * as Id from '../../src/core/id'; import * as Id from '../../src/core/id';
import { faker } from '@faker-js/faker'; import { faker } from '@faker-js/faker';
import { CommandModule, CommandType, commandModule } from '../../src'; import { CommandModule, CommandType, commandModule } from '../../src';
import { CommandTypeDiscordApi } from '../../src/core/id';
function createRandomCommandModules() { function createRandomCommandModules() {
const randomCommandType = [ const randomCommandType = [
@@ -40,8 +41,32 @@ describe('id resolution', () => {
const metadata = modules.map(createMetadata); const metadata = modules.map(createMetadata);
metadata.forEach((meta, idx) => { metadata.forEach((meta, idx) => {
const associatedModule = modules[idx]; const associatedModule = modules[idx];
const uid = Id.create(associatedModule.name!, associatedModule.type!); const am = (appBitField & associatedModule.type) !== 0 ? 'A' : 'C';
expect(meta.id).toBe(uid); let uid = 0;
if (
associatedModule.type === CommandType.Both ||
associatedModule.type === CommandType.Modal
) {
uid = 1;
} else {
uid = CommandTypeDiscordApi[Math.log2(associatedModule.type)];
}
expect(meta.id).toBe(associatedModule.name + '_' + am + uid);
}); });
}); });
it('maps commands type to discord components or application commands', () => {
expect(CommandTypeDiscordApi[Math.log2(CommandType.Text)]).toBe(1);
expect(CommandTypeDiscordApi[1]).toBe(1);
expect(CommandTypeDiscordApi[Math.log2(CommandType.CtxUser)]).toBe(2);
expect(CommandTypeDiscordApi[Math.log2(CommandType.CtxMsg)]).toBe(3);
expect(CommandTypeDiscordApi[Math.log2(CommandType.Button)]).toBe(2);
expect(CommandTypeDiscordApi[Math.log2(CommandType.StringSelect)]).toBe(3);
expect(CommandTypeDiscordApi[Math.log2(CommandType.UserSelect)]).toBe(5);
expect(CommandTypeDiscordApi[Math.log2(CommandType.RoleSelect)]).toBe(6);
expect(CommandTypeDiscordApi[Math.log2(CommandType.MentionableSelect)]).toBe(7);
expect(CommandTypeDiscordApi[Math.log2(CommandType.ChannelSelect)]).toBe(8);
expect(CommandTypeDiscordApi[6]).toBe(1);
});
}); });

344
yarn.lock
View File

@@ -12,82 +12,81 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"@discordjs/builders@npm:^1.7.0": "@discordjs/builders@npm:^1.6.3":
version: 1.7.0 version: 1.6.5
resolution: "@discordjs/builders@npm:1.7.0" resolution: "@discordjs/builders@npm:1.6.5"
dependencies: dependencies:
"@discordjs/formatters": ^0.3.3 "@discordjs/formatters": ^0.3.2
"@discordjs/util": ^1.0.2 "@discordjs/util": ^1.0.1
"@sapphire/shapeshift": ^3.9.3 "@sapphire/shapeshift": ^3.9.2
discord-api-types: 0.37.61 discord-api-types: 0.37.50
fast-deep-equal: ^3.1.3 fast-deep-equal: ^3.1.3
ts-mixer: ^6.0.3 ts-mixer: ^6.0.3
tslib: ^2.6.2 tslib: ^2.6.1
checksum: 837e7643fc8396e4914bbbfbbfa1232ab7109c931884e8df45cd7356944633590f710a18513d30a10de1b6686ed5166df702bde0c4511fb0cbcac897edd9e56a checksum: 9c5c4d483a79a7c2f73d661433365f2996ae3bc74f95b70a2a31a26b582b7327d45217a78dfe8e304737661731690ef6e34ade7575f63fe8ab61d70ca53b2279
languageName: node languageName: node
linkType: hard linkType: hard
"@discordjs/collection@npm:1.5.3": "@discordjs/collection@npm:^1.5.1":
version: 1.5.3 version: 1.5.3
resolution: "@discordjs/collection@npm:1.5.3" resolution: "@discordjs/collection@npm:1.5.3"
checksum: fefed19bea0f69053d195f9d9dc8af07ca5d8c9b1064581e0aa14bda2b70e632b93c164d5ef3e4910f5442369612ff4eec8d52a700aec562510c19b223f67023 checksum: fefed19bea0f69053d195f9d9dc8af07ca5d8c9b1064581e0aa14bda2b70e632b93c164d5ef3e4910f5442369612ff4eec8d52a700aec562510c19b223f67023
languageName: node languageName: node
linkType: hard linkType: hard
"@discordjs/collection@npm:^2.0.0": "@discordjs/formatters@npm:^0.3.1, @discordjs/formatters@npm:^0.3.2":
version: 2.0.0 version: 0.3.2
resolution: "@discordjs/collection@npm:2.0.0" resolution: "@discordjs/formatters@npm:0.3.2"
checksum: c2d05fa2b9a27bb64e93e2836bbe44c835d21f85e28cd934f6e2a81fef423ab0415968cca9d066b83347539edc8ea9afa8075d80bd62594e39f09eb881052c49 dependencies:
discord-api-types: 0.37.50
checksum: 653c88595fc6c25c1beedcd88b05a3f1241fef69844cc96e45f2cd34fea9ff07892c7f3b57edb4008ad59f7e62bca1b7b35400c6200b07ed42eef7189672d509
languageName: node languageName: node
linkType: hard linkType: hard
"@discordjs/formatters@npm:^0.3.3": "@discordjs/rest@npm:^1.7.1":
version: 0.3.3 version: 1.7.1
resolution: "@discordjs/formatters@npm:0.3.3" resolution: "@discordjs/rest@npm:1.7.1"
dependencies: dependencies:
discord-api-types: 0.37.61 "@discordjs/collection": ^1.5.1
checksum: a844628094a6effa8ac4e4a4ea9082d5c89e6cae6bbd18e60abd410769e5ea18f64aa2db8623aa3c8c572084368f6c2e27cc2d72af640aff5e4ee7fc42132c60 "@discordjs/util": ^0.3.0
languageName: node
linkType: hard
"@discordjs/rest@npm:^2.1.0":
version: 2.2.0
resolution: "@discordjs/rest@npm:2.2.0"
dependencies:
"@discordjs/collection": ^2.0.0
"@discordjs/util": ^1.0.2
"@sapphire/async-queue": ^1.5.0 "@sapphire/async-queue": ^1.5.0
"@sapphire/snowflake": ^3.5.1 "@sapphire/snowflake": ^3.4.2
"@vladfrangu/async_event_emitter": ^2.2.2 discord-api-types: ^0.37.41
discord-api-types: 0.37.61 file-type: ^18.3.0
magic-bytes.js: ^1.5.0 tslib: ^2.5.0
tslib: ^2.6.2 undici: ^5.22.0
undici: 5.27.2 checksum: 397dca0f2433dcc20c98805427388dd2ab09b906c429185e5d7cfc5057ad7b2a815653482476cffb64b8e1c3628ff254d927796316956d737375be22383c88d7
checksum: 29a14ecf3282ae3306883f1f6c870693d0ecacd080c5b66a72e31487a8070655807a80a8bf09bebea4f73e631439abc5121dfa38016ca0ccbe3f68c0f7ffc80e
languageName: node languageName: node
linkType: hard linkType: hard
"@discordjs/util@npm:^1.0.2": "@discordjs/util@npm:^0.3.0, @discordjs/util@npm:^0.3.1":
version: 1.0.2 version: 0.3.1
resolution: "@discordjs/util@npm:1.0.2" resolution: "@discordjs/util@npm:0.3.1"
checksum: 320d7e125981001160d413ae56e76e60447dce102010b80e3b1b16d885be765df5ae2551aa79fdc4d435a82361ed72246b44251f0c1f7a8fef7056a4481d5609 checksum: afd53427bc25c84e05cd34d6daf355cab14629a5f340d33528ea18d3a1177e777584bc5847cfcb7711c7387252c34917d749a0b1a91a99d2ce572878208212df
languageName: node languageName: node
linkType: hard linkType: hard
"@discordjs/ws@npm:^1.0.2": "@discordjs/util@npm:^1.0.1":
version: 1.0.2 version: 1.0.1
resolution: "@discordjs/ws@npm:1.0.2" resolution: "@discordjs/util@npm:1.0.1"
checksum: b55d5284cd8306b0e77a303c41fa99dcc650babaf9ef2f02ea38b1f8ecc7218a7694128714343379dbf6b2a402a0851e00862c0d974ad07b8e980722f5139d73
languageName: node
linkType: hard
"@discordjs/ws@npm:^0.8.3":
version: 0.8.3
resolution: "@discordjs/ws@npm:0.8.3"
dependencies: dependencies:
"@discordjs/collection": ^2.0.0 "@discordjs/collection": ^1.5.1
"@discordjs/rest": ^2.1.0 "@discordjs/rest": ^1.7.1
"@discordjs/util": ^1.0.2 "@discordjs/util": ^0.3.1
"@sapphire/async-queue": ^1.5.0 "@sapphire/async-queue": ^1.5.0
"@types/ws": ^8.5.9 "@types/ws": ^8.5.4
"@vladfrangu/async_event_emitter": ^2.2.2 "@vladfrangu/async_event_emitter": ^2.2.1
discord-api-types: 0.37.61 discord-api-types: ^0.37.41
tslib: ^2.6.2 tslib: ^2.5.0
ws: ^8.14.2 ws: ^8.13.0
checksum: 2564d3ff00d04d7638955c8c9a9f6234c50168fbe8243140bc458dc9ffa39ad5063e7d5762cdce71bb8bcf70b6353c28b8531e40f54568706898e92bc8748590 checksum: 28eb76ce58e31bc6be8b4d410aae448a8ad6388298f97392d1df002f3f5f1b0ab344bd4cb971aeebd0ea62558dcf1d9554cab3a21485d221f2a7af4ed0766a2e
languageName: node languageName: node
linkType: hard linkType: hard
@@ -448,13 +447,6 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"@fastify/busboy@npm:^2.0.0":
version: 2.1.0
resolution: "@fastify/busboy@npm:2.1.0"
checksum: 3233abd10f73e50668cb4bb278a79b7b3fadd30215ac6458299b0e5a09a29c3586ec07597aae6bd93f5cbedfcef43a8aeea51829cd28fc13850cdbcd324c28d5
languageName: node
linkType: hard
"@humanwhocodes/config-array@npm:^0.11.8": "@humanwhocodes/config-array@npm:^0.11.8":
version: 0.11.11 version: 0.11.11
resolution: "@humanwhocodes/config-array@npm:0.11.11" resolution: "@humanwhocodes/config-array@npm:0.11.11"
@@ -595,30 +587,23 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"@sapphire/shapeshift@npm:^3.9.3": "@sapphire/shapeshift@npm:^3.9.2":
version: 3.9.4 version: 3.9.2
resolution: "@sapphire/shapeshift@npm:3.9.4" resolution: "@sapphire/shapeshift@npm:3.9.2"
dependencies: dependencies:
fast-deep-equal: ^3.1.3 fast-deep-equal: ^3.1.3
lodash: ^4.17.21 lodash: ^4.17.21
checksum: 680a06823f899753c230d676a0c4c4b45e5575329d3598fb243dd5777c491955a62dcba94aac35770327a5a1103ddee6ceb8fa99c6b88de3cdd313fe3bafb2d3 checksum: 0d4572281a2a43dc444f56aef7462d16fdc49cdf0e625d521bfeae4b2219e35b53b7752b4e7396e402ce3b1a21c86afc4c3c82ce1547822a6e844116bb220760
languageName: node languageName: node
linkType: hard linkType: hard
"@sapphire/snowflake@npm:3.5.1": "@sapphire/snowflake@npm:^3.4.2":
version: 3.5.1 version: 3.5.1
resolution: "@sapphire/snowflake@npm:3.5.1" resolution: "@sapphire/snowflake@npm:3.5.1"
checksum: 8fc025020adab1a7a1a5d2cf07704d598cc1977b50e5fcd3a5dd239f00934dc936d3a4d5ae336e71d8bf1d88ec27aa814b34de79e38ff097b7b9ba5a7977a683 checksum: 8fc025020adab1a7a1a5d2cf07704d598cc1977b50e5fcd3a5dd239f00934dc936d3a4d5ae336e71d8bf1d88ec27aa814b34de79e38ff097b7b9ba5a7977a683
languageName: node languageName: node
linkType: hard linkType: hard
"@sapphire/snowflake@npm:^3.5.1":
version: 3.5.2
resolution: "@sapphire/snowflake@npm:3.5.2"
checksum: f88ee6b167abd83868092b71d68ad36599e922948d1b77ba694c1e13afafc46d4b07914d86ad5af6841cb4b95ceaffd940affe56576362a1c7a5d28a4344f3e4
languageName: node
linkType: hard
"@sern/handler@workspace:.": "@sern/handler@workspace:.":
version: 0.0.0-use.local version: 0.0.0-use.local
resolution: "@sern/handler@workspace:." resolution: "@sern/handler@workspace:."
@@ -627,8 +612,8 @@ __metadata:
"@types/node": ^18.15.11 "@types/node": ^18.15.11
"@typescript-eslint/eslint-plugin": 5.58.0 "@typescript-eslint/eslint-plugin": 5.58.0
"@typescript-eslint/parser": 5.59.1 "@typescript-eslint/parser": 5.59.1
callsites: ^3.1.0 discord.js: 14.11.0
discord.js: ^14.11.0 esbuild: ^0.17.0
eslint: 8.39.0 eslint: 8.39.0
iti: ^0.6.0 iti: ^0.6.0
prettier: 2.8.8 prettier: 2.8.8
@@ -647,6 +632,13 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"@tokenizer/token@npm:^0.3.0":
version: 0.3.0
resolution: "@tokenizer/token@npm:0.3.0"
checksum: 1d575d02d2a9f0c5a4ca5180635ebd2ad59e0f18b42a65f3d04844148b49b3db35cf00b6012a1af2d59c2ab3caca59451c5689f747ba8667ee586ad717ee58e1
languageName: node
linkType: hard
"@tootallnate/once@npm:2": "@tootallnate/once@npm:2":
version: 2.0.0 version: 2.0.0
resolution: "@tootallnate/once@npm:2.0.0" resolution: "@tootallnate/once@npm:2.0.0"
@@ -698,21 +690,12 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"@types/ws@npm:8.5.9": "@types/ws@npm:^8.5.4":
version: 8.5.9 version: 8.5.5
resolution: "@types/ws@npm:8.5.9" resolution: "@types/ws@npm:8.5.5"
dependencies: dependencies:
"@types/node": "*" "@types/node": "*"
checksum: 83f436b731d2cdc49a45ced31a0a65cdd2e39c24d7b882776c26efa190dad6553e266d624c7a7089f36ad3ed471e02e729f3219282c80689b435f665df4a2b0b checksum: d00bf8070e6938e3ccf933010921c6ce78ac3606696ce37a393b27a9a603f7bd93ea64f3c5fa295a2f743575ba9c9a9fdb904af0f5fe2229bf2adf0630386e4a
languageName: node
linkType: hard
"@types/ws@npm:^8.5.9":
version: 8.5.10
resolution: "@types/ws@npm:8.5.10"
dependencies:
"@types/node": "*"
checksum: 3ec416ea2be24042ebd677932a462cf16d2080393d8d7d0b1b3f5d6eaa4a7387aaf0eefb99193c0bfd29444857cf2e0c3ac89899e130550dc6c14ada8a46d25e
languageName: node languageName: node
linkType: hard linkType: hard
@@ -935,10 +918,10 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"@vladfrangu/async_event_emitter@npm:^2.2.2": "@vladfrangu/async_event_emitter@npm:^2.2.1":
version: 2.2.4 version: 2.2.2
resolution: "@vladfrangu/async_event_emitter@npm:2.2.4" resolution: "@vladfrangu/async_event_emitter@npm:2.2.2"
checksum: ff65ebc4d89639adecd249e24e4f6f97b7696404f2a4461160efdff628d91de543e982727c18de62a4edada3f66381b5a3cd1d4f4f33098075d839c1b4f46979 checksum: ed948294fea1a2dc8b8f307f4061bf65e2043a946132f288702f0572a806ebe3123b8c7e522e70d2abbd3616f5d67027c9e59df9ef80b0195f7502a848a426ba
languageName: node languageName: node
linkType: hard linkType: hard
@@ -1159,6 +1142,15 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"busboy@npm:^1.6.0":
version: 1.6.0
resolution: "busboy@npm:1.6.0"
dependencies:
streamsearch: ^1.1.0
checksum: 32801e2c0164e12106bf236291a00795c3c4e4b709ae02132883fe8478ba2ae23743b11c5735a0aae8afe65ac4b6ca4568b91f0d9fed1fdbc32ede824a73746e
languageName: node
linkType: hard
"cac@npm:^6.7.12, cac@npm:^6.7.14": "cac@npm:^6.7.12, cac@npm:^6.7.14":
version: 6.7.14 version: 6.7.14
resolution: "cac@npm:6.7.14" resolution: "cac@npm:6.7.14"
@@ -1186,7 +1178,7 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"callsites@npm:^3.0.0, callsites@npm:^3.1.0": "callsites@npm:^3.0.0":
version: 3.1.0 version: 3.1.0
resolution: "callsites@npm:3.1.0" resolution: "callsites@npm:3.1.0"
checksum: 072d17b6abb459c2ba96598918b55868af677154bec7e73d222ef95a8fdb9bbf7dae96a8421085cdad8cd190d86653b5b6dc55a4484f2e5b2e27d5e0c3fc15b3 checksum: 072d17b6abb459c2ba96598918b55868af677154bec7e73d222ef95a8fdb9bbf7dae96a8421085cdad8cd190d86653b5b6dc55a4484f2e5b2e27d5e0c3fc15b3
@@ -1366,32 +1358,39 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"discord-api-types@npm:0.37.61": "discord-api-types@npm:0.37.50":
version: 0.37.61 version: 0.37.50
resolution: "discord-api-types@npm:0.37.61" resolution: "discord-api-types@npm:0.37.50"
checksum: fe33d528e31a6de0bab2afb43d0e058957a6da6cfc4d797943fac83aeb8d07543dc0f85cad3c4e6789cbbac0c7ca49dae5ac465224b129c7acb716097fa0b081 checksum: 08dc5145dbefda5f52b479cd42d96ac2b8110300861855e1f92cc8a0a6525a4059e32724cd5237490c286f5afd86797a86823238cd5eee016198560bb36f6d43
languageName: node languageName: node
linkType: hard linkType: hard
"discord.js@npm:^14.11.0": "discord-api-types@npm:^0.37.41":
version: 14.14.1 version: 0.37.56
resolution: "discord.js@npm:14.14.1" resolution: "discord-api-types@npm:0.37.56"
checksum: 797be690af70a846422f955d918a5713a2c8c37bea646e2120996522afbb47fc5893122c1ddcb8f57a285ace6e1fb0237d1e63105444ae52534f0570a2f87f34
languageName: node
linkType: hard
"discord.js@npm:14.11.0":
version: 14.11.0
resolution: "discord.js@npm:14.11.0"
dependencies: dependencies:
"@discordjs/builders": ^1.7.0 "@discordjs/builders": ^1.6.3
"@discordjs/collection": 1.5.3 "@discordjs/collection": ^1.5.1
"@discordjs/formatters": ^0.3.3 "@discordjs/formatters": ^0.3.1
"@discordjs/rest": ^2.1.0 "@discordjs/rest": ^1.7.1
"@discordjs/util": ^1.0.2 "@discordjs/util": ^0.3.1
"@discordjs/ws": ^1.0.2 "@discordjs/ws": ^0.8.3
"@sapphire/snowflake": 3.5.1 "@sapphire/snowflake": ^3.4.2
"@types/ws": 8.5.9 "@types/ws": ^8.5.4
discord-api-types: 0.37.61 discord-api-types: ^0.37.41
fast-deep-equal: 3.1.3 fast-deep-equal: ^3.1.3
lodash.snakecase: 4.1.1 lodash.snakecase: ^4.1.1
tslib: 2.6.2 tslib: ^2.5.0
undici: 5.27.2 undici: ^5.22.0
ws: 8.14.2 ws: ^8.13.0
checksum: 651e61861ae33e6ec3903e72a8bf229caae5dab73f8d409c3673430cafd9c438a0dd59983242bdcff47bab50da39f7a04da5b586c35b396c102e8e87637076e5 checksum: 63e0a312c4ee89b03bfd16f3d58ff185d1e4cee75aa2d75de7a56d049a0bcddb89e16ae77cb02ddf0272072698d490c6a98959a8a90dd68ac6175a3ee50a191d
languageName: node languageName: node
linkType: hard linkType: hard
@@ -1448,7 +1447,7 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"esbuild@npm:^0.17.6": "esbuild@npm:^0.17.0, esbuild@npm:^0.17.6":
version: 0.17.19 version: 0.17.19
resolution: "esbuild@npm:0.17.19" resolution: "esbuild@npm:0.17.19"
dependencies: dependencies:
@@ -1760,7 +1759,7 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"fast-deep-equal@npm:3.1.3, fast-deep-equal@npm:^3.1.1, fast-deep-equal@npm:^3.1.3": "fast-deep-equal@npm:^3.1.1, fast-deep-equal@npm:^3.1.3":
version: 3.1.3 version: 3.1.3
resolution: "fast-deep-equal@npm:3.1.3" resolution: "fast-deep-equal@npm:3.1.3"
checksum: e21a9d8d84f53493b6aa15efc9cfd53dd5b714a1f23f67fb5dc8f574af80df889b3bce25dc081887c6d25457cce704e636395333abad896ccdec03abaf1f3f9d checksum: e21a9d8d84f53493b6aa15efc9cfd53dd5b714a1f23f67fb5dc8f574af80df889b3bce25dc081887c6d25457cce704e636395333abad896ccdec03abaf1f3f9d
@@ -1812,6 +1811,17 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"file-type@npm:^18.3.0":
version: 18.5.0
resolution: "file-type@npm:18.5.0"
dependencies:
readable-web-to-node-stream: ^3.0.2
strtok3: ^7.0.0
token-types: ^5.0.1
checksum: d2bc81d842b110970a0ca9d90356ce4e9738c1c05596ce8931f2af334477856d92bcecd0742dc6646e13a970c0125150ad4415898688d1901d80e972d90ab1ca
languageName: node
linkType: hard
"fill-range@npm:^7.0.1": "fill-range@npm:^7.0.1":
version: 7.0.1 version: 7.0.1
resolution: "fill-range@npm:7.0.1" resolution: "fill-range@npm:7.0.1"
@@ -2098,6 +2108,13 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"ieee754@npm:^1.2.1":
version: 1.2.1
resolution: "ieee754@npm:1.2.1"
checksum: 5144c0c9815e54ada181d80a0b810221a253562422e7c6c3a60b1901154184f49326ec239d618c416c1c5945a2e197107aee8d986a3dd836b53dffefd99b5e7e
languageName: node
linkType: hard
"ignore@npm:^5.2.0": "ignore@npm:^5.2.0":
version: 5.2.4 version: 5.2.4
resolution: "ignore@npm:5.2.4" resolution: "ignore@npm:5.2.4"
@@ -2358,7 +2375,7 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"lodash.snakecase@npm:4.1.1": "lodash.snakecase@npm:^4.1.1":
version: 4.1.1 version: 4.1.1
resolution: "lodash.snakecase@npm:4.1.1" resolution: "lodash.snakecase@npm:4.1.1"
checksum: 1685ed3e83dda6eae5a4dcaee161a51cd210aabb3e1c09c57150e7dd8feda19e4ca0d27d0631eabe8d0f4eaa51e376da64e8c018ae5415417c5890d42feb72a8 checksum: 1685ed3e83dda6eae5a4dcaee161a51cd210aabb3e1c09c57150e7dd8feda19e4ca0d27d0631eabe8d0f4eaa51e376da64e8c018ae5415417c5890d42feb72a8
@@ -2411,13 +2428,6 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"magic-bytes.js@npm:^1.5.0":
version: 1.7.0
resolution: "magic-bytes.js@npm:1.7.0"
checksum: c36cc3fa828ff27fc752998593dde7be8083b3608e0acec3b5091221fdea2d43b16c13ed368d5c406a120eb3812bcfe060d0aec5919e711ea780088c5b379050
languageName: node
linkType: hard
"magic-string@npm:^0.30.1": "magic-string@npm:^0.30.1":
version: 0.30.3 version: 0.30.3
resolution: "magic-string@npm:0.30.3" resolution: "magic-string@npm:0.30.3"
@@ -2855,6 +2865,13 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"peek-readable@npm:^5.0.0":
version: 5.0.0
resolution: "peek-readable@npm:5.0.0"
checksum: bef5ceb50586eb42e14efba274ac57ffe97f0ed272df9239ce029f688f495d9bf74b2886fa27847c706a9db33acda4b7d23bbd09a2d21eb4c2a54da915117414
languageName: node
linkType: hard
"picocolors@npm:^1.0.0": "picocolors@npm:^1.0.0":
version: 1.0.0 version: 1.0.0
resolution: "picocolors@npm:1.0.0" resolution: "picocolors@npm:1.0.0"
@@ -2985,6 +3002,15 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"readable-web-to-node-stream@npm:^3.0.2":
version: 3.0.2
resolution: "readable-web-to-node-stream@npm:3.0.2"
dependencies:
readable-stream: ^3.6.0
checksum: 8c56cc62c68513425ddfa721954875b382768f83fa20e6b31e365ee00cbe7a3d6296f66f7f1107b16cd3416d33aa9f1680475376400d62a081a88f81f0ea7f9c
languageName: node
linkType: hard
"readdirp@npm:~3.6.0": "readdirp@npm:~3.6.0":
version: 3.6.0 version: 3.6.0
resolution: "readdirp@npm:3.6.0" resolution: "readdirp@npm:3.6.0"
@@ -3208,6 +3234,13 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"streamsearch@npm:^1.1.0":
version: 1.1.0
resolution: "streamsearch@npm:1.1.0"
checksum: 1cce16cea8405d7a233d32ca5e00a00169cc0e19fbc02aa839959985f267335d435c07f96e5e0edd0eadc6d39c98d5435fb5bbbdefc62c41834eadc5622ad942
languageName: node
linkType: hard
"string-width-cjs@npm:string-width@^4.2.0, string-width@npm:^1.0.2 || 2 || 3 || 4, string-width@npm:^4.1.0, string-width@npm:^4.2.3": "string-width-cjs@npm:string-width@^4.2.0, string-width@npm:^1.0.2 || 2 || 3 || 4, string-width@npm:^4.1.0, string-width@npm:^4.2.3":
version: 4.2.3 version: 4.2.3
resolution: "string-width@npm:4.2.3" resolution: "string-width@npm:4.2.3"
@@ -3280,6 +3313,16 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"strtok3@npm:^7.0.0":
version: 7.0.0
resolution: "strtok3@npm:7.0.0"
dependencies:
"@tokenizer/token": ^0.3.0
peek-readable: ^5.0.0
checksum: 2ebe7ad8f2aea611dec6742cf6a42e82764892a362907f7ce493faf334501bf981ce21c828dcc300457e6d460dc9c34d644ededb3b01dcb9e37559203cf1748c
languageName: node
linkType: hard
"sucrase@npm:^3.20.3": "sucrase@npm:^3.20.3":
version: 3.34.0 version: 3.34.0
resolution: "sucrase@npm:3.34.0" resolution: "sucrase@npm:3.34.0"
@@ -3376,6 +3419,16 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"token-types@npm:^5.0.1":
version: 5.0.1
resolution: "token-types@npm:5.0.1"
dependencies:
"@tokenizer/token": ^0.3.0
ieee754: ^1.2.1
checksum: 32780123bc6ce8b6a2231d860445c994a02a720abf38df5583ea957aa6626873cd1c4dd8af62314da4cf16ede00c379a765707a3b06f04b8808c38efdae1c785
languageName: node
linkType: hard
"tr46@npm:^1.0.1": "tr46@npm:^1.0.1":
version: 1.0.1 version: 1.0.1
resolution: "tr46@npm:1.0.1" resolution: "tr46@npm:1.0.1"
@@ -3415,13 +3468,6 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"tslib@npm:2.6.2, tslib@npm:^2.1.0, tslib@npm:^2.6.2":
version: 2.6.2
resolution: "tslib@npm:2.6.2"
checksum: 329ea56123005922f39642318e3d1f0f8265d1e7fcb92c633e0809521da75eeaca28d2cf96d7248229deb40e5c19adf408259f4b9640afd20d13aecc1430f3ad
languageName: node
linkType: hard
"tslib@npm:^1.8.1": "tslib@npm:^1.8.1":
version: 1.14.1 version: 1.14.1
resolution: "tslib@npm:1.14.1" resolution: "tslib@npm:1.14.1"
@@ -3429,6 +3475,13 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"tslib@npm:^2.1.0, tslib@npm:^2.5.0, tslib@npm:^2.6.1":
version: 2.6.2
resolution: "tslib@npm:2.6.2"
checksum: 329ea56123005922f39642318e3d1f0f8265d1e7fcb92c633e0809521da75eeaca28d2cf96d7248229deb40e5c19adf408259f4b9640afd20d13aecc1430f3ad
languageName: node
linkType: hard
"tsup@npm:^6.7.0": "tsup@npm:^6.7.0":
version: 6.7.0 version: 6.7.0
resolution: "tsup@npm:6.7.0" resolution: "tsup@npm:6.7.0"
@@ -3526,12 +3579,12 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"undici@npm:5.27.2": "undici@npm:^5.22.0":
version: 5.27.2 version: 5.23.0
resolution: "undici@npm:5.27.2" resolution: "undici@npm:5.23.0"
dependencies: dependencies:
"@fastify/busboy": ^2.0.0 busboy: ^1.6.0
checksum: 22bbdd763798700979986546d70072b67223189353d2a811efa9c6e44476161a0d1781ffe24115221f69a1b344b95d5926bd39a6eb760a2cd8804781cec0c5eb checksum: 906ca4fb1d47163d2cee2ecbbc664a1d92508a2cdf1558146621109f525c983a83597910b36e6ba468240e95259be5939cea6babc99fc0c36360b16630f66784
languageName: node languageName: node
linkType: hard linkType: hard
@@ -3771,9 +3824,9 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"ws@npm:8.14.2": "ws@npm:^8.13.0":
version: 8.14.2 version: 8.13.0
resolution: "ws@npm:8.14.2" resolution: "ws@npm:8.13.0"
peerDependencies: peerDependencies:
bufferutil: ^4.0.1 bufferutil: ^4.0.1
utf-8-validate: ">=5.0.2" utf-8-validate: ">=5.0.2"
@@ -3782,22 +3835,7 @@ __metadata:
optional: true optional: true
utf-8-validate: utf-8-validate:
optional: true optional: true
checksum: 3ca0dad26e8cc6515ff392b622a1467430814c463b3368b0258e33696b1d4bed7510bc7030f7b72838b9fdeb8dbd8839cbf808367d6aae2e1d668ce741d4308b checksum: 53e991bbf928faf5dc6efac9b8eb9ab6497c69feeb94f963d648b7a3530a720b19ec2e0ec037344257e05a4f35bd9ad04d9de6f289615ffb133282031b18c61c
languageName: node
linkType: hard
"ws@npm:^8.14.2":
version: 8.15.1
resolution: "ws@npm:8.15.1"
peerDependencies:
bufferutil: ^4.0.1
utf-8-validate: ">=5.0.2"
peerDependenciesMeta:
bufferutil:
optional: true
utf-8-validate:
optional: true
checksum: 8c67365f6e6134278ad635d558bfce466d7ef7543a043baea333aaa430429f0af8a130c0c36e7dd78f918d68167a659ba9b5067330b77c4b279e91533395952b
languageName: node languageName: node
linkType: hard linkType: hard