feat: 完成DPML协议体系0~1阶段开发 - 三层协议架构100%实现,智能路径检测系统,@package://与package.json完美集成,用户项目集成方案,CLI框架完整实现,132/137核心测试通过(96.3%通过率)

This commit is contained in:
sean
2025-05-31 13:03:26 +08:00
parent 3338b7c21f
commit be285f55b8
89 changed files with 6071 additions and 467 deletions

View File

@ -0,0 +1,505 @@
const path = require('path');
const fs = require('fs');
const fsPromises = require('fs').promises;
const ResourceProtocol = require('./ResourceProtocol');
const { QueryParams } = require('../types');
/**
* 包协议实现
* 实现@package://协议智能检测并访问NPM包资源
* 支持本地开发、npm install、npm -g、npx、monorepo等场景
*/
class PackageProtocol extends ResourceProtocol {
constructor(options = {}) {
super('package', options);
// 包安装模式检测缓存
this.installModeCache = new Map();
}
/**
* 获取协议信息
*/
getProtocolInfo() {
return {
name: this.name,
description: '包协议 - 智能访问NPM包资源支持多种安装模式',
examples: [
'@package://package.json',
'@package://src/index.js',
'@package://docs/README.md',
'@package://prompt/core/thought.md',
'@package://templates/basic/template.md'
],
installModes: [
'development', // 开发模式
'local', // 本地npm install
'global', // 全局npm install -g
'npx', // npx执行
'monorepo', // monorepo workspace
'link' // npm link
]
};
}
/**
* 检测当前包安装模式
*/
detectInstallMode() {
const cacheKey = 'currentInstallMode';
if (this.installModeCache.has(cacheKey)) {
return this.installModeCache.get(cacheKey);
}
const mode = this._performInstallModeDetection();
this.installModeCache.set(cacheKey, mode);
return mode;
}
/**
* 执行安装模式检测
*/
_performInstallModeDetection() {
const cwd = process.cwd();
const execPath = process.argv[0];
const scriptPath = process.argv[1];
// 检测npx执行
if (this._isNpxExecution()) {
return 'npx';
}
// 检测全局安装
if (this._isGlobalInstall()) {
return 'global';
}
// 检测开发模式
if (this._isDevelopmentMode()) {
return 'development';
}
// 检测monorepo
if (this._isMonorepoWorkspace()) {
return 'monorepo';
}
// 检测npm link
if (this._isNpmLink()) {
return 'link';
}
// 默认为本地安装
return 'local';
}
/**
* 检测是否是npx执行
*/
_isNpxExecution() {
// 检查环境变量
if (process.env.npm_execpath && process.env.npm_execpath.includes('npx')) {
return true;
}
// 检查npm_config_cache路径
if (process.env.npm_config_cache && process.env.npm_config_cache.includes('_npx')) {
return true;
}
// 检查执行路径
const scriptPath = process.argv[1];
if (scriptPath && scriptPath.includes('_npx')) {
return true;
}
return false;
}
/**
* 检测是否是全局安装
*/
_isGlobalInstall() {
const currentPath = __dirname;
// 常见全局安装路径
const globalPaths = [
'/usr/lib/node_modules',
'/usr/local/lib/node_modules',
'/opt/homebrew/lib/node_modules',
path.join(process.env.HOME || '', '.npm-global'),
path.join(process.env.APPDATA || '', 'npm', 'node_modules'),
path.join(process.env.PREFIX || '', 'lib', 'node_modules')
];
return globalPaths.some(globalPath =>
currentPath.startsWith(globalPath)
);
}
/**
* 检测是否是开发模式
*/
_isDevelopmentMode() {
// 检查NODE_ENV
if (process.env.NODE_ENV === 'development') {
return true;
}
// 检查是否在node_modules外
const currentPath = __dirname;
if (!currentPath.includes('node_modules')) {
return true;
}
// 检查package.json中的main字段是否指向源文件
try {
const packageJsonPath = this.findPackageJson();
if (packageJsonPath) {
const packageJson = require(packageJsonPath);
const mainFile = packageJson.main || 'index.js';
return mainFile.startsWith('src/') || mainFile.startsWith('lib/');
}
} catch (error) {
// 忽略错误,继续其他检测
}
return false;
}
/**
* 检测是否是monorepo workspace
*/
_isMonorepoWorkspace() {
try {
const packageJsonPath = this.findPackageJson();
if (packageJsonPath) {
const packageJson = require(packageJsonPath);
// 检查workspaces字段
if (packageJson.workspaces) {
return true;
}
// 检查是否在workspace包内
const rootPackageJsonPath = this.findRootPackageJson();
if (rootPackageJsonPath && rootPackageJsonPath !== packageJsonPath) {
const rootPackageJson = require(rootPackageJsonPath);
return !!rootPackageJson.workspaces;
}
}
} catch (error) {
// 忽略错误
}
return false;
}
/**
* 检测是否是npm link
*/
_isNpmLink() {
try {
const currentPath = __dirname;
const stats = require('fs').lstatSync(currentPath);
return stats.isSymbolicLink();
} catch (error) {
return false;
}
}
/**
* 查找package.json文件
*/
findPackageJson(startPath = __dirname) {
let currentPath = path.resolve(startPath);
while (currentPath !== path.parse(currentPath).root) {
const packageJsonPath = path.join(currentPath, 'package.json');
if (require('fs').existsSync(packageJsonPath)) {
return packageJsonPath;
}
currentPath = path.dirname(currentPath);
}
return null;
}
/**
* 查找根package.json文件用于monorepo检测
*/
findRootPackageJson() {
let currentPath = process.cwd();
let lastValidPackageJson = null;
while (currentPath !== path.parse(currentPath).root) {
const packageJsonPath = path.join(currentPath, 'package.json');
if (require('fs').existsSync(packageJsonPath)) {
lastValidPackageJson = packageJsonPath;
}
currentPath = path.dirname(currentPath);
}
return lastValidPackageJson;
}
/**
* 获取包根目录
*/
async getPackageRoot() {
const mode = this.detectInstallMode();
switch (mode) {
case 'development':
// 开发模式:查找项目根目录
return this._findProjectRoot();
case 'global':
// 全局安装:查找全局包目录
return this._findGlobalPackageRoot();
case 'npx':
// npx查找临时包目录
return this._findNpxPackageRoot();
case 'monorepo':
// monorepo查找workspace包目录
return this._findWorkspacePackageRoot();
case 'link':
// npm link解析符号链接
return this._findLinkedPackageRoot();
case 'local':
default:
// 本地安装查找node_modules中的包目录
return this._findLocalPackageRoot();
}
}
/**
* 查找项目根目录
*/
_findProjectRoot() {
const packageJsonPath = this.findPackageJson();
return packageJsonPath ? path.dirname(packageJsonPath) : process.cwd();
}
/**
* 查找全局包根目录
*/
_findGlobalPackageRoot() {
// 从当前模块路径向上查找直到找到package.json
return this._findProjectRoot();
}
/**
* 查找npx包根目录
*/
_findNpxPackageRoot() {
// npx通常将包缓存在特定目录
const packageJsonPath = this.findPackageJson();
return packageJsonPath ? path.dirname(packageJsonPath) : process.cwd();
}
/**
* 查找workspace包根目录
*/
_findWorkspacePackageRoot() {
// 在monorepo中查找当前workspace的根目录
return this._findProjectRoot();
}
/**
* 查找链接包根目录
*/
_findLinkedPackageRoot() {
try {
// 解析符号链接
const realPath = require('fs').realpathSync(__dirname);
const packageJsonPath = this.findPackageJson(realPath);
return packageJsonPath ? path.dirname(packageJsonPath) : realPath;
} catch (error) {
return this._findProjectRoot();
}
}
/**
* 查找本地包根目录
*/
_findLocalPackageRoot() {
// 在node_modules中查找包根目录
return this._findProjectRoot();
}
/**
* 解析路径到具体的文件系统路径
* @param {string} relativePath - 相对于包根目录的路径
* @param {QueryParams} params - 查询参数
* @returns {Promise<string>} 解析后的绝对路径
*/
async resolvePath(relativePath, params = null) {
// 获取包根目录
const packageRoot = await this.getPackageRoot();
// 验证路径是否在package.json的files字段中
this.validateFileAccess(packageRoot, relativePath);
// 直接处理路径,不需要目录映射
const relativePathClean = relativePath.replace(/^\/+/, '');
const fullPath = path.resolve(packageRoot, relativePathClean);
// 安全检查:确保路径在包根目录内
if (!fullPath.startsWith(packageRoot)) {
throw new Error(`Path traversal detected: ${relativePath}`);
}
return fullPath;
}
/**
* 验证文件访问权限基于package.json的files字段
* @param {string} packageRoot - 包根目录
* @param {string} relativePath - 相对路径
*/
validateFileAccess(packageRoot, relativePath) {
try {
const packageJsonPath = path.join(packageRoot, 'package.json');
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
// 如果没有files字段允许访问所有文件开发模式
if (!packageJson.files || !Array.isArray(packageJson.files)) {
return;
}
// 标准化路径
const normalizedPath = relativePath.replace(/^\/+/, '').replace(/\\/g, '/');
// 检查是否匹配files字段中的任何模式
const isAllowed = packageJson.files.some(filePattern => {
// 标准化文件模式
const normalizedPattern = filePattern.replace(/^\/+/, '').replace(/\\/g, '/');
// 精确匹配
if (normalizedPattern === normalizedPath) {
return true;
}
// 目录匹配(以/结尾或包含/*
if (normalizedPattern.endsWith('/') || normalizedPattern.endsWith('/*')) {
const dirPattern = normalizedPattern.replace(/\/?\*?$/, '/');
return normalizedPath.startsWith(dirPattern);
}
// 通配符匹配
if (normalizedPattern.includes('*')) {
const regexPattern = normalizedPattern
.replace(/\./g, '\\.')
.replace(/\*/g, '.*');
const regex = new RegExp(`^${regexPattern}$`);
return regex.test(normalizedPath);
}
// 目录前缀匹配
if (normalizedPath.startsWith(normalizedPattern + '/')) {
return true;
}
return false;
});
if (!isAllowed) {
// 在生产环境严格检查,开发环境只警告
const installMode = this.detectInstallMode();
if (installMode === 'development') {
console.warn(`⚠️ Warning: Path '${relativePath}' not in package.json files field. This may cause issues after publishing.`);
} else {
throw new Error(`Access denied: Path '${relativePath}' is not included in package.json files field`);
}
}
} catch (error) {
// 如果读取package.json失败在开发模式下允许访问
const installMode = this.detectInstallMode();
if (installMode === 'development') {
console.warn(`⚠️ Warning: Could not validate file access for '${relativePath}': ${error.message}`);
} else {
throw error;
}
}
}
/**
* 检查资源是否存在
*/
async exists(resourcePath, queryParams) {
try {
const resolvedPath = await this.resolvePath(resourcePath, queryParams);
await fsPromises.access(resolvedPath);
return true;
} catch (error) {
return false;
}
}
/**
* 加载资源内容
*/
async loadContent(resourcePath, queryParams) {
const resolvedPath = await this.resolvePath(resourcePath, queryParams);
try {
await fsPromises.access(resolvedPath);
const content = await fsPromises.readFile(resolvedPath, 'utf8');
const stats = await fsPromises.stat(resolvedPath);
return {
content,
path: resolvedPath,
protocol: this.name,
installMode: this.detectInstallMode(),
metadata: {
size: content.length,
lastModified: stats.mtime,
absolutePath: resolvedPath,
relativePath: resourcePath
}
};
} catch (error) {
if (error.code === 'ENOENT') {
throw new Error(`包资源不存在: ${resourcePath} (解析为: ${resolvedPath})`);
}
throw new Error(`加载包资源失败: ${error.message}`);
}
}
/**
* 获取调试信息
*/
getDebugInfo() {
const mode = this.detectInstallMode();
return {
protocol: this.name,
installMode: mode,
packageRoot: this.getPackageRoot(),
currentWorkingDirectory: process.cwd(),
moduleDirectory: __dirname,
environment: {
NODE_ENV: process.env.NODE_ENV,
npm_execpath: process.env.npm_execpath,
npm_config_cache: process.env.npm_config_cache
},
cacheSize: this.cache.size
};
}
/**
* 清理缓存
*/
clearCache() {
super.clearCache();
this.installModeCache.clear();
}
}
module.exports = PackageProtocol;

View File

@ -0,0 +1,351 @@
const ResourceProtocol = require('./ResourceProtocol');
const path = require('path');
const fs = require('fs').promises;
/**
* 项目协议实现
* 实现@project://协议,通过查找.promptx目录确定项目根目录
*/
class ProjectProtocol extends ResourceProtocol {
constructor(options = {}) {
super('project', options);
// 支持的项目结构目录映射
this.projectDirs = {
'root': '', // 项目根目录
'src': 'src', // 源代码目录
'lib': 'lib', // 库目录
'build': 'build', // 构建输出目录
'dist': 'dist', // 分发目录
'docs': 'docs', // 文档目录
'test': 'test', // 测试目录
'tests': 'tests', // 测试目录(复数)
'spec': 'spec', // 规范测试目录
'config': 'config', // 配置目录
'scripts': 'scripts', // 脚本目录
'assets': 'assets', // 资源目录
'public': 'public', // 公共资源目录
'static': 'static', // 静态资源目录
'templates': 'templates', // 模板目录
'examples': 'examples', // 示例目录
'tools': 'tools' // 工具目录
};
// 项目根目录缓存
this.projectRootCache = new Map();
}
/**
* 获取协议信息
* @returns {object} 协议信息
*/
getProtocolInfo() {
return {
name: 'project',
description: '项目协议,通过.promptx目录标识提供项目结构访问',
location: 'project://{directory}/{path}',
examples: [
'project://src/index.js',
'project://lib/utils.js',
'project://docs/README.md',
'project://root/package.json',
'project://test/unit/'
],
supportedDirectories: Object.keys(this.projectDirs),
projectMarker: '.promptx',
params: this.getSupportedParams()
};
}
/**
* 支持的查询参数
* @returns {object} 参数说明
*/
getSupportedParams() {
return {
...super.getSupportedParams(),
from: 'string - 指定搜索起始目录',
create: 'boolean - 如果目录不存在是否创建',
exists: 'boolean - 仅返回存在的文件/目录',
type: 'string - 过滤类型 (file|dir|both)'
};
}
/**
* 验证项目协议路径
* @param {string} resourcePath - 资源路径
* @returns {boolean} 是否有效
*/
validatePath(resourcePath) {
if (!super.validatePath(resourcePath)) {
return false;
}
// 解析路径的第一部分(目录类型)
const parts = resourcePath.split('/');
const dirType = parts[0];
return this.projectDirs.hasOwnProperty(dirType);
}
/**
* 向上查找指定目录的同步版本
* @param {string} targetDir - 要查找的目录名(如 '.promptx'
* @param {string} startDir - 开始搜索的目录
* @returns {string|null} 找到的目录路径或null
*/
findUpDirectorySync(targetDir, startDir = process.cwd()) {
let currentDir = path.resolve(startDir);
const rootDir = path.parse(currentDir).root;
while (currentDir !== rootDir) {
const targetPath = path.join(currentDir, targetDir);
try {
const stats = require('fs').statSync(targetPath);
if (stats.isDirectory()) {
return targetPath;
}
} catch (error) {
// 目录不存在,继续向上查找
}
const parentDir = path.dirname(currentDir);
if (parentDir === currentDir) {
// 已到达根目录
break;
}
currentDir = parentDir;
}
return null;
}
/**
* 查找项目根目录
* @param {string} startDir - 开始搜索的目录
* @returns {Promise<string|null>} 项目根目录路径
*/
async findProjectRoot(startDir = process.cwd()) {
// 检查缓存
const cacheKey = path.resolve(startDir);
if (this.projectRootCache.has(cacheKey)) {
return this.projectRootCache.get(cacheKey);
}
try {
// 使用自实现的向上查找
const promptxPath = this.findUpDirectorySync('.promptx', startDir);
let projectRoot = null;
if (promptxPath) {
// .promptx 目录的父目录就是项目根目录
projectRoot = path.dirname(promptxPath);
}
// 缓存结果
this.projectRootCache.set(cacheKey, projectRoot);
return projectRoot;
} catch (error) {
throw new Error(`查找项目根目录失败: ${error.message}`);
}
}
/**
* 解析项目路径
* @param {string} resourcePath - 原始资源路径,如 "src/index.js"
* @param {QueryParams} queryParams - 查询参数
* @returns {Promise<string>} 解析后的绝对路径
*/
async resolvePath(resourcePath, queryParams) {
const parts = resourcePath.split('/');
const dirType = parts[0];
const relativePath = parts.slice(1).join('/');
// 验证目录类型
if (!this.projectDirs.hasOwnProperty(dirType)) {
throw new Error(`不支持的项目目录类型: ${dirType}。支持的类型: ${Object.keys(this.projectDirs).join(', ')}`);
}
// 确定搜索起始点
const startDir = queryParams?.get('from') || process.cwd();
// 查找项目根目录
const projectRoot = await this.findProjectRoot(startDir);
if (!projectRoot) {
throw new Error(`未找到项目根目录(.promptx标识。请确保在项目目录内或使用 'from' 参数指定项目路径`);
}
// 构建目标目录路径
const projectDirPath = this.projectDirs[dirType];
const targetDir = projectDirPath ? path.join(projectRoot, projectDirPath) : projectRoot;
// 如果没有相对路径,返回目录本身
if (!relativePath) {
return targetDir;
}
// 拼接完整路径
const fullPath = path.join(targetDir, relativePath);
// 安全检查:确保路径在项目目录内
const resolvedPath = path.resolve(fullPath);
const resolvedProjectRoot = path.resolve(projectRoot);
if (!resolvedPath.startsWith(resolvedProjectRoot)) {
throw new Error(`安全错误:路径超出项目目录范围: ${resolvedPath}`);
}
return resolvedPath;
}
/**
* 加载资源内容
* @param {string} resolvedPath - 解析后的路径
* @param {QueryParams} queryParams - 查询参数
* @returns {Promise<string>} 资源内容
*/
async loadContent(resolvedPath, queryParams) {
try {
// 检查路径是否存在
const stats = await fs.stat(resolvedPath);
if (stats.isDirectory()) {
return await this.loadDirectoryContent(resolvedPath, queryParams);
} else if (stats.isFile()) {
return await this.loadFileContent(resolvedPath, queryParams);
} else {
throw new Error(`不支持的文件类型: ${resolvedPath}`);
}
} catch (error) {
if (error.code === 'ENOENT') {
// 检查是否需要创建目录
if (queryParams?.get('create') === 'true') {
await fs.mkdir(path.dirname(resolvedPath), { recursive: true });
return ''; // 返回空内容
}
// 如果设置了exists参数为false返回空内容而不是错误
if (queryParams?.get('exists') === 'false') {
return '';
}
throw new Error(`文件或目录不存在: ${resolvedPath}`);
}
throw error;
}
}
/**
* 加载文件内容
* @param {string} filePath - 文件路径
* @param {QueryParams} queryParams - 查询参数
* @returns {Promise<string>} 文件内容
*/
async loadFileContent(filePath, queryParams) {
const encoding = queryParams?.get('encoding') || 'utf8';
return await fs.readFile(filePath, encoding);
}
/**
* 加载目录内容
* @param {string} dirPath - 目录路径
* @param {QueryParams} queryParams - 查询参数
* @returns {Promise<string>} 目录内容列表
*/
async loadDirectoryContent(dirPath, queryParams) {
const entries = await fs.readdir(dirPath, { withFileTypes: true });
// 应用类型过滤
const typeFilter = queryParams?.get('type');
let filteredEntries = entries;
if (typeFilter) {
filteredEntries = entries.filter(entry => {
switch (typeFilter) {
case 'file': return entry.isFile();
case 'dir': return entry.isDirectory();
case 'both': return true;
default: return true;
}
});
}
// 格式化输出
const format = queryParams?.get('format') || 'list';
switch (format) {
case 'json':
return JSON.stringify(
filteredEntries.map(entry => ({
name: entry.name,
type: entry.isDirectory() ? 'directory' : 'file',
path: path.join(dirPath, entry.name)
})),
null,
2
);
case 'paths':
return filteredEntries
.map(entry => path.join(dirPath, entry.name))
.join('\n');
case 'list':
default:
return filteredEntries
.map(entry => {
const type = entry.isDirectory() ? '[DIR]' : '[FILE]';
return `${type} ${entry.name}`;
})
.join('\n');
}
}
/**
* 列出项目结构信息
* @param {string} startDir - 开始搜索的目录
* @returns {Promise<object>} 项目信息
*/
async getProjectInfo(startDir = process.cwd()) {
const projectRoot = await this.findProjectRoot(startDir);
if (!projectRoot) {
return { error: '未找到项目根目录' };
}
const result = {
projectRoot,
promptxPath: path.join(projectRoot, '.promptx'),
directories: {}
};
for (const [dirType, dirPath] of Object.entries(this.projectDirs)) {
const fullPath = dirPath ? path.join(projectRoot, dirPath) : projectRoot;
try {
const stats = await fs.stat(fullPath);
result.directories[dirType] = {
path: fullPath,
exists: true,
type: stats.isDirectory() ? 'directory' : 'file'
};
} catch (error) {
result.directories[dirType] = {
path: fullPath,
exists: false
};
}
}
return result;
}
/**
* 清除缓存
*/
clearCache() {
super.clearCache();
this.projectRootCache.clear();
}
}
module.exports = ProjectProtocol;

View File

@ -0,0 +1,208 @@
/**
* 资源协议接口基类
* 定义所有DPML资源协议的统一规范
*/
class ResourceProtocol {
/**
* 构造函数
* @param {string} name - 协议名称
* @param {object} options - 配置选项
*/
constructor(name, options = {}) {
if (new.target === ResourceProtocol) {
throw new Error('ResourceProtocol是抽象类不能直接实例化');
}
this.name = name;
this.options = options;
this.cache = new Map();
this.enableCache = options.enableCache !== false;
}
/**
* 协议信息 - 需要子类实现
* @returns {object} 协议信息
*/
getProtocolInfo() {
throw new Error('子类必须实现 getProtocolInfo() 方法');
}
/**
* 解析资源路径 - 需要子类实现
* @param {string} resourcePath - 原始资源路径
* @param {QueryParams} queryParams - 查询参数
* @returns {Promise<string>} 解析后的路径
*/
async resolvePath(resourcePath, queryParams) {
throw new Error('子类必须实现 resolvePath() 方法');
}
/**
* 加载资源内容 - 需要子类实现
* @param {string} resolvedPath - 解析后的路径
* @param {QueryParams} queryParams - 查询参数
* @returns {Promise<string>} 资源内容
*/
async loadContent(resolvedPath, queryParams) {
throw new Error('子类必须实现 loadContent() 方法');
}
/**
* 验证资源路径格式 - 可选实现
* @param {string} resourcePath - 资源路径
* @returns {boolean} 是否有效
*/
validatePath(resourcePath) {
return typeof resourcePath === 'string' && resourcePath.length > 0;
}
/**
* 支持的查询参数列表 - 可选实现
* @returns {object} 参数说明
*/
getSupportedParams() {
return {
line: 'string - 行范围,如 "1-10"',
format: 'string - 输出格式',
cache: 'boolean - 是否缓存'
};
}
/**
* 统一的资源解析入口点
* @param {string} resourcePath - 资源路径
* @param {QueryParams} queryParams - 查询参数
* @returns {Promise<string>} 资源内容
*/
async resolve(resourcePath, queryParams) {
// 1. 验证路径格式
if (!this.validatePath(resourcePath)) {
throw new Error(`无效的资源路径: ${resourcePath}`);
}
// 2. 生成缓存键
const cacheKey = this.generateCacheKey(resourcePath, queryParams);
// 3. 检查缓存
if (this.enableCache && this.cache.has(cacheKey)) {
return this.cache.get(cacheKey);
}
// 4. 解析路径
const resolvedPath = await this.resolvePath(resourcePath, queryParams);
// 5. 加载内容
const content = await this.loadContent(resolvedPath, queryParams);
// 6. 应用通用查询参数过滤
const filteredContent = this.applyCommonParams(content, queryParams);
// 7. 缓存结果
if (this.enableCache) {
this.cache.set(cacheKey, filteredContent);
}
return filteredContent;
}
/**
* 生成缓存键
* @param {string} resourcePath - 资源路径
* @param {QueryParams} queryParams - 查询参数
* @returns {string} 缓存键
*/
generateCacheKey(resourcePath, queryParams) {
const params = queryParams ? queryParams.getAll() : {};
return `${this.name}:${resourcePath}:${JSON.stringify(params)}`;
}
/**
* 应用通用查询参数
* @param {string} content - 原始内容
* @param {QueryParams} queryParams - 查询参数
* @returns {string} 过滤后的内容
*/
applyCommonParams(content, queryParams) {
if (!queryParams) {
return content;
}
let result = content;
// 应用行过滤
if (queryParams.line) {
result = this.applyLineFilter(result, queryParams.line);
}
// 应用格式化(基础实现,子类可以重写)
if (queryParams.format && queryParams.format !== 'text') {
result = this.applyFormat(result, queryParams.format);
}
return result;
}
/**
* 应用行过滤
* @param {string} content - 内容
* @param {string} lineRange - 行范围,如 "5-10" 或 "5"
* @returns {string} 过滤后的内容
*/
applyLineFilter(content, lineRange) {
const lines = content.split('\n');
if (lineRange.includes('-')) {
const [start, end] = lineRange.split('-').map(n => parseInt(n.trim(), 10));
const startIndex = Math.max(0, start - 1);
const endIndex = Math.min(lines.length, end);
return lines.slice(startIndex, endIndex).join('\n');
} else {
const lineNum = parseInt(lineRange, 10);
const lineIndex = lineNum - 1;
return lines[lineIndex] || '';
}
}
/**
* 应用格式化
* @param {string} content - 内容
* @param {string} format - 格式
* @returns {string} 格式化后的内容
*/
applyFormat(content, format) {
// 基础实现,子类可以重写
switch (format) {
case 'json':
try {
return JSON.stringify(JSON.parse(content), null, 2);
} catch {
return content;
}
case 'trim':
return content.trim();
default:
return content;
}
}
/**
* 清除缓存
*/
clearCache() {
this.cache.clear();
}
/**
* 获取缓存统计
* @returns {object} 缓存统计信息
*/
getCacheStats() {
return {
protocol: this.name,
size: this.cache.size,
enabled: this.enableCache
};
}
}
module.exports = ResourceProtocol;

View File

@ -0,0 +1,299 @@
const ResourceProtocol = require('./ResourceProtocol');
const path = require('path');
const fs = require('fs').promises;
// 延迟加载platform-folders以处理可能的原生模块依赖
let platformFolders = null;
const getPlatformFolders = () => {
if (!platformFolders) {
try {
platformFolders = require('platform-folders');
} catch (error) {
// 如果platform-folders不可用回退到os.homedir()
const os = require('os');
platformFolders = {
getHomeFolder: () => os.homedir(),
getDesktopFolder: () => path.join(os.homedir(), 'Desktop'),
getDocumentsFolder: () => path.join(os.homedir(), 'Documents'),
getDownloadsFolder: () => path.join(os.homedir(), 'Downloads'),
getMusicFolder: () => path.join(os.homedir(), 'Music'),
getPicturesFolder: () => path.join(os.homedir(), 'Pictures'),
getVideosFolder: () => path.join(os.homedir(), 'Videos')
};
console.warn('platform-folders不可用使用os.homedir()回退方案');
}
}
return platformFolders;
};
/**
* 用户目录协议实现
* 实现@user://协议用于访问用户的标准目录Documents、Desktop、Downloads等
*/
class UserProtocol extends ResourceProtocol {
constructor(options = {}) {
super('user', options);
// 支持的用户目录映射
this.userDirs = {
'home': 'getHomeFolder',
'desktop': 'getDesktopFolder',
'documents': 'getDocumentsFolder',
'downloads': 'getDownloadsFolder',
'music': 'getMusicFolder',
'pictures': 'getPicturesFolder',
'videos': 'getVideosFolder'
};
// 目录路径缓存
this.dirCache = new Map();
}
/**
* 获取协议信息
* @returns {object} 协议信息
*/
getProtocolInfo() {
return {
name: 'user',
description: '用户目录协议,提供跨平台的用户标准目录访问',
location: 'user://{directory}/{path}',
examples: [
'user://documents/notes.txt',
'user://desktop/readme.md',
'user://downloads/',
'user://home/.bashrc'
],
supportedDirectories: Object.keys(this.userDirs),
params: this.getSupportedParams()
};
}
/**
* 支持的查询参数
* @returns {object} 参数说明
*/
getSupportedParams() {
return {
...super.getSupportedParams(),
exists: 'boolean - 仅返回存在的文件/目录',
type: 'string - 过滤类型 (file|dir|both)'
};
}
/**
* 验证用户协议路径
* @param {string} resourcePath - 资源路径
* @returns {boolean} 是否有效
*/
validatePath(resourcePath) {
if (!super.validatePath(resourcePath)) {
return false;
}
// 解析路径的第一部分(目录类型)
const parts = resourcePath.split('/');
const dirType = parts[0];
return this.userDirs.hasOwnProperty(dirType);
}
/**
* 解析用户目录路径
* @param {string} resourcePath - 原始资源路径,如 "documents/notes.txt"
* @param {QueryParams} queryParams - 查询参数
* @returns {Promise<string>} 解析后的绝对路径
*/
async resolvePath(resourcePath, queryParams) {
const parts = resourcePath.split('/');
const dirType = parts[0];
const relativePath = parts.slice(1).join('/');
// 验证目录类型
if (!this.userDirs[dirType]) {
throw new Error(`不支持的用户目录类型: ${dirType}。支持的类型: ${Object.keys(this.userDirs).join(', ')}`);
}
// 获取用户目录路径
const userDirPath = await this.getUserDirectory(dirType);
// 如果没有相对路径,返回目录本身
if (!relativePath) {
return userDirPath;
}
// 拼接完整路径
const fullPath = path.join(userDirPath, relativePath);
// 安全检查:确保路径在用户目录内
const resolvedPath = path.resolve(fullPath);
const resolvedUserDir = path.resolve(userDirPath);
if (!resolvedPath.startsWith(resolvedUserDir)) {
throw new Error(`安全错误:路径超出用户目录范围: ${resolvedPath}`);
}
return resolvedPath;
}
/**
* 获取用户目录路径
* @param {string} dirType - 目录类型
* @returns {Promise<string>} 目录路径
*/
async getUserDirectory(dirType) {
// 检查缓存
if (this.dirCache.has(dirType)) {
return this.dirCache.get(dirType);
}
const folders = getPlatformFolders();
const methodName = this.userDirs[dirType];
if (!folders[methodName]) {
throw new Error(`未找到用户目录获取方法: ${methodName}`);
}
try {
let dirPath;
// 调用platform-folders方法
if (typeof folders[methodName] === 'function') {
dirPath = await folders[methodName]();
} else {
dirPath = folders[methodName];
}
// 缓存结果
this.dirCache.set(dirType, dirPath);
return dirPath;
} catch (error) {
throw new Error(`获取用户目录失败 (${dirType}): ${error.message}`);
}
}
/**
* 加载资源内容
* @param {string} resolvedPath - 解析后的路径
* @param {QueryParams} queryParams - 查询参数
* @returns {Promise<string>} 资源内容
*/
async loadContent(resolvedPath, queryParams) {
try {
// 检查路径是否存在
const stats = await fs.stat(resolvedPath);
if (stats.isDirectory()) {
return await this.loadDirectoryContent(resolvedPath, queryParams);
} else if (stats.isFile()) {
return await this.loadFileContent(resolvedPath, queryParams);
} else {
throw new Error(`不支持的文件类型: ${resolvedPath}`);
}
} catch (error) {
if (error.code === 'ENOENT') {
// 如果设置了exists参数为false返回空内容而不是错误
if (queryParams && queryParams.get('exists') === 'false') {
return '';
}
throw new Error(`文件或目录不存在: ${resolvedPath}`);
}
throw error;
}
}
/**
* 加载文件内容
* @param {string} filePath - 文件路径
* @param {QueryParams} queryParams - 查询参数
* @returns {Promise<string>} 文件内容
*/
async loadFileContent(filePath, queryParams) {
const encoding = queryParams?.get('encoding') || 'utf8';
return await fs.readFile(filePath, encoding);
}
/**
* 加载目录内容
* @param {string} dirPath - 目录路径
* @param {QueryParams} queryParams - 查询参数
* @returns {Promise<string>} 目录内容列表
*/
async loadDirectoryContent(dirPath, queryParams) {
const entries = await fs.readdir(dirPath, { withFileTypes: true });
// 应用类型过滤
const typeFilter = queryParams?.get('type');
let filteredEntries = entries;
if (typeFilter) {
filteredEntries = entries.filter(entry => {
switch (typeFilter) {
case 'file': return entry.isFile();
case 'dir': return entry.isDirectory();
case 'both': return true;
default: return true;
}
});
}
// 格式化输出
const format = queryParams?.get('format') || 'list';
switch (format) {
case 'json':
return JSON.stringify(
filteredEntries.map(entry => ({
name: entry.name,
type: entry.isDirectory() ? 'directory' : 'file',
path: path.join(dirPath, entry.name)
})),
null,
2
);
case 'paths':
return filteredEntries
.map(entry => path.join(dirPath, entry.name))
.join('\n');
case 'list':
default:
return filteredEntries
.map(entry => {
const type = entry.isDirectory() ? '[DIR]' : '[FILE]';
return `${type} ${entry.name}`;
})
.join('\n');
}
}
/**
* 列出所有支持的用户目录
* @returns {Promise<object>} 目录信息
*/
async listUserDirectories() {
const result = {};
for (const dirType of Object.keys(this.userDirs)) {
try {
result[dirType] = await this.getUserDirectory(dirType);
} catch (error) {
result[dirType] = { error: error.message };
}
}
return result;
}
/**
* 清除目录缓存
*/
clearCache() {
super.clearCache();
this.dirCache.clear();
}
}
module.exports = UserProtocol;