Compare commits

..
15 Commits
Author SHA1 Message Date
手瓜一十雪 adabc4da46 Improve schema parsing and error handling in API debug tools
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
Enhances the TypeBox schema parser to better handle deep nesting, circular references, and union truncation, and adds error handling for schema parsing and default value generation in the OneBot API debug UI. Updates the display component to show clear messages for circular or truncated schemas, and improves robustness in HTTP debug command execution. Also synchronizes the ParsedSchema type in the Zod utility for consistency.
2026-01-28 16:07:23 +08:00
手瓜一十雪 bf073b544b Refactor schema ID handling and reduce parse depth
Changed MAX_PARSE_DEPTH from 10 to 6 to limit nesting. Improved schema ID retrieval to only use $id if present, and added a utility to collect all $id values in a schema for better circular reference detection. Updated font file AaCute.woff.
2026-01-28 16:01:43 +08:00
手瓜一十雪 a71219062a Enhance TypeBox schema parsing with circular ref detection
Added detection and handling for circular references and excessive nesting in TypeBox schema parsing and default value generation. Introduced depth limits and a visited set to prevent infinite recursion, and updated the parseTypeBox and generateDefaultFromTypeBox functions accordingly.
2026-01-28 15:59:27 +08:00
手瓜一十雪 001fe01ace Add plugin logger interface and update builtin plugin
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
Introduces a PluginLogger interface and injects a plugin-specific logger into the plugin context for consistent logging. Refactors the builtin plugin to use the new logger instead of direct console calls. Updates napcat-types to version 0.0.9 in dependencies and lock files.
2026-01-28 15:07:06 +08:00
手瓜一十雪 0aa0c44634 Refactor plugin identification to use package name and dirname
Updated plugin manager and API to distinguish between plugin package name and directory name (dirname) for more robust plugin identification and path resolution. Adjusted context creation, status management, and API handlers to use package name for identification and dirname for filesystem operations. Also replaced console.error with console.log in builtin plugin for consistency.
2026-01-28 15:02:47 +08:00
手瓜一十雪 93126e514e Refactor builtin plugin for improved type safety
Replaced generic 'any' types with 'NetworkAdapterConfig' for better type safety in getVersionInfo and sendMessage functions. Removed redundant comments and improved code clarity. Changed a warning log to a standard log for config load failures.
2026-01-28 14:54:43 +08:00
手瓜一十雪 1ae10ae0c6 Refactor plugin to use context actions and update deps
Refactored the builtin plugin to pass actions and adapterName explicitly from context instead of relying on a global variable. Updated napcat-types dependency to version 0.0.8.
2026-01-28 14:42:44 +08:00
手瓜一十雪 4b693bf6e2 Refactor plugin manager to support only directory plugins
Removed support for single-file plugins in OB11PluginMangerAdapter, simplifying plugin identification to use directory names as unique IDs. Updated related logic in the backend API to align with this change, ensuring consistent plugin management and status handling.
2026-01-28 14:38:11 +08:00
手瓜一十雪 574c257591 Refactor plugin manager to support only directory plugins
Removed support for single-file plugins in OB11PluginMangerAdapter, simplifying plugin identification to use directory names as unique IDs. Updated related logic in the backend API to align with this change, ensuring consistent plugin management and status handling.
2026-01-28 14:18:44 +08:00
手瓜一十雪 d680328762 Add config UI and persistence to builtin plugin
Introduces a configuration UI schema and persistent config storage for the napcat-plugin-builtin. The plugin now loads and saves its configuration, supports dynamic prefix and reply toggling, and updates dependencies to napcat-types v0.0.6.
2026-01-28 14:13:48 +08:00
手瓜一十雪 d711cdecaf Add plugin config management to backend and frontend
Introduces a unified plugin configuration schema and API in the backend, with endpoints for getting and setting plugin config. Updates the frontend to support plugin config modals, including a UI for editing plugin settings. Also adds support for uninstalling plugins with optional data cleanup, and updates dependencies to use napcat-types@0.0.5.
2026-01-28 13:56:40 +08:00
手瓜一十雪 c5f1792009 Add plugin data management API and frontend support
Introduced backend API endpoints for managing plugin configuration data, including listing, reading, saving, and deleting plugin data files. Added a new PluginData API module and registered related routes. Updated the frontend plugin manager controller to support these new API methods and corresponding TypeScript interfaces. Also fixed minor typos in documentation prompts.
2026-01-28 13:39:36 +08:00
手瓜一十雪 a5e705e6a4 Fix typo in Windows deployment instructions
Corrected a grammatical error in the Windows one-click deployment section in both the default prompt and release note prompt files.
2026-01-27 23:01:16 +08:00
手瓜一十雪 007f1db339 Update OpenAPI schema copy path in release workflow
The workflow now copies openapi.json from the dist directory instead of the package root, ensuring the built schema is used during the release process.
2026-01-27 23:00:14 +08:00
手瓜一十雪 008fb39f8f Reduce WebSocket maxPayload to 50 MB
Lowered the maxPayload limit from 1 GB to 50 MB in both the WebSocket client and server adapters to improve resource management and prevent excessively large payloads.
2026-01-27 22:56:27 +08:00
32 changed files with 911 additions and 502 deletions

No files matched your search

+1 -1
View File
@@ -2,7 +2,7 @@
[使用文档](https://napneko.github.io/)
## Windows 一键包
我们为提供了的轻量化一键部署方案
我们提供了轻量化的一键部署方案
相对于普通需要安装QQ的方案,下面已内置QQ和Napcat 阅读使用文档参考
你可以下载
+1 -1
View File
@@ -31,7 +31,7 @@
[使用文档](https://napneko.github.io/)
## Windows 一键包
我们为提供了的轻量化一键部署方案
我们提供了轻量化的一键部署方案
相对于普通需要安装QQ的方案,下面已内置QQ和Napcat 阅读使用文档参考
你可以下载
+1 -1
View File
@@ -50,7 +50,7 @@ jobs:
- name: Copy OpenAPI Schema
run: |
mkdir -p napcat-docs/src/api/${{ env.version }}
cp packages/napcat-schema/openapi.json napcat-docs/src/api/${{ env.version }}/openapi.json
cp packages/napcat-schema/dist/openapi.json napcat-docs/src/api/${{ env.version }}/openapi.json
echo "OpenAPI schema copied to napcat-docs/src/api/${{ env.version }}/openapi.json"
- name: Commit and Push
-24
View File
@@ -1,24 +0,0 @@
{
"name": "napcat-types",
"version": "0.0.1",
"type": "module",
"types": "./napcat-types/index.d.ts",
"files": [
"**/*"
],
"dependencies": {
"@types/node": "^22.10.7",
"@types/express": "^4.17.21",
"@types/ws": "^8.5.12",
"@types/cors": "^2.8.17",
"@types/multer": "^1.4.12",
"@types/winston": "^2.4.4",
"@types/yaml": "^1.9.7",
"@types/ip": "^1.1.3"
},
"publishConfig": {
"registry": "https://registry.npmjs.org/",
"access": "public",
"tag": "latest"
}
}
@@ -22,7 +22,7 @@ export class CreateFlashTask extends OneBotAction<CreateFlashTaskPayload, any> {
override actionName = ActionName.CreateFlashTask;
override payloadSchema = CreateFlashTaskPayloadSchema;
override returnSchema = Type.Any({ description: '任务创建结果' });
override actionSummary = '创建闪照任务';
override actionSummary = '创建闪传任务';
override actionTags = ['文件扩展'];
override payloadExample = {
files: 'C:\\test.jpg',
@@ -12,7 +12,7 @@ export class GetFlashFileList extends OneBotAction<GetFlashFileListPayload, any>
override actionName = ActionName.GetFlashFileList;
override payloadSchema = GetFlashFileListPayloadSchema;
override returnSchema = Type.Any({ description: '文件列表' });
override actionSummary = '获取闪照文件列表';
override actionSummary = '获取闪传文件列表';
override actionTags = ['文件扩展'];
override payloadExample = {
fileset_id: 'set_123'
@@ -14,7 +14,7 @@ export class GetFlashFileUrl extends OneBotAction<GetFlashFileUrlPayload, any> {
override actionName = ActionName.GetFlashFileUrl;
override payloadSchema = GetFlashFileUrlPayloadSchema;
override returnSchema = Type.Any({ description: '文件下载链接' });
override actionSummary = '获取闪照文件链接';
override actionSummary = '获取闪传文件链接';
override actionTags = ['文件扩展'];
override payloadExample = {
fileset_id: 'set_123'
@@ -15,7 +15,7 @@ export class SendFlashMsg extends OneBotAction<SendFlashMsgPayload, any> {
override actionName = ActionName.SendFlashMsg;
override payloadSchema = SendFlashMsgPayloadSchema;
override returnSchema = Type.Any({ description: '发送结果' });
override actionSummary = '发送闪照消息';
override actionSummary = '发送闪传消息';
override actionTags = ['文件扩展'];
override payloadExample = {
fileset_id: 'set_123',
+170 -183
View File
@@ -15,44 +15,104 @@ export interface PluginPackageJson {
author?: string;
}
export interface PluginConfigItem {
key: string;
type: 'string' | 'number' | 'boolean' | 'select' | 'multi-select' | 'html' | 'text';
label: string;
description?: string;
default?: any;
options?: { label: string; value: string | number; }[];
placeholder?: string;
}
export class NapCatConfig {
static text (key: string, label: string, defaultValue?: string, description?: string): PluginConfigItem {
return { key, type: 'string', label, default: defaultValue, description };
}
static number (key: string, label: string, defaultValue?: number, description?: string): PluginConfigItem {
return { key, type: 'number', label, default: defaultValue, description };
}
static boolean (key: string, label: string, defaultValue?: boolean, description?: string): PluginConfigItem {
return { key, type: 'boolean', label, default: defaultValue, description };
}
static select (key: string, label: string, options: { label: string; value: string | number; }[], defaultValue?: string | number, description?: string): PluginConfigItem {
return { key, type: 'select', label, options, default: defaultValue, description };
}
static multiSelect (key: string, label: string, options: { label: string; value: string | number; }[], defaultValue?: (string | number)[], description?: string): PluginConfigItem {
return { key, type: 'multi-select', label, options, default: defaultValue, description };
}
static html (content: string): PluginConfigItem {
return { key: `_html_${Math.random().toString(36).slice(2)}`, type: 'html', label: '', default: content };
}
static plainText (content: string): PluginConfigItem {
return { key: `_text_${Math.random().toString(36).slice(2)}`, type: 'text', label: '', default: content };
}
static combine (...items: PluginConfigItem[]): PluginConfigSchema {
return items;
}
}
export type PluginConfigSchema = PluginConfigItem[];
/**
* 插件日志接口 - 简化的日志 API
*/
export interface PluginLogger {
/** 普通日志 */
log (...args: any[]): void;
/** 调试日志 */
debug (...args: any[]): void;
/** 信息日志 */
info (...args: any[]): void;
/** 警告日志 */
warn (...args: any[]): void;
/** 错误日志 */
error (...args: any[]): void;
}
export interface NapCatPluginContext {
core: NapCatCore;
oneBot: NapCatOneBot11Adapter;
actions: ActionMap;
pluginName: string;
pluginPath: string;
configPath: string;
dataPath: string;
NapCatConfig: typeof NapCatConfig;
adapterName: string;
pluginManager: OB11PluginMangerAdapter;
/** 插件日志器 - 自动添加插件名称前缀 */
logger: PluginLogger;
}
export interface PluginModule<T extends OB11EmitEventContent = OB11EmitEventContent> {
plugin_init: (
core: NapCatCore,
obContext: NapCatOneBot11Adapter,
actions: ActionMap,
instance: OB11PluginMangerAdapter
) => void | Promise<void>;
plugin_init: (ctx: NapCatPluginContext) => void | Promise<void>;
plugin_onmessage?: (
adapter: string,
core: NapCatCore,
obCtx: NapCatOneBot11Adapter,
ctx: NapCatPluginContext,
event: OB11Message,
actions: ActionMap,
instance: OB11PluginMangerAdapter
) => void | Promise<void>;
plugin_onevent?: (
adapter: string,
core: NapCatCore,
obCtx: NapCatOneBot11Adapter,
ctx: NapCatPluginContext,
event: T,
actions: ActionMap,
instance: OB11PluginMangerAdapter
) => void | Promise<void>;
plugin_cleanup?: (
core: NapCatCore,
obContext: NapCatOneBot11Adapter,
actions: ActionMap,
instance: OB11PluginMangerAdapter
ctx: NapCatPluginContext
) => void | Promise<void>;
plugin_config_schema?: PluginConfigSchema;
plugin_config_ui?: PluginConfigSchema;
plugin_get_config?: (ctx: NapCatPluginContext) => any | Promise<any>;
plugin_set_config?: (ctx: NapCatPluginContext, config: any) => void | Promise<void>;
}
export interface LoadedPlugin {
name: string;
dirname: string; // Actual directory name for path resolution
version?: string;
pluginPath: string;
entryPath: string;
packageJson?: PluginPackageJson;
module: PluginModule;
context: NapCatPluginContext; // Store context
}
export interface PluginStatusConfig {
@@ -63,7 +123,10 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
private readonly pluginPath: string;
private readonly configPath: string;
private loadedPlugins: Map<string, LoadedPlugin> = new Map();
// Track failed plugins: ID -> Error Message
private failedPlugins: Map<string, string> = new Map();
declare config: PluginConfig;
public NapCatConfig = NapCatConfig;
override get isActive (): boolean {
return this.isEnable && this.loadedPlugins.size > 0;
@@ -123,28 +186,22 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
const items = fs.readdirSync(this.pluginPath, { withFileTypes: true });
const pluginConfig = this.loadPluginConfig();
// 扫描文件和目录
// 扫描文件和目录 (Only support directories as plugins now)
for (const item of items) {
let pluginName = '';
if (item.isFile()) {
pluginName = path.parse(item.name).name;
} else if (item.isDirectory()) {
pluginName = item.name;
}
// Check if plugin is disabled in config
if (pluginConfig[pluginName] === false) {
this.logger.log(`[Plugin Adapter] Plugin ${pluginName} is disabled in config, skipping`);
if (!item.isDirectory()) {
continue;
}
if (item.isFile()) {
// 处理单文件插件
await this.loadFilePlugin(item.name);
} else if (item.isDirectory()) {
// 处理目录插件
await this.loadDirectoryPlugin(item.name);
const pluginId = item.name;
// Check if plugin is disabled in config
if (pluginConfig[pluginId] === false) {
this.logger.log(`[Plugin Adapter] Plugin ${pluginId} is disabled in config, skipping`);
continue;
}
// 处理目录插件
await this.loadDirectoryPlugin(item.name);
}
this.logger.log(
@@ -155,49 +212,7 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
}
}
/**
* 加载单文件插件 (.mjs, .js)
*/
public async loadFilePlugin (filename: string): Promise<void> {
// 只处理支持的文件类型
if (!this.isSupportedFile(filename)) {
return;
}
const filePath = path.join(this.pluginPath, filename);
const pluginName = path.parse(filename).name;
const pluginConfig = this.loadPluginConfig();
// Check if plugin is disabled in config
if (pluginConfig[pluginName] === false) {
this.logger.log(`[Plugin Adapter] Plugin ${pluginName} is disabled by user`);
return;
}
try {
const module = await this.importModule(filePath);
if (!this.isValidPluginModule(module)) {
this.logger.logWarn(
`[Plugin Adapter] File ${filename} is not a valid plugin (missing plugin methods)`
);
return;
}
const plugin: LoadedPlugin = {
name: pluginName,
pluginPath: this.pluginPath,
entryPath: filePath,
module,
};
await this.registerPlugin(plugin);
} catch (error) {
this.logger.logError(
`[Plugin Adapter] Error loading file plugin ${filename}:`,
error
);
}
}
// loadFilePlugin removed
/**
* 加载目录插件
@@ -205,16 +220,10 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
public async loadDirectoryPlugin (dirname: string): Promise<void> {
const pluginDir = path.join(this.pluginPath, dirname);
const pluginConfig = this.loadPluginConfig();
const pluginId = dirname; // Use directory name as unique ID
// Ideally we'd get the name from package.json first, but we can use dirname as a fallback identifier initially.
// However, the list scan uses item.name (dirname) as the key. Let's stick to using dirname/filename as the config key for simplicity and consistency.
// Wait, package.json name might override. But for management, consistent ID is better.
// Let's check config after parsing package.json?
// User expects to disable 'plugin-name'. But if multiple folders have same name? Not handled.
// Let's use dirname as the key for config to be consistent with file system.
if (pluginConfig[dirname] === false) {
this.logger.log(`[Plugin Adapter] Plugin ${dirname} is disabled by user`);
if (pluginConfig[pluginId] === false) {
this.logger.log(`[Plugin Adapter] Plugin ${pluginId} is disabled by user`);
return;
}
@@ -235,9 +244,6 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
}
}
// Check if disabled by package name IF package.json exists?
// No, file system name is more reliable ID for resource management here.
// 确定入口文件
const entryFile = this.findEntryFile(pluginDir, packageJson);
if (!entryFile) {
@@ -258,12 +264,14 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
}
const plugin: LoadedPlugin = {
name: packageJson?.name || dirname,
name: packageJson?.name || pluginId, // Use package.json name for API lookups, fallback to dir name
dirname: pluginId, // Keep track of actual directory name for path resolution
version: packageJson?.version,
pluginPath: pluginDir,
entryPath,
packageJson,
module,
context: {} as NapCatPluginContext // Will be populated in registerPlugin
};
await this.registerPlugin(plugin);
@@ -301,13 +309,7 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
return null;
}
/**
* 检查是否为支持的文件类型
*/
private isSupportedFile (filename: string): boolean {
const ext = path.extname(filename).toLowerCase();
return ['.mjs', '.js'].includes(ext);
}
/**
* 动态导入模块
@@ -327,6 +329,9 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
return module && typeof module.plugin_init === 'function';
}
/**
* 注册插件
*/
/**
* 注册插件
*/
@@ -339,6 +344,38 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
return;
}
// Create Context
// Use dirname for path resolution, name for identification
const dataPath = path.join(this.pluginPath, plugin.dirname, 'data');
const configPath = path.join(dataPath, 'config.json');
// Create plugin-specific logger with prefix
const pluginPrefix = `[Plugin: ${plugin.name}]`;
const coreLogger = this.logger;
const pluginLogger: PluginLogger = {
log: (...args: any[]) => coreLogger.log(pluginPrefix, ...args),
debug: (...args: any[]) => coreLogger.logDebug(pluginPrefix, ...args),
info: (...args: any[]) => coreLogger.log(pluginPrefix, ...args),
warn: (...args: any[]) => coreLogger.logWarn(pluginPrefix, ...args),
error: (...args: any[]) => coreLogger.logError(pluginPrefix, ...args),
};
const context: NapCatPluginContext = {
core: this.core,
oneBot: this.obContext,
actions: this.actions,
pluginName: plugin.name, // Use package name for identification
pluginPath: plugin.pluginPath,
dataPath: dataPath,
configPath: configPath,
NapCatConfig: NapCatConfig,
adapterName: this.name,
pluginManager: this,
logger: pluginLogger
};
plugin.context = context; // Store context on plugin object
this.loadedPlugins.set(plugin.name, plugin);
this.logger.log(
`[Plugin Adapter] Registered plugin: ${plugin.name}${plugin.version ? ` v${plugin.version}` : ''
@@ -347,18 +384,16 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
// 调用插件初始化方法(必须存在)
try {
await plugin.module.plugin_init(
this.core,
this.obContext,
this.actions,
this
);
await plugin.module.plugin_init(context);
this.logger.log(`[Plugin Adapter] Initialized plugin: ${plugin.name}`);
} catch (error) {
} catch (error: any) {
this.logger.logError(
`[Plugin Adapter] Error initializing plugin ${plugin.name}:`,
error
);
// Mark as failed
this.failedPlugins.set(plugin.name, error.message || 'Initialization failed');
this.loadedPlugins.delete(plugin.name);
}
}
@@ -374,12 +409,7 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
// 调用插件清理方法
if (typeof plugin.module.plugin_cleanup === 'function') {
try {
await plugin.module.plugin_cleanup(
this.core,
this.obContext,
this.actions,
this
);
await plugin.module.plugin_cleanup(plugin.context);
this.logger.log(`[Plugin Adapter] Cleaned up plugin: ${pluginName}`);
} catch (error) {
this.logger.logError(
@@ -406,54 +436,19 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
}
public setPluginStatus (pluginName: string, enable: boolean): void {
// Try to find plugin by package name first
const plugin = this.loadedPlugins.get(pluginName);
// Use dirname for config storage (if plugin is loaded), otherwise assume pluginName is dirname
const configKey = plugin?.dirname || pluginName;
const config = this.loadPluginConfig();
config[pluginName] = enable;
config[configKey] = enable;
this.savePluginConfig(config);
// If disabling, unload immediately if loaded
if (!enable) {
// Note: pluginName passed here might be the package name or the filename/dirname
// But our registerPlugin uses plugin.name which comes from package.json or dirname.
// This mismatch is tricky.
// Ideally, we should use a consistent ID.
// Let's assume pluginName passed here effectively matches the ID used in loadedPlugins.
// But wait, loadDirectoryPlugin logic: name = packageJson.name || dirname.
// config key = dirname.
// If packageJson.name != dirname, we have a problem.
// To fix this properly:
// 1. We need to know which LoadedPlugin corresponds to the enabled/disabled item.
// 2. Or we iterate loadedPlugins and find match.
for (const [_, loaded] of this.loadedPlugins.entries()) {
const dirOrFile = path.basename(loaded.pluginPath === this.pluginPath ? loaded.entryPath : loaded.pluginPath);
const ext = path.extname(dirOrFile);
const simpleName = ext ? path.parse(dirOrFile).name : dirOrFile; // filename without ext
// But wait, config key is the FILENAME (with ext for files?).
// In Scan loop:
// pluginName = path.parse(item.name).name (for file)
// pluginName = item.name (for dir)
// config[pluginName] check.
// So if file is "test.js", pluginName is "test". Config key "test".
// If dir is "test-plugin", pluginName is "test-plugin". Config key "test-plugin".
// loadedPlugin.name might be distinct.
// So we need to match loadedPlugin back to its fs source to unload it?
// loadedPlugin.entryPath or pluginPath helps.
// If it's a file plugin: loaded.entryPath ends with pluginName + ext.
// If it's a dir plugin: loaded.pluginPath ends with pluginName.
if (pluginName === simpleName) {
this.unloadPlugin(loaded.name).catch(e => this.logger.logError('Error unloading', e));
}
}
if (!enable && plugin) {
// Unload by plugin.name (package name, which is the key in loadedPlugins)
this.unloadPlugin(plugin.name).catch(e => this.logger.logError('Error unloading', e));
}
// If enabling, we need to load it.
// But we can just rely on the API handler to call loadFile/DirectoryPlugin which now checks config.
// Wait, if I call loadFilePlugin("test.js") and config says enable=true, it loads.
// API handler needs to change to pass filename/dirname.
}
async onEvent<T extends OB11EmitEventContent> (event: T) {
@@ -461,7 +456,6 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
return;
}
// 遍历所有已加载的插件,调用它们的事件处理方法
try {
await Promise.allSettled(
Array.from(this.loadedPlugins.values()).map((plugin) =>
@@ -484,12 +478,8 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
// 优先使用 plugin_onevent 方法
if (typeof plugin.module.plugin_onevent === 'function') {
await plugin.module.plugin_onevent(
this.name,
this.core,
this.obContext,
event,
this.actions,
this
plugin.context,
event
);
}
@@ -499,12 +489,8 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
typeof plugin.module.plugin_onmessage === 'function'
) {
await plugin.module.plugin_onmessage(
this.name,
this.core,
this.obContext,
event as OB11Message,
this.actions,
this
plugin.context,
event as OB11Message
);
}
} catch (error) {
@@ -583,23 +569,14 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
return false;
}
const dirname = plugin.dirname;
try {
// 卸载插件
await this.unloadPlugin(pluginName);
// 重新加载插件
// Use logic to re-determine if it is directory or file based on original paths
// Note: we can't fully trust fs status if it's gone.
const isDirectory =
plugin.pluginPath !== this.pluginPath; // Simple check: if path is nested, it's a dir plugin
if (isDirectory) {
const dirname = path.basename(plugin.pluginPath);
await this.loadDirectoryPlugin(dirname);
} else {
const filename = path.basename(plugin.entryPath);
await this.loadFilePlugin(filename);
}
// 重新加载插件 - use dirname for directory loading
await this.loadDirectoryPlugin(dirname);
this.logger.log(
`[Plugin Adapter] Plugin ${pluginName} reloaded successfully`
@@ -613,4 +590,14 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
return false;
}
}
public getPluginDataPath (pluginName: string): string {
// Lookup plugin by name (package name) and use dirname for path
const plugin = this.loadedPlugins.get(pluginName);
const dirname = plugin?.dirname || pluginName; // fallback to pluginName if not found
return path.join(this.pluginPath, dirname, 'data');
}
public getPluginConfigPath (pluginName: string): string {
return path.join(this.getPluginDataPath(pluginName), 'config.json');
}
}
@@ -74,7 +74,7 @@ export class OB11WebSocketClientAdapter extends IOB11NetworkAdapter<WebsocketCli
let isClosedByError = false;
this.connection = new WebSocket(this.config.url, {
maxPayload: 1024 * 1024 * 1024,
maxPayload: 50 * 1024 * 1024, // 50 MB
handshakeTimeout: 2000,
perMessageDeflate: false,
headers: {
@@ -32,7 +32,7 @@ export class OB11WebSocketServerAdapter extends IOB11NetworkAdapter<WebsocketSer
this.wsServer = new WebSocketServer({
port: this.config.port,
host: this.config.host === '0.0.0.0' ? '' : this.config.host,
maxPayload: 1024 * 1024 * 1024,
maxPayload: 50 * 1024 * 1024, // 50 MB
});
this.createServer(this.wsServer);
}
@@ -237,7 +237,7 @@ export class OB11WebSocketServerAdapter extends IOB11NetworkAdapter<WebsocketSer
this.wsServer = new WebSocketServer({
port: newConfig.port,
host: newConfig.host === '0.0.0.0' ? '' : newConfig.host,
maxPayload: 1024 * 1024 * 1024,
maxPayload: 50 * 1024 * 1024, // 50 MB
});
this.createServer(this.wsServer);
if (newConfig.enable) {
+89 -37
View File
@@ -1,45 +1,108 @@
import type { ActionMap } from 'napcat-types/napcat-onebot/action/index';
import { EventType } from 'napcat-types/napcat-onebot/event/index';
import type { PluginModule } from 'napcat-types/napcat-onebot/network/plugin-manger';
import type { PluginModule, PluginLogger, PluginConfigSchema } from 'napcat-types/napcat-onebot/network/plugin-manger';
import type { OB11Message, OB11PostSendMsg } from 'napcat-types/napcat-onebot/types/index';
let actions: ActionMap | undefined = undefined;
import fs from 'fs';
import path from 'path';
import { NetworkAdapterConfig } from 'napcat-types/napcat-onebot/config/config';
let startTime: number = Date.now();
let logger: PluginLogger | null = null;
/**
* 插件初始化
*/
const plugin_init: PluginModule['plugin_init'] = async (_core, _obContext, _actions, _instance) => {
console.log('[Plugin: builtin] NapCat 内置插件已初始化');
actions = _actions;
interface BuiltinPluginConfig {
prefix: string;
enableReply: boolean;
description: string;
theme?: string;
features?: string[];
[key: string]: unknown;
}
let currentConfig: BuiltinPluginConfig = {
prefix: '#napcat',
enableReply: true,
description: '这是一个内置插件的配置示例'
};
/**
* 消息处理
* 当收到包含 #napcat 的消息时,回复版本信息
*/
const plugin_onmessage: PluginModule['plugin_onmessage'] = async (adapter, _core, _obCtx, event, _actions, instance) => {
if (event.post_type !== EventType.MESSAGE || !event.raw_message.startsWith('#napcat')) {
export let plugin_config_ui: PluginConfigSchema = [];
const plugin_init: PluginModule['plugin_init'] = async (ctx) => {
logger = ctx.logger;
logger.info('NapCat 内置插件已初始化');
plugin_config_ui = ctx.NapCatConfig.combine(
ctx.NapCatConfig.html('<div style="padding: 10px; background: rgba(0,0,0,0.05); border-radius: 8px;"><h3>👋 Welcome to NapCat Builtin Plugin</h3><p>This is a demonstration of the plugin configuration interface.</p></div>'),
ctx.NapCatConfig.text('prefix', 'Command Prefix', '#napcat', 'The prefix to trigger the version info command'),
ctx.NapCatConfig.boolean('enableReply', 'Enable Reply', true, 'Switch to enable or disable the reply functionality'),
ctx.NapCatConfig.select('theme', 'Theme Selection', [
{ label: 'Light Mode', value: 'light' },
{ label: 'Dark Mode', value: 'dark' },
{ label: 'Auto', value: 'auto' }
], 'light', 'Select a theme for the response (Demo purpose only)'),
ctx.NapCatConfig.multiSelect('features', 'Enabled Features', [
{ label: 'Version Info', value: 'version' },
{ label: 'Status Report', value: 'status' },
{ label: 'Debug Log', value: 'debug' }
], ['version'], 'Select features to enable'),
ctx.NapCatConfig.text('description', 'Description', '这是一个内置插件的配置示例', 'A multi-line text area for notes')
);
// Try to load config
try {
// Use ctx.configPath
if (fs.existsSync(ctx.configPath)) {
const savedConfig = JSON.parse(fs.readFileSync(ctx.configPath, 'utf-8'));
Object.assign(currentConfig, savedConfig);
}
} catch (e) {
logger?.warn('Failed to load config', e);
}
};
export const plugin_get_config = async () => {
return currentConfig;
};
export const plugin_set_config = async (ctx: any, config: BuiltinPluginConfig) => {
currentConfig = config;
if (ctx && ctx.configPath) {
try {
const configPath = ctx.configPath;
const configDir = path.dirname(configPath);
if (!fs.existsSync(configDir)) {
fs.mkdirSync(configDir, { recursive: true });
}
fs.writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf-8');
} catch (e) {
logger?.error('Failed to save config', e);
throw e;
}
}
};
const plugin_onmessage: PluginModule['plugin_onmessage'] = async (_ctx, event) => {
if (currentConfig.enableReply === false) {
return;
}
const prefix = currentConfig.prefix || '#napcat';
if (event.post_type !== EventType.MESSAGE || !event.raw_message.startsWith(prefix)) {
return;
}
try {
const versionInfo = await getVersionInfo(adapter, instance.config);
const versionInfo = await getVersionInfo(_ctx.actions, _ctx.adapterName, _ctx.pluginManager.config);
if (!versionInfo) return;
const message = formatVersionMessage(versionInfo);
await sendMessage(event, message, adapter, instance.config);
await sendMessage(_ctx.actions, event, message, _ctx.adapterName, _ctx.pluginManager.config);
console.log('[Plugin: builtin] 已回复版本信息');
logger?.info('已回复版本信息');
} catch (error) {
console.error('[Plugin: builtin] 处理消息时发生错误:', error);
logger?.error('处理消息时发生错误:', error);
}
};
/**
* 获取版本信息(完美的类型推导,无需 as 断言)
*/
async function getVersionInfo (adapter: string, config: any) {
async function getVersionInfo (actions: ActionMap, adapter: string, config: NetworkAdapterConfig) {
if (!actions) return null;
try {
@@ -50,14 +113,11 @@ async function getVersionInfo (adapter: string, config: any) {
protocolVersion: data.protocol_version,
};
} catch (error) {
console.error('[Plugin: builtin] 获取版本信息失败:', error);
logger?.error('获取版本信息失败:', error);
return null;
}
}
/**
* 格式化运行时间
*/
function formatUptime (ms: number): string {
const seconds = Math.floor(ms / 1000);
const minutes = Math.floor(seconds / 60);
@@ -75,20 +135,12 @@ function formatUptime (ms: number): string {
}
}
/**
* 格式化版本信息消息
*/
function formatVersionMessage (info: { appName: string; appVersion: string; protocolVersion: string; }) {
const uptime = Date.now() - startTime;
return `NapCat 信息\n版本: ${info.appVersion}\n平台: ${process.platform}${process.arch === 'x64' ? ' (64-bit)' : ''}\n运行时间: ${formatUptime(uptime)}`;
}
/**
* 发送消息(完美的类型推导)
*/
async function sendMessage (event: OB11Message, message: string, adapter: string, config: any) {
if (!actions) return;
async function sendMessage (actions: ActionMap, event: OB11Message, message: string, adapter: string, config: NetworkAdapterConfig) {
const params: OB11PostSendMsg = {
message,
message_type: event.message_type,
@@ -99,7 +151,7 @@ async function sendMessage (event: OB11Message, message: string, adapter: string
try {
await actions.call('send_msg', params, adapter, config);
} catch (error) {
console.error('[Plugin: builtin] 发送消息失败:', error);
logger?.error('发送消息失败:', error);
}
}
+1 -1
View File
@@ -6,7 +6,7 @@
"description": "NapCat 内置插件",
"author": "NapNeko",
"dependencies": {
"napcat-types": "0.0.3"
"napcat-types": "0.0.9"
},
"devDependencies": {
"@types/node": "^22.0.1"
-3
View File
@@ -1,3 +0,0 @@
# Example Plugin
## Install
安装只需要将dist产物 `index.mjs` 目录放入 napcat根目录下`plugins/example`,如果没有这个目录请创建。
-22
View File
@@ -1,22 +0,0 @@
import type { createActionMap } from 'napcat-types/dist/napcat-onebot/action/index.js';
import { EventType } from 'napcat-types/dist/napcat-onebot/event/index.js';
import type { PluginModule } from 'napcat-types/dist/napcat-onebot/network/plugin-manger';
/**
* 导入 napcat 包时候不使用 @/napcat...,直接使用 napcat...
* 因为 @/napcat... 会导致打包时包含整个 napcat 包,而不是只包含需要的部分
*/
// action 作为参数传递时请用这个
let actionMap: ReturnType<typeof createActionMap> | undefined = undefined;
const plugin_init: PluginModule['plugin_init'] = async (_core, _obContext, _actions, _instance) => {
console.log('[Plugin: example] 插件已初始化');
actionMap = _actions;
};
const plugin_onmessage: PluginModule['plugin_onmessage'] = async (adapter, _core, _obCtx, event, actions, instance) => {
if (event.post_type === EventType.MESSAGE && event.raw_message.includes('ping')) {
await actions.get('send_group_msg')?.handle({ group_id: String(event.group_id), message: 'pong' }, adapter, instance.config);
}
};
export { plugin_init, plugin_onmessage, actionMap };
-16
View File
@@ -1,16 +0,0 @@
{
"name": "napcat-plugin",
"version": "1.0.0",
"type": "module",
"main": "index.mjs",
"description": "一个高级的 NapCat 插件示例",
"dependencies": {
"napcat-types": "workspace:*"
},
"devDependencies": {
"@types/node": "^22.0.1"
},
"scripts": {
"build": "vite build"
}
}
-11
View File
@@ -1,11 +0,0 @@
{
"extends": "../../tsconfig.base.json",
"include": [
"*.ts",
"**/*.ts"
],
"exclude": [
"node_modules",
"dist"
]
}
-30
View File
@@ -1,30 +0,0 @@
import { defineConfig } from 'vite';
import { resolve } from 'path';
import nodeResolve from '@rollup/plugin-node-resolve';
import { builtinModules } from 'module';
const nodeModules = [...builtinModules, builtinModules.map((m) => `node:${m}`)].flat();
export default defineConfig({
resolve: {
conditions: ['node', 'default'],
alias: {
'@/napcat-core': resolve(__dirname, '../napcat-core'),
'@': resolve(__dirname, '../'),
},
},
build: {
sourcemap: false,
target: 'esnext',
minify: false,
lib: {
entry: 'index.ts',
formats: ['es'],
fileName: () => 'index.mjs',
},
rollupOptions: {
external: [...nodeModules],
},
},
plugins: [nodeResolve()],
});
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "napcat-types",
"version": "0.0.4",
"version": "0.0.9",
"private": false,
"type": "module",
"types": "./napcat-types/index.d.ts",
+105 -50
View File
@@ -33,21 +33,20 @@ export const GetPluginListHandler: RequestHandler = async (_req, res) => {
// 1. 整理已加载的插件
for (const p of loadedPlugins) {
// 计算 ID:需要回溯到加载时的入口信息
// 对于已加载的插件,我们通过判断 pluginPath 是否等于根 pluginPath 来判断它是单文件还是目录
const isFilePlugin = p.pluginPath === pluginManager.getPluginPath();
const fsName = isFilePlugin ? path.basename(p.entryPath) : path.basename(p.pluginPath);
const id = getPluginId(fsName, isFilePlugin);
// Use dirname for map key (matches filesystem scan)
const id = p.dirname;
const fsName = p.dirname; // dirname is the actual filesystem directory name
loadedPluginMap.set(id, {
name: p.packageJson?.name || p.name, // 优先使用 package.json 的 name
name: p.name, // This is now package name (from packageJson.name || dirname)
id: id,
version: p.version || '0.0.0',
description: p.packageJson?.description || '',
author: p.packageJson?.author || '',
status: 'active',
filename: fsName, // 真实文件/目录名
loadedName: p.name // 运行时注册的名称,用于重载/卸载
loadedName: p.name, // 运行时注册的名称,用于重载/卸载 (package name)
hasConfig: !!(p.module.plugin_config_schema || p.module.plugin_config_ui)
});
}
@@ -117,67 +116,43 @@ export const GetPluginListHandler: RequestHandler = async (_req, res) => {
return sendSuccess(res, { plugins: allPlugins, pluginManagerNotFound: false });
};
export const ReloadPluginHandler: RequestHandler = async (req, res) => {
const { name } = req.body;
// Note: we should probably accept ID or Name. But ReloadPlugin uses valid loaded name.
// Let's stick to name for now, but be aware of ambiguity.
if (!name) return sendError(res, 'Plugin Name is required');
const pluginManager = getPluginManager();
if (!pluginManager) {
return sendError(res, '插件管理器未加载,请检查 plugins 目录是否存在');
}
const success = await pluginManager.reloadPlugin(name);
if (success) {
return sendSuccess(res, { message: 'Reloaded successfully' });
} else {
return sendError(res, 'Failed to reload plugin');
}
};
// ReloadPluginHandler removed
export const SetPluginStatusHandler: RequestHandler = async (req, res) => {
const { enable, filename } = req.body;
// We Use filename / id to control config
// Front-end should pass the 'filename' or 'id' as the key identifier
const { enable, filename, name } = req.body;
// filename is the directory name (used for fs checks)
// name is the package name (used for plugin manager API, if provided)
// We need to determine: which to use for setPluginStatus call
if (!filename) return sendError(res, 'Plugin Filename/ID is required');
if (!filename && !name) return sendError(res, 'Plugin Filename or Name is required');
const pluginManager = getPluginManager();
if (!pluginManager) {
return sendError(res, 'Plugin Manager not found');
}
// Calculate ID from filename (remove ext if file)
// Or just use the logic consistent with loadPlugins
let id = filename;
// If it has extension .js/.mjs, remove it to get the ID used in config
if (filename.endsWith('.js') || filename.endsWith('.mjs')) {
id = path.parse(filename).name;
}
// Determine which ID to use
// If 'name' (package name) is provided, use it for pluginManager calls
// But 'filename' (dirname) is needed for filesystem operations
const dirname = filename || name; // fallback
const pluginName = name || filename; // fallback
try {
pluginManager.setPluginStatus(id, enable);
// setPluginStatus now handles both package name and dirname lookup internally
pluginManager.setPluginStatus(pluginName, enable);
// If enabling, trigger load
if (enable) {
const pluginPath = pluginManager.getPluginPath();
const fullPath = path.join(pluginPath, filename);
const fullPath = path.join(pluginPath, dirname);
if (fs.statSync(fullPath).isDirectory()) {
await pluginManager.loadDirectoryPlugin(filename);
if (fs.existsSync(fullPath) && fs.statSync(fullPath).isDirectory()) {
await pluginManager.loadDirectoryPlugin(dirname);
} else {
await pluginManager.loadFilePlugin(filename);
return sendError(res, 'Plugin directory not found: ' + dirname);
}
} else {
// Disabling is handled inside setPluginStatus usually if implemented,
// OR we can explicitly unload here using the loaded name.
// The Manager's setPluginStatus implementation (if added) might logic this out.
// But our current Manager implementation just saves config.
// Wait, I updated Manager to try to unload.
// Let's rely on Manager's setPluginStatus or do it here?
// I implemented a basic unload loop in Manager.setPluginStatus.
}
// Disabling is handled by setPluginStatus
return sendSuccess(res, { message: 'Status updated successfully' });
} catch (e: any) {
@@ -186,7 +161,7 @@ export const SetPluginStatusHandler: RequestHandler = async (req, res) => {
};
export const UninstallPluginHandler: RequestHandler = async (req, res) => {
const { name, filename } = req.body;
const { name, filename, cleanData } = req.body;
// If it's loaded, we use name. If it's disabled, we might use filename.
const pluginManager = getPluginManager();
@@ -219,8 +194,88 @@ export const UninstallPluginHandler: RequestHandler = async (req, res) => {
if (fs.existsSync(fsPath)) {
fs.rmSync(fsPath, { recursive: true, force: true });
}
if (cleanData && name) {
const dataPath = pluginManager.getPluginDataPath(name);
if (fs.existsSync(dataPath)) {
fs.rmSync(dataPath, { recursive: true, force: true });
}
}
return sendSuccess(res, { message: 'Uninstalled successfully' });
} catch (e: any) {
return sendError(res, 'Failed to uninstall: ' + e.message);
}
};
export const GetPluginConfigHandler: RequestHandler = async (req, res) => {
const name = req.query['name'] as string;
if (!name) return sendError(res, 'Plugin Name is required');
const pluginManager = getPluginManager();
if (!pluginManager) return sendError(res, 'Plugin Manager not found');
const plugin = pluginManager.getPluginInfo(name);
if (!plugin) return sendError(res, 'Plugin not loaded');
// Support legacy schema or new API
const schema = plugin.module.plugin_config_schema || plugin.module.plugin_config_ui;
let config = {};
if (plugin.module.plugin_get_config) {
try {
config = await plugin.module.plugin_get_config(plugin.context);
} catch (e) { }
} else if (schema) {
// Default behavior: read from default config path
try {
// Use context configPath if available
const configPath = plugin.context?.configPath || pluginManager.getPluginConfigPath(name);
if (fs.existsSync(configPath)) {
config = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
}
} catch (e) { }
}
return sendSuccess(res, { schema, config });
};
export const SetPluginConfigHandler: RequestHandler = async (req, res) => {
const { name, config } = req.body;
if (!name || !config) return sendError(res, 'Name and Config required');
const pluginManager = getPluginManager();
if (!pluginManager) return sendError(res, 'Plugin Manager not found');
const plugin = pluginManager.getPluginInfo(name);
if (!plugin) return sendError(res, 'Plugin not loaded');
if (plugin.module.plugin_set_config) {
try {
await plugin.module.plugin_set_config(plugin.context, config);
return sendSuccess(res, { message: 'Config updated' });
} catch (e: any) {
return sendError(res, 'Error updating config: ' + e.message);
}
} else if (plugin.module.plugin_config_schema || plugin.module.plugin_config_ui) {
// Default behavior: write to default config path
try {
const configPath = plugin.context?.configPath || pluginManager.getPluginConfigPath(name);
const configDir = path.dirname(configPath);
if (!fs.existsSync(configDir)) {
fs.mkdirSync(configDir, { recursive: true });
}
fs.writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf-8');
// Auto-Reload plugin to apply changes
await pluginManager.reloadPlugin(name);
return sendSuccess(res, { message: 'Config saved and plugin reloaded' });
} catch (e: any) {
return sendError(res, 'Error saving config: ' + e.message);
}
} else {
return sendError(res, 'Plugin does not support config update');
}
};
@@ -1,13 +1,25 @@
import { Router } from 'express';
import { GetPluginListHandler, ReloadPluginHandler, SetPluginStatusHandler, UninstallPluginHandler } from '@/napcat-webui-backend/src/api/Plugin';
import { GetPluginStoreListHandler, GetPluginStoreDetailHandler, InstallPluginFromStoreHandler, InstallPluginFromStoreSSEHandler } from '@/napcat-webui-backend/src/api/PluginStore';
import {
GetPluginListHandler,
SetPluginStatusHandler,
UninstallPluginHandler,
GetPluginConfigHandler,
SetPluginConfigHandler
} from '@/napcat-webui-backend/src/api/Plugin';
import {
GetPluginStoreListHandler,
GetPluginStoreDetailHandler,
InstallPluginFromStoreHandler,
InstallPluginFromStoreSSEHandler
} from '@/napcat-webui-backend/src/api/PluginStore';
const router: Router = Router();
router.get('/List', GetPluginListHandler);
router.post('/Reload', ReloadPluginHandler);
router.post('/SetStatus', SetPluginStatusHandler);
router.post('/Uninstall', UninstallPluginHandler);
router.get('/Config', GetPluginConfigHandler);
router.post('/Config', SetPluginConfigHandler);
// 插件商店相关路由
router.get('/Store/List', GetPluginStoreListHandler);
@@ -3,23 +3,25 @@ import { Switch } from '@heroui/switch';
import { Chip } from '@heroui/chip';
import { useState } from 'react';
import { MdDeleteForever, MdPublishedWithChanges } from 'react-icons/md';
import { MdDeleteForever, MdSettings } from 'react-icons/md';
import DisplayCardContainer from './container';
import { PluginItem } from '@/controllers/plugin_manager';
export interface PluginDisplayCardProps {
data: PluginItem;
onReload: () => Promise<void>;
onToggleStatus: () => Promise<void>;
onUninstall: () => Promise<void>;
onConfig?: () => void;
hasConfig?: boolean;
}
const PluginDisplayCard: React.FC<PluginDisplayCardProps> = ({
data,
onReload,
onToggleStatus,
onUninstall,
onConfig,
hasConfig = false,
}) => {
const { name, version, author, description, status } = data;
const isEnabled = status !== 'disabled';
@@ -30,11 +32,6 @@ const PluginDisplayCard: React.FC<PluginDisplayCardProps> = ({
onToggleStatus().finally(() => setProcessing(false));
};
const handleReload = () => {
setProcessing(true);
onReload().finally(() => setProcessing(false));
};
const handleUninstall = () => {
setProcessing(true);
onUninstall().finally(() => setProcessing(false));
@@ -44,32 +41,34 @@ const PluginDisplayCard: React.FC<PluginDisplayCardProps> = ({
<DisplayCardContainer
className='w-full max-w-[420px]'
action={
<div className='flex gap-2 w-full'>
<Button
fullWidth
radius='full'
size='sm'
variant='flat'
className='flex-1 bg-default-100 dark:bg-default-50 text-default-600 font-medium hover:bg-primary/20 hover:text-primary transition-colors'
startContent={<MdPublishedWithChanges size={16} />}
onPress={handleReload}
isDisabled={!isEnabled || processing}
>
重载
</Button>
<Button
fullWidth
radius='full'
size='sm'
variant='flat'
className='flex-1 bg-default-100 dark:bg-default-50 text-default-600 font-medium hover:bg-danger/20 hover:text-danger transition-colors'
startContent={<MdDeleteForever size={16} />}
onPress={handleUninstall}
isDisabled={processing}
>
卸载
</Button>
<div className='flex flex-col gap-2 w-full'>
<div className='flex gap-2 w-full'>
<Button
fullWidth
radius='full'
size='sm'
variant='flat'
className='flex-1 bg-default-100 dark:bg-default-50 text-default-600 font-medium hover:bg-danger/20 hover:text-danger transition-colors'
startContent={<MdDeleteForever size={16} />}
onPress={handleUninstall}
isDisabled={processing}
>
卸载
</Button>
</div>
{hasConfig && (
<Button
fullWidth
radius='full'
size='sm'
variant='flat'
className='bg-default-100 dark:bg-default-50 text-default-600 font-medium hover:bg-secondary/20 hover:text-secondary transition-colors'
startContent={<MdSettings size={16} />}
onPress={onConfig}
>
配置
</Button>
)}
</div>
}
enableSwitch={
@@ -7,7 +7,7 @@ import { Tab, Tabs } from '@heroui/tabs';
import { Chip } from '@heroui/chip';
import { useLocalStorage } from '@uidotdev/usehooks';
import clsx from 'clsx';
import { forwardRef, useEffect, useImperativeHandle, useState, useCallback } from 'react';
import { forwardRef, useEffect, useImperativeHandle, useState, useCallback, useMemo } from 'react';
import toast from 'react-hot-toast';
import { IoChevronDown, IoSend, IoSettingsSharp, IoCopy } from 'react-icons/io5';
import { TbCode, TbMessageCode } from 'react-icons/tb';
@@ -59,16 +59,30 @@ const OneBotApiDebug = forwardRef<OneBotApiDebugRef, OneBotApiDebugProps>((props
const [responseHeight, setResponseHeight] = useState(240);
const [storedHeight, setStoredHeight] = useLocalStorage('napcat_debug_response_height', 240);
const parsedRequest = parseTypeBox(data?.payload);
// 使用 useMemo 缓存解析结果,避免每次渲染都重新解析
const parsedRequest = useMemo(() => {
try {
return parseTypeBox(data?.payload);
} catch (e) {
console.error('Error parsing request schema:', e);
return [];
}
}, [data?.payload]);
// 将返回值的 data 结构包装进 BaseResponseSchema 进行展示
// 使用解构属性的方式重新构建对象,确保 parseTypeBox 能够识别为 object 类型
const wrappedResponseSchema = Type.Object({
...BaseResponseSchema.properties,
data: data?.response || Type.Any({ description: '数据' })
});
const parsedResponse = parseTypeBox(wrappedResponseSchema);
const parsedResponse = useMemo(() => {
try {
const wrappedResponseSchema = Type.Object({
...BaseResponseSchema.properties,
data: data?.response || Type.Any({ description: '数据' })
});
return parseTypeBox(wrappedResponseSchema);
} catch (e) {
console.error('Error parsing response schema:', e);
return [];
}
}, [data?.response]);
const [backgroundImage] = useLocalStorage<string>(key.backgroundImage, '');
const hasBackground = !!backgroundImage;
@@ -166,7 +180,12 @@ const OneBotApiDebug = forwardRef<OneBotApiDebugRef, OneBotApiDebugProps>((props
if (data?.payloadExample) {
setRequestBody(JSON.stringify(data.payloadExample, null, 2));
} else {
setRequestBody(JSON.stringify(generateDefaultFromTypeBox(data?.payload), null, 2));
try {
setRequestBody(JSON.stringify(generateDefaultFromTypeBox(data?.payload), null, 2));
} catch (e) {
console.error('Error generating default:', e);
setRequestBody('{}');
}
}
setResponseContent('');
setResponseStatus(null);
@@ -320,7 +339,14 @@ const OneBotApiDebug = forwardRef<OneBotApiDebugRef, OneBotApiDebugProps>((props
)}
</ChatInputModal>
<Tooltip content="生成示例" closeDelay={0}>
<Button isIconOnly size='sm' variant='light' radius='sm' className='w-8 h-8' onPress={() => setRequestBody(JSON.stringify(generateDefaultFromTypeBox(data?.payload), null, 2))}>
<Button isIconOnly size='sm' variant='light' radius='sm' className='w-8 h-8' onPress={() => {
try {
setRequestBody(JSON.stringify(generateDefaultFromTypeBox(data?.payload), null, 2));
} catch (e) {
console.error('Error generating default:', e);
toast.error('生成示例失败');
}
}}>
<TbCode size={16} />
</Button>
</Tooltip>
@@ -127,6 +127,20 @@ const SchemaContainer: React.FC<{
};
const RenderSchema: React.FC<{ schema: ParsedSchema; }> = ({ schema }) => {
// 处理循环引用和截断的情况,直接显示提示而不继续递归
if (schema.isCircularRef || schema.isTruncated) {
return (
<div className='mb-2 flex items-center gap-1 pl-5'>
{schema.name && (
<span className='text-default-400'>{schema.name}</span>
)}
<Chip size='sm' color='default' variant='flat'>
{schema.description || '...'}
</Chip>
</div>
);
}
if (schema.type === 'object') {
return (
<SchemaContainer schema={schema}>
@@ -8,6 +8,7 @@ export interface PluginItem {
author: string;
status: 'active' | 'disabled' | 'stopped';
filename?: string;
hasConfig?: boolean;
}
export interface PluginListResponse {
@@ -15,6 +16,21 @@ export interface PluginListResponse {
pluginManagerNotFound: boolean;
}
export interface PluginConfigSchemaItem {
key: string;
type: 'string' | 'number' | 'boolean' | 'select' | 'multi-select' | 'html' | 'text';
label: string;
description?: string;
default?: any;
options?: { label: string; value: string | number; }[];
placeholder?: string;
}
export interface PluginConfigResponse {
schema: PluginConfigSchemaItem[];
config: any;
}
export interface ServerResponse<T> {
code: number;
message: string;
@@ -27,16 +43,14 @@ export default class PluginManager {
return data.data;
}
public static async reloadPlugin (name: string) {
await serverRequest.post<ServerResponse<void>>('/Plugin/Reload', { name });
}
public static async setPluginStatus (name: string, enable: boolean, filename?: string) {
await serverRequest.post<ServerResponse<void>>('/Plugin/SetStatus', { name, enable, filename });
}
public static async uninstallPlugin (name: string, filename?: string) {
await serverRequest.post<ServerResponse<void>>('/Plugin/Uninstall', { name, filename });
public static async uninstallPlugin (name: string, filename?: string, cleanData?: boolean) {
await serverRequest.post<ServerResponse<void>>('/Plugin/Uninstall', { name, filename, cleanData });
}
// 插件商店相关方法
@@ -56,4 +70,14 @@ export default class PluginManager {
timeout: 300000, // 5分钟
});
}
// 插件配置相关方法
public static async getPluginConfig (name: string) {
const { data } = await serverRequest.get<ServerResponse<PluginConfigResponse>>('/Plugin/Config', { params: { name } });
return data.data;
}
public static async setPluginConfig (name: string, config: any) {
await serverRequest.post<ServerResponse<void>>('/Plugin/Config', { name, config });
}
}
@@ -112,9 +112,17 @@ export default function HttpDebug () {
const executeCommand = (commandId: string, mode: CommandPaletteExecuteMode) => {
const api = commandId as OneBotHttpApiPath;
const item = oneBotHttpApi[api];
const body = item?.payloadExample
? JSON.stringify(item.payloadExample, null, 2)
: (item?.payload ? JSON.stringify(generateDefaultFromTypeBox(item.payload), null, 2) : '{}');
let body = '{}';
if (item?.payloadExample) {
body = JSON.stringify(item.payloadExample, null, 2);
} else if (item?.payload) {
try {
body = JSON.stringify(generateDefaultFromTypeBox(item.payload), null, 2);
} catch (e) {
console.error('Error generating default:', e);
body = '{}';
}
}
handleSelectApi(api);
// 确保请求参数可见
@@ -2,11 +2,13 @@ import { Button } from '@heroui/button';
import { useEffect, useState } from 'react';
import toast from 'react-hot-toast';
import { IoMdRefresh } from 'react-icons/io';
import { useDisclosure } from '@heroui/modal';
import PageLoading from '@/components/page_loading';
import PluginDisplayCard from '@/components/display_card/plugin_card';
import PluginManager, { PluginItem } from '@/controllers/plugin_manager';
import useDialog from '@/hooks/use-dialog';
import PluginConfigModal from '@/pages/dashboard/plugin_config_modal';
export default function PluginPage () {
const [plugins, setPlugins] = useState<PluginItem[]>([]);
@@ -14,16 +16,20 @@ export default function PluginPage () {
const [pluginManagerNotFound, setPluginManagerNotFound] = useState(false);
const dialog = useDialog();
const { isOpen, onOpen, onOpenChange } = useDisclosure();
const [currentPluginName, setCurrentPluginName] = useState<string>('');
const loadPlugins = async () => {
setLoading(true);
setPluginManagerNotFound(false);
try {
const result = await PluginManager.getPluginList();
if (result.pluginManagerNotFound) {
const listResult = await PluginManager.getPluginList();
if (listResult.pluginManagerNotFound) {
setPluginManagerNotFound(true);
setPlugins([]);
} else {
setPlugins(result.plugins);
setPlugins(listResult.plugins);
}
} catch (e: any) {
toast.error(e.message);
@@ -36,16 +42,7 @@ export default function PluginPage () {
loadPlugins();
}, []);
const handleReload = async (name: string) => {
const loadingToast = toast.loading('重载中...');
try {
await PluginManager.reloadPlugin(name);
toast.success('重载成功', { id: loadingToast });
loadPlugins();
} catch (e: any) {
toast.error(e.message, { id: loadingToast });
}
};
const handleToggle = async (plugin: PluginItem) => {
const isEnable = plugin.status !== 'active';
@@ -64,11 +61,31 @@ export default function PluginPage () {
return new Promise<void>((resolve, reject) => {
dialog.confirm({
title: '卸载插件',
content: `确定要卸载插件「${plugin.name}」吗? 此操作不可恢复。`,
content: (
<div className="flex flex-col gap-2">
<p>确定要卸载插件「{plugin.name}」吗? 此操作不可恢复。</p>
<p className="text-small text-default-500">如果插件创建了数据文件,是否一并删除?</p>
</div>
),
// This 'dialog' utility might not support returning a value from UI interacting.
// We might need to implement a custom confirmation flow if we want a checkbox.
// Alternatively, use two buttons? "Uninstall & Clean", "Uninstall Only"?
// Standard dialog usually has Confirm/Cancel.
// Let's stick to a simpler "Uninstall" and then maybe a second prompt? Or just clean data?
// User requested: "Uninstall prompts whether to clean data".
// Let's use `window.confirm` for the second step or assume `dialog.confirm` is flexible enough?
// I will implement a two-step confirmation or try to modify the dialog hook if visible (not visible here).
// Let's use a standard `window.confirm` for the data cleanup question if the custom dialog doesn't support complex return.
// Better: Inside onConfirm, ask again?
onConfirm: async () => {
// Ask for data cleanup
// Since we are in an async callback, we can use another dialog or confirm.
// Native confirm is ugly but works reliably for logic:
const cleanData = window.confirm(`是否同时清理插件「${plugin.name}」的数据文件?\n点击“确定”清理数据,点击“取消”仅卸载插件。`);
const loadingToast = toast.loading('卸载中...');
try {
await PluginManager.uninstallPlugin(plugin.name, plugin.filename);
await PluginManager.uninstallPlugin(plugin.name, plugin.filename, cleanData);
toast.success('卸载成功', { id: loadingToast });
loadPlugins();
resolve();
@@ -84,11 +101,22 @@ export default function PluginPage () {
});
};
const handleConfig = (plugin: PluginItem) => {
setCurrentPluginName(plugin.name); // Use Loaded Name for config lookup
onOpen();
};
return (
<>
<title>插件管理 - NapCat WebUI</title>
<div className='p-2 md:p-4 relative'>
<PageLoading loading={loading} />
<PluginConfigModal
isOpen={isOpen}
onOpenChange={onOpenChange}
pluginName={currentPluginName}
/>
<div className='flex mb-6 items-center gap-4'>
<h1 className="text-2xl font-bold">插件管理</h1>
<Button
@@ -119,9 +147,16 @@ export default function PluginPage () {
<PluginDisplayCard
key={plugin.name}
data={plugin}
onReload={() => handleReload(plugin.name)}
onToggleStatus={() => handleToggle(plugin)}
onUninstall={() => handleUninstall(plugin)}
onConfig={() => {
if (plugin.hasConfig) {
handleConfig(plugin);
} else {
toast.error('此插件没有配置哦');
}
}}
hasConfig={true}
/>
))}
</div>
@@ -0,0 +1,208 @@
import { Modal, ModalContent, ModalHeader, ModalBody, ModalFooter } from '@heroui/modal';
import { Button } from '@heroui/button';
import { Input } from '@heroui/input';
import { Select, SelectItem } from '@heroui/select';
import { Switch } from '@heroui/switch';
import { useEffect, useState } from 'react';
import toast from 'react-hot-toast';
import PluginManager, { PluginConfigSchemaItem } from '@/controllers/plugin_manager';
interface Props {
isOpen: boolean;
onOpenChange: () => void;
pluginName: string;
}
export default function PluginConfigModal ({ isOpen, onOpenChange, pluginName }: Props) {
const [loading, setLoading] = useState(false);
const [schema, setSchema] = useState<PluginConfigSchemaItem[]>([]);
const [config, setConfig] = useState<any>({});
const [saving, setSaving] = useState(false);
useEffect(() => {
if (isOpen && pluginName) {
loadConfig();
}
}, [isOpen, pluginName]);
const loadConfig = async () => {
setLoading(true);
setSchema([]);
setConfig({});
try {
const data = await PluginManager.getPluginConfig(pluginName);
setSchema(data.schema || []);
setConfig(data.config || {});
} catch (e: any) {
toast.error('Load config failed: ' + e.message);
} finally {
setLoading(false);
}
};
const handleSave = async () => {
setSaving(true);
try {
await PluginManager.setPluginConfig(pluginName, config);
toast.success('Configuration saved');
onOpenChange();
} catch (e: any) {
toast.error('Save failed: ' + e.message);
} finally {
setSaving(false);
}
};
const updateConfig = (key: string, value: any) => {
setConfig((prev: any) => ({ ...prev, [key]: value }));
};
const renderField = (item: PluginConfigSchemaItem) => {
const value = config[item.key] ?? item.default;
switch (item.type) {
case 'string':
return (
<Input
key={item.key}
label={item.label}
placeholder={item.placeholder || item.description}
value={value || ''}
onValueChange={(val) => updateConfig(item.key, val)}
description={item.description}
className="mb-4"
/>
);
case 'number':
return (
<Input
key={item.key}
type="number"
label={item.label}
placeholder={item.placeholder || item.description}
value={String(value ?? 0)}
onValueChange={(val) => updateConfig(item.key, Number(val))}
description={item.description}
className="mb-4"
/>
);
case 'boolean':
return (
<div key={item.key} className="flex justify-between items-center mb-4 p-2 bg-default-100 rounded-lg">
<div className="flex flex-col">
<span className="text-small">{item.label}</span>
{item.description && <span className="text-tiny text-default-500">{item.description}</span>}
</div>
<Switch
isSelected={!!value}
onValueChange={(val) => updateConfig(item.key, val)}
/>
</div>
);
case 'select':
// Handle value matching for default selected keys
const selectedValue = value !== undefined ? String(value) : undefined;
return (
<Select
key={item.key}
label={item.label}
placeholder={item.placeholder || 'Select an option'}
selectedKeys={selectedValue ? [selectedValue] : []}
onSelectionChange={(keys) => {
const val = Array.from(keys)[0];
// Map back to value
const opt = item.options?.find(o => String(o.value) === val);
updateConfig(item.key, opt ? opt.value : val);
}}
description={item.description}
className="mb-4"
>
{(item.options || []).map((opt) => (
<SelectItem key={String(opt.value)} textValue={opt.label}>
{opt.label}
</SelectItem>
))}
</Select>
);
case 'multi-select':
const selectedKeys = Array.isArray(value) ? value.map(String) : [];
return (
<Select
key={item.key}
label={item.label}
placeholder={item.placeholder || 'Select options'}
selectionMode="multiple"
selectedKeys={new Set(selectedKeys)}
onSelectionChange={(keys) => {
const selected = Array.from(keys).map(k => {
const opt = item.options?.find(o => String(o.value) === k);
return opt ? opt.value : k;
});
updateConfig(item.key, selected);
}}
description={item.description}
className="mb-4"
>
{(item.options || []).map((opt) => (
<SelectItem key={String(opt.value)} textValue={opt.label}>
{opt.label}
</SelectItem>
))}
</Select>
);
case 'html':
return (
<div key={item.key} className="mb-4">
{item.label && <h4 className="text-small font-bold mb-1">{item.label}</h4>}
<div dangerouslySetInnerHTML={{ __html: item.default || '' }} className="prose dark:prose-invert max-w-none" />
{item.description && <p className="text-tiny text-default-500 mt-1">{item.description}</p>}
</div>
);
case 'text':
return (
<div key={item.key} className="mb-4">
{item.label && <h4 className="text-small font-bold mb-1">{item.label}</h4>}
<div className="whitespace-pre-wrap text-default-700">{item.default || ''}</div>
{item.description && <p className="text-tiny text-default-500 mt-1">{item.description}</p>}
</div>
);
default:
return null;
}
};
return (
<Modal isOpen={isOpen} onOpenChange={onOpenChange} size="2xl" scrollBehavior="inside">
<ModalContent>
{(onClose) => (
<>
<ModalHeader className="flex flex-col gap-1">
Configuration: {pluginName}
</ModalHeader>
<ModalBody>
{loading ? (
<div className="flex justify-center p-8">Loading configuration...</div>
) : (
<div className="flex flex-col gap-2">
{schema.length === 0 ? (
<div className="text-center text-default-500">No configuration schema available.</div>
) : (
schema.map(renderField)
)}
</div>
)}
</ModalBody>
<ModalFooter>
<Button color="danger" variant="light" onPress={onClose}>
Close
</Button>
<Button color="primary" onPress={handleSave} isLoading={saving}>
Save
</Button>
</ModalFooter>
</>
)}
</ModalContent>
</Modal>
);
}
@@ -8,6 +8,8 @@ export type ParsedSchema = {
enum?: any[];
children?: ParsedSchema[];
description?: string;
isCircularRef?: boolean; // 标记循环引用
isTruncated?: boolean; // 标记被截断
};
// 定义基础响应结构 (TypeBox 格式)
@@ -20,37 +22,79 @@ export const BaseResponseSchema = Type.Object({
echo: Type.Optional(Type.String({ description: '回显' })),
});
export function parseTypeBox (schema: TSchema | undefined, name?: string, isRoot = true): ParsedSchema | ParsedSchema[] {
// 最大解析深度
const MAX_PARSE_DEPTH = 4;
// 最大生成深度
const MAX_GENERATE_DEPTH = 3;
// anyOf/oneOf 最大解析选项数量
const MAX_UNION_OPTIONS = 5;
export function parseTypeBox (
schema: TSchema | undefined,
name?: string,
isRoot = true,
visitedIds: Set<string> = new Set(),
depth = 0
): ParsedSchema | ParsedSchema[] {
// 基础检查
if (!schema) {
return isRoot ? [] : { name, type: 'unknown', optional: false };
}
// 如果是根节点解析,且我们需要将其包装在 BaseResponse 中(通常用于 response)
// 但这里我们根据传入的 schema 决定
// 深度限制检查
if (depth > MAX_PARSE_DEPTH) {
return { name, type: 'object', optional: false, description: '...', isCircularRef: true };
}
// $id 循环引用检查
const schemaId = schema.$id;
if (schemaId && visitedIds.has(schemaId)) {
return { name, type: 'object', optional: false, description: `(${schemaId})`, isCircularRef: true };
}
// 创建副本并添加当前 $id
const newVisitedIds = new Set(visitedIds);
if (schemaId) {
newVisitedIds.add(schemaId);
}
const description = schema.description;
const optional = false; // TypeBox schema doesn't store optionality in the same way Zod does, usually handled by parent object
// Handle specific types
const optional = false;
const type = schema.type;
// 常量值
if (schema.const !== undefined) {
return { name, type: 'value', value: schema.const, optional, description };
}
// 枚举
if (schema.enum) {
return { name, type: 'enum', enum: schema.enum, optional, description };
}
// 联合类型 (anyOf/oneOf) - 限制解析的选项数量
if (schema.anyOf || schema.oneOf) {
const options = (schema.anyOf || schema.oneOf) as TSchema[];
const children = options.map(opt => parseTypeBox(opt, undefined, false) as ParsedSchema);
const allOptions = (schema.anyOf || schema.oneOf) as TSchema[];
// 只取前 MAX_UNION_OPTIONS 个选项
const options = allOptions.slice(0, MAX_UNION_OPTIONS);
const children = options.map(opt => parseTypeBox(opt, undefined, false, newVisitedIds, depth + 1) as ParsedSchema);
// 如果有更多选项被截断
if (allOptions.length > MAX_UNION_OPTIONS) {
children.push({
name: undefined,
type: 'object',
optional: false,
description: `... 还有 ${allOptions.length - MAX_UNION_OPTIONS} 个类型`,
isTruncated: true
});
}
return { name, type: 'union', children, optional, description };
}
// allOf 交叉类型
if (schema.allOf) {
const parts = schema.allOf as TSchema[];
// 如果全是对象,尝试合并属性
const allProperties: Record<string, TSchema> = {};
const allRequired: string[] = [];
let canMerge = true;
@@ -64,18 +108,19 @@ export function parseTypeBox (schema: TSchema | undefined, name?: string, isRoot
});
if (canMerge) {
return parseTypeBox({ ...schema, type: 'object', properties: allProperties, required: allRequired }, name, isRoot);
return parseTypeBox({ ...schema, type: 'object', properties: allProperties, required: allRequired }, name, isRoot, newVisitedIds, depth);
}
// 无法简单合并,当作联合展示
const children = parts.map(part => parseTypeBox(part, undefined, false) as ParsedSchema);
const children = parts.slice(0, MAX_UNION_OPTIONS).map(part => parseTypeBox(part, undefined, false, newVisitedIds, depth + 1) as ParsedSchema);
return { name, type: 'intersection', children, optional, description };
}
// 对象类型
if (type === 'object') {
const properties = schema.properties || {};
const required = schema.required || [];
const children = Object.keys(properties).map(key => {
const child = parseTypeBox(properties[key], key, false) as ParsedSchema;
const keys = Object.keys(properties);
const children = keys.map(key => {
const child = parseTypeBox(properties[key], key, false, newVisitedIds, depth + 1) as ParsedSchema;
child.optional = !required.includes(key);
return child;
});
@@ -83,12 +128,17 @@ export function parseTypeBox (schema: TSchema | undefined, name?: string, isRoot
return { name, type: 'object', children, optional, description };
}
// 数组类型
if (type === 'array') {
const items = schema.items as TSchema;
const child = parseTypeBox(items, undefined, false) as ParsedSchema;
return { name, type: 'array', children: [child], optional, description };
if (items) {
const child = parseTypeBox(items, undefined, false, newVisitedIds, depth + 1) as ParsedSchema;
return { name, type: 'array', children: [child], optional, description };
}
return { name, type: 'array', children: [], optional, description };
}
// 基础类型
if (type === 'string') return { name, type: 'string', optional, description };
if (type === 'number' || type === 'integer') return { name, type: 'number', optional, description };
if (type === 'boolean') return { name, type: 'boolean', optional, description };
@@ -97,24 +147,76 @@ export function parseTypeBox (schema: TSchema | undefined, name?: string, isRoot
return { name, type: type || 'unknown', optional, description };
}
export function generateDefaultFromTypeBox (schema: TSchema | undefined): any {
export function generateDefaultFromTypeBox (
schema: TSchema | undefined,
visitedIds: Set<string> = new Set(),
depth = 0
): any {
// 基础检查
if (!schema) return {};
// 深度限制
if (depth > MAX_GENERATE_DEPTH) {
return null;
}
// $id 循环引用检查
const schemaId = schema.$id;
if (schemaId && visitedIds.has(schemaId)) {
return schema.type === 'array' ? [] : schema.type === 'object' ? {} : null;
}
// 创建副本并添加当前 $id
const newVisitedIds = new Set(visitedIds);
if (schemaId) {
newVisitedIds.add(schemaId);
}
// 常量/默认值/枚举
if (schema.const !== undefined) return schema.const;
if (schema.default !== undefined) return schema.default;
if (schema.enum) return schema.enum[0];
if (schema.anyOf || schema.oneOf) return generateDefaultFromTypeBox((schema.anyOf || schema.oneOf)[0]);
// 联合类型 - 优先选择简单类型
if (schema.anyOf || schema.oneOf) {
const options = (schema.anyOf || schema.oneOf) as TSchema[];
// 优先找简单类型
const stringOption = options.find(opt => opt.type === 'string');
if (stringOption) return '';
const numberOption = options.find(opt => opt.type === 'number' || opt.type === 'integer');
if (numberOption) return 0;
const boolOption = options.find(opt => opt.type === 'boolean');
if (boolOption) return false;
// 否则只取第一个
if (options.length > 0) {
return generateDefaultFromTypeBox(options[0], newVisitedIds, depth + 1);
}
return null;
}
const type = schema.type;
// 对象类型
if (type === 'object') {
const obj: any = {};
const props = schema.properties || {};
const required = schema.required || [];
// 只为必填字段和浅层字段生成默认值
for (const key in props) {
// Only generate defaults for required properties or if we want a full example
obj[key] = generateDefaultFromTypeBox(props[key]);
if (required.includes(key) || depth < 1) {
obj[key] = generateDefaultFromTypeBox(props[key], newVisitedIds, depth + 1);
}
}
return obj;
}
if (type === 'array') return [];
// 数组类型 - 返回空数组
if (type === 'array') {
return [];
}
// 基础类型
if (type === 'string') return '';
if (type === 'number' || type === 'integer') return 0;
if (type === 'boolean') return false;
@@ -25,13 +25,15 @@ import {
export type LiteralValue = string | number | boolean | null;
export type ParsedSchema = {
name?: string
type: string | string[]
optional: boolean
value?: LiteralValue
enum?: LiteralValue[]
children?: ParsedSchema[]
description?: string
name?: string;
type: string | string[];
optional: boolean;
value?: LiteralValue;
enum?: LiteralValue[];
children?: ParsedSchema[];
description?: string;
isCircularRef?: boolean; // 标记循环引用
isTruncated?: boolean; // 标记被截断
};
export function parse (
+6 -15
View File
@@ -210,21 +210,11 @@ importers:
specifier: ^1.6.7
version: 1.6.7
packages/napcat-plugin:
dependencies:
napcat-types:
specifier: workspace:*
version: link:../napcat-types
devDependencies:
'@types/node':
specifier: ^22.0.1
version: 22.19.1
packages/napcat-plugin-builtin:
dependencies:
napcat-types:
specifier: 0.0.3
version: 0.0.3
specifier: 0.0.9
version: 0.0.9
devDependencies:
'@types/node':
specifier: ^22.0.1
@@ -5448,8 +5438,8 @@ packages:
engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
hasBin: true
napcat-types@0.0.3:
resolution: {integrity: sha512-YZVBvtIw7N2TRck+JcVAoZJRqcoKf9PbKhHggZ/EcQzTkqGLgu8iIgMfQnCYscgXRglYBPexpb78piaEwlVcjQ==}
napcat-types@0.0.9:
resolution: {integrity: sha512-lhK9SgGotQc58jobqnZEnDTadwcwT/Y62aGCH4hQijdiP2eSiu3YWX2oFFoUJxyIpUKFYAfWJkPUv1YHZ/aaWQ==}
napcat.protobuf@1.1.4:
resolution: {integrity: sha512-z7XtLSBJ/PxmYb0VD/w+eYr/X3LyGz+SZ2QejFTOczwt6zWNxy2yV1mTMTvJoc3BWkI3ESVFRxkuT6+pj1tb1Q==}
@@ -12819,8 +12809,9 @@ snapshots:
nanoid@3.3.11: {}
napcat-types@0.0.3:
napcat-types@0.0.9:
dependencies:
'@sinclair/typebox': 0.34.41
'@types/cors': 2.8.19
'@types/express': 4.17.25
'@types/ip': 1.1.3