Commit 0aa183e2 authored by nanahira's avatar nanahira

finish

parent 33ad7ee2
# compiled output
/dist
/node_modules
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# OS
.DS_Store
# Tests
/coverage
/.nyc_output
# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
/data
/output
/config.yaml
.git*
Dockerfile
.dockerignore
/tests
webpack.config.js
dist/*
build/*
*.js
module.exports = {
parser: '@typescript-eslint/parser',
parserOptions: {
project: 'tsconfig.json',
sourceType: 'module',
},
plugins: ['@typescript-eslint/eslint-plugin'],
extends: [
'plugin:@typescript-eslint/recommended',
'plugin:prettier/recommended',
],
root: true,
env: {
node: true,
jest: true,
},
ignorePatterns: ['.eslintrc.js'],
rules: {
'@typescript-eslint/interface-name-prefix': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/no-explicit-any': 'off',
},
};
# compiled output
/dist
/node_modules
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# OS
.DS_Store
# Tests
/coverage
/.nyc_output
# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
/data
/output
/config.yaml
stages:
- install
- build
- deploy
variables:
GIT_DEPTH: "1"
npm_ci:
stage: install
tags:
- linux
script:
- npm ci
artifacts:
paths:
- node_modules
.build_base:
stage: build
tags:
- linux
dependencies:
- npm_ci
build:
extends:
- .build_base
script:
- npm run build
artifacts:
paths:
- dist/
unit-test:
extends:
- .build_base
script:
- npm run test
deploy_npm:
stage: deploy
dependencies:
- build
tags:
- linux
script:
- apt update;apt -y install coreutils
- echo $NPMRC | base64 --decode > ~/.npmrc
- npm publish . || true
only:
- master
/install-npm.sh
.git*
/data
/output
/config.yaml
.idea
.dockerignore
Dockerfile
/src
/coverage
/tests
/dist/tests
{
"singleQuote": true,
"trailingComma": "all"
}
\ No newline at end of file
FROM node:bullseye-slim as base
LABEL Author="Nanahira <nanahira@momobako.com>"
RUN apt update && apt -y install python3 build-essential && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
WORKDIR /usr/src/app
COPY ./package*.json ./
FROM base as builder
RUN npm ci && npm cache clean --force
COPY . ./
RUN npm run build
FROM base
ENV NODE_ENV production
RUN npm ci && npm cache clean --force
COPY --from=builder /usr/src/app/dist ./dist
CMD [ "npm", "start" ]
The MIT License (MIT)
Copyright (c) 2021 Nanahira
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
import 'reflect-metadata';
export * from './src/register';
export * from './src/decorators';
export * from './src/def/interfaces';
export * from './src/utility';
This diff is collapsed.
{
"name": "koishi-decorators",
"description": "Decorator defs for thirdeye and nestjs.",
"version": "1.0.0",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"scripts": {
"lint": "eslint --fix .",
"build": "rimraf dist && tsc",
"test": "jest --passWithNoTests",
"start": "node dist/index.js"
},
"repository": {
"type": "git",
"url": "https://code.mycard.moe/3rdeye/koishi-decorators.git"
},
"author": "Nanahira <nanahira@momobako.com>",
"license": "MIT",
"keywords": [],
"bugs": {
"url": "https://code.mycard.moe/3rdeye/koishi-decorators/issues"
},
"homepage": "https://code.mycard.moe/3rdeye/koishi-decorators",
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "tests",
"testRegex": ".*\\.spec\\.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
},
"devDependencies": {
"@koishijs/plugin-mock": "^1.0.0",
"@types/jest": "^27.4.0",
"@types/lodash": "^4.14.178",
"@types/node": "^17.0.10",
"@typescript-eslint/eslint-plugin": "^4.33.0",
"@typescript-eslint/parser": "^4.33.0",
"eslint": "^7.32.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-prettier": "^3.4.1",
"jest": "^27.4.7",
"koishi": "^4.1.0",
"prettier": "^2.5.1",
"rimraf": "^3.0.2",
"ts-jest": "^27.1.3",
"typescript": "^4.5.5"
},
"peerDependencies": {
"koishi": "^4.1.0"
},
"dependencies": {
"@types/koa": "^2.13.4",
"@types/koa__router": "^8.0.11",
"lodash": "^4.17.21",
"reflect-metadata": "^0.1.13",
"typed-reflector": "^1.0.9"
}
}
......@@ -15,12 +15,13 @@ import { CommandPut, DoRegister } from './registry';
// Register method
export const UseMiddleware = DoRegister.middleware;
export const UseEvent = (name: EventName, prepend?: boolean): MethodDecorator =>
export const UseMiddleware = (prepend = false): MethodDecorator =>
DoRegister.middleware(prepend);
export const UseEvent = (name: EventName, prepend = false): MethodDecorator =>
DoRegister.event({ name, prepend });
export const UseBeforeEvent = (
name: BeforeEventName,
prepend?: boolean,
prepend = false,
): MethodDecorator => DoRegister.beforeEvent({ name, prepend });
export const UsePlugin = (): MethodDecorator => DoRegister.plugin();
......
......@@ -8,12 +8,12 @@ import { Context } from 'koishi';
import { getContextFromFilters } from './utility';
import { DoRegister } from './registry';
export interface DoRegisterResult extends DoRegister.Config {
key: string;
export interface DoRegisterResult<T> extends DoRegister.Config {
key: keyof T & string;
result: any;
}
export class DeclarationRegistrar<T = any> {
export class Registrar<T = any> {
constructor(private obj: T, private alternativeObject?: any) {}
getAllFieldsToRegister(): (keyof T)[] {
......@@ -21,43 +21,50 @@ export class DeclarationRegistrar<T = any> {
return arr as (keyof T)[];
}
getScopeContext(ctx: Context, key?: keyof T & string) {
getScopeContext(ctx: Context, key?: keyof T, autoScope = true) {
if (key && autoScope) {
ctx = this.getScopeContext(ctx);
}
let contextFilters = reflector.getArray(
KoishiOnContextScope,
this.obj,
key,
key as string,
);
if (this.alternativeObject) {
contextFilters = contextFilters.concat(
reflector.getArray(KoishiOnContextScope, this.alternativeObject, key),
reflector.getArray(
KoishiOnContextScope,
this.alternativeObject,
key as string,
),
);
}
return getContextFromFilters(ctx, contextFilters);
}
register(ctx: Context, key: keyof T & string): DoRegisterResult {
const data = reflector.get(KoishiDoRegister, this, key);
register(ctx: Context, key: keyof T, autoScope = true): DoRegisterResult<T> {
if (autoScope) {
ctx = this.getScopeContext(ctx, key, true);
}
const _key = key as string;
const data = reflector.get(KoishiDoRegister, this.obj, _key);
if (!data) return;
const result = DoRegister.registry.execute(
data,
ctx,
this.obj,
key,
_key,
this.alternativeObject,
);
return { ...data, key, result };
return { ...data, key: key as keyof T & string, result };
}
registerAll(ctx: Context, autoScope = false) {
if (autoScope) {
ctx = this.getScopeContext(ctx);
}
return this.getAllFieldsToRegister().map((_key) => {
const key = _key as keyof T & string;
return this.register(
this.getScopeContext(ctx, key),
key as keyof T & string,
return this.getAllFieldsToRegister().map((key) =>
this.register(ctx, key, true),
);
});
}
}
......@@ -143,6 +143,7 @@ export namespace DoRegister {
});
}
}
return command;
},
);
}
import {
CommandUsage,
PutOption,
UseCommand,
UseEvent,
UseMiddleware,
} from '../src/decorators';
import { App, Command, Next, Session } from 'koishi';
import { Registrar } from '../src/register';
import { EventNameAndPrepend } from '../src/def';
class MyClass {
@UseMiddleware()
async onPing(session: Session, next: Next) {
if (session.content === 'ping') {
return 'pong';
}
return next;
}
@UseEvent('message')
async onMessage(session: Session) {
if (session.content === 'pang') {
return session.send('peng');
}
}
@UseCommand('echo', 'hi')
@CommandUsage('foo')
async onEcho(@PutOption('content', '-c <content:string>') content: string) {
return `bot: ${content}`;
}
}
const registrar = new Registrar(new MyClass());
describe('Register', () => {
let app: App;
beforeEach(async () => {
app = new App();
await app.start();
});
it('should register middleware', () => {
const result = registrar.register(app, 'onPing');
expect(result.type).toBe('middleware');
expect(result.data).toEqual(false);
});
it('should register event', () => {
const result = registrar.register(app, 'onMessage');
expect(result.type).toBe('onEvent');
expect((result.data as EventNameAndPrepend).name).toBe('message');
});
it('should register command', () => {
const result = registrar.register(app, 'onEcho');
expect(result.type).toBe('command');
const command: Command = result.result;
expect(command._usage).toBe('foo');
expect(command._options.content.name).toBe('content');
expect(command.execute({ options: { content: 'hello' } })).resolves.toBe(
'bot: hello',
);
});
});
import { OnGuild, OnPlatform } from '../src/decorators';
import { App, Session } from 'koishi';
import { Registrar } from '../src/register';
@OnPlatform('discord')
class MyClass {
@OnGuild('1111111111')
foo() {}
}
describe('Scope', () => {
let app: App;
beforeEach(async () => {
app = new App();
await app.start();
});
it('should check scope', () => {
const correctSession = {
guildId: '1111111111',
platform: 'discord',
} as Session;
const wrongSession1 = {
guildId: '2222222222',
platform: 'discord',
} as Session;
const wrongSession2 = {
guildId: '1111111111',
platform: 'telegram',
} as Session;
const registrar = new Registrar(new MyClass());
const globalCtx = registrar.getScopeContext(app);
const methodCtx = registrar.getScopeContext(app, 'foo', true);
expect(globalCtx.filter(correctSession)).toBe(true);
expect(globalCtx.filter(wrongSession1)).toBe(true);
expect(globalCtx.filter(wrongSession2)).toBe(false);
expect(methodCtx.filter(correctSession)).toBe(true);
expect(methodCtx.filter(wrongSession1)).toBe(false);
expect(methodCtx.filter(wrongSession2)).toBe(false);
});
});
{
"compilerOptions": {
"outDir": "dist",
"module": "commonjs",
"target": "es2021",
"esModuleInterop": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"declaration": true,
"sourceMap": true,
"skipLibCheck": true
},
"compileOnSave": true,
"allowJs": true,
"include": [
"*.ts",
"src/**/*.ts",
"test/**/*.ts",
"tests/**/*.ts"
]
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment