framework: upgrade cordis

This commit is contained in:
undefined committed 2026-04-17 18:03:41 +08:00
1 parent 772cb7837a
commit 6bdac9fe25
24 files changed
+108 -128

No files matched your search

+2 -2
View File
@@ -187,7 +187,7 @@ declare module 'cordis' {
}
}
export class ApiHandler<C extends Context> extends Handler<C> {
export class ApiHandler extends Handler {
@param('op', Types.String)
async all({ }, op: string) {
if (!['get', 'post'].includes(this.request.method.toLowerCase())) {
@@ -219,7 +219,7 @@ export class ApiHandler<C extends Context> extends Handler<C> {
}
}
export class ApiConnectionHandler<C extends Context> extends ConnectionHandler<C> {
export class ApiConnectionHandler extends ConnectionHandler {
dispose: () => Promise<void> | void;
isRpc: boolean;
+2 -3
View File
@@ -1,4 +1,3 @@
import { Context } from 'cordis';
import Schema from 'schemastery';
import { ValidationError } from './error';
import type { Handler } from './server';
@@ -57,7 +56,7 @@ function _buildParam(name: string, source: 'get' | 'post' | 'all' | 'route', ...
}
function _descriptor(v: ParamOption<any>) {
return function desc<T extends Context>(this: Handler<T>, target: any, funcName: string, obj: any) {
return function desc(this: Handler, target: any, funcName: string, obj: any) {
target.__param ||= {};
target.__param[target.constructor.name] ||= {};
if (!target.__param[target.constructor.name][funcName]) {
@@ -66,7 +65,7 @@ function _descriptor(v: ParamOption<any>) {
const firstArg = val.split(')')[0]?.split(',')[0]?.split('(')[1]?.trim() || '';
const domainIdStyle = firstArg.toLowerCase().startsWith('domainid');
target.__param[target.constructor.name][funcName] = [];
obj.value = function validate(this: Handler<T>, rawArgs: any, ...extra: any[]) {
obj.value = function validate(this: Handler, rawArgs: any, ...extra: any[]) {
if (typeof rawArgs !== 'object' || extra.length) return originalMethod.call(this, rawArgs, ...extra);
const c = [];
const arglist: ParamOption<any>[] = target.__param[target.constructor.name][funcName];
+13 -14
View File
@@ -1,4 +1,3 @@
import type { Context } from 'cordis';
import type { ApiHandler } from './api';
import type { ConnectionHandler, Handler, NotFoundHandler } from './server';
@@ -6,7 +5,7 @@ export interface KnownHandlers {
NotFound: NotFoundHandler;
}
type MapHandlerEvents<N extends string, H extends Handler<any>> =
type MapHandlerEvents<N extends string, H extends Handler> =
Record<`handler/${HookType}/${N}`, (thisArg: H) => VoidReturn>
& Record<`handler/${HookWithMethod}/${N}/${Methods}`, (thisArg: H) => VoidReturn>;
@@ -14,8 +13,8 @@ type KnownHandlerEvents = {
[key in keyof KnownHandlers]: MapHandlerEvents<key, KnownHandlers[key]>
}[keyof KnownHandlers];
type HandlerEvents<C> =
Record<`handler/${HookType}`, (thisArg: Handler<C>) => VoidReturn>
type HandlerEvents =
Record<`handler/${HookType}`, (thisArg: Handler) => VoidReturn>
& Record<`connection/${'create' | 'active' | 'close'}`, (thisArg: any) => VoidReturn>;
export type VoidReturn = Promise<any> | any;
@@ -23,23 +22,23 @@ export type HookType = 'before-prepare' | 'before' | 'before-operation' | 'after
export type Methods = 'get' | 'post' | 'put' | 'delete' | 'patch';
export type HookWithMethod = Exclude<HookType, 'before-operation'>;
export interface ServerEvents<C extends Context> extends KnownHandlerEvents, HandlerEvents<C> {
'handler/create': (thisArg: Handler<C> | ConnectionHandler<C>, type: 'ws' | 'http') => VoidReturn;
'handler/create/http': (thisArg: Handler<C>) => VoidReturn;
'handler/create/ws': (thisArg: ConnectionHandler<C>) => VoidReturn;
'handler/init': (thisArg: Handler<C>) => VoidReturn;
'handler/error': (thisArg: Handler<C> | ConnectionHandler<C>, e: Error) => VoidReturn;
'handler/api/before': (thisArg: ApiHandler<C>) => VoidReturn;
export interface ServerEvents extends KnownHandlerEvents, HandlerEvents {
'handler/create': (thisArg: Handler | ConnectionHandler, type: 'ws' | 'http') => VoidReturn;
'handler/create/http': (thisArg: Handler) => VoidReturn;
'handler/create/ws': (thisArg: ConnectionHandler) => VoidReturn;
'handler/init': (thisArg: Handler) => VoidReturn;
'handler/error': (thisArg: Handler | ConnectionHandler, e: Error) => VoidReturn;
'handler/api/before': (thisArg: ApiHandler) => VoidReturn;
'api/before': (args: any) => VoidReturn;
[k: `handler/${HookType}/${string}`]: (thisArg: any) => VoidReturn;
[k: `handler/${HookWithMethod}/${string}/${Methods}`]: (thisArg: any) => VoidReturn;
[k: `handler/register/${string}`]: (HandlerClass: new (...args: any[]) => any) => VoidReturn;
[k: `handler/error/${string}`]: (thisArg: Handler<C>, e: Error) => VoidReturn;
[k: `handler/api/before/${string}`]: (thisArg: ApiHandler<C>) => VoidReturn;
[k: `handler/error/${string}`]: (thisArg: Handler, e: Error) => VoidReturn;
[k: `handler/api/before/${string}`]: (thisArg: ApiHandler) => VoidReturn;
[k: `api/before/${string}`]: (args: any) => VoidReturn;
}
declare module 'cordis' {
interface Events<C> extends ServerEvents<C> {
interface Events extends ServerEvents {
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
import type { HandlerCommon } from './server';
export default function serializer<T>(ignoreSerializeFunction = false, h?: HandlerCommon<T>) {
export default function serializer(ignoreSerializeFunction = false, h?: HandlerCommon) {
return (k: string, v: any) => {
if (k.startsWith('_') && k !== '_id') return undefined;
if (typeof v === 'bigint') return `BigInt::${v.toString()}`;
+26 -25
View File
@@ -3,6 +3,7 @@ import http from 'http';
import { tmpdir } from 'os';
import { join } from 'path';
import { PassThrough } from 'stream';
import type { } from '@cordisjs/plugin-timer';
import { Context as CordisContext, Service } from 'cordis';
import type { Files } from 'formidable';
import fs from 'fs-extra';
@@ -43,7 +44,7 @@ export function encodeRFC5987ValueChars(str: string) {
);
}
async function forkContextWithScope<C extends CordisContext>(ctx: C) {
async function forkContextWithScope(ctx: CordisContext) {
const scope = ctx.plugin(() => { });
await scope;
const dispose = () => scope.dispose();
@@ -141,8 +142,8 @@ export interface UserModel {
_id: number;
}
export interface HandlerCommon<C> { } // eslint-disable-line ts/no-unused-vars
export class HandlerCommon<C> {
export interface HandlerCommon { }
export class HandlerCommon {
static [kHandler]: string | boolean = 'HandlerCommon';
session: Record<string, any>;
args: Record<string, any>;
@@ -151,7 +152,7 @@ export class HandlerCommon<C> {
UiContext: Record<string, any>;
user: UserModel;
constructor(public context: KoaContext, public ctx: C) {
constructor(public context: KoaContext, public ctx: CordisContext) {
this.renderHTML = this.renderHTML.bind(this);
this.url = this.url.bind(this);
this.session = context.session;
@@ -212,7 +213,7 @@ export class HandlerCommon<C> {
}
}
export class Handler<C = CordisContext> extends HandlerCommon<C> {
export class Handler extends HandlerCommon {
static [kHandler] = 'Handler';
loginMethods: any;
@@ -260,7 +261,7 @@ export class Handler<C = CordisContext> extends HandlerCommon<C> {
}
}
export class ConnectionHandler<C> extends HandlerCommon<C> {
export class ConnectionHandler extends HandlerCommon {
static [kHandler] = 'ConnectionHandler';
conn: WebSocket;
@@ -300,7 +301,7 @@ export class ConnectionHandler<C> extends HandlerCommon<C> {
}
}
export class NotFoundHandler extends Handler<CordisContext> {
export class NotFoundHandler extends Handler {
prepare() { throw new NotFoundError(this.request.path); }
all() { }
}
@@ -328,7 +329,7 @@ function executeMiddlewareStack(context: any, middlewares: { name: string, func:
return dispatch(0);
}
export class WebService<C extends CordisContext = CordisContext> extends Service<never, C> {
export class WebService extends Service<never> {
static Config = Schema.object({
keys: Schema.array(Schema.string()),
proxy: Schema.boolean(),
@@ -347,8 +348,8 @@ export class WebService<C extends CordisContext = CordisContext> extends Service
private handlerLayers = [];
private wsLayers = [];
private captureAllRoutes = Object.create(null);
private customDefaultContext: C;
private activeHandlers: Map<Handler<C>, { start: number, name: string }> = new Map();
private customDefaultContext: CordisContext;
private activeHandlers: Map<Handler, { start: number, name: string }> = new Map();
renderers: Record<string, Renderer> = Object.create(null);
server = koa;
@@ -357,7 +358,7 @@ export class WebService<C extends CordisContext = CordisContext> extends Service
Handler = Handler;
ConnectionHandler = ConnectionHandler;
constructor(ctx: C, public config: ReturnType<typeof WebService.Config>) {
constructor(ctx: CordisContext, public config: ReturnType<typeof WebService.Config>) {
super(ctx, 'server');
ctx.mixin('server', ['Route', 'Connection', 'withHandlerClass']);
this.server.keys = this.config.keys;
@@ -503,7 +504,7 @@ ${c.response.status} ${endTime - startTime}ms ${c.response.length}`);
});
}
private async handleHttp(ctx: KoaContext, HandlerClass, checker, savedContext: C) {
private async handleHttp(ctx: KoaContext, HandlerClass, checker, savedContext: CordisContext) {
const { args } = ctx.HydroContext;
Object.assign(args, ctx.params);
await using sub = await forkContextWithScope(savedContext);
@@ -589,7 +590,7 @@ ${c.response.status} ${endTime - startTime}ms ${c.response.length}`);
}
}
private async handleWS(ctx: KoaContext, HandlerClass, checker, conn?, layer?, savedContext?) {
private async handleWS(ctx: KoaContext, HandlerClass, checker, conn?, layer?, savedContext?: CordisContext) {
const { args } = ctx.HydroContext;
const sub = await forkContextWithScope(savedContext);
const h = new HandlerClass(ctx, sub.ctx);
@@ -731,7 +732,7 @@ ${c.response.status} ${endTime - startTime}ms ${c.response.length}`);
perm = item;
}
}
return function check(this: Handler<C>) {
return function check(this: Handler) {
checker();
if (perm) this.checkPerm(perm);
if (priv) this.checkPriv(priv);
@@ -767,7 +768,7 @@ ${c.response.status} ${endTime - startTime}ms ${c.response.length}`);
});
}
public setDefaultContext(ctx: C) {
public setDefaultContext(ctx: CordisContext) {
try {
if (!ctx.server) throw new Error();
} catch (e) {
@@ -783,7 +784,7 @@ ${c.response.status} ${endTime - startTime}ms ${c.response.length}`);
}
public withHandlerClass<T extends string>(
name: T, callback: (HandlerClass: T extends `${string}ConnectionHandler` ? typeof ConnectionHandler<C> : typeof Handler<C>) => any,
name: T, callback: (HandlerClass: T extends `${string}ConnectionHandler` ? typeof ConnectionHandler : typeof Handler) => any,
) {
name = name.replace(/Handler$/, '') as any;
if (this.registry[name]) callback(this.registry[name]);
@@ -792,7 +793,7 @@ ${c.response.status} ${endTime - startTime}ms ${c.response.length}`);
}
// eslint-disable-next-line ts/naming-convention
public Route(name: string, path: string, RouteHandler: typeof Handler<C>, ...permPrivChecker) {
public Route(name: string, path: string, RouteHandler: typeof Handler, ...permPrivChecker) {
// if (name === 'contest_scoreboard') {
// console.log('+++', this.ctx);
// console.log(this.ctx.scoreboard);
@@ -801,7 +802,7 @@ ${c.response.status} ${endTime - startTime}ms ${c.response.length}`);
}
// eslint-disable-next-line ts/naming-convention
public Connection(name: string, path: string, RouteHandler: typeof ConnectionHandler<C>, ...permPrivChecker) {
public Connection(name: string, path: string, RouteHandler: typeof ConnectionHandler, ...permPrivChecker) {
return this.register('conn', name, path, RouteHandler, ...permPrivChecker);
}
@@ -866,15 +867,15 @@ ${c.response.status} ${endTime - startTime}ms ${c.response.length}`);
});
}
public handlerMixin(MixinClass: Partial<HandlerCommon<C>> | ((s: HandlerCommon<C>) => Partial<HandlerCommon<C>>)) {
public handlerMixin(MixinClass: Partial<HandlerCommon> | ((s: HandlerCommon) => Partial<HandlerCommon>)) {
return this._applyMixin(HandlerCommon, MixinClass);
}
public httpHandlerMixin(MixinClass: Partial<Handler<C>> | ((s: Handler<C>) => Partial<Handler<C>>)) {
public httpHandlerMixin(MixinClass: Partial<Handler> | ((s: Handler) => Partial<Handler>)) {
return this._applyMixin(Handler, MixinClass);
}
public wsHandlerMixin(MixinClass: Partial<ConnectionHandler<C>> | ((s: ConnectionHandler<C>) => Partial<ConnectionHandler<C>>)) {
public wsHandlerMixin(MixinClass: Partial<ConnectionHandler> | ((s: ConnectionHandler) => Partial<ConnectionHandler>)) {
return this._applyMixin(ConnectionHandler, MixinClass);
}
@@ -891,9 +892,9 @@ ${c.response.status} ${endTime - startTime}ms ${c.response.length}`);
declare module 'cordis' {
interface Context {
server: WebService<this>;
Route: WebService<this>['Route'];
Connection: WebService<this>['Connection'];
withHandlerClass: WebService<this>['withHandlerClass'];
server: WebService;
Route: WebService['Route'];
Connection: WebService['Connection'];
withHandlerClass: WebService['withHandlerClass'];
}
}