Replace AJV with TypeBox validation
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
Migrate schema validation from AJV to @sinclair/typebox across the monorepo. Key changes: - Core validation: ConfigBase now uses TypeCompiler/Value (TypeBox) for compile/defaults/coercion and replaces Ajv usage. - OneBot & Protocol: loadConfig functions and related config loaders updated to use Value.Default/Convert and TypeCompiler.Compile with improved error reporting. - OneBot action validation: OneBotAction now compiles TypeBox schemas, applies defaults/conversions and returns TypeBox errors. - Web UI backend: use TypeBox Value/TypeCompiler to fetch and validate defaults for Napcat/Web UI configs. - Types/scripts: removed AJV type shims and adjusted post-build script to stop special-casing AJV types. - Dependencies: removed ajv from several package.json files and added/normalized @sinclair/typebox usage; updated pnpm-lock accordingly. - Tests/tools: added schema validation test utilities and tests (packages/napcat-onebot/test_schema.ts and packages/napcat-test/schema.test.ts) to validate schema compilation, coercion, and defaults. This change standardizes on TypeBox for runtime schema compilation, default population and type coercion, simplifying validation logic and improving default handling across packages.
This commit is contained in:
1 parent
4ed4dfd450
commit
36ae7bf923
21 files changed
+370
-245
No files matched your search
@@ -1,5 +1,6 @@
|
||||
import { ActionName, BaseCheckResult } from './router';
|
||||
import Ajv, { ErrorObject, ValidateFunction } from 'ajv';
|
||||
import { TypeCompiler, TypeCheck } from '@sinclair/typebox/compiler';
|
||||
import { Value } from '@sinclair/typebox/value';
|
||||
import { NapCatCore } from 'napcat-core';
|
||||
import { NapCatOneBot11Adapter, OB11Return } from '@/napcat-onebot/index';
|
||||
import { NetworkAdapterConfig } from '../config/config';
|
||||
@@ -46,7 +47,7 @@ export abstract class OneBotRequestToolkit {
|
||||
export abstract class OneBotAction<PayloadType, ReturnDataType> {
|
||||
actionName: typeof ActionName[keyof typeof ActionName] = ActionName.Unknown;
|
||||
core: NapCatCore;
|
||||
private validate?: ValidateFunction<unknown> = undefined;
|
||||
private validate?: TypeCheck<TSchema> = undefined;
|
||||
payloadSchema?: TSchema = undefined;
|
||||
returnSchema?: TSchema = undefined;
|
||||
payloadExample?: unknown = undefined;
|
||||
@@ -64,15 +65,24 @@ export abstract class OneBotAction<PayloadType, ReturnDataType> {
|
||||
}
|
||||
|
||||
protected async check (payload: PayloadType): Promise<BaseCheckResult> {
|
||||
if (this.payloadSchema) {
|
||||
this.validate = new Ajv({ allowUnionTypes: true, useDefaults: true, coerceTypes: true }).compile(this.payloadSchema);
|
||||
if (!this.payloadSchema) return { valid: true };
|
||||
try {
|
||||
this.validate = TypeCompiler.Compile(this.payloadSchema);
|
||||
let data = payload;
|
||||
data = Value.Default(this.payloadSchema, data) as PayloadType;
|
||||
data = Value.Convert(this.payloadSchema, data) as PayloadType;
|
||||
if (typeof payload === 'object' && payload !== null && data !== null) {
|
||||
Object.assign(payload, data);
|
||||
}
|
||||
} catch (e: any) {
|
||||
return { valid: false, message: `Schema compilation error: ${e.message}` };
|
||||
}
|
||||
if (this.validate && !this.validate(payload)) {
|
||||
const errors = this.validate.errors as ErrorObject[];
|
||||
const errorMessages = errors.map(e => `Key: ${e.instancePath.split('/').slice(1).join('.')}, Message: ${e.message}`);
|
||||
if (this.validate && !this.validate.Check(payload)) {
|
||||
const errors = [...this.validate.Errors(payload)];
|
||||
const errorMessages = errors.map(e => `Key: ${e.path.split('/').slice(1).join('.')}, Message: ${e.message}`);
|
||||
return {
|
||||
valid: false,
|
||||
message: errorMessages.join('\n') ?? '未知错误',
|
||||
message: errorMessages.length > 0 ? errorMessages.join('\n') : '未知错误',
|
||||
};
|
||||
}
|
||||
return { valid: true };
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Type, Static } from '@sinclair/typebox';
|
||||
import Ajv from 'ajv';
|
||||
import { TypeCompiler } from '@sinclair/typebox/compiler';
|
||||
import { Value } from '@sinclair/typebox/value';
|
||||
const HttpServerConfigSchema = Type.Object({
|
||||
name: Type.String({ default: 'http-server' }),
|
||||
enable: Type.Boolean({ default: false }),
|
||||
@@ -97,11 +98,14 @@ export type NetworkAdapterConfig = HttpServerConfig | HttpSseServerConfig | Http
|
||||
export type NetworkConfigKey = keyof OneBotConfig['network'];
|
||||
|
||||
export function loadConfig (config: Partial<OneBotConfig>): OneBotConfig {
|
||||
const ajv = new Ajv({ useDefaults: true, coerceTypes: true });
|
||||
const validate = ajv.compile(OneBotConfigSchema);
|
||||
const valid = validate(config);
|
||||
let data = config;
|
||||
data = Value.Default(OneBotConfigSchema, data) as Partial<OneBotConfig>;
|
||||
data = Value.Convert(OneBotConfigSchema, data) as Partial<OneBotConfig>;
|
||||
const validate = TypeCompiler.Compile(OneBotConfigSchema);
|
||||
const valid = validate.Check(data);
|
||||
if (!valid) {
|
||||
throw new Error(ajv.errorsText(validate.errors));
|
||||
const errorMsg = [...validate.Errors(data)].map(e => e.message).join(', ');
|
||||
throw new Error(errorMsg);
|
||||
}
|
||||
return config as OneBotConfig;
|
||||
return data as OneBotConfig;
|
||||
}
|
||||
@@ -1,12 +1,12 @@
|
||||
import { ConfigBase } from 'napcat-core/helper/config-base';
|
||||
import type { NapCatCore } from 'napcat-core';
|
||||
import { OneBotConfig } from './config';
|
||||
import { AnySchema } from 'ajv';
|
||||
import { TSchema } from '@sinclair/typebox';
|
||||
|
||||
export * from './config';
|
||||
|
||||
export class OB11ConfigLoader extends ConfigBase<OneBotConfig> {
|
||||
constructor (core: NapCatCore, configPath: string, schema: AnySchema) {
|
||||
constructor (core: NapCatCore, configPath: string, schema: TSchema) {
|
||||
super('onebot11', core, configPath, schema);
|
||||
}
|
||||
}
|
||||
@@ -16,29 +16,28 @@
|
||||
}
|
||||
},
|
||||
"dependencies": {
|
||||
"napcat.protobuf": "^1.1.4",
|
||||
"fast-xml-parser": "^4.3.6",
|
||||
"type-is": "^1.6.7",
|
||||
"on-finished": "^2.3.5",
|
||||
"ajv": "^8.13.0",
|
||||
"@sinclair/typebox": "^0.34.38",
|
||||
"cors": "^2.8.5",
|
||||
"express": "^5.0.0",
|
||||
"ws": "^8.18.3",
|
||||
"fast-xml-parser": "^4.3.6",
|
||||
"file-type": "^21.0.0",
|
||||
"napcat-protobuf": "workspace:*",
|
||||
"json5": "^2.2.3",
|
||||
"napcat-common": "workspace:*",
|
||||
"napcat-core": "workspace:*",
|
||||
"napcat-webui-backend": "workspace:*",
|
||||
"napcat-image-size": "workspace:*",
|
||||
"napcat-common": "workspace:*"
|
||||
"napcat-protobuf": "workspace:*",
|
||||
"napcat-webui-backend": "workspace:*",
|
||||
"napcat.protobuf": "^1.1.4",
|
||||
"on-finished": "^2.3.5",
|
||||
"type-is": "^1.6.7",
|
||||
"ws": "^8.18.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/cors": "^2.8.17",
|
||||
"@types/type-is": "^1.6.7",
|
||||
"@types/on-finished": "^2.3.4",
|
||||
"@types/express": "^5.0.0",
|
||||
"@types/node": "^22.0.1"
|
||||
"@types/node": "^22.0.1",
|
||||
"@types/on-finished": "^2.3.4",
|
||||
"@types/type-is": "^1.6.7"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18.0.0"
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import { TypeCompiler } from '@sinclair/typebox/compiler';
|
||||
import { Value } from '@sinclair/typebox/value';
|
||||
import { OB11MessageDataSchema, OB11MessageSchema, OB11PostSendMsgSchema } from './types/message';
|
||||
import { OB11MessageSchema as OB11ActionMessageSchema } from './action/schemas';
|
||||
|
||||
try {
|
||||
TypeCompiler.Compile(OB11MessageDataSchema);
|
||||
console.log("Compile OB11MessageDataSchema OK");
|
||||
} catch (e: any) {
|
||||
console.error("Error in OB11MessageDataSchema:", e.message);
|
||||
}
|
||||
|
||||
try {
|
||||
TypeCompiler.Compile(OB11MessageSchema);
|
||||
console.log("Compile OB11MessageSchema OK");
|
||||
} catch (e: any) {
|
||||
console.error("Error in OB11MessageSchema:", e.message);
|
||||
}
|
||||
|
||||
try {
|
||||
TypeCompiler.Compile(OB11ActionMessageSchema);
|
||||
console.log("Compile OB11ActionMessageSchema OK");
|
||||
} catch (e: any) {
|
||||
console.error("Error in OB11ActionMessageSchema:", e.message);
|
||||
}
|
||||
|
||||
import { Type } from '@sinclair/typebox';
|
||||
try {
|
||||
const QA = Type.Object({ message: OB11PostSendMsgSchema, quick_action: OB11ActionMessageSchema });
|
||||
TypeCompiler.Compile(QA);
|
||||
console.log("Compile Quick Action OK");
|
||||
} catch (e: any) {
|
||||
console.error("Error in Quick Action:", e.message);
|
||||
}
|
||||
|
||||
// Test validation
|
||||
const testObj = {
|
||||
message_type: 'private',
|
||||
user_id: 12345,
|
||||
message: [
|
||||
{ type: 'text', data: { text: 'hello' } }
|
||||
]
|
||||
};
|
||||
|
||||
try {
|
||||
let data = structuredClone(testObj);
|
||||
data = Value.Default(OB11PostSendMsgSchema, data) as any;
|
||||
data = Value.Convert(OB11PostSendMsgSchema, data) as any;
|
||||
|
||||
const compiler = TypeCompiler.Compile(OB11PostSendMsgSchema);
|
||||
const isValid = compiler.Check(data);
|
||||
console.log("Validation result:", isValid);
|
||||
if (!isValid) {
|
||||
const errors = [...compiler.Errors(data)];
|
||||
errors.forEach(e => console.error(e.path, e.message));
|
||||
} else {
|
||||
console.log("Data after Convert and Check:", JSON.stringify(data, null, 2));
|
||||
}
|
||||
} catch (e: any) {
|
||||
console.error("Test validation error:", e.message);
|
||||
}
|
||||
Reference in new issue
Block a user