Compare commits

..
65 Commits
Author SHA1 Message Date
xiaojunnuo 255960d434 feat: 支持在线插件下载安装审核等 2026-08-02 00:46:29 +08:00
xiaojunnuo a237179a72 Merge remote-tracking branch 'origin/v2-dev' into v2_audit_log 2026-07-26 20:37:28 +08:00
xiaojunnuo 967846bef5 perf(tencent-clb): 为腾讯云CLB部署插件支持远程选择输入
- 重构插件输入配置,使用createRemoteSelectInputDefine统一封装远程选择组件
- 新增onGetCLBList、onGetListenerList、onGetDomainList方法实现数据拉取和格式转换
- 补全完整的单元测试用例,覆盖输入配置校验和数据映射逻辑
2026-07-26 19:01:18 +08:00
xiaojunnuo 0bf9a2d3da chore: plugin 有store page版本 2026-07-25 13:46:11 +08:00
xiaojunnuo 18b2d3ac20 perf: 优化第三方依赖安装失败日志输出 2026-07-23 18:35:04 +08:00
xiaojunnuo 7d22fe3d7d perf: 优化SqliteError: disk I/O error报错修复提示 2026-07-23 10:49:00 +08:00
xiaojunnuo ee67b6c042 Merge branch 'v2-dev' of https://github.com/certd/certd into v2-dev 2026-07-21 14:13:16 +08:00
xiaojunnuo 1cfa76683b perf: 优化宝塔报错提示 2026-07-21 14:13:07 +08:00
xiaojunnuo 4662e45e58 build: release 2026-07-19 01:28:05 +08:00
xiaojunnuo 1fefbdc9ab build: publish 2026-07-19 01:14:35 +08:00
xiaojunnuo 1cb2a57c55 build: trigger build image 2026-07-19 01:14:24 +08:00
xiaojunnuo 246ee83015 v1.42.6 2026-07-19 01:13:42 +08:00
xiaojunnuo 335ddfc7a5 build: prepare to build 2026-07-19 01:12:01 +08:00
xiaojunnuo 5b500830a1 fix: 修复正常批量删除流水线报权限不足的bug 2026-07-19 01:05:03 +08:00
xiaojunnuo ce4839bd80 chore: 完善审计日志 2026-07-19 00:49:38 +08:00
xiaojunnuo eee22154e3 chore: 1 2026-07-18 23:52:34 +08:00
xiaojunnuo 49007d3915 perf: 统一镜像地址格式 certd/certd 2026-07-18 23:51:24 +08:00
xiaojunnuo f9b453ca8c Merge remote-tracking branch 'origin/v2-dev' into v2_audit_log 2026-07-18 21:28:30 +08:00
xiaojunnuo 5f53b81c75 perf: 优化动态加载依赖镜像地址,多次重试 2026-07-18 21:07:56 +08:00
xiaojunnuo 9d83adaac8 chore: 1 2026-07-18 19:58:16 +08:00
xiaojunnuo c8c269f612 chore: 1 2026-07-17 15:44:23 +08:00
xiaojunnuo 15740904e5 perf: 增加稳定版,预览版区分,预览版是最新版,稳定版在预览版验证稳定后,再将预览版转为稳定版 2026-07-17 00:58:19 +08:00
xiaojunnuo 85e9ff7a96 Merge branch 'v2-dev' into v2_audit_log 2026-07-16 22:19:04 +08:00
xiaojunnuo 743617dbda build: release 2026-07-15 23:54:59 +08:00
xiaojunnuo 89806b828a build: publish 2026-07-15 23:35:15 +08:00
xiaojunnuo 2e530bfdb0 build: trigger build image 2026-07-15 23:35:05 +08:00
xiaojunnuo 83495b3213 v1.42.5 2026-07-15 23:34:16 +08:00
xiaojunnuo 5108416904 build: prepare to build 2026-07-15 23:31:35 +08:00
xiaojunnuo 5589da1822 chore: 修复单元测试 2026-07-15 23:30:49 +08:00
xiaojunnuo 21e5aed3f3 chore: 修复单元测试的问题 2026-07-15 23:25:28 +08:00
xiaojunnuo 4a88f795e1 chore: vke kubeconfig 有效期校验 2026-07-15 23:10:58 +08:00
xiaojunnuo 604fa5be63 perf: 优化vke keubconfig获取方式,改成先查询,如果没有再创建临时config 2026-07-15 23:01:32 +08:00
xiaojunnuo 7ed1be994f fix: 修复dingtalk通知格式没有换行的bug 2026-07-15 23:00:42 +08:00
xiaojunnuo 6cc74a1c0a chore: lint 2026-07-15 01:25:55 +08:00
xiaojunnuo 167b303fae fix: 修复上传到cos报runtimeDepsService未初始化的问题 2026-07-15 01:09:57 +08:00
xiaojunnuo b91c9e4ea6 perf: 给SQLITE_IOERR_WRITE增加友好报错提示,将certd:latest镜像改为certd:slim 2026-07-14 21:32:32 +08:00
xiaojunnuo 947fe729cb chore: 继续完善审计日志 2026-07-13 00:53:19 +08:00
xiaojunnuo bfb3ee4c43 chore: 登录失败也记录日志 2026-07-12 22:28:51 +08:00
xiaojunnuo bab1df2c78 chore(i18n): add permanent VIP label and handle permanent VIP case
为国际化多语言添加永久VIP的翻译文本,同时在激活成功弹窗中处理永久会员的过期日期显示逻辑,当过期时间为-1时显示永久而非固定日期
2026-07-12 17:37:25 +08:00
xiaojunnuo 00eabec771 Merge branch 'v2-dev' into v2_audit_log 2026-07-12 17:28:21 +08:00
xiaojunnuo 584b7b6f45 build: release 2026-07-12 03:41:59 +08:00
xiaojunnuo 2312c444ef build: release 2026-07-12 03:36:09 +08:00
xiaojunnuo 0373d019f8 Merge branch 'v2-dev' of https://github.com/certd/certd into v2-dev 2026-07-12 03:11:04 +08:00
xiaojunnuo fe09e75b80 refactor(nginx-proxy-manager): 替换直接动态导入为运行时依赖导入
将插件中直接使用的动态导入改为通过runtimeDepsService统一处理,同时重构导入方式为runtimeImport变量,移除冗余的form-data和otplib直接导入,统一导入逻辑
2026-07-12 03:10:52 +08:00
xiaojunnuo 432c9c6cc1 build: publish 2026-07-12 02:48:34 +08:00
xiaojunnuo 5fc1d55879 build: trigger build image 2026-07-12 02:48:22 +08:00
xiaojunnuo 268cd6cc9c v1.42.4 2026-07-12 02:47:26 +08:00
xiaojunnuo 20ffe31638 build: prepare to build 2026-07-12 02:45:04 +08:00
xiaojunnuo 02d30067ea chore: 1 2026-07-12 02:44:16 +08:00
xiaojunnuo 0ce7808e08 build: prepare to build 2026-07-12 02:39:50 +08:00
xiaojunnuo d609ee2b7a chore(base-service): 完善batchDelete方法的返回类型并添加返回值
为batchDelete方法添加明确的Promise<number>返回类型,同时返回实际删除的id数量
2026-07-12 02:38:49 +08:00
xiaojunnuo 083df61fcc build: prepare to build 2026-07-12 02:33:34 +08:00
xiaojunnuo a524988be6 chore: 1 2026-07-12 02:32:49 +08:00
xiaojunnuo f2855d6dac feat: 支持审计日志,操作日志 2026-07-12 02:29:54 +08:00
xiaojunnuo 8517a0b564 refactor(certd-server): 移除非运行时依赖到动态导入
将alipay-sdk、openid-client、otplib、wechatpay-node-v3改为动态导入,从dependencies移到devDependencies?不,是改为通过importRuntime动态加载,移除顶层静态引入,优化启动时依赖加载,减少初始包体积和启动耗时
2026-07-12 00:04:06 +08:00
xiaojunnuo ec69b8f11b fix(pipeline): 重构运行时依赖加载逻辑,修复火山引擎DNS解析报runtimeDepsService未初始化的bug 2026-07-11 23:40:13 +08:00
xiaojunnuo 4250d0e266 chore: audit log first 2026-07-10 19:24:42 +08:00
xiaojunnuo edda1b57f3 chore: 火山vod 上传后等待3秒 2026-07-09 19:09:08 +08:00
xiaojunnuo 5a7766992d chore: 修复update domain传参问题 2026-07-09 16:42:48 +08:00
xiaojunnuo 02dabe11db fix: 修复火山引擎查不到自定义源站域名的问题 2026-07-09 16:39:08 +08:00
xiaojunnuo 58024128d8 Merge branch 'v2-dev' of https://github.com/certd/certd into v2-dev 2026-07-09 14:47:33 +08:00
xiaojunnuo e44bf9d773 fix: 修复火山引擎自定义源站域名查询不到的问题 2026-07-09 14:47:05 +08:00
xiaojunnuo 1114223bda build: release 2026-07-09 00:00:53 +08:00
xiaojunnuo 55022e5fa6 build: publish 2026-07-08 23:48:41 +08:00
xiaojunnuo ae732fb298 build: trigger build image 2026-07-08 23:48:29 +08:00
252 changed files with 10026 additions and 3908 deletions
+8 -4
View File
@@ -105,8 +105,10 @@ jobs:
tags: |
registry.cn-shenzhen.aliyuncs.com/handsfree/certd:slim
registry.cn-shenzhen.aliyuncs.com/handsfree/certd:${{steps.get_certd_version.outputs.result}}-slim
greper/certd:slim
greper/certd:${{steps.get_certd_version.outputs.result}}-slim
registry.cn-shenzhen.aliyuncs.com/certd/certd:slim
registry.cn-shenzhen.aliyuncs.com/certd/certd:${{steps.get_certd_version.outputs.result}}-slim
certd/certd:slim
certd/certd:${{steps.get_certd_version.outputs.result}}-slim
ghcr.io/${{ github.repository }}:slim
ghcr.io/${{ github.repository }}:${{steps.get_certd_version.outputs.result}}-slim
@@ -119,8 +121,10 @@ jobs:
tags: |
registry.cn-shenzhen.aliyuncs.com/handsfree/certd:armv7
registry.cn-shenzhen.aliyuncs.com/handsfree/certd:${{steps.get_certd_version.outputs.result}}-armv7
greper/certd:armv7
greper/certd:${{steps.get_certd_version.outputs.result}}-armv7
registry.cn-shenzhen.aliyuncs.com/certd/certd:armv7
registry.cn-shenzhen.aliyuncs.com/certd/certd:${{steps.get_certd_version.outputs.result}}-armv7
certd/certd:armv7
certd/certd:${{steps.get_certd_version.outputs.result}}-armv7
ghcr.io/${{ github.repository }}:armv7
ghcr.io/${{ github.repository }}:${{steps.get_certd_version.outputs.result}}-armv7
+88
View File
@@ -0,0 +1,88 @@
name: stable-release
on:
workflow_dispatch:
inputs:
version:
description: "版本号(如 v1.42.5"
required: true
type: string
permissions:
contents: read
packages: write
jobs:
make-stable:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Login to aliyun container Registry
uses: docker/login-action@v3
with:
registry: registry.cn-shenzhen.aliyuncs.com
username: ${{ secrets.aliyun_cs_username }}
password: ${{ secrets.aliyun_cs_password }}
- name: Login to GitHub Packages
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Login to Docker Hub
uses: docker/login-action@v3
with:
username: ${{ secrets.dockerhub_username }}
password: ${{ secrets.dockerhub_password }}
# stable 镜像:叠加 ENV 层
- name: Build and push stable images
run: |
echo "FROM greper/certd:${{ inputs.version }}
ENV certd_release_mode=stable" > Dockerfile.stable
docker buildx build \
--platform linux/amd64,linux/arm64 \
--push \
-f Dockerfile.stable \
-t registry.cn-shenzhen.aliyuncs.com/handsfree/certd:stable \
-t registry.cn-shenzhen.aliyuncs.com/handsfree/certd:${{ inputs.version }}-stable \
-t registry.cn-shenzhen.aliyuncs.com/certd/certd:stable \
-t registry.cn-shenzhen.aliyuncs.com/certd/certd:${{ inputs.version }}-stable \
-t certd/certd:stable \
-t certd/certd:${{ inputs.version }}-stable \
-t ghcr.io/${{ github.repository }}:stable \
-t ghcr.io/${{ github.repository }}:${{ inputs.version }}-stable \
.
# slim-stable 镜像
- name: Build and push slim-stable images
run: |
echo "FROM greper/certd:${{ inputs.version }}-slim
ENV certd_release_mode=stable" > Dockerfile.slim-stable
docker buildx build \
--platform linux/amd64,linux/arm64 \
--push \
-f Dockerfile.slim-stable \
-t registry.cn-shenzhen.aliyuncs.com/handsfree/certd:slim-stable \
-t registry.cn-shenzhen.aliyuncs.com/handsfree/certd:${{ inputs.version }}-slim-stable \
-t registry.cn-shenzhen.aliyuncs.com/certd/certd:slim-stable \
-t registry.cn-shenzhen.aliyuncs.com/certd/certd:${{ inputs.version }}-slim-stable \
-t certd/certd:slim-stable \
-t certd/certd:${{ inputs.version }}-slim-stable \
-t ghcr.io/${{ github.repository }}:slim-stable \
-t ghcr.io/${{ github.repository }}:${{ inputs.version }}-slim-stable \
.
- name: Set AtomGit release as stable
run: |
export ATOMGIT_TOKEN=${{ secrets.ATOMGIT_TOKEN }}
export VERSION=${{ inputs.version }}
npm run set-release-stable
@@ -1,412 +0,0 @@
# 插件依赖按需加载方案
## 背景与目标
### 当前问题
- `packages/ui/certd-server/node_modules` 包含 50+ 个插件的所有依赖,体积庞大
- 大量云厂商 SDK(AWS、阿里云、腾讯云、华为云等)只在特定插件中使用
- 用户通常只使用少数几个插件,但必须安装所有依赖
### 目标
实现依赖的按需下载和加载:
1. 插件依赖独立管理,不占用主 `node_modules` 空间
2. 只有当用户首次使用某插件时,才动态下载该插件需要的依赖
3. 依赖安装完成后,通过 `await import()` 从独立路径加载
4. 保持现有插件代码的最小改动
## 当前架构分析
### 插件加载机制
- 插件位于 `packages/ui/certd-server/src/plugins/` 下(50+ 个插件目录)
- `AutoLoadPlugins` 类在启动时扫描 `dist/plugins` 目录并动态导入
- 插件注册到不同的 registry`accessRegistry`, `pluginRegistry`, `dnsProviderRegistry`
- 插件代码已经使用 `await import()` 进行懒加载(如 `await import("@aws-sdk/client-acm")`
### 重型依赖分布
`packages/ui/certd-server/package.json` 分析,以下依赖体积大且仅特定插件使用:
**云厂商 SDK(按插件分组):**
- **AWS 插件**`@aws-sdk/client-acm`, `@aws-sdk/client-cloudfront`, `@aws-sdk/client-iam`, `@aws-sdk/client-route-53`, `@aws-sdk/client-s3`, `@aws-sdk/client-sts`
- **阿里云插件**`@alicloud/openapi-client`, `@alicloud/pop-core`, `@alicloud/tea-typescript`, `@alicloud/fc20230330`
- **腾讯云插件**`tencentcloud-sdk-nodejs`, `cos-nodejs-sdk-v5`
- **华为云插件**`@huaweicloud/huaweicloud-sdk-cdn`, `@huaweicloud/huaweicloud-sdk-core`
- **Azure 插件**`@azure/arm-dns`, `@azure/identity`
- **Google Cloud 插件**`@google-cloud/dns`, `@google-cloud/publicca`
- **火山引擎插件**`@volcengine/openapi`, `@volcengine/tos-sdk`
**网络/工具库:**
- `ssh2`, `socks`, `socks-proxy-agent`SSH 相关插件)
- `ali-oss`, `qiniu`, `basic-ftp`(存储/传输插件)
- `nodemailer`(邮件通知插件)
**通用依赖(保留在主 package.json):**
- `@midwayjs/*` 系列(框架核心)
- `@certd/*` 系列(项目内部包)
- `axios`, `lodash-es`, `dayjs`, `js-yaml` 等基础工具
## 设计方案
### 架构概览
```
packages/ui/certd-server/
├── package.json # 主依赖(框架、通用工具)
├── node_modules/ # 主依赖安装目录
├── optional-deps/ # 新增:可选依赖管理目录
│ ├── package.json # 可选依赖总配置(用于 pnpm install
│ ├── pnpm-lock.yaml # 可选依赖锁文件
│ └── node_modules/ # 可选依赖安装目录
├── src/
│ └── modules/
│ └── dependency/ # 新增:依赖管理模块
│ ├── dependency-manager.ts # 核心:依赖管理器
│ ├── dependency-registry.ts # 依赖注册表(插件 -> 依赖映射)
│ └── types.ts # 类型定义
```
### 核心组件
#### 1. 依赖管理器(DependencyManager
**职责:**
- 检查依赖是否已安装
- 动态执行 `pnpm install` 安装缺失依赖
- 提供从 `optional-deps/node_modules` 加载依赖的方法
- 并发控制:避免多个插件同时触发安装
**关键方法:**
```typescript
class DependencyManager {
// 确保依赖已安装,返回依赖模块
async ensureAndImport<T>(packageName: string): Promise<T>
// 检查依赖是否已安装
async isInstalled(packageName: string): Promise<boolean>
// 安装依赖(带锁,避免并发)
async installDependencies(packages: string[]): Promise<void>
// 从 optional-deps/node_modules 加载依赖
async loadModule<T>(packageName: string): Promise<T>
}
```
**实现要点:**
- 使用文件锁(如 `proper-lockfile`)防止并发安装
- 安装前检查 `optional-deps/node_modules/{packageName}` 是否存在
- 安装命令:`pnpm install --dir optional-deps --ignore-workspace`
- 加载时使用绝对路径:`import('file:///absolute/path/to/optional-deps/node_modules/package')`
#### 2. 依赖注册表(DependencyRegistry
**职责:**
- 维护插件名称到依赖列表的映射
- 提供依赖查询接口
**数据结构:**
```typescript
interface PluginDependencyConfig {
pluginName: string;
dependencies: {
packageName: string;
version: string;
optional?: boolean; // 是否可选(安装失败不阻塞)
}[];
}
// 示例注册
dependencyRegistry.register('plugin-aws', [
{ packageName: '@aws-sdk/client-acm', version: '^3.964.0' },
{ packageName: '@aws-sdk/client-cloudfront', version: '^3.964.0' },
{ packageName: '@aws-sdk/client-route-53', version: '^3.964.0' },
]);
```
#### 3. 插件集成
**改造现有插件代码:**
改造前(`plugin-aws/libs/aws-client.ts`):
```typescript
const { ACMClient, ImportCertificateCommand } = await import("@aws-sdk/client-acm");
```
改造后:
```typescript
import { DependencyManager } from "../../../modules/dependency/dependency-manager.js";
const depManager = new DependencyManager();
const { ACMClient, ImportCertificateCommand } = await depManager.ensureAndImport("@aws-sdk/client-acm");
```
**简化方案(推荐):**
创建辅助函数,减少改动量:
```typescript
// src/modules/dependency/import-helper.ts
export async function importOptionalDep<T>(packageName: string): Promise<T> {
const depManager = new DependencyManager();
return await depManager.ensureAndImport<T>(packageName);
}
// 插件中使用
import { importOptionalDep } from "../../../modules/dependency/import-helper.js";
const { ACMClient } = await importOptionalDep("@aws-sdk/client-acm");
```
### 实施步骤
#### 阶段一:基础设施搭建
1. 创建 `optional-deps/` 目录结构
2. 生成 `optional-deps/package.json`(包含所有可选依赖)
3. 实现 `DependencyManager` 核心逻辑
4. 实现依赖安装锁机制
5. 编写单元测试
#### 阶段二:依赖迁移
6. 从主 `package.json` 移除可选依赖
7. 将依赖添加到 `optional-deps/package.json`
8. 创建依赖注册表,映射插件到依赖
#### 阶段三:插件改造
9. 创建 `import-helper.ts` 辅助函数
10. 逐步改造插件代码,使用 `importOptionalDep` 加载依赖
11. 优先改造重型依赖(AWS、阿里云、腾讯云等)
#### 阶段四:测试与优化
12. 端到端测试:验证依赖按需安装和加载
13. 性能优化:缓存已加载的模块
14. 错误处理:安装失败时的降级策略
15. 文档:编写使用说明和迁移指南
## 关键技术决策
### 1. 依赖分组策略
**选择:按插件分组**
- 每个插件声明自己需要的依赖
- 优点:职责清晰,易于维护
- 缺点:可能有重复依赖(但 pnpm 会去重)
**备选:按功能分组**
- 将依赖按功能分组(如 "aws-deps", "aliyun-deps"
- 优点:更细粒度控制
- 缺点:增加复杂度
### 2. 安装触发时机
**选择:首次使用时触发**
- 在插件的 `execute()``getClient()` 方法中触发安装
- 优点:真正的按需加载
- 缺点:首次使用有延迟
**备选:启动时预检查**
- 启动时扫描启用的插件,预安装依赖
- 优点:避免运行时延迟
- 缺点:可能安装不需要的依赖
### 3. 依赖路径解析
**选择:使用绝对路径 + `file://` 协议**
```typescript
const modulePath = path.resolve(__dirname, '../../optional-deps/node_modules', packageName);
return await import(`file://${modulePath}/index.js`);
```
**原因:**
- Node.js ESM 要求明确的 URL 格式
- 避免模块解析冲突
### 4. 并发控制
**选择:文件锁 + 内存锁双重保护**
- 使用 `proper-lockfile` 锁定 `optional-deps/` 目录
- 内存中使用 `Map` 记录正在安装的依赖
- 避免多个插件同时触发安装
### 5. 错误处理
**策略:**
- 安装失败时记录日志,抛出明确的错误信息
- 提供手动安装命令提示:`请运行: cd optional-deps && pnpm install`
- 支持降级:某些非核心依赖安装失败时,插件可以部分功能可用
## 验证方案
### 单元测试
1. 测试 `DependencyManager.isInstalled()` 正确检测依赖状态
2. 测试 `DependencyManager.installDependencies()` 成功安装依赖
3. 测试并发安装时的锁机制
4. 测试从 `optional-deps/node_modules` 加载模块
### 集成测试
1. 清空 `optional-deps/node_modules`
2. 启动服务,验证不触发安装
3. 调用 AWS 插件,验证触发安装并成功加载
4. 再次调用,验证不重复安装
5. 验证主 `node_modules` 体积减少
### 性能测试
1. 测量首次安装依赖的耗时
2. 测量后续加载的耗时(应该与正常 import 相近)
3. 对比改造前后的 `node_modules` 大小
## 风险与挑战
### 1. 首次使用延迟
**风险:** 用户首次使用插件时需要等待依赖安装(可能几十秒)
**缓解:**
- 在 UI 上显示安装进度
- 提供预安装命令:`pnpm run install-optional-deps`
- 文档说明首次使用会有延迟
### 2. 离线环境
**风险:** 离线环境无法下载依赖
**缓解:**
- 提供完整安装包(包含所有可选依赖)
- 支持手动复制 `node_modules`
### 3. 版本冲突
**风险:** 可选依赖与主依赖版本冲突
**缓解:**
- 使用 `--ignore-workspace` 隔离安装
- 定期同步主依赖版本
### 4. TypeScript 类型
**风险:** 动态导入的类型推断
**缓解:**
- 保留 `@types/*` 在主 `devDependencies`
- 使用泛型和类型断言
## 预期收益
1. **空间节省:**`node_modules` 体积减少 60-70%(估算)
2. **安装速度:** 初始 `pnpm install` 速度提升 3-5 倍
3. **用户体验:** 不使用的插件不占用空间,按需加载
4. **维护性:** 依赖分组清晰,易于管理
## 后续优化
1. **依赖预热:** 在后台预安装常用插件依赖
2. **依赖缓存:** 支持从 CDN 或本地缓存安装
3. **依赖更新:** 提供命令批量更新可选依赖
4. **插件市场:** 支持从远程下载插件及其依赖配置
## 附录:依赖分类清单
### 可选依赖(迁移到 optional-deps/package.json
**AWS 相关(plugin-aws, plugin-aws-cn):**
```json
{
"@aws-sdk/client-acm": "^3.964.0",
"@aws-sdk/client-cloudfront": "^3.964.0",
"@aws-sdk/client-iam": "^3.964.0",
"@aws-sdk/client-route-53": "^3.964.0",
"@aws-sdk/client-s3": "^3.964.0",
"@aws-sdk/client-sts": "^3.990.0"
}
```
**阿里云相关(plugin-aliyun, plugin-lib/aliyun):**
```json
{
"@alicloud/fc20230330": "^4.1.7",
"@alicloud/openapi-client": "^0.4.12",
"@alicloud/openapi-util": "^0.3.2",
"@alicloud/pop-core": "^1.7.10",
"@alicloud/sts-sdk": "^1.0.2",
"@alicloud/tea-typescript": "^1.8.0",
"@alicloud/tea-util": "^1.4.10",
"ali-oss": "^6.21.0"
}
```
**腾讯云相关(plugin-tencent, plugin-lib/tencent):**
```json
{
"tencentcloud-sdk-nodejs": "^4.1.112",
"cos-nodejs-sdk-v5": "^2.14.6"
}
```
**华为云相关(plugin-huawei):**
```json
{
"@huaweicloud/huaweicloud-sdk-cdn": "3.1.185",
"@huaweicloud/huaweicloud-sdk-core": "3.1.185",
"@huaweicloud/huaweicloud-sdk-elb": "3.1.185",
"@huaweicloud/huaweicloud-sdk-iam": "3.1.185",
"esdk-obs-nodejs": "^3.25.6"
}
```
**Azure 相关(plugin-azure):**
```json
{
"@azure/arm-dns": "^5.1.0",
"@azure/identity": "^4.13.1"
}
```
**Google Cloud 相关(plugin-google, plugin-cert/google):**
```json
{
"@google-cloud/dns": "^5.3.1",
"@google-cloud/publicca": "^1.3.0"
}
```
**火山引擎相关(plugin-volcengine):**
```json
{
"@volcengine/openapi": "^1.28.1",
"@volcengine/tos-sdk": "^2.9.1"
}
```
**SSH/网络相关(plugin-host, plugin-lib/ssh):**
```json
{
"ssh2": "^1.17.0",
"socks": "^2.8.3",
"socks-proxy-agent": "^8.0.4",
"basic-ftp": "^5.0.5"
}
```
**其他存储/传输(plugin-qiniu, plugin-lib/qiniu):**
```json
{
"qiniu": "^7.12.0"
}
```
**邮件通知(plugin-notification/email):**
```json
{
"nodemailer": "^6.9.16"
}
```
### 主依赖(保留在主 package.json
**框架核心:**
- `@midwayjs/*` 系列
- `@koa/cors`
- `typeorm`, `better-sqlite3`, `mysql2`, `pg`
**项目内部包:**
- `@certd/*` 系列
**通用工具:**
- `axios`, `lodash-es`, `dayjs`, `js-yaml`
- `crypto-js`, `jsonwebtoken`, `bcryptjs`
- `reflect-metadata`, `uuid`, `nanoid`
- 等等
## 总结
本方案通过引入独立的可选依赖管理机制,实现了插件依赖的按需下载和加载。核心思路是:
1. **隔离管理:**`optional-deps/` 目录下维护独立的 `package.json``node_modules`
2. **动态安装:** 通过 `DependencyManager` 在首次使用时触发 `pnpm install`
3. **路径加载:** 使用绝对路径从独立目录加载依赖模块
4. **最小改动:** 通过辅助函数 `importOptionalDep` 简化插件代码改造
该方案可以显著减少主 `node_modules` 体积,提升初始安装速度,同时保持现有架构的兼容性和可维护性。
+2 -2
View File
@@ -281,12 +281,12 @@ export class DemoTest extends AbstractTaskPlugin {
return {
value: item.siteName,
label: item.siteName,
domain: item.siteName,
domain: item.siteName, //这里必须要包含domain 否则后面分组时候全部分配到未匹配中
};
});
//将站点域名名称根据证书域名进行匹配分组,分成匹配的和不匹配的两组选项,返回给前端,供用户选择
return {
list: optionsUtils.buildGroupOptions(options, this.certDomains),
list: optionsUtils.buildGroupOptions(options, this.certDomains), //分组后的列表
total: siteRes.length,
};
}
+14
View File
@@ -87,6 +87,20 @@
"plus_use_prod": "false",
"PLUS_SERVER_BASE_URL": "http://127.0.0.1:11007"
}
},
{
"name": "server-local-comm",
"type": "node",
"request": "launch",
"cwd": "${workspaceFolder}/packages/ui/certd-server",
"runtimeExecutable": "npm",
"runtimeArgs": ["run", "dev-localcomm"],
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"env": {
"plus_use_prod": "false",
"PLUS_SERVER_BASE_URL": "http://127.0.0.1:11007"
}
}
],
"compounds": [
+21 -1
View File
@@ -70,6 +70,8 @@ Certd 是可私有化部署的 SSL/TLS 证书自动化管理平台,提供 Web
- 先读本文,再按任务读取具体代码或技能文件。
- PowerShell 读取中文、Markdown、locale、文档类文件时使用 `Get-Content -Raw -Encoding UTF8`;仍乱码时先执行 `[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new()`
- PowerShell 中用 `rg` 搜索含引号、括号、反斜杠的 pattern 时,优先用单引号包裹整个 pattern,例如 `rg 'await import\("tencentcloud-sdk-nodejs' packages/ui/certd-server/src -g '*.ts'`
- 手工编辑或创建文件时优先使用 `apply_patch`。单个文件内有多处不连续改动时,拆成多个独立的 `*** Update File` 块,每块只改一处附近上下文;不要在同一个 update hunk 里强塞多个 `@@`
- 只有真正机械化的大批量替换、格式化或生成任务才考虑脚本/工具。若必须使用临时脚本,应放在临时目录并在同一个受控步骤内完成创建、执行、删除;不要把临时脚本落在仓库里跨多步工具调用执行。
- 不要主动运行 `pnpm install`;缺依赖、TTY、网络导致安装或测试失败时,停止尝试并说明环境问题。
- 优先沿用现有模块、插件、service、页面模式;不要为形式上的复用制造过度抽象。
- 代码可读性优先于短写法。复杂条件、三元表达式、链式调用、内联对象和多层 helper 调用要拆成命名清晰的中间变量或小方法。
@@ -137,6 +139,9 @@ Certd 是可私有化部署的 SSL/TLS 证书自动化管理平台,提供 Web
- 列表管理、后台管理、记录查询、CRUD 表格页面优先使用 Fast Crud;开发或重构前读 `.trae/skills/fast-crud-page-dev/SKILL.md`
- 只有轻量只读展示、强交互自定义界面或既有页面模式明显不适合 Fast Crud 时,才手写 `a-table` / 自定义列表,并在回复中说明。
- 内嵌 Fast Crud 时,外层必须有稳定高度或完整 `flex: 1; min-height: 0` 链路。
- 前端组件样式统一写在 `<style>` / Less / CSS 文件里,通过样式名映射到元素;尽量不要在元素上直接写 `style`
- 每个组件都要有一个稳定的根样式名,并把组件下方样式全部包在该根样式名内;尽量不要使用 `scoped`
- 可复用的公共样式名放在 `packages/ui/certd-client/src/style` 下维护,优先使用 `cd-` 前缀,避免散落在业务组件里重复定义。
- 后台管理列表展示或筛选用户字段时,优先参考 `packages/ui/certd-client/src/views/sys/suite/user-suite/crud.tsx``userId` 字段模式,用 `table-select` + `/sys/authority/user/getSimpleUserByIds` 字典回显和搜索。
- 对话框里只做确认可用 `Modal.confirm`;有字段输入、表单校验或提交字段时,必须用 `useFormDialog` / `openFormDialog`
@@ -210,8 +215,23 @@ Certd 是可私有化部署的 SSL/TLS 证书自动化管理平台,提供 Web
- 后端业务数据、接口、实体、权限、迁移:改 `packages/ui/certd-server/src/modules``src/controller`
- 表单、列表、插件配置 UI:改 `packages/ui/certd-client/src/views/certd` 及对应 `src/api`
## 注意事项
## 其他注意事项
### 旧版数据兼容
- 新增插件参数时,必须要考虑旧版数据兼容,比如新增一个deployType参数,有两种值:`default``custom`,需要在使用时判空,走旧版逻辑。
## 前端路由与国际化
- 路由 `meta.title`**i18n 国际化 key**,必须在 `src/locales/langs/zh-CN/``src/locales/langs/en-US/` 对应的模块文件中添加翻译。
- 示例:路由 `title: "certd.auditLog"` 需要在中英 locales 文件中有对应 key`"certd.auditLog": "操作日志"` / `"certd.auditLog": "Audit Log"`)。
- 菜单通过路由自动生成,需设置 `meta.isMenu: true` 才会出现在左侧菜单。
- Plus 版功能菜单需设置 `meta.show: () => { const settingStore = useSettingStore(); return settingStore.isPlus; }`
## 审计日志
- 审计日志是 Plus 版功能,非 Plus 版不会写入。
- Controller 继承 `BaseController`,通过 `this.auditLog({ content: "xxx" })` 记录日志。
- Controller 中的 `@Post("/add", { summary: "xxxx" })`, 这个summary是必须要的,他是日志action字段的来源
- `getAuditType()` 返回类型常量,中间件自动从 ctx.path 判定 scope`/api/sys/` → system,其他 → user)。
- 操作日志有系统级(scope=system)和用户级(scope=user)区分。
+30
View File
@@ -3,6 +3,36 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.42.6](https://github.com/certd/certd/compare/v1.42.5...v1.42.6) (2026-07-18)
### Bug Fixes
* 修复正常批量删除流水线报权限不足的bug ([5b50083](https://github.com/certd/certd/commit/5b500830a122c6c42dab054e57fed509050f94da))
### Performance Improvements
* 优化动态加载依赖镜像地址,多次重试 ([5f53b81](https://github.com/certd/certd/commit/5f53b81c75dd242b4260ac08cae14c6d1a08a883))
## [1.42.5](https://github.com/certd/certd/compare/v1.42.4...v1.42.5) (2026-07-15)
### Bug Fixes
* 修复上传到cos报runtimeDepsService未初始化的问题 ([167b303](https://github.com/certd/certd/commit/167b303faeca02cc11cf97e4be2a3df914852167))
* 修复dingtalk通知格式没有换行的bug ([7ed1be9](https://github.com/certd/certd/commit/7ed1be994f8b4b74cdeb38743060c912c027248b))
### Performance Improvements
* 给SQLITE_IOERR_WRITE增加友好报错提示,将certd:latest镜像改为certd:slim ([b91c9e4](https://github.com/certd/certd/commit/b91c9e4ea671cb359ef164e27864de1d66cba9d3))
* 优化vke keubconfig获取方式,改成先查询,如果没有再创建临时config ([604fa5b](https://github.com/certd/certd/commit/604fa5be634d099d797bfee5c2b0f26ce0ac8461))
## [1.42.4](https://github.com/certd/certd/compare/v1.42.3...v1.42.4) (2026-07-11)
### Bug Fixes
* 修复火山引擎查不到自定义源站域名的问题 ([02dabe1](https://github.com/certd/certd/commit/02dabe11db3e9b13ca4621ce9ddd2b808bfca390))
* 修复火山引擎自定义源站域名查询不到的问题 ([e44bf9d](https://github.com/certd/certd/commit/e44bf9d77375d48ac7fd1582e69fae02dfd248fa))
* **pipeline:** 重构运行时依赖加载逻辑,修复火山引擎DNS解析报runtimeDepsService未初始化的bug ([ec69b8f](https://github.com/certd/certd/commit/ec69b8f11bfd4b20991aef74a72a47182ca79a9d))
## [1.42.3](https://github.com/certd/certd/compare/v1.42.2...v1.42.3) (2026-07-08)
### Bug Fixes
+41 -16
View File
@@ -1,4 +1,4 @@
# Certd
# Certd
中文 | [English](./README_en.md)
@@ -105,31 +105,56 @@ https://certd.handfree.work/
#### Docker镜像说明:
**镜像版本:**
##### 1. 镜像地址格式:
| 版本标签 | 基础系统 | 说明 |
```
registry.cn-shenzhen.aliyuncs.com/certd/certd:[version-][system-][latest/stable]
------------ ↑ 镜像地址 ------------- ↑ 镜像名 -- ↑指定版本- ↑基础系统- ↑最新版本类型
```
##### 2. 版本标签:
**最新版本标签:**
| 版本 | 标签 | 说明 |
| --- | --- | --- |
| 最新预览版【默认】 | `certd:latest` | 指向最新开发版本,包含最新功能,但稳定性不如稳定版 |
| 最新稳定版 | `certd:stable` | 指向经过充分测试的生产就绪版本,推荐生产环境使用 |
**系统分支版本:**
> 根据基础镜像不同,分为如下三个分支版本,没有特殊需求选择默认的即可(他们功能是一样的)
| 系统版本 | 版本标签 | 基础系统 | 说明 | 稳定版标签 |
| --- | --- | --- | --- | --- |
| alpine【默认】 | `certd:latest` | Alpine Linux | 默认版本,镜像体积小 | `certd:stable` |
| slim | `certd:slim` | Debian slim | 基于glibcdns解析兼容性好 | `certd:slim-stable` |
| armv7 | `certd:armv7` | Alpine Linux | ARMv7 架构专用版本 | `certd:armv7-stable` |
##### 2. 镜像地址:
| 镜像仓库 | 最新预览版 | slim | armv7 |
| --- | --- | --- | --- |
| `latest` / `[version]` | Alpine Linux | 默认版本,镜像体积小 |
| `slim` / `[version]-slim` | Debian slim | 基于glibcdns解析兼容性好(可能需要配置security_opt -seccomp=unconfined |
| `armv7` / `[version]-armv7` | Alpine Linux | ARMv7 架构专用版本 |
| 阿里云【默认】 | `registry.cn-shenzhen.aliyuncs.com/certd/certd:latest` | `certd:slim` | `certd:armv7` |
| Docker Hub | `greper/certd:latest` | `certd:slim` |
| GitHub Packages | `ghcr.io/certd/certd:latest` | `certd:slim` | `certd:armv7` |
**镜像地址:**
| 镜像仓库 | latest | slim | armv7 |
| --- | --- | --- | --- |
| 阿里云 | `registry.cn-shenzhen.aliyuncs.com/handsfree/certd:latest` | `registry.cn-shenzhen.aliyuncs.com/handsfree/certd:slim` | `registry.cn-shenzhen.aliyuncs.com/handsfree/certd:armv7` |
| Docker Hub | `greper/certd:latest` | `greper/certd:slim` | `greper/certd:armv7` |
| GitHub Packages | `ghcr.io/certd/certd:latest` | `ghcr.io/certd/certd:slim` | `ghcr.io/certd/certd:armv7` |
> 注意:
> 1. 后面的各个版本省略了镜像地址,使用时需要将镜像地址拼接完整。
> 2. 稳定版在后面加 `-stable` 即可。
> 3. 如需指定具体的版本号,在冒号后面加 `version-`即可,例如 `certd:1.42.1-stable`。
> 带版本号的标签请将 `latest` / `slim` / `armv7` 替换为 `[version]` / `[version]-slim` / `[version]-armv7`
##### 3. 镜像构建说明:
- 镜像构建通过`Actions`自动执行,过程公开透明,请放心使用
- [点我查看镜像构建日志](https://github.com/certd/certd/actions/workflows/build-image.yml)
- [点我查看预览版构建日志](https://github.com/certd/certd/actions/workflows/release-image.yml)
- [点我查看稳定版发布日志](https://github.com/certd/certd/actions/workflows/stable-release.yml)
![](./docs/images/action/action-build.jpg)
> 注意
>
##### 4. 安全注意事项
> - 本应用存储的证书、授权信息等属于高度敏感数据,请做好安全防护
> - 请务必使用HTTPS协议访问本应用,避免被中间人攻击
> - 请务必使用web应用防火墙防护本应用,防止XSS、SQL注入等攻击
+36 -13
View File
@@ -1,4 +1,4 @@
# Certd
# Certd
[中文](./README.md) | English
@@ -95,21 +95,44 @@ You can choose one of the following deployment methods based on your needs:
#### Docker Image Information:
- Domestic Image Addresses:
- `registry.cn-shenzhen.aliyuncs.com/handsfree/certd:latest`
- `registry.cn-shenzhen.aliyuncs.com/handsfree/certd:armv7`, `[version]-armv7`
- DockerHub Addresses:
- `https://hub.docker.com/r/greper/certd`
- `greper/certd:latest`
- `greper/certd:armv7`, `greper/certd:[version]-armv7`
- GitHub Packages Addresses:
**Release channels:**
- `ghcr.io/certd/certd:latest`
- `ghcr.io/certd/certd:armv7`, `ghcr.io/certd/certd:[version]-armv7`
| Channel | Description |
| --- | --- |
| `stable` / `slim-stable` | **Stable version**, production-ready and fully tested, recommended for production environments |
| `latest` / `slim` / `armv7` | **Preview version**, latest development build with newest features but potentially less stable |
**Image tags:**
| Channel | Tag | Versioned Tag | Base System | Description |
| --- | --- | --- | --- | --- |
| **Stable** | `stable` | `[version]-stable` | Alpine Linux | Recommended for production |
| | `slim-stable` | `[version]-slim-stable` | Debian slim | Better DNS resolution compatibility |
| **Preview** | `latest` | `[version]` | Alpine Linux | Default, small image size |
| | `slim` | `[version]-slim` | Debian slim | Better DNS resolution compatibility |
| | `armv7` | `[version]-armv7` | Alpine Linux | ARMv7 architecture |
**Stable version image addresses:**
| Registry | `stable` | `slim-stable` |
| --- | --- | --- |
| Aliyun | `registry.cn-shenzhen.aliyuncs.com/handsfree/certd:stable` | `registry.cn-shenzhen.aliyuncs.com/handsfree/certd:slim-stable` |
| Docker Hub | `greper/certd:stable` | `greper/certd:slim-stable` |
| GitHub Packages | `ghcr.io/certd/certd:stable` | `ghcr.io/certd/certd:slim-stable` |
**Preview version image addresses:**
| Registry | `latest` | `slim` | `armv7` |
| --- | --- | --- | --- |
| Aliyun | `registry.cn-shenzhen.aliyuncs.com/handsfree/certd:latest` | `registry.cn-shenzhen.aliyuncs.com/handsfree/certd:slim` | `registry.cn-shenzhen.aliyuncs.com/handsfree/certd:armv7` |
| Docker Hub | `greper/certd:latest` | `greper/certd:slim` | `greper/certd:armv7` |
| GitHub Packages | `ghcr.io/certd/certd:latest` | `ghcr.io/certd/certd:slim` | `ghcr.io/certd/certd:armv7` |
> For versioned tags, replace tag name with `[version]-tag`, e.g. replace `stable` with `[version]-stable`
- Images are built automatically by `Actions`, with a transparent process. Please use them with confidence.
- [Click here to view image build logs](https://github.com/certd/certd/actions/workflows/build-image.yml)
- [Click here to view preview version build logs](https://github.com/certd/certd/actions/workflows/release-image.yml)
- [Click here to view stable version release logs](https://github.com/certd/certd/actions/workflows/stable-release.yml)
![](./docs/images/action/action-build.jpg)
> Note:
+5 -1
View File
@@ -2,9 +2,13 @@ version: '3.3' # 兼容旧版docker-compose
services:
certd:
# 镜像 # ↓↓↓↓↓ ---- 镜像版本号,建议改成固定版本号,例如:certd:1.29.0
image: registry.cn-shenzhen.aliyuncs.com/handsfree/certd:latest
image: registry.cn-shenzhen.aliyuncs.com/certd/certd:latest
# image: ghcr.io/certd/certd:latest # --------- 如果 报镜像not found,可以尝试其他镜像源
# image: greper/certd:latest
# --------- 生产建议使用稳定版, latest改成stable即可
# image: registry.cn-shenzhen.aliyuncs.com/certd/certd:stable
# security_opt: # --------- 如果slim镜像下启动报错,尝试去掉这两行注释
# - seccomp=unconfined # 解决slim镜像下WorkerThreadsTaskRunner::DelayedTaskScheduler::Start() 报错问题
container_name: certd # 容器名
+36
View File
@@ -3,6 +3,42 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.42.6](https://github.com/certd/certd/compare/v1.42.5...v1.42.6) (2026-07-18)
### Bug Fixes
* 修复正常批量删除流水线报权限不足的bug ([5b50083](https://github.com/certd/certd/commit/5b500830a122c6c42dab054e57fed509050f94da))
### Performance Improvements
* 优化动态加载依赖镜像地址,多次重试 ([5f53b81](https://github.com/certd/certd/commit/5f53b81c75dd242b4260ac08cae14c6d1a08a883))
## [1.42.5](https://github.com/certd/certd/compare/v1.42.4...v1.42.5) (2026-07-15)
### Bug Fixes
* 修复上传到cos报runtimeDepsService未初始化的问题 ([167b303](https://github.com/certd/certd/commit/167b303faeca02cc11cf97e4be2a3df914852167))
* 修复dingtalk通知格式没有换行的bug ([7ed1be9](https://github.com/certd/certd/commit/7ed1be994f8b4b74cdeb38743060c912c027248b))
### Performance Improvements
* 给SQLITE_IOERR_WRITE增加友好报错提示,将certd:latest镜像改为certd:slim ([b91c9e4](https://github.com/certd/certd/commit/b91c9e4ea671cb359ef164e27864de1d66cba9d3))
* 优化vke keubconfig获取方式,改成先查询,如果没有再创建临时config ([604fa5b](https://github.com/certd/certd/commit/604fa5be634d099d797bfee5c2b0f26ce0ac8461))
## [1.42.4](https://github.com/certd/certd/compare/v1.42.3...v1.42.4) (2026-07-11)
### Bug Fixes
* 修复火山引擎查不到自定义源站域名的问题 ([02dabe1](https://github.com/certd/certd/commit/02dabe11db3e9b13ca4621ce9ddd2b808bfca390))
* 修复火山引擎自定义源站域名查询不到的问题 ([e44bf9d](https://github.com/certd/certd/commit/e44bf9d77375d48ac7fd1582e69fae02dfd248fa))
* **pipeline:** 重构运行时依赖加载逻辑,修复火山引擎DNS解析报runtimeDepsService未初始化的bug ([ec69b8f](https://github.com/certd/certd/commit/ec69b8f11bfd4b20991aef74a72a47182ca79a9d))
## [1.42.3](https://github.com/certd/certd/compare/v1.42.2...v1.42.3) (2026-07-08)
### Bug Fixes
* **volcengine-alb:** 修复火山引擎ALB 默认证书部署类型会部署到扩展证书的问题 ([0a068a2](https://github.com/certd/certd/commit/0a068a274673e9768954e9f7367c267d44f3b530))
## [1.42.2](https://github.com/certd/certd/compare/v1.42.1...v1.42.2) (2026-07-07)
### Bug Fixes
+15 -6
View File
@@ -6,13 +6,22 @@
Certd 提供多种 Docker 镜像版本,您可以根据需要选择:
| 版本标签 | 基础系统 | 说明 |
| --- | --- | --- | --- |
| `latest` / `[version]` | Alpine Linux | 默认版本,镜像体积小 |
| `slim` / `[version]-slim` | Debian slim | glibc版本,dns解析兼容性更好(可能需要配置security_opt -seccomp=unconfined|
| `armv7` / `[version]-armv7` | Alpine Linux | ARMv7 架构专用版本 |
**最新版本:**
> 如果您不确定使用哪个版本,请使用默认的 `latest` 版本。
| 版本 | 标签 | 说明 |
| --- | --- | --- |
| 预览版【默认】 | `certd:latest` | 指向最新开发版本,包含最新功能,但稳定性不如稳定版 |
| 稳定版 | `certd:stable` | 指向经过充分测试的生产就绪版本,推荐生产环境使用 |
**系统版本分支:**
| 分支版本标签 | 基础系统 | 说明 | 指定版本 | 稳定版 |
| --- | --- | --- | --- | --- |
| `certd:latest` 【默认】 | Alpine Linux | 默认版本,镜像体积小 | `certd:[version]` | `certd:[version-]stable` |
| `certd:slim` | Debian slim | glibc版本,dns解析兼容性更好(可能需要配置security_opt -seccomp=unconfined| `certd:[version-]slim` | `certd:[version-]slim-stable` |
| `certd:armv7` | Alpine Linux | ARMv7 架构专用版本 | `certd:[version]-armv7` | `certd:[version-]armv7-ststable` |
> 如果您不确定使用哪个版本,请使用默认的 `certd:latest` 版本。
### 一键脚本安装(推荐)
+1 -1
View File
@@ -9,5 +9,5 @@
}
},
"npmClient": "pnpm",
"version": "1.42.3"
"version": "1.42.6"
}
+5 -2
View File
@@ -19,7 +19,7 @@
"devb": "lerna run dev-build",
"i-all": "lerna link && lerna exec npm install ",
"publish": "pnpm run prepublishOnly2 && lerna publish --force-publish=pro/plus-core --conventional-commits && pnpm run afterpublishOnly ",
"publish2":" npm run pub_all && pnpm run afterpublishOnly",
"publish2": " npm run pub_all && pnpm run afterpublishOnly",
"afterpublishOnly": "pnpm run copylogs && time /t >trigger/build.trigger && git add ./trigger/build.trigger && git commit -m \"build: trigger build image\" && TIMEOUT /T 10 && pnpm run commitAll",
"transform-sql": "cd ./packages/ui/certd-server/db/ && node --experimental-json-modules transform.js",
"plugin-doc-gen": "cd ./packages/ui/certd-server/ && pnpm run export-metadata",
@@ -39,12 +39,15 @@
"test:unit": "cross-env NODE_ENV=unittest pnpm -r --workspace-concurrency=1 run test:unit",
"pub": "echo 1",
"dev": "pnpm run -r --parallel compile ",
"lint_all": "pnpm run -r --parallel lint ",
"pub_all": "node ./scripts/pub-all.js",
"release": "time /t >trigger/release.trigger && git add trigger/release.trigger && git commit -m \"build: release\" && git push",
"publish_to_atomgit": "node --experimental-json-modules ./scripts/publish-atomgit.js",
"publish_to_gitee": "node --experimental-json-modules ./scripts/publish-gitee.js",
"publish_to_github": "node --experimental-json-modules ./scripts/publish-github.js",
"get_version": "node --experimental-json-modules ./scripts/version.js"
"get_version": "node --experimental-json-modules ./scripts/version.js",
"stable": "node ./scripts/stable.js",
"set-release-stable": "node ./scripts/set-release-stable.js"
},
"license": "AGPL-3.0",
"dependencies": {
+12
View File
@@ -3,6 +3,18 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.42.6](https://github.com/publishlab/node-acme-client/compare/v1.42.5...v1.42.6) (2026-07-18)
**Note:** Version bump only for package @certd/acme-client
## [1.42.5](https://github.com/publishlab/node-acme-client/compare/v1.42.4...v1.42.5) (2026-07-15)
**Note:** Version bump only for package @certd/acme-client
## [1.42.4](https://github.com/publishlab/node-acme-client/compare/v1.42.3...v1.42.4) (2026-07-11)
**Note:** Version bump only for package @certd/acme-client
## [1.42.3](https://github.com/publishlab/node-acme-client/compare/v1.42.2...v1.42.3) (2026-07-08)
**Note:** Version bump only for package @certd/acme-client
+3 -3
View File
@@ -3,7 +3,7 @@
"description": "Simple and unopinionated ACME client",
"private": false,
"author": "nmorsman",
"version": "1.42.3",
"version": "1.42.6",
"type": "module",
"module": "./dist/index.js",
"main": "./dist/index.js",
@@ -18,7 +18,7 @@
"types"
],
"dependencies": {
"@certd/basic": "^1.42.3",
"@certd/basic": "^1.42.6",
"@peculiar/x509": "^1.11.0",
"asn1js": "^3.0.5",
"axios": "^1.9.0",
@@ -75,5 +75,5 @@
"bugs": {
"url": "https://github.com/publishlab/node-acme-client/issues"
},
"gitHead": "7808d028e9c7e1b1e3ebc41f12b023d7b553300b"
"gitHead": "246ee83015bf5589adc2a5fa3d1388c8d9a2a252"
}
+12
View File
@@ -3,6 +3,18 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.42.6](https://github.com/certd/certd/compare/v1.42.5...v1.42.6) (2026-07-18)
**Note:** Version bump only for package @certd/basic
## [1.42.5](https://github.com/certd/certd/compare/v1.42.4...v1.42.5) (2026-07-15)
**Note:** Version bump only for package @certd/basic
## [1.42.4](https://github.com/certd/certd/compare/v1.42.3...v1.42.4) (2026-07-11)
**Note:** Version bump only for package @certd/basic
## [1.42.3](https://github.com/certd/certd/compare/v1.42.2...v1.42.3) (2026-07-08)
**Note:** Version bump only for package @certd/basic
+1 -1
View File
@@ -1 +1 @@
23:45
01:12
+2 -2
View File
@@ -1,7 +1,7 @@
{
"name": "@certd/basic",
"private": false,
"version": "1.42.3",
"version": "1.42.6",
"type": "module",
"main": "./dist/index.js",
"module": "./dist/index.js",
@@ -54,5 +54,5 @@
"tslib": "^2.8.1",
"typescript": "^5.4.2"
},
"gitHead": "7808d028e9c7e1b1e3ebc41f12b023d7b553300b"
"gitHead": "246ee83015bf5589adc2a5fa3d1388c8d9a2a252"
}
+22
View File
@@ -3,6 +3,28 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.42.6](https://github.com/certd/certd/compare/v1.42.5...v1.42.6) (2026-07-18)
### Performance Improvements
* 优化动态加载依赖镜像地址,多次重试 ([5f53b81](https://github.com/certd/certd/commit/5f53b81c75dd242b4260ac08cae14c6d1a08a883))
## [1.42.5](https://github.com/certd/certd/compare/v1.42.4...v1.42.5) (2026-07-15)
### Bug Fixes
* 修复上传到cos报runtimeDepsService未初始化的问题 ([167b303](https://github.com/certd/certd/commit/167b303faeca02cc11cf97e4be2a3df914852167))
### Performance Improvements
* 优化vke keubconfig获取方式,改成先查询,如果没有再创建临时config ([604fa5b](https://github.com/certd/certd/commit/604fa5be634d099d797bfee5c2b0f26ce0ac8461))
## [1.42.4](https://github.com/certd/certd/compare/v1.42.3...v1.42.4) (2026-07-11)
### Bug Fixes
* **pipeline:** 重构运行时依赖加载逻辑,修复火山引擎DNS解析报runtimeDepsService未初始化的bug ([ec69b8f](https://github.com/certd/certd/commit/ec69b8f11bfd4b20991aef74a72a47182ca79a9d))
## [1.42.3](https://github.com/certd/certd/compare/v1.42.2...v1.42.3) (2026-07-08)
**Note:** Version bump only for package @certd/pipeline
+4 -4
View File
@@ -1,7 +1,7 @@
{
"name": "@certd/pipeline",
"private": false,
"version": "1.42.3",
"version": "1.42.6",
"type": "module",
"main": "./dist/index.js",
"module": "./dist/index.js",
@@ -21,8 +21,8 @@
"lint": "eslint --fix"
},
"dependencies": {
"@certd/basic": "^1.42.3",
"@certd/plus-core": "^1.42.3",
"@certd/basic": "^1.42.6",
"@certd/plus-core": "^1.42.6",
"dayjs": "^1.11.7",
"lodash-es": "^4.17.21",
"reflect-metadata": "^0.2.2"
@@ -51,5 +51,5 @@
"tslib": "^2.8.1",
"typescript": "^5.4.2"
},
"gitHead": "7808d028e9c7e1b1e3ebc41f12b023d7b553300b"
"gitHead": "246ee83015bf5589adc2a5fa3d1388c8d9a2a252"
}
+2 -12
View File
@@ -3,7 +3,7 @@ import { FormItemProps } from "../dt/index.js";
import { HttpClient, ILogger, utils } from "@certd/basic";
import * as _ from "lodash-es";
import { PluginRequestHandleReq } from "../plugin/index.js";
import { IRuntimeDepsService, IServiceGetter } from "../service/index.js";
import { IServiceGetter, getRuntimeDepsService } from "../service/index.js";
// export type AccessRequestHandleReqInput<T = any> = {
// id?: number;
@@ -48,23 +48,13 @@ export type AccessContext = {
export abstract class BaseAccess implements IAccess {
ctx!: AccessContext;
runtimeDepsService?: IRuntimeDepsService;
async importRuntime(specifier: string) {
if (!this.runtimeDepsService) {
throw new Error("runtimeDepsService 未初始化");
}
return await this.runtimeDepsService.importRuntime(specifier, this.ctx.logger);
return await getRuntimeDepsService().importRuntime(specifier, this.ctx.logger);
}
async setCtx(ctx: AccessContext) {
this.ctx = ctx;
if (!this.runtimeDepsService && this.ctx.serviceGetter) {
this.runtimeDepsService = await this.ctx.serviceGetter.get("runtimeDepsService");
}
if (this.runtimeDepsService && this.ctx.define?.name) {
await this.runtimeDepsService.ensureRuntimeDependencies({ pluginKeys: `access:${this.ctx.define.name}`, logger: this.ctx.logger });
}
}
async onRequest(req: AccessRequestHandleReq) {
@@ -47,7 +47,7 @@ export function AccessInput(input?: AccessInputDefine): PropertyDecorator {
};
}
export async function newAccess(type: string, input: any, accessService: IAccessService, ctx?: AccessContext) {
export async function newAccess(type: string, input: any, accessService: IAccessService, ctx: AccessContext) {
const register = accessRegistry.get(type);
if (register == null) {
throw new Error(`access ${type} not found`);
+6 -1
View File
@@ -389,6 +389,9 @@ export class Executor {
};
await instance.setCtx(taskCtx);
if (!(instance instanceof AbstractTaskPlugin)) {
throw new Error(`插件类型错误:${step.type}不是AbstractTaskPlugin的实例`);
}
await instance.onInstance();
const result = await instance.execute();
//执行结果处理
@@ -398,6 +401,7 @@ export class Executor {
}
//输出上下文变量到output context
forEach(define.output, (item: any, key: any) => {
// @ts-ignore
step.status!.output[key] = instance[key];
// const stepOutputKey = `step.${step.id}.${key}`;
// this.runtime.context[stepOutputKey] = instance[key];
@@ -411,7 +415,8 @@ export class Executor {
merge(vars, instance._result.pipelineVars);
await this.pipelineContext.setObj("vars", vars);
}
if (Object.keys(instance._result.pipelinePrivateVars).length > 0) {
// @ts-ignore
if (Object.keys(instance._result?.pipelinePrivateVars).length > 0) {
// 判断 pipelineVars 有值时更新
let vars = await this.pipelineContext.getObj("privateVars");
vars = vars || {};
+6 -12
View File
@@ -3,7 +3,7 @@ import { Registrable } from "../registry/index.js";
import { FormItemProps, HistoryResult, Pipeline } from "../dt/index.js";
import { HttpClient, ILogger, utils } from "@certd/basic";
import * as _ from "lodash-es";
import { IEmailService, IRuntimeDepsService, IServiceGetter } from "../service/index.js";
import { IEmailService, IServiceGetter, getRuntimeDepsService } from "../service/index.js";
export type NotificationBody = {
userId?: number;
@@ -89,16 +89,16 @@ export abstract class BaseNotification implements INotification {
ctx!: NotificationContext;
http!: HttpClient;
logger!: ILogger;
runtimeDepsService?: IRuntimeDepsService;
async importRuntime(specifier: string) {
if (!this.runtimeDepsService) {
return await import(specifier);
}
return await this.runtimeDepsService.importRuntime(specifier, this.logger);
return await getRuntimeDepsService().importRuntime(specifier, this.logger);
}
async doSend(body: NotificationBody) {
if (body.content) {
const content = body.content?.replace(/\n/g, " \n");
body.content = content;
}
return await this.send(body);
}
abstract send(body: NotificationBody): Promise<void>;
@@ -109,12 +109,6 @@ export abstract class BaseNotification implements INotification {
this.ctx = ctx;
this.http = ctx.http;
this.logger = ctx.logger;
if (!this.runtimeDepsService && this.ctx.serviceGetter) {
this.runtimeDepsService = await this.ctx.serviceGetter.get("runtimeDepsService");
}
if (this.runtimeDepsService && this.ctx.define?.name) {
await this.runtimeDepsService.ensureRuntimeDependencies({ pluginKeys: `notification:${this.ctx.define.name}`, logger: this.logger });
}
}
setDefine = (define: NotificationDefine) => {
this.define = define;
+3 -13
View File
@@ -10,7 +10,7 @@ import { INotificationService } from "../notification/index.js";
import { Registrable } from "../registry/index.js";
import { IPluginConfigService } from "../service/config.js";
import { TaskEmitter } from "../service/emit.js";
import { ICnameProxyService, IEmailService, IRuntimeDepsService, IServiceGetter, IUrlService } from "../service/index.js";
import { ICnameProxyService, IEmailService, IServiceGetter, IUrlService, getRuntimeDepsService } from "../service/index.js";
export type PluginRequestHandleReq<T = any> = {
typeName: string;
@@ -76,7 +76,7 @@ export type ITaskPlugin = {
execute(): Promise<void | string>;
onRequest(req: PluginRequestHandleReq<any>): Promise<any>;
setCtx(ctx: TaskInstanceContext): Promise<void>;
importRuntime?(specifier: string): Promise<any>;
importRuntime(specifier: string): Promise<any>;
[key: string]: any;
};
@@ -150,13 +150,9 @@ export abstract class AbstractTaskPlugin implements ITaskPlugin {
logger!: ILogger;
http!: HttpClient;
accessService!: IAccessService;
runtimeDepsService!: IRuntimeDepsService;
async importRuntime(specifier: string) {
if (!this.runtimeDepsService) {
throw new Error("runtimeDepsService 未初始化");
}
return await this.runtimeDepsService.importRuntime(specifier, this.logger);
return await getRuntimeDepsService().importRuntime(specifier, this.logger);
}
clearLastStatus() {
@@ -178,12 +174,6 @@ export abstract class AbstractTaskPlugin implements ITaskPlugin {
this.logger = ctx.logger;
this.accessService = ctx.accessService;
this.http = ctx.http;
if (!this.runtimeDepsService && this.ctx.serviceGetter) {
this.runtimeDepsService = await this.ctx.serviceGetter.get("runtimeDepsService");
}
if (this.runtimeDepsService && this.ctx.define?.name) {
await this.runtimeDepsService.ensureRuntimeDependencies({ pluginKeys: `plugin:${this.ctx.define.name}`, logger: this.logger });
}
// 将证书加入secret
// @ts-ignore
if (this.cert && this.cert.crt && this.cert.key) {
@@ -2,41 +2,41 @@ import assert from "assert";
import fs from "fs";
import path from "path";
import os from "os";
import { RuntimeDepsService, type RuntimeDependencyPluginDefine } from "./runtime-deps-service.js";
import { accessRegistry, pluginRegistry } from "@certd/pipeline";
import { addonRegistry } from "@certd/lib-server";
import { RuntimeDepsService, NpmRegistryResolver, type RuntimeDependencyPluginDefine } from "./runtime.js";
import { accessRegistry } from "../access/registry.js";
import { pluginRegistry } from "../plugin/registry.js";
describe("RuntimeDepsService", () => {
it("detects conflicting dependency ranges across plugins", () => {
const service = new RuntimeDepsService();
const service = new RuntimeDepsService({}, null);
const merged = service.collectDependencies([
{ name: "a", dependPackages: { foo: "^1.0.0" } },
{ name: "b", dependPackages: { foo: "^1.2.0" } },
]);
assert.deepEqual(merged.dependencies, { foo: "^1.0.0" });
assert.equal(merged.conflicts.length, 0);
});
it("reports incompatible dependency ranges", () => {
const service = new RuntimeDepsService();
const service = new RuntimeDepsService({}, null);
const merged = service.collectDependencies([
{ name: "a", dependPackages: { foo: "^1.0.0" } },
{ name: "b", dependPackages: { foo: "^2.0.0" } },
]);
assert.equal(merged.conflicts.length, 1);
assert.equal(merged.conflicts[0].packageName, "foo");
});
it("builds a runtime package manifest in the target directory", async () => {
const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), "certd-runtime-deps-"));
const service = new RuntimeDepsService();
service.runtimeDepsRootDir = rootDir;
const service = new RuntimeDepsService({ rootDir }, null);
service.registryResolver = {
async resolve() {
return "https://registry.npmmirror.com";
},
async resolveOrdered() {
return ["https://registry.npmmirror.com"];
},
} as any;
service.commandRunner = {
async run(command: string, args: string[]) {
@@ -50,22 +50,22 @@ describe("RuntimeDepsService", () => {
return { stdout: "", stderr: "", code: 0 };
},
} as any;
const plugins: RuntimeDependencyPluginDefine[] = [{ name: "a", dependPackages: { foo: "^1.0.0" } }];
const result = await service.ensureInstalled({ plugins });
assert.equal(result.registryUrl, "https://registry.npmmirror.com");
assert.ok(fs.existsSync(path.join(rootDir, "package.json")));
});
it("installs direct dependency maps without plugin metadata", async () => {
const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), "certd-runtime-deps-direct-"));
const service = new RuntimeDepsService();
service.runtimeDepsRootDir = rootDir;
const service = new RuntimeDepsService({ rootDir }, null);
service.registryResolver = {
async resolve() {
return "";
},
async resolveOrdered() {
return [""];
},
} as any;
service.commandRunner = {
async run(command: string, args: string[]) {
@@ -77,9 +77,7 @@ describe("RuntimeDepsService", () => {
return { stdout: "", stderr: "", code: 0 };
},
} as any;
await service.ensureDependencies({ dependencies: { directPkg: "^1.0.0" } });
const manifest = JSON.parse(fs.readFileSync(path.join(rootDir, "package.json"), "utf8"));
assert.deepEqual(manifest.dependencies, { directPkg: "^1.0.0" });
});
@@ -91,31 +89,26 @@ describe("RuntimeDepsService", () => {
fs.writeFileSync(path.join(rootDir, "package.json"), JSON.stringify({ name: "runtime-root", type: "module" }), "utf8");
fs.writeFileSync(path.join(packageDir, "package.json"), JSON.stringify({ name: "runtime-only", type: "module", main: "index.js" }), "utf8");
fs.writeFileSync(path.join(packageDir, "index.js"), "export const value = 42;\n", "utf8");
const service = new RuntimeDepsService();
service.runtimeDepsRootDir = rootDir;
const service = new RuntimeDepsService({ rootDir }, null);
service.commandRunner = {
async run() {
throw new Error("install should not run");
},
} as any;
const mod = await service.importRuntime("runtime-only");
assert.equal(mod.value, 42);
});
it("installs configured lazy dependency when import target is missing", async () => {
const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), "certd-runtime-deps-lazy-"));
const service = new RuntimeDepsService();
service.runtimeDepsRootDir = rootDir;
service.lazyDependencies = {
"lazy-pkg": "^1.2.3",
};
const service = new RuntimeDepsService({ rootDir, lazyDependencies: { "lazy-pkg": "^1.2.3" } }, null);
service.registryResolver = {
async resolve() {
return "";
},
async resolveOrdered() {
return [""];
},
} as any;
service.commandRunner = {
async run(command: string, args: string[]) {
@@ -130,9 +123,7 @@ describe("RuntimeDepsService", () => {
return { stdout: "", stderr: "", code: 0 };
},
} as any;
const mod = await service.importRuntime("lazy-pkg/sub/entry.js");
const manifest = JSON.parse(fs.readFileSync(path.join(rootDir, "package.json"), "utf8"));
assert.deepEqual(manifest.dependencies, { "lazy-pkg": "^1.2.3" });
assert.equal(mod.value, 7);
@@ -140,15 +131,14 @@ describe("RuntimeDepsService", () => {
it("resolves scoped package names for lazy imports", async () => {
const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), "certd-runtime-deps-scoped-"));
const service = new RuntimeDepsService();
service.runtimeDepsRootDir = rootDir;
service.lazyDependencies = {
"@scope/lazy": "^2.0.0",
};
const service = new RuntimeDepsService({ rootDir, lazyDependencies: { "@scope/lazy": "^2.0.0" } }, null);
service.registryResolver = {
async resolve() {
return "";
},
async resolveOrdered() {
return [""];
},
} as any;
service.commandRunner = {
async run(command: string, args: string[]) {
@@ -163,9 +153,7 @@ describe("RuntimeDepsService", () => {
return { stdout: "", stderr: "", code: 0 };
},
} as any;
const mod = await service.importRuntime("@scope/lazy/dist/index.js");
const manifest = JSON.parse(fs.readFileSync(path.join(rootDir, "package.json"), "utf8"));
assert.deepEqual(manifest.dependencies, { "@scope/lazy": "^2.0.0" });
assert.equal(mod.scoped, true);
@@ -173,59 +161,27 @@ describe("RuntimeDepsService", () => {
it("reports missing lazy dependency configuration", async () => {
const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), "certd-runtime-deps-lazy-missing-"));
const service = new RuntimeDepsService();
service.runtimeDepsRootDir = rootDir;
service.lazyDependencies = {};
const service = new RuntimeDepsService({ rootDir, lazyDependencies: {} }, null);
await assert.rejects(() => service.importRuntime("missing-pkg/sub.js"), /未配置懒加载版本: missing-pkg/);
});
it("falls back to project node_modules when lazy dependency is not configured", async () => {
const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), "certd-runtime-deps-project-fallback-"));
const service = new RuntimeDepsService();
service.runtimeDepsRootDir = rootDir;
service.lazyDependencies = {};
const service = new RuntimeDepsService({ rootDir, lazyDependencies: {} }, null);
const mod = await service.importRuntime("dayjs");
assert.equal(typeof mod.default, "function");
});
it("falls back to project node_modules when lazy install fails", async () => {
const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), "certd-runtime-deps-project-fallback-install-"));
const service = new RuntimeDepsService();
service.runtimeDepsRootDir = rootDir;
service.lazyDependencies = {
dayjs: "^1.11.7",
};
service.registryResolver = {
async resolve() {
return "";
},
} as any;
service.commandRunner = {
async run(command: string, args: string[]) {
assert.equal(command, "pnpm");
if (args.includes("--version")) {
return { stdout: "9.1.0\n", stderr: "", code: 0 };
}
return { stdout: "", stderr: "install failed in test", code: 1 };
},
} as any;
const mod = await service.importRuntime("dayjs");
assert.equal(typeof mod.default, "function");
});
it("keeps previously installed dependencies when installing a later plugin", async () => {
const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), "certd-runtime-deps-merge-"));
const service = new RuntimeDepsService();
service.runtimeDepsRootDir = rootDir;
const service = new RuntimeDepsService({ rootDir }, null);
service.registryResolver = {
async resolve() {
return "";
},
async resolveOrdered() {
return [""];
},
} as any;
service.commandRunner = {
async run(command: string, args: string[]) {
@@ -237,22 +193,17 @@ describe("RuntimeDepsService", () => {
return { stdout: "", stderr: "", code: 0 };
},
} as any;
await service.ensureInstalled({ plugins: [{ name: "a", pluginType: "deploy", dependPackages: { foo: "^1.0.0" } }] });
await service.ensureInstalled({ plugins: [{ name: "b", pluginType: "deploy", dependPackages: { bar: "^2.0.0" } }] });
const manifest = JSON.parse(fs.readFileSync(path.join(rootDir, "package.json"), "utf8"));
assert.deepEqual(manifest.dependencies, {
foo: "^1.0.0",
bar: "^2.0.0",
});
assert.deepEqual(manifest.dependencies, { foo: "^1.0.0", bar: "^2.0.0" });
});
it("includes npm dependencies from dependent plugins", () => {
const service = new RuntimeDepsService();
it("includes npm dependencies from dependent plugins", async () => {
const service = new RuntimeDepsService({}, { accessRegistry, pluginRegistry });
accessRegistry.register("runtimeDepsAccess", {
define: { name: "runtimeDepsAccess", title: "access", dependPackages: { accessOnly: "^1.0.0" } } as any,
target: async () => ({} as any),
target: async () => ({}) as any,
});
try {
const resolved = service.resolvePluginDependencies({
@@ -262,11 +213,7 @@ describe("RuntimeDepsService", () => {
dependPackages: { deployOnly: "^1.0.0" },
});
const merged = service.collectDependencies(resolved);
assert.deepEqual(merged.dependencies, {
deployOnly: "^1.0.0",
accessOnly: "^1.0.0",
});
assert.deepEqual(merged.dependencies, { deployOnly: "^1.0.0", accessOnly: "^1.0.0" });
} finally {
accessRegistry.unRegister("runtimeDepsAccess");
}
@@ -274,12 +221,14 @@ describe("RuntimeDepsService", () => {
it("installs dependencies by registered plugin key", async () => {
const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), "certd-runtime-deps-key-"));
const service = new RuntimeDepsService();
service.runtimeDepsRootDir = rootDir;
const service = new RuntimeDepsService({ rootDir }, { pluginRegistry, accessRegistry });
service.registryResolver = {
async resolve() {
return "";
},
async resolveOrdered() {
return [""];
},
} as any;
service.commandRunner = {
async run(command: string, args: string[]) {
@@ -293,11 +242,11 @@ describe("RuntimeDepsService", () => {
} as any;
pluginRegistry.register("runtimeDepsKey", {
define: { name: "runtimeDepsKey", title: "key", dependPackages: { keyed: "^1.0.0" } } as any,
target: async () => ({} as any),
target: async () => ({}) as any,
});
try {
service.setRegistries({ pluginRegistry, accessRegistry });
await service.ensureRuntimeDependencies({ pluginKeys: "plugin:runtimeDepsKey" });
const manifest = JSON.parse(fs.readFileSync(path.join(rootDir, "package.json"), "utf8"));
assert.deepEqual(manifest.dependencies, { keyed: "^1.0.0" });
} finally {
@@ -305,58 +254,16 @@ describe("RuntimeDepsService", () => {
}
});
it("installs dependencies from multiple plugin keys including addon subtype keys", async () => {
const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), "certd-runtime-deps-keys-"));
const service = new RuntimeDepsService();
service.runtimeDepsRootDir = rootDir;
service.registryResolver = {
async resolve() {
return "";
},
} as any;
service.commandRunner = {
async run(command: string, args: string[]) {
assert.equal(command, "pnpm");
if (args.includes("--version")) {
return { stdout: "9.1.0\n", stderr: "", code: 0 };
}
fs.mkdirSync(path.join(rootDir, "node_modules"), { recursive: true });
return { stdout: "", stderr: "", code: 0 };
},
} as any;
accessRegistry.register("runtimeDepsArrayAccess", {
define: { name: "runtimeDepsArrayAccess", title: "access", dependPackages: { accessPkg: "^1.0.0" } } as any,
target: async () => ({} as any),
});
addonRegistry.register("captcha:runtimeDepsArrayAddon", {
define: { addonType: "captcha", name: "runtimeDepsArrayAddon", title: "addon", dependPackages: { addonPkg: "^2.0.0" } } as any,
target: async () => ({} as any),
});
try {
await service.ensureRuntimeDependencies({ pluginKeys: ["access:runtimeDepsArrayAccess", "addon:captcha:runtimeDepsArrayAddon"] });
const manifest = JSON.parse(fs.readFileSync(path.join(rootDir, "package.json"), "utf8"));
assert.deepEqual(manifest.dependencies, {
accessPkg: "^1.0.0",
addonPkg: "^2.0.0",
});
} finally {
accessRegistry.unRegister("runtimeDepsArrayAccess");
addonRegistry.unRegister("captcha:runtimeDepsArrayAddon");
}
});
it("reports missing dependent plugins", () => {
const service = new RuntimeDepsService();
const service = new RuntimeDepsService({}, { accessRegistry, pluginRegistry });
assert.throws(() => service.resolvePluginDependencies({ name: "deploy", pluginType: "deploy", dependPlugins: { "access:access": "*" } }), /插件依赖缺失/);
});
it("reports incompatible dependent plugin versions", () => {
const service = new RuntimeDepsService();
const service = new RuntimeDepsService({}, { accessRegistry, pluginRegistry });
accessRegistry.register("runtimeDepsVersionedAccess", {
define: { name: "runtimeDepsVersionedAccess", title: "access", version: "1.4.0", dependPackages: { accessOnly: "^1.0.0" } } as any,
target: async () => ({} as any),
target: async () => ({}) as any,
});
try {
assert.throws(
@@ -374,73 +281,10 @@ describe("RuntimeDepsService", () => {
});
it("reports bare dependent plugin names as invalid format", () => {
const service = new RuntimeDepsService();
const service = new RuntimeDepsService({}, null);
assert.throws(() => service.resolvePluginDependencies({ name: "deploy", pluginType: "deploy", dependPlugins: { runtimeDepsBareName: "*" } }), /插件依赖格式错误/);
});
it("records runtime install environment state", async () => {
const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), "certd-runtime-deps-state-"));
const service = new RuntimeDepsService();
service.runtimeDepsRootDir = rootDir;
service.registryResolver = {
async resolve() {
return "";
},
} as any;
service.commandRunner = {
async run(command: string, args: string[]) {
assert.equal(command, "pnpm");
if (args.includes("--version")) {
return { stdout: "9.1.0\n", stderr: "", code: 0 };
}
assert.equal(args[0], "install");
return { stdout: "", stderr: "", code: 0 };
},
} as any;
await service.ensureInstalled({ plugins: [{ name: "a", dependPackages: { foo: "^1.0.0" } }] });
const state = JSON.parse(fs.readFileSync(path.join(rootDir, "install-state.json"), "utf8"));
assert.equal(state.nodeVersion, process.version);
assert.equal(state.pnpmVersion, "9.1.0");
assert.equal(state.lastError, undefined);
});
it("serializes installs with a file lock", async () => {
const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), "certd-runtime-deps-lock-"));
const serviceA = new RuntimeDepsService();
const serviceB = new RuntimeDepsService();
for (const service of [serviceA, serviceB]) {
service.runtimeDepsRootDir = rootDir;
service.registryResolver = {
async resolve() {
return "";
},
} as any;
}
let installCount = 0;
const commandRunner = {
async run(command: string, args: string[]) {
assert.equal(command, "pnpm");
if (args.includes("--version")) {
return { stdout: "9.1.0\n", stderr: "", code: 0 };
}
assert.equal(args[0], "install");
installCount++;
await new Promise(resolve => setTimeout(resolve, 50));
fs.mkdirSync(path.join(rootDir, "node_modules"), { recursive: true });
return { stdout: "", stderr: "", code: 0 };
},
};
serviceA.commandRunner = commandRunner as any;
serviceB.commandRunner = commandRunner as any;
await Promise.all([serviceA.ensureInstalled({ plugins: [{ name: "a", dependPackages: { foo: "^1.0.0" } }] }), serviceB.ensureInstalled({ plugins: [{ name: "a", dependPackages: { foo: "^1.0.0" } }] })]);
assert.equal(installCount, 1);
});
it("does not pass node debugger options to pnpm child process", async () => {
const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), "certd-runtime-deps-env-"));
const oldNodeOptions = process.env.NODE_OPTIONS;
@@ -448,12 +292,14 @@ describe("RuntimeDepsService", () => {
process.env.NODE_OPTIONS = "--inspect=127.0.0.1:9229 --max-old-space-size=4096";
process.env.VSCODE_INSPECTOR_OPTIONS = '{"inspectorIpc":"test"}';
try {
const service = new RuntimeDepsService();
service.runtimeDepsRootDir = rootDir;
const service = new RuntimeDepsService({ rootDir }, null);
service.registryResolver = {
async resolve() {
return "";
},
async resolveOrdered() {
return [""];
},
} as any;
service.commandRunner = {
async run(command: string, args: string[], options: { env?: NodeJS.ProcessEnv }) {
@@ -467,7 +313,6 @@ describe("RuntimeDepsService", () => {
return { stdout: "", stderr: "", code: 0 };
},
} as any;
await service.ensureInstalled({ plugins: [{ name: "a", dependPackages: { foo: "^1.0.0" } }] });
} finally {
if (oldNodeOptions == null) {
@@ -483,27 +328,94 @@ describe("RuntimeDepsService", () => {
}
});
it.skip("clears runtime dependency directory", async () => {
const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), "certd-runtime-clear-"));
const runtimeRootDir = path.join(rootDir, ".runtime-deps");
fs.mkdirSync(path.join(runtimeRootDir, "node_modules", "foo"), { recursive: true });
fs.writeFileSync(path.join(runtimeRootDir, "package.json"), "{}", "utf8");
const service = new RuntimeDepsService();
service.runtimeDepsRootDir = runtimeRootDir;
service.installTimeoutMs = 1000;
await service.clearRuntimeDeps();
assert.equal(fs.existsSync(runtimeRootDir), true);
const remainingEntries = fs.readdirSync(runtimeRootDir).filter(e => e !== ".install.lock");
assert.equal(remainingEntries.length, 0);
});
it("rejects clearing unexpected runtime dependency path", async () => {
const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), "certd-runtime-clear-invalid-"));
const service = new RuntimeDepsService();
service.runtimeDepsRootDir = rootDir;
const service = new RuntimeDepsService({ rootDir }, null);
await assert.rejects(() => service.clearRuntimeDeps(), /动态依赖目录配置异常/);
});
});
describe("NpmRegistryResolver", () => {
it("returns the fastest successful registry via resolve()", async () => {
const resolver = new NpmRegistryResolver({
mode: "auto",
candidates: ["https://slow.example.com", "https://fast.example.com"],
probeTimeoutMs: 100,
cacheTtlMs: 1000,
});
resolver.probe = async (registryUrl: string) => ({
registryUrl,
ok: true,
elapsedMs: registryUrl.includes("fast") ? 10 : 50,
});
const result = await resolver.resolve();
assert.equal(result, "https://fast.example.com");
});
it("uses fixed registry without probing", async () => {
const resolver = new NpmRegistryResolver({
mode: "fixed",
fixedUrl: "https://registry.example.com",
probeTimeoutMs: 100,
cacheTtlMs: 1000,
});
const result = await resolver.resolve();
assert.equal(result, "https://registry.example.com");
});
it("returns ordered list via resolveOrdered (fastest first)", async () => {
const resolver = new NpmRegistryResolver({
mode: "auto",
candidates: ["https://slow.example.com", "https://fast.example.com"],
probeTimeoutMs: 100,
cacheTtlMs: 1000,
});
resolver.probe = async (registryUrl: string) => ({
registryUrl,
ok: true,
elapsedMs: registryUrl.includes("fast") ? 10 : 50,
});
const result = await resolver.resolveOrdered();
assert.deepEqual(result, ["https://fast.example.com", "https://slow.example.com"]);
});
it("includes failed registries at the end of resolveOrdered", async () => {
const resolver = new NpmRegistryResolver({
mode: "auto",
candidates: ["https://good.example.com", "https://bad.example.com"],
probeTimeoutMs: 100,
cacheTtlMs: 1000,
});
resolver.probe = async (registryUrl: string) => {
if (registryUrl.includes("bad")) {
return { registryUrl, ok: false, elapsedMs: 200 };
}
return { registryUrl, ok: true, elapsedMs: 30 };
};
const result = await resolver.resolveOrdered();
assert.deepEqual(result, ["https://good.example.com", "https://bad.example.com"]);
});
it("returns empty ordered list when no candidates", async () => {
const resolver = new NpmRegistryResolver({ mode: "auto", candidates: [] });
const result = await resolver.resolveOrdered();
assert.deepEqual(result, []);
const single = await resolver.resolve();
assert.equal(single, "");
});
it("re-validates cached URL on resolveOrdered call", async () => {
let probeCount = 0;
const resolver = new NpmRegistryResolver({
mode: "auto",
candidates: ["https://mirror.example.com"],
cacheTtlMs: 60000,
});
resolver.probe = async (registryUrl: string) => {
probeCount++;
return { registryUrl, ok: true, elapsedMs: 10 };
};
const first = await resolver.resolveOrdered();
assert.deepEqual(first, ["https://mirror.example.com"]);
assert.equal(probeCount, 1);
const second = await resolver.resolveOrdered();
assert.deepEqual(second, ["https://mirror.example.com"]);
assert.equal(probeCount, 2);
});
});
+821 -14
View File
@@ -1,27 +1,834 @@
/**
*
*/
export type ImportRuntime = (specifier: string, logger?: ILogger) => Promise<any>;
/**
*
*/
import fs from "fs";
import path from "path";
import { spawn } from "child_process";
import crypto from "crypto";
import { createRequire } from "module";
import { pathToFileURL } from "url";
import { logger as defaultLogger } from "@certd/basic";
import type { Registry } from "../registry/registry.js";
export type ILogger = {
info: (message: string) => void;
warn?: (message: string) => void;
error?: (message: string, ...args: any[]) => void;
};
/**
*
*/
export type ImportRuntime = (specifier: string, logger?: ILogger) => Promise<any>;
export type EnsureRuntimeDepsOptions = {
pluginKeys: string | string[];
logger?: ILogger;
};
/**
*
*/
export interface IRuntimeDepsService {
ensureRuntimeDependencies(options: EnsureRuntimeDepsOptions): Promise<any>;
importRuntime: ImportRuntime;
}
export type RuntimeDependencyPluginDefine = {
name: string;
key?: string;
title?: string;
version?: string;
pluginType?: string;
addonType?: string;
dependPlugins?: Record<string, string>;
dependPackages?: Record<string, string>;
};
type RegisteredDefineLike = RuntimeDependencyPluginDefine & {
key?: string;
pluginType?: string;
addonType?: string;
dependPlugins?: Record<string, string>;
dependPackages?: Record<string, string>;
};
type DependencyConflict = {
packageName: string;
ranges: Array<{ pluginName: string; range: string }>;
};
type CollectDependenciesResult = {
dependencies: Record<string, string>;
conflicts: DependencyConflict[];
};
type InstallResult = {
registryUrl: string;
packageJsonPath: string;
};
type RuntimeImportResolveResult = {
resolved: string;
packageName: string;
};
type CommandRunnerResult = {
stdout: string;
stderr: string;
code: number;
};
type CommandRunner = {
run(command: string, args: string[], options: { cwd: string; timeoutMs: number; env?: NodeJS.ProcessEnv }): Promise<CommandRunnerResult>;
};
export type NpmRegistryResolverConfig = {
mode?: "auto" | "fixed" | "system";
fixedUrl?: string;
candidates?: string[];
probeTimeoutMs?: number;
cacheTtlMs?: number;
};
export type RegistryProbeResult = {
registryUrl: string;
ok: boolean;
elapsedMs: number;
};
export class NpmRegistryResolver {
config: NpmRegistryResolverConfig;
private cache?: { orderedUrls: string[]; expiresAt: number };
constructor(config?: NpmRegistryResolverConfig) {
this.config = config || {};
}
async resolve(): Promise<string> {
const config = this.config;
if (config?.mode === "fixed" && config.fixedUrl) {
return config.fixedUrl;
}
if (config?.mode === "system") {
return "";
}
const cached = this.cache;
if (cached && cached.expiresAt > Date.now()) {
const fastUrl = cached.orderedUrls[0];
if (fastUrl) {
const probeResult = await this.probe(fastUrl);
if (probeResult.ok) {
return cached.orderedUrls[0] || "";
}
}
this.cache = undefined;
}
const candidates = (config?.candidates || []).filter(Boolean);
if (candidates.length === 0) {
return "";
}
const orderedUrls = await this.internalProbeAll(candidates);
this.cache = { orderedUrls, expiresAt: Date.now() + (config?.cacheTtlMs ?? 300_000) };
return orderedUrls[0] || "";
}
async resolveOrdered(): Promise<string[]> {
const config = this.config;
if (config?.mode === "fixed" && config.fixedUrl) {
return [config.fixedUrl];
}
if (config?.mode === "system") {
return [];
}
const cached = this.cache;
if (cached && cached.expiresAt > Date.now()) {
const fastUrl = cached.orderedUrls[0];
if (fastUrl) {
const probeResult = await this.probe(fastUrl);
if (probeResult.ok) {
return cached.orderedUrls;
}
}
this.cache = undefined;
}
const candidates = (config?.candidates || []).filter(Boolean);
if (candidates.length === 0) {
return [];
}
const orderedUrls = await this.internalProbeAll(candidates);
this.cache = { orderedUrls, expiresAt: Date.now() + (config?.cacheTtlMs ?? 300_000) };
return orderedUrls;
}
private async internalProbeAll(candidates: string[]): Promise<string[]> {
const probes = await Promise.allSettled(candidates.map(registryUrl => this.probe(registryUrl)));
const okList: RegistryProbeResult[] = [];
const failList: RegistryProbeResult[] = [];
for (const item of probes) {
const result = item.status === "fulfilled" ? item.value : null;
if (result && result.ok) {
okList.push(result);
} else if (result) {
failList.push(result);
}
}
okList.sort((a, b) => a.elapsedMs - b.elapsedMs);
failList.sort((a, b) => a.elapsedMs - b.elapsedMs);
return [...okList.map(r => r.registryUrl), ...failList.map(r => r.registryUrl)];
}
async probe(registryUrl: string): Promise<RegistryProbeResult> {
const timeoutMs = this.config?.probeTimeoutMs || 3000;
const started = Date.now();
try {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeoutMs);
try {
const res = await fetch(`${registryUrl.replace(/\/$/, "")}/-/ping`, { signal: controller.signal });
return { registryUrl, ok: res.ok, elapsedMs: Date.now() - started };
} finally {
clearTimeout(timer);
}
} catch {
return { registryUrl, ok: false, elapsedMs: Date.now() - started };
}
}
}
export type RuntimeDepsConfig = {
rootDir?: string;
autoInstall?: boolean;
enabled?: boolean;
installTimeoutMs?: number;
pnpmCommand?: string;
lazyDependencies?: Record<string, string>;
registry?: NpmRegistryResolverConfig;
};
function normalizeRange(range: string) {
return range.trim().replace(/^\^/, "").replace(/^~?/, "");
}
function areRangesCompatible(a: string, b: string) {
if (!a || !b) {
return true;
}
if (a === "*" || b === "*") {
return true;
}
const left = normalizeRange(a).split(".");
const right = normalizeRange(b).split(".");
return left[0] === right[0];
}
const PROCESS_LOCKS = new Map<string, Promise<unknown>>();
class DefaultCommandRunner implements CommandRunner {
async run(command: string, args: string[], options: { cwd: string; timeoutMs: number; env?: NodeJS.ProcessEnv }): Promise<CommandRunnerResult> {
return await new Promise<CommandRunnerResult>(resolve => {
let stdout = "";
let stderr = "";
let settled = false;
const child = spawn(command, args, { cwd: options.cwd, env: options.env, windowsHide: true, shell: process.platform === "win32" });
const timer = setTimeout(() => {
if (settled) {
return;
}
settled = true;
child.kill("SIGTERM");
resolve({ stdout, stderr: stderr || `command timeout after ${options.timeoutMs}ms`, code: 1 });
}, options.timeoutMs);
child.stdout?.on("data", chunk => {
stdout += chunk.toString();
});
child.stderr?.on("data", chunk => {
stderr += chunk.toString();
});
child.on("error", error => {
if (settled) {
return;
}
settled = true;
clearTimeout(timer);
resolve({ stdout, stderr: error.message, code: 1 });
});
child.on("close", code => {
if (settled) {
return;
}
settled = true;
clearTimeout(timer);
resolve({ stdout, stderr, code: code || 0 });
});
});
}
}
export class RuntimeDepsService {
runtimeDepsRootDir: string;
autoInstall: boolean;
enabled: boolean;
installTimeoutMs: number;
pnpmCommand: string;
lazyDependencies: Record<string, string>;
registryResolver!: NpmRegistryResolver;
commandRunner: CommandRunner = new DefaultCommandRunner();
pluginLazyDependencies: Record<string, string> = {};
private installPromises = new Map<string, Promise<InstallResult>>();
private registriesMap: Record<string, { registry: Registry<any>; pluginType: string; addonType?: string }> | null = null;
constructor(config: RuntimeDepsConfig, registries: any) {
this.runtimeDepsRootDir = config?.rootDir ?? "./data/.runtime-deps";
this.autoInstall = config?.autoInstall ?? true;
this.enabled = config?.enabled ?? true;
this.installTimeoutMs = config?.installTimeoutMs ?? 120000;
this.pnpmCommand = config?.pnpmCommand ?? "";
this.lazyDependencies = config?.lazyDependencies ?? {};
this.registryResolver = new NpmRegistryResolver(config?.registry);
if (registries) {
this.setRegistries(registries);
}
}
setRegistries(registries: { pluginRegistry?: Registry<any>; accessRegistry?: Registry<any>; notificationRegistry?: Registry<any>; dnsProviderRegistry?: Registry<any>; addonRegistry?: Registry<any> }) {
const map: Record<string, { registry: Registry<any>; pluginType: string; addonType?: string }> = {};
if (registries.pluginRegistry) {
map["plugin"] = { registry: registries.pluginRegistry, pluginType: "plugin" };
}
if (registries.accessRegistry) {
map["access"] = { registry: registries.accessRegistry, pluginType: "access" };
}
if (registries.notificationRegistry) {
map["notification"] = { registry: registries.notificationRegistry, pluginType: "notification" };
}
if (registries.dnsProviderRegistry) {
map["dnsProvider"] = { registry: registries.dnsProviderRegistry, pluginType: "dnsProvider" };
}
if (registries.addonRegistry) {
map["addon"] = { registry: registries.addonRegistry, pluginType: "addon", addonType: "" };
}
this.registriesMap = map;
}
collectDependencies(plugins: RuntimeDependencyPluginDefine[]): CollectDependenciesResult {
const merged: Record<string, string> = {};
const seen: Record<string, Array<{ pluginName: string; range: string }>> = {};
for (const plugin of plugins) {
const deps = plugin.dependPackages || {};
for (const [packageName, range] of Object.entries(deps)) {
seen[packageName] ||= [];
seen[packageName].push({ pluginName: plugin.name, range });
}
}
const conflicts: DependencyConflict[] = [];
for (const [packageName, ranges] of Object.entries(seen)) {
const first = ranges[0]?.range;
if (!first) {
continue;
}
const conflict = ranges.some(item => !areRangesCompatible(first, item.range));
if (conflict) {
conflicts.push({ packageName, ranges });
continue;
}
merged[packageName] = first;
}
return { dependencies: merged, conflicts };
}
async ensureInstalled(options: { plugins: RuntimeDependencyPluginDefine[]; logger?: ILogger }): Promise<InstallResult> {
const { plugins, logger: log } = options;
const { dependencies, conflicts } = this.resolveDependenciesFromPlugins(plugins);
if (conflicts.length > 0) {
const conflict = conflicts[0];
throw new Error(`动态依赖版本冲突: ${conflict.packageName} => ${conflict.ranges.map(item => `${item.pluginName}:${item.range}`).join(", ")}`);
}
return await this.ensureDependencies({ dependencies, logger: log });
}
async ensureDependencies(options: { dependencies: Record<string, string>; logger?: ILogger }): Promise<InstallResult> {
const { dependencies, logger: log } = options;
if (!this.enabled) {
return { registryUrl: "", packageJsonPath: path.join(this.getRuntimeDepsRootDir(), "package.json") };
}
if (!this.autoInstall) {
return { registryUrl: "", packageJsonPath: path.join(this.getRuntimeDepsRootDir(), "package.json") };
}
const dependenciesHash = this.createDependenciesHash(dependencies);
let installPromise = this.installPromises.get(dependenciesHash);
if (installPromise) {
const nodeModulesPath = path.join(this.getRuntimeDepsRootDir(), "node_modules");
if (!fs.existsSync(nodeModulesPath)) {
this.installPromises.delete(dependenciesHash);
installPromise = undefined;
}
}
if (!installPromise) {
installPromise = this.doEnsureInstalled({ dependencies, logger: log }).catch(error => {
this.installPromises.delete(dependenciesHash);
throw error;
});
this.installPromises.set(dependenciesHash, installPromise);
}
return await installPromise;
}
resolveDependenciesFromPlugins(plugins: RuntimeDependencyPluginDefine[]): CollectDependenciesResult {
const expandedPlugins = plugins.flatMap(plugin => this.resolvePluginDependencies(plugin));
return this.collectDependencies(expandedPlugins);
}
async ensureRuntimeDependencies(options: { pluginKeys: string | string[]; logger?: ILogger }): Promise<InstallResult> {
const { pluginKeys, logger: log } = options;
const keys = Array.isArray(pluginKeys) ? pluginKeys : [pluginKeys];
const pluginDefines = keys.map(pluginKey => this.getDefineByPluginKey(pluginKey));
if (pluginDefines.every(pluginDefine => !pluginDefine.dependPackages && !pluginDefine.dependPlugins)) {
return { registryUrl: "", packageJsonPath: path.join(this.getRuntimeDepsRootDir(), "package.json") };
}
const expandedPluginDefines = pluginDefines.flatMap(pluginDefine => this.resolvePluginDependencies(pluginDefine));
return await this.ensureInstalled({ plugins: expandedPluginDefines, logger: log });
}
async importRuntime(specifier: string, logger: ILogger = defaultLogger) {
if (this.isNativeImportSpecifier(specifier)) {
return await import(specifier);
}
const resolved = await this.resolveImportSpecifier(specifier, logger);
return await import(pathToFileURL(resolved).href);
}
private async resolveImportSpecifier(specifier: string, logger: ILogger = defaultLogger) {
try {
return this.resolveRuntimeSpecifier(specifier).resolved;
} catch (runtimeError: any) {
if (!this.isModuleNotFoundError(runtimeError)) {
throw runtimeError;
}
return await this.resolveMissingRuntimeSpecifier(specifier, runtimeError, logger);
}
}
private async resolveMissingRuntimeSpecifier(specifier: string, runtimeError: any, logger?: ILogger) {
const packageName = this.parsePackageName(specifier);
const mergedDeps = this.getMergedLazyDependencies();
const lazyRange = mergedDeps[packageName];
if (!lazyRange) {
try {
return this.resolveProjectSpecifier(specifier, runtimeError).resolved;
} catch {
throw new Error(`动态依赖未安装且未配置懒加载版本: ${packageName}`);
}
}
try {
await this.ensureLazyDependency(packageName, logger);
return this.resolveRuntimeSpecifier(specifier).resolved;
} catch (lazyError: any) {
logger?.error?.(`动态依赖安装失败: ${lazyError.message}`);
return this.resolveProjectSpecifier(specifier, lazyError).resolved;
}
}
private isNativeImportSpecifier(specifier: string) {
return specifier.startsWith(".") || specifier.startsWith("/") || specifier.startsWith("file:") || specifier.startsWith("node:");
}
private resolveRuntimeSpecifier(specifier: string): RuntimeImportResolveResult {
const packageName = this.parsePackageName(specifier);
const packageJsonPath = path.join(this.getRuntimeDepsRootDir(), "package.json");
const require = createRequire(packageJsonPath);
const resolved = require.resolve(specifier);
return { packageName, resolved };
}
private resolveProjectSpecifier(specifier: string, cause?: any): RuntimeImportResolveResult {
try {
const packageName = this.parsePackageName(specifier);
const packageJsonPath = path.resolve("package.json");
const require = createRequire(packageJsonPath);
const resolved = require.resolve(specifier);
return { packageName, resolved };
} catch (projectError: any) {
if (cause) {
projectError.cause = cause;
}
throw projectError;
}
}
private parsePackageName(specifier: string) {
if (!specifier || specifier.trim() !== specifier) {
throw new Error(`动态依赖导入路径无效: ${specifier}`);
}
const parts = specifier.split("/");
if (specifier.startsWith("@")) {
if (parts.length < 2 || !parts[0] || !parts[1]) {
throw new Error(`动态依赖导入路径无效: ${specifier}`);
}
return `${parts[0]}/${parts[1]}`;
}
if (!parts[0]) {
throw new Error(`动态依赖导入路径无效: ${specifier}`);
}
return parts[0];
}
private async ensureLazyDependency(packageName: string, logger?: ILogger) {
const range = this.lazyDependencies?.[packageName];
if (!range) {
throw new Error(`动态依赖未安装且未配置懒加载版本: ${packageName}`);
}
await this.ensureDependencies({ dependencies: { [packageName]: range }, logger });
}
private isModuleNotFoundError(error: any) {
return error?.code === "MODULE_NOT_FOUND" || error?.code === "ERR_MODULE_NOT_FOUND";
}
resolvePluginDependencies(current: RuntimeDependencyPluginDefine): RuntimeDependencyPluginDefine[] {
const resolved: RuntimeDependencyPluginDefine[] = [];
const visited = new Set<string>();
const visit = (item: RuntimeDependencyPluginDefine) => {
const key = this.buildPluginDependencyKey(item);
if (visited.has(key)) {
return;
}
visited.add(key);
resolved.push(item);
for (const [dependencyName, expectedRange] of Object.entries(item.dependPlugins || {})) {
const dependency = this.getDefineByPluginKey(dependencyName, item);
if (!isPluginVersionCompatible(dependency, expectedRange)) {
throw new Error(`插件依赖版本冲突: ${item.name} 依赖 ${dependencyName}@${expectedRange},当前版本为 ${dependency.version || "未声明"}`);
}
visit(dependency);
}
};
visit(current);
return resolved;
}
private buildPluginDependencyKey(plugin: RuntimeDependencyPluginDefine) {
if (plugin.pluginType === "addon" && plugin.addonType) {
return `addon:${plugin.addonType}:${plugin.name}`;
}
const pluginType = plugin.pluginType === "deploy" ? "plugin" : plugin.pluginType || "unknown";
return `${pluginType}:${plugin.name}`;
}
private getDefineByPluginKey(pluginKey: string, owner?: RuntimeDependencyPluginDefine): RuntimeDependencyPluginDefine {
const parts = pluginKey.split(":");
let pluginType: string, name: string, subtype: string | undefined;
if (parts.length === 2) {
[pluginType, name] = parts;
} else if (parts.length === 3) {
[pluginType, subtype, name] = parts;
} else {
const ownerName = owner?.name || pluginKey;
throw new Error(`插件依赖格式错误: ${ownerName} 依赖 ${pluginKey}`);
}
if (!this.registriesMap) {
throw new Error("注册表未设置,请先调用 setRegistries");
}
const target = this.registriesMap[pluginType];
if (!target) {
const ownerName = owner?.name || pluginKey;
throw new Error(`插件依赖格式错误: ${ownerName} 依赖 ${pluginKey},未知插件类型 ${pluginType}`);
}
// addon 类型的 key 需要包含 subtype
const registryKey = pluginType === "addon" && subtype ? `${subtype}:${name}` : name;
const define = target.registry.getDefine(registryKey) as RegisteredDefineLike;
if (!define) {
throw new Error(`插件依赖缺失: ${owner?.name || pluginKey} 依赖 ${pluginKey},但该插件未注册或已禁用`);
}
return { ...define, key: pluginKey, pluginType: target.pluginType, addonType: target.addonType };
}
private async doEnsureInstalled(options: { dependencies: Record<string, string>; logger?: ILogger }): Promise<InstallResult> {
let { dependencies } = options;
const log = options.logger || defaultLogger;
return await this.withInstallLock(async () => {
const rootDir = this.getRuntimeDepsRootDir();
const packageJsonPath = path.join(rootDir, "package.json");
const lockPath = path.join(rootDir, "pnpm-lock.yaml");
log.info(`第三方依赖安装: ${JSON.stringify(dependencies)}`);
dependencies = this.mergeInstalledDependencies(this.readManifestDependencies(packageJsonPath), dependencies);
const dependenciesHash = this.createDependenciesHash(dependencies);
const statePath = path.join(rootDir, "install-state.json");
const currentState = this.readInstallState(statePath);
if (currentState?.dependenciesHash === dependenciesHash && fs.existsSync(path.join(rootDir, "node_modules"))) {
log.info("第三方依赖已安装");
return { registryUrl: currentState.registryUrl || "", packageJsonPath };
}
const manifest = { name: "certd-runtime-deps", private: true, type: "module", dependencies };
fs.writeFileSync(packageJsonPath, JSON.stringify(manifest, null, 2), "utf8");
const registryUrl = await this.registryResolver.resolve();
const env = this.buildChildEnv(registryUrl);
const command = this.getPnpmCommand();
const pnpmVersion = await this.getPnpmVersion(command, env);
const allRegistryUrls = await this.registryResolver.resolveOrdered();
const urlsToTry = allRegistryUrls.length > 0 ? allRegistryUrls : [""];
let lastError: string | undefined;
for (const tryUrl of urlsToTry) {
const args = ["install", "--prod", "--ignore-scripts", "--ignore-workspace", "--no-frozen-lockfile", "--reporter=append-only"];
if (tryUrl) {
args.push(`--registry=${tryUrl}`);
}
const tryEnv = tryUrl ? this.buildChildEnv(tryUrl) : env;
log.info(`开始安装第三方依赖: ${Object.keys(dependencies).join(", ")}${tryUrl ? `,镜像: ${tryUrl}` : ""}`);
const result = await this.commandRunner.run(command, args, { cwd: rootDir, timeoutMs: this.installTimeoutMs, env: tryEnv });
if (result.code === 0) {
this.writeInstallState(statePath, { installedAt: new Date().toISOString(), registryUrl: tryUrl, dependenciesHash, nodeVersion: process.version, pnpmVersion, lockFileExists: fs.existsSync(lockPath) });
log.info(`${result.stdout?.slice(-2000) || "无npm安装日志输出"}`);
log.info("第三方依赖安装完成");
return { registryUrl: tryUrl, packageJsonPath };
}
const errOutput = (result.stderr || "").trim();
const outOutput = (result.stdout || "").trim();
lastError = errOutput || outOutput || "unknown error";
log.info(`镜像 ${tryUrl || "默认"} 安装失败,退出码: ${result.code}${urlsToTry.length > 1 ? ",尝试下一个镜像..." : ""}`);
log.info(` pnpm stderr: ${(errOutput || "无npm安装日志输出").slice(-2000)}`);
if (outOutput) {
log.info(` pnpm stdout: ${outOutput.slice(-2000)}`);
}
}
this.writeInstallState(statePath, {
...currentState,
installedAt: currentState?.installedAt,
failedAt: new Date().toISOString(),
registryUrl: urlsToTry[0],
dependenciesHash,
nodeVersion: process.version,
pnpmVersion,
lockFileExists: fs.existsSync(lockPath),
lastError,
});
throw new Error(`动态依赖安装失败: ${lastError}`);
});
}
private async withInstallLock<T>(run: () => Promise<T>): Promise<T> {
const rootDir = this.getRuntimeDepsRootDir();
fs.mkdirSync(rootDir, { recursive: true });
const lockFile = path.join(rootDir, ".install.lock");
const previous = PROCESS_LOCKS.get(lockFile);
if (previous) {
await previous.catch(() => undefined);
}
let releaseProcessLock!: () => void;
const current = new Promise<void>(resolve => {
releaseProcessLock = resolve;
});
PROCESS_LOCKS.set(lockFile, current);
let fd: number | undefined;
try {
fd = await this.acquireFileLock(lockFile);
return await run();
} finally {
if (fd != null) {
fs.closeSync(fd);
try {
fs.rmSync(lockFile, { force: true });
} catch {
try {
fs.rmSync(lockFile, { force: true });
} catch {}
}
}
releaseProcessLock();
if (PROCESS_LOCKS.get(lockFile) === current) {
PROCESS_LOCKS.delete(lockFile);
}
}
}
private async acquireFileLock(lockFile: string) {
const deadline = Date.now() + this.installTimeoutMs;
while (true) {
try {
const fd = fs.openSync(lockFile, "wx");
fs.writeFileSync(fd, JSON.stringify({ pid: process.pid, createdAt: new Date().toISOString() }), "utf8");
return fd;
} catch (error: any) {
if (error?.code !== "EEXIST") {
throw error;
}
if (Date.now() > deadline) {
throw new Error(`动态依赖安装锁等待超时: ${lockFile}`);
}
await this.waitForExternalLock(lockFile, deadline);
}
}
}
private async waitForExternalLock(lockFile: string, deadline: number) {
while (fs.existsSync(lockFile)) {
if (Date.now() > deadline) {
throw new Error(`动态依赖安装锁等待超时: ${lockFile}`);
}
await new Promise(resolve => setTimeout(resolve, 300));
}
}
async clearRuntimeDeps() {
const rootDir = this.getRuntimeDepsRootDir();
const normalizedRootDir = path.normalize(rootDir);
if (!normalizedRootDir.endsWith(path.normalize(".runtime-deps"))) {
throw new Error(`动态依赖目录配置异常,拒绝清理: ${rootDir}`);
}
await this.withInstallLock(async () => {
if (fs.existsSync(rootDir)) {
const entries = fs.readdirSync(rootDir);
for (const entry of entries) {
if (entry === ".install.lock") {
continue;
}
fs.rmSync(path.join(rootDir, entry), { recursive: true, force: true });
}
}
this.installPromises.clear();
return undefined;
});
}
getMergedLazyDependencies(): Record<string, string> {
return { ...this.lazyDependencies, ...this.pluginLazyDependencies };
}
collectPluginDeps(logger?: ILogger) {
if (!this.registriesMap) {
return;
}
const deps: Record<string, string> = {};
for (const { registry } of Object.values(this.registriesMap)) {
const defineList = registry.getDefineList();
for (const define of defineList) {
const dependPackages = (define as any).dependPackages as Record<string, string> | undefined;
if (!dependPackages) {
continue;
}
for (const [pkgName, range] of Object.entries(dependPackages)) {
const existing = deps[pkgName];
if (existing && !areRangesCompatible(existing, range)) {
(logger || defaultLogger).warn?.(`懒加载依赖版本冲突: ${pkgName} => ${existing} vs ${range},保留已有版本`);
continue;
}
deps[pkgName] = range;
}
}
}
this.pluginLazyDependencies = deps;
(logger || defaultLogger).info(`从插件注册表收集到 ${Object.keys(deps).length} 个懒加载依赖`);
}
refreshPluginDeps(logger?: ILogger) {
this.collectPluginDeps(logger);
}
private readInstallState(statePath: string): any {
if (!fs.existsSync(statePath)) {
return null;
}
try {
return JSON.parse(fs.readFileSync(statePath, "utf8"));
} catch {
return null;
}
}
private writeInstallState(statePath: string, state: any) {
fs.writeFileSync(statePath, JSON.stringify(state, null, 2), "utf8");
}
private readManifestDependencies(packageJsonPath: string): Record<string, string> {
if (!fs.existsSync(packageJsonPath)) {
return {};
}
try {
const manifest = JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));
return manifest.dependencies || {};
} catch {
return {};
}
}
private mergeInstalledDependencies(installed: Record<string, string>, requested: Record<string, string>) {
const dependencies = { ...installed };
for (const [packageName, range] of Object.entries(requested)) {
const installedRange = dependencies[packageName];
if (installedRange && !areRangesCompatible(installedRange, range)) {
throw new Error(`动态依赖版本冲突: ${packageName} => installed:${installedRange}, requested:${range}`);
}
dependencies[packageName] = installedRange || range;
}
return dependencies;
}
private async getPnpmVersion(command: string, env: NodeJS.ProcessEnv) {
const result = await this.commandRunner.run(command, ["--version"], { cwd: this.getRuntimeDepsRootDir(), timeoutMs: Math.min(this.installTimeoutMs, 10000), env });
if (result.code !== 0) {
return "";
}
return (result.stdout || result.stderr || "").trim();
}
private getPnpmCommand() {
return this.pnpmCommand || "pnpm";
}
private buildChildEnv(registryUrl: string) {
const env = { ...process.env };
for (const key of ["NODE_OPTIONS", "VSCODE_INSPECTOR_OPTIONS", "NODE_INSPECTOR_PORT", "NODE_DEBUG"]) {
if (!env[key]) {
continue;
}
if (key === "NODE_OPTIONS") {
env[key] = this.stripDebugNodeOptions(env[key] as string);
} else {
delete env[key];
}
}
if (registryUrl) {
env.npm_config_registry = registryUrl;
env.pnpm_config_registry = registryUrl;
}
env.CI = env.CI || "true";
env.npm_config_confirm_modules_purge = "false";
env.pnpm_config_confirm_modules_purge = "false";
return env;
}
private stripDebugNodeOptions(value: string) {
return value
.split(/\s+/)
.filter(Boolean)
.filter(item => !/^--inspect(-brk|-port)?(=|$)/.test(item))
.filter(item => !/^--debug(=|$)/.test(item))
.join(" ");
}
getRuntimeDepsRootDir() {
return path.resolve(this.runtimeDepsRootDir);
}
private createDependenciesHash(dependencies: Record<string, string>) {
return crypto.createHash("sha256").update(JSON.stringify(dependencies)).digest("hex");
}
}
function isPluginVersionCompatible(plugin: RuntimeDependencyPluginDefine, expectedRange: string) {
if (!expectedRange || expectedRange === "*") {
return true;
}
if (!plugin.version) {
return false;
}
return areRangesCompatible(expectedRange, plugin.version);
}
let runtimeDepsServiceInstance: RuntimeDepsService | null = null;
export function initRuntimeDepsService(config: RuntimeDepsConfig, registries: any): RuntimeDepsService {
runtimeDepsServiceInstance = new RuntimeDepsService(config, registries);
return runtimeDepsServiceInstance;
}
export function getRuntimeDepsService(): RuntimeDepsService {
if (!runtimeDepsServiceInstance) {
throw new Error("RuntimeDepsService 未初始化");
}
return runtimeDepsServiceInstance!;
}
export async function importRuntime(specifier: string, logger: ILogger = defaultLogger): Promise<any> {
return getRuntimeDepsService().importRuntime(specifier, logger);
}
+12
View File
@@ -3,6 +3,18 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.42.6](https://github.com/certd/certd/compare/v1.42.5...v1.42.6) (2026-07-18)
**Note:** Version bump only for package @certd/lib-huawei
## [1.42.5](https://github.com/certd/certd/compare/v1.42.4...v1.42.5) (2026-07-15)
**Note:** Version bump only for package @certd/lib-huawei
## [1.42.4](https://github.com/certd/certd/compare/v1.42.3...v1.42.4) (2026-07-11)
**Note:** Version bump only for package @certd/lib-huawei
## [1.42.3](https://github.com/certd/certd/compare/v1.42.2...v1.42.3) (2026-07-08)
**Note:** Version bump only for package @certd/lib-huawei
+3 -2
View File
@@ -1,7 +1,7 @@
{
"name": "@certd/lib-huawei",
"private": false,
"version": "1.42.3",
"version": "1.42.6",
"main": "./dist/bundle.js",
"module": "./dist/bundle.js",
"types": "./dist/d/index.d.ts",
@@ -26,9 +26,10 @@
"@typescript-eslint/eslint-plugin": "^8.26.1",
"@typescript-eslint/parser": "^8.26.1",
"cross-env": "^7.0.3",
"eslint": "^8.57.0",
"esmock": "^2.7.5",
"prettier": "3.3.3",
"tslib": "^2.8.1"
},
"gitHead": "7808d028e9c7e1b1e3ebc41f12b023d7b553300b"
"gitHead": "246ee83015bf5589adc2a5fa3d1388c8d9a2a252"
}
+12
View File
@@ -3,6 +3,18 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.42.6](https://github.com/certd/certd/compare/v1.42.5...v1.42.6) (2026-07-18)
**Note:** Version bump only for package @certd/lib-iframe
## [1.42.5](https://github.com/certd/certd/compare/v1.42.4...v1.42.5) (2026-07-15)
**Note:** Version bump only for package @certd/lib-iframe
## [1.42.4](https://github.com/certd/certd/compare/v1.42.3...v1.42.4) (2026-07-11)
**Note:** Version bump only for package @certd/lib-iframe
## [1.42.3](https://github.com/certd/certd/compare/v1.42.2...v1.42.3) (2026-07-08)
**Note:** Version bump only for package @certd/lib-iframe
+2 -2
View File
@@ -1,7 +1,7 @@
{
"name": "@certd/lib-iframe",
"private": false,
"version": "1.42.3",
"version": "1.42.6",
"type": "module",
"main": "./dist/index.js",
"module": "./dist/index.js",
@@ -37,5 +37,5 @@
"tslib": "^2.8.1",
"typescript": "^5.4.2"
},
"gitHead": "7808d028e9c7e1b1e3ebc41f12b023d7b553300b"
"gitHead": "246ee83015bf5589adc2a5fa3d1388c8d9a2a252"
}
@@ -1,4 +1,4 @@
import { nanoid } from 'nanoid';
import { nanoid } from "nanoid";
export type IframeMessageData<T> = {
action: string;
@@ -29,10 +29,12 @@ export class IframeClient {
onError?: any;
handlers: Record<string, (data: IframeMessageData<any>) => Promise<void>> = {};
private messageHandler: (event: MessageEvent<IframeMessageData<any>>) => Promise<void>;
constructor(iframe?: HTMLIFrameElement, onError?: (e: any) => void) {
this.iframe = iframe;
this.onError = onError;
window.addEventListener('message', async (event: MessageEvent<IframeMessageData<any>>) => {
this.messageHandler = async (event: MessageEvent<IframeMessageData<any>>) => {
const data = event.data;
if (data.action) {
console.log(`收到消息[isSub:${this.isInFrame()}]`, data);
@@ -40,20 +42,21 @@ export class IframeClient {
const handler = this.handlers[data.action];
if (handler) {
const res = await handler(data);
if (data.id && data.action !== 'reply') {
await this.send('reply', res, data.id);
if (data.id && data.action !== "reply") {
await this.send("reply", res, data.id);
}
} else {
throw new Error(`action:${data.action} 未注册处理器,可能版本过低`);
}
} catch (e: any) {
console.error(e);
await this.send('reply', {}, data.id, 500, e.message);
await this.send("reply", {}, data.id, 500, e.message);
}
}
});
};
window.addEventListener("message", this.messageHandler);
this.register('reply', async data => {
this.register("reply", async data => {
const req = this.requestQueue[data.replyId!];
if (req) {
req.onReply(data);
@@ -61,11 +64,17 @@ export class IframeClient {
}
});
}
isInFrame() {
public destroy() {
window.removeEventListener("message", this.messageHandler);
this.requestQueue = {};
this.handlers = {};
}
public isInFrame() {
return window.self !== window.top;
}
register<T = any>(action: string, handler: (data: IframeMessageData<T>) => Promise<any>) {
public register<T = any>(action: string, handler: (data: IframeMessageData<T>) => Promise<any>) {
this.handlers[action] = handler;
}
@@ -106,12 +115,12 @@ export class IframeClient {
console.log(`send message[isSub:${this.isInFrame()}]:`, reqMessageData);
if (!this.iframe) {
if (!window.parent) {
reject('当前页面不在 iframe 中');
reject("当前页面不在 iframe 中");
}
window.parent.postMessage(reqMessageData, '*');
window.parent.postMessage(reqMessageData, "*");
} else {
//子页面
this.iframe.contentWindow?.postMessage(reqMessageData, '*');
this.iframe.contentWindow?.postMessage(reqMessageData, "*");
}
} catch (e) {
console.error(e);
+12
View File
@@ -3,6 +3,18 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.42.6](https://github.com/certd/certd/compare/v1.42.5...v1.42.6) (2026-07-18)
**Note:** Version bump only for package @certd/jdcloud
## [1.42.5](https://github.com/certd/certd/compare/v1.42.4...v1.42.5) (2026-07-15)
**Note:** Version bump only for package @certd/jdcloud
## [1.42.4](https://github.com/certd/certd/compare/v1.42.3...v1.42.4) (2026-07-11)
**Note:** Version bump only for package @certd/jdcloud
## [1.42.3](https://github.com/certd/certd/compare/v1.42.2...v1.42.3) (2026-07-08)
**Note:** Version bump only for package @certd/jdcloud
+3 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@certd/jdcloud",
"version": "1.42.3",
"version": "1.42.6",
"description": "jdcloud openApi sdk",
"main": "./dist/bundle.js",
"module": "./dist/bundle.js",
@@ -35,6 +35,7 @@
"chai": "^5.1.0",
"config": "^1.30.0",
"cross-env": "^7.0.3",
"eslint": "^8.57.0",
"esmock": "^2.7.5",
"js-yaml": "^3.11.0",
"mocha": "^10.6.0",
@@ -62,5 +63,5 @@
"fetch"
]
},
"gitHead": "7808d028e9c7e1b1e3ebc41f12b023d7b553300b"
"gitHead": "246ee83015bf5589adc2a5fa3d1388c8d9a2a252"
}
+12
View File
@@ -3,6 +3,18 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.42.6](https://github.com/certd/certd/compare/v1.42.5...v1.42.6) (2026-07-18)
**Note:** Version bump only for package @certd/lib-k8s
## [1.42.5](https://github.com/certd/certd/compare/v1.42.4...v1.42.5) (2026-07-15)
**Note:** Version bump only for package @certd/lib-k8s
## [1.42.4](https://github.com/certd/certd/compare/v1.42.3...v1.42.4) (2026-07-11)
**Note:** Version bump only for package @certd/lib-k8s
## [1.42.3](https://github.com/certd/certd/compare/v1.42.2...v1.42.3) (2026-07-08)
**Note:** Version bump only for package @certd/lib-k8s
+3 -3
View File
@@ -1,7 +1,7 @@
{
"name": "@certd/lib-k8s",
"private": false,
"version": "1.42.3",
"version": "1.42.6",
"type": "module",
"main": "./dist/index.js",
"module": "./dist/index.js",
@@ -21,7 +21,7 @@
"lint": "eslint --fix"
},
"dependencies": {
"@certd/basic": "^1.42.3",
"@certd/basic": "^1.42.6",
"@kubernetes/client-node": "0.21.0"
},
"devDependencies": {
@@ -38,5 +38,5 @@
"tslib": "^2.8.1",
"typescript": "^5.4.2"
},
"gitHead": "7808d028e9c7e1b1e3ebc41f12b023d7b553300b"
"gitHead": "246ee83015bf5589adc2a5fa3d1388c8d9a2a252"
}
+18
View File
@@ -3,6 +3,24 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.42.6](https://github.com/certd/certd/compare/v1.42.5...v1.42.6) (2026-07-18)
### Bug Fixes
* 修复正常批量删除流水线报权限不足的bug ([5b50083](https://github.com/certd/certd/commit/5b500830a122c6c42dab054e57fed509050f94da))
## [1.42.5](https://github.com/certd/certd/compare/v1.42.4...v1.42.5) (2026-07-15)
### Bug Fixes
* 修复上传到cos报runtimeDepsService未初始化的问题 ([167b303](https://github.com/certd/certd/commit/167b303faeca02cc11cf97e4be2a3df914852167))
## [1.42.4](https://github.com/certd/certd/compare/v1.42.3...v1.42.4) (2026-07-11)
### Bug Fixes
* **pipeline:** 重构运行时依赖加载逻辑,修复火山引擎DNS解析报runtimeDepsService未初始化的bug ([ec69b8f](https://github.com/certd/certd/commit/ec69b8f11bfd4b20991aef74a72a47182ca79a9d))
## [1.42.3](https://github.com/certd/certd/compare/v1.42.2...v1.42.3) (2026-07-08)
**Note:** Version bump only for package @certd/lib-server
+7 -7
View File
@@ -1,6 +1,6 @@
{
"name": "@certd/lib-server",
"version": "1.42.3",
"version": "1.42.6",
"description": "midway with flyway, sql upgrade way ",
"private": false,
"type": "module",
@@ -29,11 +29,11 @@
],
"license": "AGPL",
"dependencies": {
"@certd/acme-client": "^1.42.3",
"@certd/basic": "^1.42.3",
"@certd/pipeline": "^1.42.3",
"@certd/plugin-lib": "^1.42.3",
"@certd/plus-core": "^1.42.3",
"@certd/acme-client": "^1.42.6",
"@certd/basic": "^1.42.6",
"@certd/pipeline": "^1.42.6",
"@certd/plugin-lib": "^1.42.6",
"@certd/plus-core": "^1.42.6",
"@midwayjs/cache": "3.14.0",
"@midwayjs/core": "3.20.11",
"@midwayjs/i18n": "3.20.13",
@@ -69,5 +69,5 @@
"typeorm": "^0.3.20",
"typescript": "^5.4.2"
},
"gitHead": "7808d028e9c7e1b1e3ebc41f12b023d7b553300b"
"gitHead": "246ee83015bf5589adc2a5fa3d1388c8d9a2a252"
}
@@ -0,0 +1,34 @@
/// <reference types="mocha" />
import assert from "node:assert/strict";
import { AuditLogContext } from "./audit.js";
// AuditLog decorator and getAuditLogOptions are removed since auditLog()
// now signals audit intent directly via ctx.auditLog.enabled
describe("AuditLogContext type", () => {
it("supports enabled flag", () => {
const ctx: AuditLogContext = {
type: "pipeline",
action: "删除流水线",
append: ["ID:5"],
content: "删除了流水线(ID:5)",
projectId: 3,
enabled: true,
};
assert.equal(ctx.enabled, true);
assert.equal(ctx.type, "pipeline");
assert.equal(ctx.content, "删除了流水线(ID:5)");
assert.equal(ctx.projectId, 3);
});
it("works with minimal fields", () => {
const ctx: AuditLogContext = {
enabled: true,
append: ["提交2条"],
};
assert.equal(ctx.enabled, true);
});
});
@@ -0,0 +1,44 @@
export type AuditLogOptions = {
type?: string;
action?: string;
content?: string;
template?: string;
disabled?: boolean;
};
export type AuditLogContext = {
type?: string;
action?: string;
append?: string | string[];
content?: string;
projectId?: number;
enabled?: boolean;
scope?: string;
userId?: number;
username?: string;
success?: boolean;
};
/** 审计日志方法的参数类型 */
export type AuditLogParam = {
type?: string;
action?: string;
content?: string;
append?: string | string[];
projectId?: number;
userId?: number;
username?: string;
};
/** AuditService.log() 参数类型 */
export type AuditLogWriteParam = {
userId: number;
type: string;
action: string;
content: string;
username?: string;
projectId?: number;
ipAddress?: string;
scope?: string;
success?: boolean;
};
@@ -3,6 +3,7 @@ import type { IMidwayContainer } from "@midwayjs/core";
import * as koa from "@midwayjs/koa";
import { Constants } from "./constants.js";
import { isEnterprise } from "./mode.js";
import type { AuditLogContext, AuditLogParam } from "./audit.js";
export abstract class BaseController {
@Inject()
@@ -127,4 +128,43 @@ export abstract class BaseController {
}
return { projectId, userId };
}
getAuditType(): string {
return "unknown";
}
auditLog(bean: AuditLogParam = {}) {
const auditLog = this.ensureAuditLogContext();
auditLog.enabled = true;
if (bean.userId != null) {
auditLog.userId = bean.userId;
}
if (bean.username != null) {
auditLog.username = bean.username;
}
if (bean.type != null) {
auditLog.type = bean.type;
}
if (bean.action != null) {
auditLog.action = bean.action;
}
if (bean.projectId != null) {
auditLog.projectId = bean.projectId;
}
if (bean.content) {
auditLog.content = bean.content;
}
if (bean.append) {
const items = Array.isArray(bean.append) ? bean.append : [bean.append];
const old = Array.isArray(auditLog.append) ? auditLog.append : auditLog.append ? [auditLog.append] : [];
auditLog.append = [...old, ...items].filter(item => item && String(item).trim());
}
}
private ensureAuditLogContext(): AuditLogContext {
if (!this.ctx.auditLog) {
this.ctx.auditLog = {};
}
return this.ctx.auditLog;
}
}
@@ -253,7 +253,6 @@ export abstract class BaseService<T> {
if (!Array.isArray(ids)) {
ids = [ids];
}
ids = this.filterIds(ids);
const res = await this.getRepository().find({
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
@@ -266,7 +265,7 @@ export abstract class BaseService<T> {
},
});
if (!res || res.length === ids.length) {
return;
return ids;
}
throw new PermissionException("权限不足");
}
@@ -279,7 +278,13 @@ export abstract class BaseService<T> {
return item != null && item != "";
});
}
async batchDelete(ids: number[], userId: number, projectId?: number) {
async batchDelete(ids: number[], userId: number, projectId?: number): Promise<number> {
if (!ids || ids.length === 0) {
throw new ValidateException("ids不能为空");
}
if (!Array.isArray(ids)) {
ids = [ids];
}
ids = this.filterIds(ids);
if (userId != null) {
const userProjectQuery = this.buildUserProjectQuery(userId, projectId);
@@ -295,6 +300,7 @@ export abstract class BaseService<T> {
}
await this.delete(ids);
return ids.length;
}
async findOne(options: FindOneOptions<T>) {
+35 -35
View File
@@ -1,21 +1,21 @@
export const Constants = {
dataDir: './data',
dataDir: "./data",
role: {
defaultUser: 3,
},
per: {
//无需登录
guest: '_guest_',
guest: "_guest_",
//无需登录
anonymous: '_guest_',
anonymous: "_guest_",
//无需登录,有 token 时解析当前用户
guestOptionalAuth: '_guestOptionalAuth_',
guestOptionalAuth: "_guestOptionalAuth_",
//仅需要登录
authOnly: '_authOnly_',
authOnly: "_authOnly_",
//仅需要登录
loginOnly: '_authOnly_',
loginOnly: "_authOnly_",
open: '_open_',
open: "_open_",
},
res: {
serverError(message: string) {
@@ -26,102 +26,102 @@ export const Constants = {
},
error: {
code: 1,
message: 'Internal server error',
message: "Internal server error",
},
success: {
code: 0,
message: 'success',
message: "success",
},
validation: {
code: 10,
message: '参数错误',
message: "参数错误",
},
needvip: {
code: 88,
message: '需要VIP',
message: "需要VIP",
},
needsuite: {
code: 89,
message: '需要购买或升级套餐',
message: "需要购买或升级套餐",
},
loginError: {
code: 2,
message: '登录失败',
message: "登录失败",
},
codeError: {
code: 3,
message: '验证码错误',
message: "验证码错误",
},
auth: {
code: 401,
message: '您还未登录或token已过期',
message: "您还未登录或token已过期",
},
permission: {
code: 402,
message: '您没有权限',
message: "您没有权限",
},
param: {
code: 400,
message: '参数错误',
message: "参数错误",
},
notFound: {
code: 404,
message: '页面/文件/资源不存在',
message: "页面/文件/资源不存在",
},
preview: {
code: 10001,
message: '对不起,预览环境不允许修改此数据',
message: "对不起,预览环境不允许修改此数据",
},
siteOff:{
siteOff: {
code: 10010,
message: '站点已关闭',
message: "站点已关闭",
},
need2fa:{
need2fa: {
code: 10020,
message: '需要2FA认证',
message: "需要2FA认证",
},
openKeyError: {
code: 20000,
message: 'ApiToken错误',
message: "ApiToken错误",
},
openKeySignError: {
code: 20001,
message: 'ApiToken签名错误',
message: "ApiToken签名错误",
},
openKeyExpiresError: {
code: 20002,
message: 'ApiToken时间戳错误',
message: "ApiToken时间戳错误",
},
openKeySignTypeError: {
code: 20003,
message: 'ApiToken签名类型不支持',
message: "ApiToken签名类型不支持",
},
openParamError: {
code: 20010,
message: '请求参数错误',
message: "请求参数错误",
},
openCertNotFound: {
code: 20011,
message: '证书不存在',
message: "证书不存在",
},
openCertNotReady: {
code: 20012,
message: '证书还未生成',
message: "证书还未生成",
},
openCertApplying: {
code: 20013,
message: '证书正在申请中,请稍后重新获取',
message: "证书正在申请中,请稍后重新获取",
},
openDomainNoVerifier:{
openDomainNoVerifier: {
code: 20014,
message: '域名校验方式未配置',
message: "域名校验方式未配置",
},
openEmailNotFound: {
code: 20021,
message: '用户邮箱还未配置',
message: "用户邮箱还未配置",
},
},
systemUserId: 0, // 系统级别userid固定为0
enterpriseUserId: -1 // 企业模式用户id固定为-1
enterpriseUserId: -1, // 企业模式用户id固定为-1
};
@@ -0,0 +1,20 @@
import { createRequestParamDecorator } from "@midwayjs/core";
export const AuditLog = (opts: { type?: string; action?: string; content?: string; enabled?: boolean } = {}) => {
return createRequestParamDecorator(ctx => {
if (!ctx.auditLog) {
ctx.auditLog = {};
}
ctx.auditLog.enabled = opts.enabled !== false;
if (opts.type != null) {
ctx.auditLog.type = opts.type;
}
if (opts.action != null) {
ctx.auditLog.action = opts.action;
}
if (opts.content != null) {
ctx.auditLog.content = opts.content;
}
return ctx.auditLog;
});
};
@@ -0,0 +1 @@
export * from "./decoractor.js";
@@ -1,11 +1,11 @@
import { ALL, Body, Post, Query } from '@midwayjs/core';
import { BaseController } from './base-controller.js';
import { ALL, Body, Post, Query } from "@midwayjs/core";
import { BaseController } from "./base-controller.js";
export abstract class CrudController<T> extends BaseController {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
abstract getService<T>();
@Post('/page')
@Post("/page")
async page(@Body(ALL) body: any) {
const pageRet = await this.getService().page({
query: body.query ?? {},
@@ -16,7 +16,7 @@ export abstract class CrudController<T> extends BaseController {
return this.ok(pageRet);
}
@Post('/list')
@Post("/list")
async list(@Body(ALL) body: any) {
const listRet = await this.getService().list({
query: body.query ?? {},
@@ -25,33 +25,33 @@ export abstract class CrudController<T> extends BaseController {
return this.ok(listRet);
}
@Post('/add')
@Post("/add")
async add(@Body(ALL) bean: any) {
delete bean.id;
const id = await this.getService().add(bean);
return this.ok(id);
}
@Post('/info')
async info(@Query('id') id: number) {
@Post("/info")
async info(@Query("id") id: number) {
const bean = await this.getService().info(id);
return this.ok(bean);
}
@Post('/update')
@Post("/update")
async update(@Body(ALL) bean: any) {
await this.getService().update(bean);
return this.ok(null);
}
@Post('/delete')
async delete(@Query('id') id: number) {
@Post("/delete")
async delete(@Query("id") id: number) {
await this.getService().delete([id]);
return this.ok(null);
}
@Post('/deleteByIds')
async deleteByIds(@Body('ids') ids: number[]) {
@Post("/deleteByIds")
async deleteByIds(@Body("ids") ids: number[]) {
await this.getService().delete(ids);
return this.ok(null);
}
@@ -1,12 +1,14 @@
import { Constants } from '../constants.js';
import { BaseException } from './base-exception.js';
import { Constants } from "../constants.js";
import { BaseException } from "./base-exception.js";
/**
*
*/
export class LoginErrorException extends BaseException {
leftCount: number;
constructor(message, leftCount: number) {
super('LoginErrorException', Constants.res.loginError.code, message ? message : Constants.res.loginError.message);
userId?: number;
constructor(message, leftCount: number, userId?: number) {
super("LoginErrorException", Constants.res.loginError.code, message ? message : Constants.res.loginError.message);
this.leftCount = leftCount;
this.userId = userId;
}
}
+10 -8
View File
@@ -1,8 +1,10 @@
export * from './base-controller.js';
export * from './constants.js';
export * from './crud-controller.js';
export * from './enum-item.js';
export * from './exception/index.js';
export * from './result.js';
export * from './base-service.js';
export * from "./mode.js"
export * from "./base-controller.js";
export * from "./constants.js";
export * from "./crud-controller.js";
export * from "./enum-item.js";
export * from "./exception/index.js";
export * from "./result.js";
export * from "./base-service.js";
export * from "./audit.js";
export * from "./mode.js";
export * from "./core/index.js";
+7 -7
View File
@@ -1,12 +1,12 @@
let adminMode = "saas"
let adminMode = "saas";
export function setAdminMode(mode:string = "saas"){
adminMode = mode
export function setAdminMode(mode: string = "saas") {
adminMode = mode;
}
export function getAdminMode(){
return adminMode
export function getAdminMode() {
return adminMode;
}
export function isEnterprise(){
return adminMode === "enterprise"
export function isEnterprise() {
return adminMode === "enterprise";
}
@@ -164,7 +164,7 @@ export class PlusService {
baseURL: plusRequestService.getBaseURL(),
method: "post",
headers: {
Authorization: `Berear ${token}`,
Authorization: `Bearer ${token}`,
},
});
const res = await http.request(config);
@@ -173,4 +173,9 @@ export class PlusService {
}
return res.data;
}
async request(config: HttpRequestConfig) {
const plusRequestService = await this.getPlusRequestService();
return await plusRequestService.request(config);
}
}
@@ -279,3 +279,11 @@ export class SysSafeSetting extends BaseSettings {
autoHiddenTimes: 5,
};
}
export class SysPluginSetting extends BaseSettings {
static __title__ = "系统插件设置";
static __key__ = "sys.plugin";
static __access__ = "private";
lastSyncTime?: number;
}
@@ -1,29 +1,20 @@
import { IAccessService, IRuntimeDepsService } from "@certd/pipeline";
export type AccessRuntimeDepsService = IRuntimeDepsService;
import { IAccessService } from "@certd/pipeline";
export class AccessGetter implements IAccessService {
userId: number;
projectId?: number;
runtimeDepsService?: AccessRuntimeDepsService;
getter: <T>(id: any, userId?: number, projectId?: number, ignorePermission?: boolean, runtimeDepsService?: AccessRuntimeDepsService) => Promise<T>;
constructor(
userId: number,
projectId: number,
getter: (id: any, userId: number, projectId?: number, ignorePermission?: boolean, runtimeDepsService?: AccessRuntimeDepsService) => Promise<any>,
runtimeDepsService?: AccessRuntimeDepsService
) {
getter: <T>(id: any, userId?: number, projectId?: number, ignorePermission?: boolean) => Promise<T>;
constructor(userId: number, projectId: number, getter: (id: any, userId: number, projectId?: number, ignorePermission?: boolean) => Promise<any>) {
this.userId = userId;
this.projectId = projectId;
this.getter = getter;
this.runtimeDepsService = runtimeDepsService;
}
async getById<T = any>(id: any) {
return await this.getter<T>(id, this.userId, this.projectId, false, this.runtimeDepsService);
return await this.getter<T>(id, this.userId, this.projectId, false);
}
async getCommonById<T = any>(id: any) {
return await this.getter<T>(id, 0, null, false, this.runtimeDepsService);
return await this.getter<T>(id, 0, null, false);
}
}
@@ -1,8 +1,8 @@
import { Inject, Provide, Scope, ScopeEnum } from "@midwayjs/core";
import { ApplicationContext, Inject, Provide, Scope, ScopeEnum } from "@midwayjs/core";
import type { IMidwayContainer } from "@midwayjs/core";
import { InjectEntityModel } from "@midwayjs/typeorm";
import { In, Repository } from "typeorm";
import { AccessGetter, BaseService, PageReq, PermissionException, ValidateException } from "../../../index.js";
import type { AccessRuntimeDepsService } from "./access-getter.js";
import { AccessEntity } from "../entity/access.js";
import { AccessDefine, accessRegistry, newAccess } from "@certd/pipeline";
import { EncryptService } from "./encrypt-service.js";
@@ -20,6 +20,9 @@ export class AccessService extends BaseService<AccessEntity> {
@Inject()
encryptService: EncryptService;
@ApplicationContext()
applicationContext: IMidwayContainer;
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
//@ts-ignore
getRepository() {
@@ -161,7 +164,7 @@ export class AccessService extends BaseService<AccessEntity> {
};
}
async getAccessById(id: any, checkUserId: boolean, userId?: number, projectId?: number, runtimeDepsService?: AccessRuntimeDepsService): Promise<any> {
async getAccessById(id: any, checkUserId: boolean, userId?: number, projectId?: number): Promise<any> {
const entity = await this.info(id);
if (entity == null) {
throw new Error(`该授权配置不存在,请确认是否已被删除:id=${id}`);
@@ -184,20 +187,23 @@ export class AccessService extends BaseService<AccessEntity> {
id: entity.id,
...setting,
};
const taskServiceBuilder: any = await this.applicationContext.getAsync("taskServiceBuilder");
const serviceGetter = taskServiceBuilder.create({ userId: userId || 0, projectId });
const getAccessById = this.getById.bind(this);
const accessGetter = new AccessGetter(userId, projectId, getAccessById, runtimeDepsService);
const accessGetter = new AccessGetter(userId, projectId, getAccessById);
const accessContext = {
logger,
http,
utils,
accessService: accessGetter,
serviceGetter,
} as any;
const access = await newAccess(entity.type, input, accessGetter, accessContext);
return access;
}
async getById(id: any, userId: number, projectId?: number, _ignorePermission?: boolean, runtimeDepsService?: AccessRuntimeDepsService): Promise<any> {
return await this.getAccessById(id, true, userId, projectId, runtimeDepsService);
async getById(id: any, userId: number, projectId?: number, _ignorePermission?: boolean): Promise<any> {
return await this.getAccessById(id, true, userId, projectId);
}
decryptAccessEntity(entity: AccessEntity): any {
@@ -1,15 +1,6 @@
import { HttpClient, ILogger, utils } from "@certd/basic";
import {upperFirst} from "lodash-es";
import {
accessRegistry,
FormItemProps,
IAccessService,
IRuntimeDepsService,
IServiceGetter,
PluginRequestHandleReq,
Registrable
} from "@certd/pipeline";
import { upperFirst } from "lodash-es";
import { accessRegistry, FormItemProps, IAccessService, IServiceGetter, PluginRequestHandleReq, Registrable, getRuntimeDepsService } from "@certd/pipeline";
export type AddonRequestHandleReqInput<T = any> = {
id?: number;
@@ -19,7 +10,7 @@ export type AddonRequestHandleReqInput<T = any> = {
export type AddonRequestHandleReq<T = any> = {
addonType: string;
} &PluginRequestHandleReq<AddonRequestHandleReqInput<T>>;
} & PluginRequestHandleReq<AddonRequestHandleReqInput<T>>;
export type AddonInputDefine = FormItemProps & {
title: string;
@@ -48,8 +39,6 @@ export type AddonInstanceConfig = {
};
};
export interface IAddon {
ctx: AddonContext;
[key: string]: any;
@@ -67,13 +56,9 @@ export abstract class BaseAddon implements IAddon {
ctx!: AddonContext;
http!: HttpClient;
logger!: ILogger;
runtimeDepsService?: IRuntimeDepsService;
async importRuntime(specifier: string) {
if (!this.runtimeDepsService) {
return await import(specifier);
}
return await this.runtimeDepsService.importRuntime(specifier, this.logger);
return await getRuntimeDepsService().importRuntime(specifier, this.logger);
}
title!: string;
@@ -85,7 +70,7 @@ export abstract class BaseAddon implements IAddon {
if (accessId == null) {
throw new Error("您还没有配置授权");
}
const accessService = await this.ctx.serviceGetter.get<IAccessService>("accessService")
const accessService = await this.ctx.serviceGetter.get<IAccessService>("accessService");
let res: any = null;
if (isCommon) {
res = await accessService.getCommonById(accessId);
@@ -118,18 +103,12 @@ export abstract class BaseAddon implements IAddon {
this.ctx = ctx;
this.http = ctx.http;
this.logger = ctx.logger;
if (!this.runtimeDepsService && this.ctx.serviceGetter) {
this.runtimeDepsService = await this.ctx.serviceGetter.get("runtimeDepsService");
}
if (this.runtimeDepsService && this.define?.addonType && this.define?.name) {
await this.runtimeDepsService.ensureRuntimeDependencies({ pluginKeys: `addon:${this.define.addonType}:${this.define.name}`, logger: this.logger });
}
}
setDefine = (define:AddonDefine) => {
setDefine = (define: AddonDefine) => {
this.define = define;
};
async onRequest(req:AddonRequestHandleReq) {
async onRequest(req: AddonRequestHandleReq) {
if (!req.action) {
throw new Error("action is required");
}
@@ -147,10 +126,8 @@ export abstract class BaseAddon implements IAddon {
}
throw new Error(`action ${req.action} not found`);
}
}
export interface IAddonGetter {
getById<T = any>(id: any): Promise<T>;
getCommonById<T = any>(id: any): Promise<T>;
@@ -3,6 +3,20 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.42.6](https://github.com/certd/certd/compare/v1.42.5...v1.42.6) (2026-07-18)
**Note:** Version bump only for package @certd/midway-flyway-js
## [1.42.5](https://github.com/certd/certd/compare/v1.42.4...v1.42.5) (2026-07-15)
### Performance Improvements
* 给SQLITE_IOERR_WRITE增加友好报错提示,将certd:latest镜像改为certd:slim ([b91c9e4](https://github.com/certd/certd/commit/b91c9e4ea671cb359ef164e27864de1d66cba9d3))
## [1.42.4](https://github.com/certd/certd/compare/v1.42.3...v1.42.4) (2026-07-11)
**Note:** Version bump only for package @certd/midway-flyway-js
## [1.42.3](https://github.com/certd/certd/compare/v1.42.2...v1.42.3) (2026-07-08)
**Note:** Version bump only for package @certd/midway-flyway-js
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@certd/midway-flyway-js",
"version": "1.42.3",
"version": "1.42.6",
"description": "midway with flyway, sql upgrade way ",
"private": false,
"type": "module",
@@ -52,5 +52,5 @@
"typeorm": "^0.3.20",
"typescript": "^5.4.2"
},
"gitHead": "7808d028e9c7e1b1e3ebc41f12b023d7b553300b"
"gitHead": "246ee83015bf5589adc2a5fa3d1388c8d9a2a252"
}
+40 -32
View File
@@ -1,8 +1,8 @@
import * as path from 'path';
import * as fs from 'fs';
import { QueryRunner, Table } from 'typeorm';
import { FlywayHistory } from './entity.js';
import * as crypto from 'crypto';
import * as path from "path";
import * as fs from "fs";
import { QueryRunner, Table } from "typeorm";
import { FlywayHistory } from "./entity.js";
import * as crypto from "crypto";
/**
*
@@ -32,10 +32,10 @@ const DefaultLogger = {
},
};
let customLogger:any = null;
export function setFlywayLogger (logger: any) {
let customLogger: any = null;
export function setFlywayLogger(logger: any) {
customLogger = logger;
};
}
export class Flyway {
scriptDir;
@@ -45,8 +45,8 @@ export class Flyway {
connection;
logger;
constructor(opts: any) {
this.scriptDir = opts.scriptDir ?? 'db/migration';
this.flywayTableName = opts.flywayTableName ?? 'flyway_history';
this.scriptDir = opts.scriptDir ?? "db/migration";
this.flywayTableName = opts.flywayTableName ?? "flyway_history";
this.baseline = opts.baseline ?? false;
this.allowHashNotMatch = opts.allowHashNotMatch ?? false;
this.logger = customLogger || opts.logger || DefaultLogger;
@@ -54,9 +54,9 @@ export class Flyway {
}
async run(ignores?: (RegExp | string)[]) {
this.logger.info('[ midfly ] start-------------');
this.logger.info("[ midfly ] start-------------");
if (!fs.existsSync(this.scriptDir)) {
this.logger.info('[ midfly ] scriptDir<' + this.scriptDir + '> not found');
this.logger.info("[ midfly ] scriptDir<" + this.scriptDir + "> not found");
return;
}
@@ -77,7 +77,7 @@ export class Flyway {
continue;
}
if (!file.isBaseline) {
this.logger.info('need exec script file: ', file.script);
this.logger.info("need exec script file: ", file.script);
//执行sql文件
if (/\.sql$/.test(file.script)) {
await this.execSql(filepath, queryRunner);
@@ -87,18 +87,25 @@ export class Flyway {
// await this.execJsOrTs(filepath, t);
// }
} else {
this.logger.info('baseline script file: ', file.script);
this.logger.info("baseline script file: ", file.script);
}
await this.storeSqlExecLog(file.script, filepath, true, queryRunner);
await queryRunner.commitTransaction();
} catch (err) {
this.logger.error(err);
this.errorTip(err);
await this.storeSqlExecLog(file.script, filepath, false, queryRunner);
await queryRunner.rollbackTransaction();
throw err;
}
}
this.logger.info('[ midfly ] end-------------');
this.logger.info("[ midfly ] end-------------");
}
private errorTip(err: any) {
if (err.code === "SQLITE_IOERR_WRITE") {
this.logger.warn("SQLite数据库写入失败,可能您的操作系统版本太低,请将「certd:latest」镜像改为「certd:slim」即可。(如需指定版本可以修改成「certd:[version]-slim」)");
}
}
private async storeSqlExecLog(filename: string, filepath: string, success: boolean, queryRunner: QueryRunner) {
@@ -160,17 +167,17 @@ export class Flyway {
name: this.flywayTableName,
columns: [
{
name: 'id',
name: "id",
type: this.connection.driver.normalizeType({
type: this.connection.driver.mappedDataTypes.migrationId,
}),
isGenerated: true,
generationStrategy: 'increment',
generationStrategy: "increment",
isPrimary: true,
isNullable: false,
},
{
name: 'timestamp',
name: "timestamp",
type: this.connection.driver.normalizeType({
type: this.connection.driver.mappedDataTypes.migrationTimestamp,
}),
@@ -178,23 +185,23 @@ export class Flyway {
isNullable: false,
},
{
name: 'name',
name: "name",
type: this.connection.driver.normalizeType({
type: this.connection.driver.mappedDataTypes.migrationName,
}),
isNullable: false,
},
{
name: 'hash',
name: "hash",
type: this.connection.driver.normalizeType({
type: this.connection.driver.mappedDataTypes.migrationName,
}),
isNullable: true,
},
{
name: 'success',
name: "success",
type: this.connection.driver.normalizeType({
type: 'boolean',
type: "boolean",
}),
isNullable: true,
},
@@ -210,7 +217,7 @@ export class Flyway {
}
let ret = false;
for (const ignore of ignores) {
if (typeof ignore === 'string' && file === ignore) {
if (typeof ignore === "string" && file === ignore) {
ret = true;
break;
}
@@ -233,20 +240,20 @@ export class Flyway {
if (history.hash !== hash && this.allowHashNotMatch === false) {
throw new Error(file + `hash conflict ,old: ${history.hash} != new: ${hash}`);
}
this.logger.info('[ midfly ] script<' + file + '> already executed');
this.logger.info("[ midfly ] script<" + file + "> already executed");
return true;
}
this.logger.info('[ midfly ] script<' + file + '> not yet execute');
this.logger.info("[ midfly ] script<" + file + "> not yet execute");
return false;
}
private async getFileHash(filepath: string) {
const content = fs.readFileSync(filepath).toString();
return crypto.createHash('md5').update(content.toString()).digest('hex');
return crypto.createHash("md5").update(content.toString()).digest("hex");
}
private async execSql(filepath: string, queryRunner: QueryRunner) {
this.logger.info('[ midfly ] exec ', filepath);
this.logger.info("[ midfly ] exec ", filepath);
const content = fs.readFileSync(filepath).toString().trim();
const arr = this.splitSql2Array(content);
for (const s of arr) {
@@ -255,11 +262,12 @@ export class Flyway {
}
private async execOnePart(sql: string, queryRunner: QueryRunner) {
this.logger.debug('exec sql index: ', sql);
this.logger.debug("exec sql index: ", sql);
try {
await queryRunner.query(sql);
} catch (err: any) {
this.logger.error('exec sql error ', err.message, err);
this.logger.error("exec sql error ", err.message, err);
this.errorTip(err);
throw err;
}
}
@@ -275,11 +283,11 @@ export class Flyway {
const temp = String(str).trim();
if (temp === 'null') {
if (temp === "null") {
return [];
}
const semicolon = ';';
const semicolon = ";";
const deepChars = ['"', "'"];
const splits = [];
@@ -289,7 +297,7 @@ export class Flyway {
if (deepChars.indexOf(charAt) >= 0) {
//如果是深度char
if (i !== 0 && temp.charAt(i - 1) === '\\') {
if (i !== 0 && temp.charAt(i - 1) === "\\") {
//如果前一个是转义字符,忽略它
} else {
//说明需要进出深度了
+12
View File
@@ -3,6 +3,18 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.42.6](https://github.com/certd/certd/compare/v1.42.5...v1.42.6) (2026-07-18)
**Note:** Version bump only for package @certd/plugin-cert
## [1.42.5](https://github.com/certd/certd/compare/v1.42.4...v1.42.5) (2026-07-15)
**Note:** Version bump only for package @certd/plugin-cert
## [1.42.4](https://github.com/certd/certd/compare/v1.42.3...v1.42.4) (2026-07-11)
**Note:** Version bump only for package @certd/plugin-cert
## [1.42.3](https://github.com/certd/certd/compare/v1.42.2...v1.42.3) (2026-07-08)
**Note:** Version bump only for package @certd/plugin-cert
+3 -3
View File
@@ -1,7 +1,7 @@
{
"name": "@certd/plugin-cert",
"private": false,
"version": "1.42.3",
"version": "1.42.6",
"type": "module",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
@@ -20,7 +20,7 @@
"lint": "eslint --fix"
},
"dependencies": {
"@certd/plugin-lib": "^1.42.3"
"@certd/plugin-lib": "^1.42.6"
},
"devDependencies": {
"@types/chai": "^4.3.12",
@@ -38,5 +38,5 @@
"tslib": "^2.8.1",
"typescript": "^5.4.2"
},
"gitHead": "7808d028e9c7e1b1e3ebc41f12b023d7b553300b"
"gitHead": "246ee83015bf5589adc2a5fa3d1388c8d9a2a252"
}
+16
View File
@@ -3,6 +3,22 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.42.6](https://github.com/certd/certd/compare/v1.42.5...v1.42.6) (2026-07-18)
**Note:** Version bump only for package @certd/plugin-lib
## [1.42.5](https://github.com/certd/certd/compare/v1.42.4...v1.42.5) (2026-07-15)
### Bug Fixes
* 修复上传到cos报runtimeDepsService未初始化的问题 ([167b303](https://github.com/certd/certd/commit/167b303faeca02cc11cf97e4be2a3df914852167))
## [1.42.4](https://github.com/certd/certd/compare/v1.42.3...v1.42.4) (2026-07-11)
### Bug Fixes
* **pipeline:** 重构运行时依赖加载逻辑,修复火山引擎DNS解析报runtimeDepsService未初始化的bug ([ec69b8f](https://github.com/certd/certd/commit/ec69b8f11bfd4b20991aef74a72a47182ca79a9d))
## [1.42.3](https://github.com/certd/certd/compare/v1.42.2...v1.42.3) (2026-07-08)
**Note:** Version bump only for package @certd/plugin-lib
+5 -5
View File
@@ -1,7 +1,7 @@
{
"name": "@certd/plugin-lib",
"private": false,
"version": "1.42.3",
"version": "1.42.6",
"type": "module",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
@@ -17,9 +17,9 @@
"lint": "eslint --fix"
},
"dependencies": {
"@certd/acme-client": "^1.42.3",
"@certd/basic": "^1.42.3",
"@certd/pipeline": "^1.42.3",
"@certd/acme-client": "^1.42.6",
"@certd/basic": "^1.42.6",
"@certd/pipeline": "^1.42.6",
"dayjs": "^1.11.7",
"jszip": "^3.10.1",
"lodash-es": "^4.17.21",
@@ -45,5 +45,5 @@
"tslib": "^2.8.1",
"typescript": "^5.4.2"
},
"gitHead": "7808d028e9c7e1b1e3ebc41f12b023d7b553300b"
"gitHead": "246ee83015bf5589adc2a5fa3d1388c8d9a2a252"
}
@@ -1,5 +1,5 @@
import { HttpClient, ILogger } from "@certd/basic";
import { IAccessService, IRuntimeDepsService, PageRes, PageSearch } from "@certd/pipeline";
import { IAccessService, PageRes, PageSearch, getRuntimeDepsService } from "@certd/pipeline";
import punycode from "punycode.js";
import { CreateRecordOptions, DnsProviderContext, DnsProviderDefine, DnsResolveRecord, DomainRecord, IDnsProvider, RemoveRecordOptions } from "./api.js";
import { dnsProviderRegistry } from "./registry.js";
@@ -7,13 +7,9 @@ export abstract class AbstractDnsProvider<T = any> implements IDnsProvider<T> {
ctx!: DnsProviderContext;
http!: HttpClient;
logger!: ILogger;
runtimeDepsService?: IRuntimeDepsService;
async importRuntime(specifier: string) {
if (!this.runtimeDepsService) {
throw new Error("runtimeDepsService 未初始化");
}
return await this.runtimeDepsService.importRuntime(specifier, this.logger);
return await getRuntimeDepsService().importRuntime(specifier, this.logger);
}
usePunyCode(): boolean {
@@ -42,12 +38,6 @@ export abstract class AbstractDnsProvider<T = any> implements IDnsProvider<T> {
this.ctx = ctx;
this.logger = ctx.logger;
this.http = ctx.http;
if (!this.runtimeDepsService && this.ctx.serviceGetter) {
this.runtimeDepsService = await this.ctx.serviceGetter.get("runtimeDepsService");
}
if (this.runtimeDepsService && this.ctx.define?.name) {
await this.runtimeDepsService.ensureRuntimeDependencies({ pluginKeys: `dnsProvider:${this.ctx.define.name}`, logger: this.logger });
}
}
async parseDomain(fullDomain: string) {
+2 -1
View File
@@ -1,4 +1,4 @@
ARG base_type=alpine
ARG base_type=alpine
# 根据 base_type 参数选择基础镜像系列
FROM --platform=linux/amd64 node:22-alpine AS base-amd64-alpine
@@ -99,6 +99,7 @@ RUN ARCH=$(uname -m) && \
ENV TZ=Asia/Shanghai
ENV NODE_ENV=production
ENV certd_release_mode=latest
ENV MIDWAY_SERVER_ENV=production
RUN npm install -g pnpm@10.33.4
+14
View File
@@ -3,6 +3,20 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.42.6](https://github.com/certd/certd/compare/v1.42.5...v1.42.6) (2026-07-18)
**Note:** Version bump only for package @certd/ui-client
## [1.42.5](https://github.com/certd/certd/compare/v1.42.4...v1.42.5) (2026-07-15)
### Bug Fixes
* 修复上传到cos报runtimeDepsService未初始化的问题 ([167b303](https://github.com/certd/certd/commit/167b303faeca02cc11cf97e4be2a3df914852167))
## [1.42.4](https://github.com/certd/certd/compare/v1.42.3...v1.42.4) (2026-07-11)
**Note:** Version bump only for package @certd/ui-client
## [1.42.3](https://github.com/certd/certd/compare/v1.42.2...v1.42.3) (2026-07-08)
**Note:** Version bump only for package @certd/ui-client
+3 -4
View File
@@ -1,6 +1,6 @@
{
"name": "@certd/ui-client",
"version": "1.42.3",
"version": "1.42.6",
"private": true,
"scripts": {
"dev": "vite --open",
@@ -59,7 +59,6 @@
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"core-js": "^3.36.0",
"cos-js-sdk-v5": "^1.7.0",
"cron-parser": "^4.9.0",
"cropperjs": "^1.6.1",
"cssnano": "^7.0.6",
@@ -105,8 +104,8 @@
"zod-defaults": "^0.1.3"
},
"devDependencies": {
"@certd/lib-iframe": "^1.42.3",
"@certd/pipeline": "^1.42.3",
"@certd/lib-iframe": "^1.42.6",
"@certd/pipeline": "^1.42.6",
"@rollup/plugin-commonjs": "^25.0.7",
"@rollup/plugin-node-resolve": "^15.2.3",
"@types/chai": "^4.3.12",
@@ -139,7 +139,7 @@ async function doActive() {
title: t("vip.successTitle"),
content: t("vip.successContent", {
vipLabel,
expireDate: dayjs(settingStore.plusInfo.expireTime).format("YYYY-MM-DD"),
expireDate: settingStore.plusInfo.expireTime === -1 ? t("vip.permanent") : dayjs(settingStore.plusInfo.expireTime).format("YYYY-MM-DD"),
}),
onOk() {
if (!(settingStore.installInfo.bindUserId > 0)) {
@@ -108,10 +108,10 @@ const projectStore = useProjectStore();
<div v-if="!settingStore.isComm" class="hover:bg-accent ml-1 mr-2 cursor-pointer rounded-full hidden md:block">
<fs-button shape="circle" type="text" icon="ion:logo-github" :text="null" @click="goGithub" />
</div>
<MaxKBChat v-if="settingsStore.sysPublic.aiChatEnabled !== false" ref="chatBox" />
</template>
<template #footer>
<PageFooter></PageFooter>
<MaxKBChat v-if="settingsStore.sysPublic.aiChatEnabled !== false" ref="chatBox" />
</template>
</BasicLayout>
</template>
@@ -2,9 +2,8 @@
<router-view> </router-view>
</template>
<!--<script lang="ts" setup>-->
<!--import { usePageStore } from "/@/store/modules/page";-->
<script lang="ts" setup>
import { useSettingStore } from "../store/settings";
<!--const pageStore = usePageStore();-->
<!--const keepAlive = pageStore.keepAlive;-->
<!--</script>-->
const settingsStore = useSettingStore();
</script>
@@ -46,6 +46,7 @@ export default {
default: "Default",
success: "Success",
test: "Test",
operation: "Operation",
testButton: "Test",
operationSuccess: "Operation successful",
batch_delete: "Batch Delete",
@@ -25,5 +25,7 @@ export default {
expiringCerts: "Soon-to-Expire Certificates",
supportedTasks: "Overview of Supported Deployment Tasks",
changeLog: "Change Log",
stableRelease: "Stable",
latestRelease: "Preview",
},
};
@@ -18,6 +18,7 @@ export default {
openKey: "Open API Key",
notification: "Notification Settings",
siteMonitorSetting: "Site Monitor Settings",
auditLog: "Audit Log",
userSecurity: "Security Settings",
userProfile: "Account Info",
userGrant: "Grant Delegation",
@@ -39,7 +40,6 @@ export default {
headerMenus: "Top Menu Settings",
sysAccess: "System-level Authorization",
sysPlugin: "Plugin Management",
sysPluginEdit: "Edit Plugin",
sysPluginConfig: "Certificate Plugin Configuration",
accountBind: "Account Binding",
permissionManager: "Permission Management",
@@ -67,6 +67,7 @@ export default {
projectJoin: "Join Project",
currentProject: "Current Project",
projectMemberManager: "Project Member",
auditLog: "Audit Log",
domainMonitorSetting: "Domain Monitor Settings",
},
};
@@ -42,6 +42,72 @@ export default {
pluginGroup: "Plugin Group",
pluginManagement: "Plugin Management",
pluginBetaWarning: "Custom plugins are in BETA and may have breaking changes in future",
localPlugin: "Installed",
pluginMarket: "Plugin Market",
installedStorePlugin: "Installed",
onlinePluginManagement: "Online Plugins",
onlinePluginSearch: "Search online plugins",
onlinePluginSync: "Sync Plugin Market",
onlinePluginSyncFirst: "Sync the plugin market list first, then search and install plugins",
onlinePluginSyncSuccess: "Plugin market list synced successfully",
onlinePluginLastSyncTime: "Last synced: {time}",
onlinePluginNotSynced: "Plugin market has not been synced",
onlinePluginRefresh: "Refresh List",
onlinePluginInstall: "Install",
onlinePluginUpdate: "Update",
onlinePluginReinstall: "Reinstall",
onlinePluginUninstall: "Uninstall",
onlinePluginStatus: "Status",
onlinePluginInstalled: "Installed",
onlinePluginAiReviewPassed: "AI reviewed",
onlinePluginEnabled: "Enabled",
onlinePluginDisabled: "Disabled",
onlinePluginClickToEnable: "Click to enable",
onlinePluginClickToDisable: "Click to disable",
onlinePluginDownloadCount: "Downloads: {count}",
onlinePluginNotInstalled: "Not Installed",
onlinePluginUpgradeAvailable: "Upgradeable",
onlinePluginCurrentVersion: "Current {version}",
onlinePluginAlreadyLatest: "Already up to date",
onlinePluginClickToUpdate: "Click to update",
onlinePluginSelfAuthored: "Mine",
onlinePluginInstallSuccess: "Online plugin installed successfully",
onlinePluginUninstallSuccess: "Online plugin uninstalled successfully",
onlinePluginDeleteConfirm: 'Are you sure you want to uninstall online plugin "{name}"? Pipelines using this plugin may fail after deletion.',
onlinePluginPublish: "Publish to Plugin Market",
onlinePluginPublishManage: "Plugin Publish Management",
onlinePluginPublishConfirm: 'Publish "{name}" to the plugin market? It will be checked by AI and then wait for administrator review.',
onlinePluginPublishConfirmTip: "Please confirm the plugin information. It will be checked by AI and then wait for administrator review.",
onlinePluginPublishManageTip: "Confirm the current plugin information. If it has been submitted before, versions, publish status, and rejection reasons are shown here.",
onlinePluginPublishSubmit: "Submit Publish",
onlinePluginPublishSuccess: "Submitted, waiting for AI security review",
onlinePluginPublishVersionRequired: "Please set the plugin version before publishing",
onlinePluginPublishStatus: "Publish Status",
onlinePluginNotSubmitted: "Not Submitted",
onlinePluginVersionManagement: "Versions",
onlinePluginLatestVersion: "Latest Version",
onlinePluginCurrentRelease: "This Release",
onlinePluginPublishPrompt: "Release Notes",
onlinePluginVersionRejectedReason: "Rejection Reason",
onlinePluginNoSubmittedVersion: "No release has been submitted yet",
onlinePluginVersionFormatError: "Use a dotted numeric version, for example 1.0.0",
onlinePluginVersionBaselineError: "Enter a version greater than v{version}",
onlinePluginStatusDraft: "Draft",
onlinePluginStatusReviewing: "Reviewing",
onlinePluginStatusPublished: "Published",
onlinePluginStatusRejected: "Rejected",
onlinePluginStatusOffline: "Offline",
onlinePluginReviewAiPending: "Pending AI Review",
onlinePluginReviewPending: "Pending Manual Review",
onlinePluginReviewPassed: "Passed",
onlinePluginReviewRejected: "Rejected",
onlinePluginAuthorRegister: "Register Plugin Author",
onlinePluginAuthorName: "Author Name",
onlinePluginAuthorDisplayName: "Display Name",
onlinePluginAuthorNotRegistered: "Not Registered",
onlinePluginAuthorNameRequired: "Please enter an author name",
onlinePluginAuthorNameHelper: "Used as the plugin market author prefix. Each bound user can register only one author.",
onlinePluginAuthorNameRuleMsg: "Must start with a letter and contain only letters, digits, hyphens, or underscores",
pleaseSelectRecord: "Please select records first",
clearRuntimeDeps: "Clear Runtime Deps Cache",
clearRuntimeDepsTooltip: "Restart the certd container after clearing, otherwise cached modules will not be reloaded",
@@ -104,4 +104,5 @@ export default {
not_effective: "Not effective or duration not sync?",
learn_more: "More privileges",
question: "More VIP related questions",
permanent: "Permanent",
};
@@ -50,6 +50,7 @@ export default {
default: "默认",
success: "成功",
test: "测试",
operation: "操作",
testButton: "测试",
operationSuccess: "操作成功",
batch_delete: "批量删除",
@@ -26,5 +26,7 @@ export default {
expiringCerts: "最快到期证书",
supportedTasks: "已支持的部署任务总览",
changeLog: "更新日志",
stableRelease: "稳定版",
latestRelease: "预览版",
},
};
@@ -18,6 +18,7 @@ export default {
openKey: "开放接口密钥",
notification: "通知设置",
siteMonitorSetting: "站点监控设置",
auditLog: "操作日志",
userSecurity: "认证安全设置",
userProfile: "账号信息",
userGrant: "授权委托",
@@ -40,7 +41,6 @@ export default {
headerMenus: "顶部菜单设置",
sysAccess: "系统级授权",
sysPlugin: "插件管理",
sysPluginEdit: "编辑插件",
sysPluginConfig: "证书插件配置",
accountBind: "账号绑定",
permissionManager: "权限管理",
@@ -67,6 +67,7 @@ export default {
projectJoin: "加入项目",
currentProject: "当前项目",
projectMemberManager: "项目成员管理",
auditLog: "审计日志",
domainMonitorSetting: "域名监控设置",
jobHistory: "监控执行记录",
},
@@ -41,6 +41,72 @@ export default {
pluginGroup: "插件分组",
pluginManagement: "插件管理",
pluginBetaWarning: "自定义插件处于BETA测试版,后续可能会有破坏性变更",
localPlugin: "本地插件",
pluginMarket: "插件市场",
installedStorePlugin: "插件市场",
onlinePluginManagement: "在线插件",
onlinePluginSearch: "搜索在线插件",
onlinePluginSync: "同步插件市场",
onlinePluginSyncFirst: "请先同步插件市场列表,然后再搜索和安装插件",
onlinePluginSyncSuccess: "插件市场列表同步成功",
onlinePluginLastSyncTime: "上次同步时间:{time}",
onlinePluginNotSynced: "尚未同步插件市场",
onlinePluginRefresh: "刷新列表",
onlinePluginInstall: "安装",
onlinePluginUpdate: "更新",
onlinePluginReinstall: "重新安装",
onlinePluginUninstall: "卸载",
onlinePluginStatus: "状态",
onlinePluginInstalled: "已安装",
onlinePluginAiReviewPassed: "AI审核通过",
onlinePluginEnabled: "已启用",
onlinePluginDisabled: "已禁用",
onlinePluginClickToEnable: "点击启用",
onlinePluginClickToDisable: "点击禁用",
onlinePluginDownloadCount: "下载量:{count}",
onlinePluginNotInstalled: "未安装",
onlinePluginUpgradeAvailable: "可更新",
onlinePluginCurrentVersion: "当前 {version}",
onlinePluginAlreadyLatest: "当前已是最新版本",
onlinePluginClickToUpdate: "点击更新",
onlinePluginSelfAuthored: "我的",
onlinePluginInstallSuccess: "在线插件安装成功",
onlinePluginUninstallSuccess: "在线插件卸载成功",
onlinePluginDeleteConfirm: "确定要卸载在线插件「{name}」吗?如果该插件已被流水线使用,删除可能会导致执行失败。",
onlinePluginPublish: "发布到插件市场",
onlinePluginPublishManage: "插件发布管理",
onlinePluginPublishConfirm: "确定要将「{name}」发布到插件市场吗?提交后会进行 AI 安全审查,通过后等待管理员审核。",
onlinePluginPublishConfirmTip: "请确认以下插件信息,提交后会进行 AI 安全审查,通过后等待管理员审核。",
onlinePluginPublishManageTip: "请确认当前插件信息;如已提交过发布,可以在这里查看版本、发布状态和拒绝原因。",
onlinePluginPublishSubmit: "提交发布",
onlinePluginPublishSuccess: "已提交,等待 AI 安全审查",
onlinePluginPublishVersionRequired: "请先设置插件版本号后再发布",
onlinePluginPublishStatus: "发布状态",
onlinePluginNotSubmitted: "未提交",
onlinePluginVersionManagement: "版本管理",
onlinePluginLatestVersion: "最新版本",
onlinePluginCurrentRelease: "本次发布",
onlinePluginPublishPrompt: "发布提示",
onlinePluginVersionRejectedReason: "拒绝原因",
onlinePluginNoSubmittedVersion: "尚未提交过发布版本",
onlinePluginVersionFormatError: "版本号只能使用数字点分格式,例如 1.0.0",
onlinePluginVersionBaselineError: "请输入大于 v{version} 的版本号",
onlinePluginStatusDraft: "草稿",
onlinePluginStatusReviewing: "审核中",
onlinePluginStatusPublished: "已发布",
onlinePluginStatusRejected: "已拒绝",
onlinePluginStatusOffline: "已下架",
onlinePluginReviewAiPending: "待 AI 审查",
onlinePluginReviewPending: "待人工审核",
onlinePluginReviewPassed: "已通过",
onlinePluginReviewRejected: "已拒绝",
onlinePluginAuthorRegister: "注册插件作者",
onlinePluginAuthorName: "作者名称",
onlinePluginAuthorDisplayName: "显示名称",
onlinePluginAuthorNotRegistered: "未注册",
onlinePluginAuthorNameRequired: "请输入作者名称",
onlinePluginAuthorNameHelper: "作为插件市场作者前缀,同一个绑定用户只能注册一个作者",
onlinePluginAuthorNameRuleMsg: "必须以英文字母开头,只能包含英文字母、数字、中划线或下划线",
pleaseSelectRecord: "请先勾选记录",
clearRuntimeDeps: "清理第三方依赖缓存",
clearRuntimeDepsTooltip: "清除后需重启 certd 容器,否则已缓存模块不会重新读取",
@@ -103,4 +103,5 @@ export default {
not_effective: "VIP没有生效/时长未同步?",
learn_more: "更多特权(加VIP群等)",
question: "更多VIP相关问题",
permanent: "永久",
};
@@ -287,6 +287,22 @@ export const certdResources = [
isMenu: true,
},
},
{
title: "certd.auditLog",
name: "AuditLog",
path: "/certd/audit",
component: "/certd/audit/index.vue",
meta: {
icon: "ion:document-text-outline",
auth: true,
keepAlive: true,
isMenu: true,
show: () => {
const settingStore = useSettingStore();
return settingStore.isPlus;
},
},
},
{
title: "certd.userSecurity",
name: "UserSecurity",
@@ -154,19 +154,6 @@ export const sysResources = [
auth: true,
},
},
{
title: "certd.sysResources.sysPluginEdit",
name: "SysPluginEdit",
path: "/sys/plugin/edit",
component: "/sys/plugin/edit.vue",
meta: {
isMenu: false,
icon: "ion:extension-puzzle",
permission: "sys:settings:view",
keepAlive: true,
auth: true,
},
},
{
title: "certd.sysResources.sysPluginConfig",
name: "SysPluginConfig",
@@ -410,6 +397,22 @@ export const sysResources = [
},
],
},
{
title: "certd.sysResources.auditLog",
name: "SysAuditLog",
path: "/sys/enterprise/audit",
component: "/sys/enterprise/audit/index.vue",
meta: {
icon: "ion:document-text-outline",
keepAlive: true,
auth: true,
isMenu: true,
show: () => {
const settingStore = useSettingStore();
return settingStore.isPlus;
},
},
},
{
title: "certd.sysResources.netTest",
name: "NetTest",
@@ -153,6 +153,22 @@ export class PluginGroups {
}
}
function filterInstalledPluginGroups(groups: { [key: string]: PluginGroup }) {
const filteredGroups: { [key: string]: PluginGroup } = {};
for (const [key, group] of Object.entries(groups)) {
filteredGroups[key] = {
...group,
plugins: group.plugins.filter(plugin => {
if (plugin.type !== "store") {
return true;
}
return plugin.installed === true;
}),
};
}
return filteredGroups;
}
export const usePluginStore = defineStore({
id: "app.plugin",
state: (): PluginState => ({
@@ -162,8 +178,9 @@ export const usePluginStore = defineStore({
actions: {
async reload() {
const groups = await api.GetGroups({});
this.group = new PluginGroups(groups, { mergeSetting: true });
this.originGroup = new PluginGroups(cloneDeep(groups));
const installedGroups = filterInstalledPluginGroups(groups);
this.group = new PluginGroups(installedGroups, { mergeSetting: true });
this.originGroup = new PluginGroups(cloneDeep(installedGroups));
console.log("group", this.group);
console.log("originGroup", this.originGroup);
},
@@ -11,6 +11,7 @@ export type AppInfo = {
version?: string;
time?: number;
deltaTime?: number;
releaseMode?: string;
};
export type SiteInfo = {
title?: string;
@@ -35,6 +35,7 @@ export interface SettingState {
version?: string;
time?: number;
deltaTime?: number;
releaseMode?: string;
};
productInfo: {
notice?: string;
@@ -109,6 +110,7 @@ export const useSettingStore = defineStore({
version: "",
time: 0,
deltaTime: 0,
releaseMode: "latest",
},
productInfo: {
notice: "",
@@ -229,6 +231,9 @@ export const useSettingStore = defineStore({
this.app.time = appInfo.time;
this.app.version = appInfo.version;
this.app.deltaTime = new Date().getTime() - this.app.time;
if (appInfo.releaseMode) {
this.app.releaseMode = appInfo.releaseMode;
}
},
initSiteInfo(siteInfo: SiteInfo) {
//@ts-ignore
@@ -75,3 +75,9 @@ footer {
.ant-input-number {
min-width: 150px;
}
.ant-dropdown-menu-title-content{
display: flex;
align-items: center;
gap: 6px;
}
@@ -36,6 +36,116 @@
align-items: center;
}
.cd-card-section {
padding: 14px;
border: 1px solid #e8edf3;
border-radius: 10px;
background: #ffffff;
}
.cd-card-section-title {
margin-bottom: 12px;
color: #1f2937;
font-weight: 700;
&.cd-card-section-title--compact {
margin-bottom: 10px;
}
}
.cd-meta-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px 14px;
}
.cd-meta-item {
display: grid;
grid-template-columns: 72px minmax(0, 1fr);
align-items: start;
gap: 10px;
}
.cd-meta-label {
color: #7b8794;
}
.cd-meta-value {
min-width: 0;
color: #1f2937;
font-weight: 500;
word-break: break-all;
}
.cd-tip-box {
padding: 10px 12px;
border: 1px solid #e8edf3;
border-radius: 8px;
background: #f6f8fb;
color: #526172;
line-height: 22px;
&.cd-tip-box-warning {
border-color: #ffd591;
background: #fff7e6;
color: #ad6800;
}
&.cd-tip-box-danger {
border-color: #ffccc7;
background: #fff2f0;
color: #cf1322;
line-height: 21px;
}
}
.cd-tip-title {
margin-bottom: 3px;
font-weight: 600;
}
.cd-form-row {
display: grid;
grid-template-columns: 82px minmax(0, 1fr);
align-items: start;
gap: 10px;
}
.cd-form-label {
padding-top: 5px;
color: #5f6b7a;
}
.cd-text-input {
box-sizing: border-box;
width: 100%;
height: 32px;
padding: 4px 11px;
border: 1px solid #d9d9d9;
border-radius: 6px;
outline: none;
background: #ffffff;
color: #1f2937;
&.cd-text-input-error {
border-color: #ff4d4f;
}
}
.cd-field-error {
margin-top: 6px;
color: #cf1322;
font-size: 12px;
}
.cd-text-danger {
color: #cf1322;
}
.cd-text-muted {
color: #8c8c8c;
}
.ant-drawer-content {
&.fullscreen {
position: fixed;
@@ -140,3 +250,9 @@ button.ant-btn.ant-btn-default.isPlus {
}
}
}
.fs-form-none-content {
.fs-form-wrapper{
.fs-form-content{display: none;}
}
}
@@ -9,12 +9,14 @@ export type FormOptionReq = {
initialForm?: any;
zIndex?: number;
wrapper?: any;
noneForm?: boolean; //是否隐藏表单,只显示注入的body
};
export function useFormDialog() {
const { openCrudFormDialog } = useFormWrapper();
async function openFormDialog(req: FormOptionReq) {
const noneForm = req.noneForm ?? Object.keys(req.columns).length === 0;
function createCrudOptions() {
const warpper = merge(
{
@@ -24,6 +26,7 @@ export function useFormDialog() {
slots: {
"form-body-top": req.body,
},
wrapClassName: noneForm ? "fs-form-none-content" : "",
},
req.wrapper
);
@@ -0,0 +1,28 @@
import { request } from "/src/api/service";
const apiPrefix = "/pi/audit";
export function createAuditApi() {
return {
async GetList(query: any) {
return await request({
url: apiPrefix + "/page",
method: "post",
data: query,
});
},
async DelObj(id: number) {
return await request({
url: apiPrefix + "/delete",
method: "post",
params: { id },
});
},
async GetDict() {
return await request({
url: apiPrefix + "/dict",
method: "post",
});
},
};
}
@@ -0,0 +1,132 @@
import { ColumnProps, DataFormatterContext, CreateCrudOptionsProps, CreateCrudOptionsRet, DelReq, UserPageQuery, UserPageRes, dict } from "@fast-crud/fast-crud";
import { useI18n } from "/src/locales";
import { useDicts } from "../dicts";
const typeDict = dict({
url: "/pi/audit/dict",
getData: async () => {
const { createAuditApi } = await import("./api");
const api = createAuditApi();
const res = await api.GetDict();
return res.types || [];
},
});
export default function ({ crudExpose, context }: CreateCrudOptionsProps): CreateCrudOptionsRet {
const { t } = useI18n();
const { myProjectDict } = useDicts();
const api = context.api;
const pageRequest = async (query: UserPageQuery): Promise<UserPageRes> => {
return await api.GetList(query);
};
const delRequest = async (req: DelReq) => {
return await api.DelObj(req.row.id);
};
return {
crudOptions: {
request: { pageRequest, delRequest },
toolbar: {
buttons: {
export: { show: true },
},
export: {
dataFrom: "search",
columnFilter: (col: ColumnProps) => col.show === true,
dataFormatter: (opts: DataFormatterContext) => {
const { row, originalRow, col } = opts;
const key = col.key;
if (key === "createTime" && originalRow[key]) {
row[key] = new Date(originalRow[key]).toLocaleString();
}
},
},
},
actionbar: {
buttons: {
add: { show: false },
},
},
rowHandle: {
width: 120,
fixed: "right",
buttons: {
view: { show: false },
edit: { show: false },
remove: { show: true },
copy: { show: false },
},
},
columns: {
id: {
title: "ID",
type: "number",
column: { width: 80 },
form: { show: false },
},
createTime: {
title: "操作时间",
type: "datetime",
search: {
show: true,
component: {
name: "a-range-picker",
},
},
column: { width: 170, sorter: true },
form: { show: false },
},
type: {
title: "操作类型",
type: "dict-select",
dict: typeDict,
search: { show: true },
column: { width: 120 },
form: { show: false },
},
action: {
title: "操作动作",
type: "text",
search: { show: true },
column: { width: 200, tooltip: true },
form: { show: false },
},
success: {
title: "结果",
type: "dict-switch",
dict: dict({
data: [
{ value: true, label: "成功", color: "success" },
{ value: false, label: "失败", color: "error" },
],
}),
column: { width: 100, align: "center" },
form: { show: false },
search: { show: true },
},
content: {
title: "备注",
type: "text",
search: { show: true },
column: { width: 700, tooltip: true },
form: { show: false },
},
ipAddress: {
title: "IP地址",
type: "text",
column: { width: 140 },
form: { show: false },
},
projectId: {
title: t("certd.fields.projectName"),
type: "dict-select",
dict: myProjectDict,
form: {
show: false,
},
},
},
},
};
}
@@ -0,0 +1,24 @@
<template>
<fs-page>
<template #header>
<div class="title">
操作日志
<span class="sub">查看您的操作记录</span>
</div>
</template>
<fs-crud ref="crudRef" v-bind="crudBinding" />
</fs-page>
</template>
<script lang="ts" setup>
import { useFs } from "@fast-crud/fast-crud";
import createCrudOptions from "./crud";
import { createAuditApi } from "./api";
import { useMounted } from "/@/use/use-mounted";
defineOptions({ name: "AuditLog" });
const api = createAuditApi();
const { crudBinding, crudRef, crudExpose } = useFs({ createCrudOptions, context: { api } });
useMounted(() => crudExpose.doRefresh());
</script>
@@ -1,5 +1,5 @@
<template>
<a-drawer v-model:open="stepDrawerVisible" :wrap-style="{ maxWidth: '100vw' }" placement="right" :closable="true" width="760px" class="step-form-drawer" :class="{ fullscreen }">
<a-drawer v-model:open="stepDrawerVisible" placement="right" :closable="true" width="760px" class="step-form-drawer" :class="{ fullscreen }">
<template #title>
<div>
编辑步骤
@@ -12,63 +12,25 @@
</template>
</div>
<div class="hidden md:block">
<fs-icon class="icon-button" :icon="fullscreen ? 'material-symbols:fullscreen-exit' : 'material-symbols:fullscreen'" @click="fullscreen = !fullscreen"></fs-icon>
<a-space>
<fs-icon class="icon-button" :icon="fullscreen ? 'material-symbols:fullscreen-exit' : 'material-symbols:fullscreen'" @click="fullscreen = !fullscreen"></fs-icon>
</a-space>
</div>
</template>
<template v-if="currentStep">
<pi-container v-if="currentStep._isAdd" class="pi-step-form">
<template #header>
<a-row :gutter="10" class="mb-10">
<a-col :span="24" style="padding-left: 20px">
<a-input-search v-model:value="pluginSearch.keyword" placeholder="搜索插件" :allow-clear="true" :show-search="true"></a-input-search>
</a-col>
</a-row>
</template>
<div class="flex-col h-100 overflow-hidden md:ml-5 md:mr-5 step-form-body">
<a-tabs v-model:active-key="pluginGroupActive" tab-position="left" class="flex-1 overflow-hidden h-full">
<template v-for="group of computedPluginGroups" :key="group.key">
<a-tab-pane v-if="(group.key === 'admin' && userStore.isAdmin) || group.key !== 'admin'" :key="group.key" class="scroll-y">
<template #tab>
<div class="cd-step-form-tab-label">
<fs-icon :icon="group.icon" class="mr-2" />
<div>{{ group.title }}</div>
</div>
</template>
<a-row v-if="!group.plugins || group.plugins.length === 0" :gutter="10">
<a-col class="flex-o">
<div class="flex-o m-10">没有找到插件</div>
</a-col>
</a-row>
<a-row v-else :gutter="10">
<a-col v-for="item of group.plugins" :key="item.key" class="step-plugin w-full md:w-[50%]">
<a-card
hoverable
:class="{ current: item.name === currentStep.type }"
@click="stepTypeSelected(item)"
@dblclick="
stepTypeSelected(item);
stepTypeSave();
"
>
<a-card-meta>
<template #title>
<fs-icon class="plugin-icon" :icon="item.icon || 'clarity:plugin-line'"></fs-icon>
<span class="title" :title="item.title">{{ item.title }}</span>
<vip-button v-if="item.needPlus" mode="icon" />
</template>
<template #description>
<span :title="item.desc" v-html="transformDesc(item.desc)"></span>
</template>
</a-card-meta>
</a-card>
</a-col>
</a-row>
</a-tab-pane>
</template>
<a-tabs v-model:active-key="pluginSourceActive" class="step-plugin-source-tabs flex-1 overflow-hidden h-full">
<a-tab-pane key="local" tab="已安装插件" class="h-full">
<LocalPluginSelector :selected-type="currentStep.type" @select="stepTypeSelected" @confirm="handlePluginConfirm" />
</a-tab-pane>
<a-tab-pane v-if="userStore.isAdmin" key="market" tab="插件市场" class="h-full step-market-pane">
<OnlinePluginSelector :selected-type="currentStep.type" @select="stepTypeSelected" @confirm="handlePluginConfirm" @uninstalled="handleOnlinePluginUninstalled" />
</a-tab-pane>
</a-tabs>
</div>
<template #footer>
<div style="padding: 20px; margin-left: 100px">
<div class="bottom-button">
<a-button v-if="editMode" type="primary" @click="stepTypeSave"> 确定</a-button>
</div>
</template>
@@ -117,28 +79,30 @@
<script lang="tsx" setup>
import { message, Modal } from "ant-design-vue";
import { computed, provide, ref, Ref, watch } from "vue";
import { provide, ref, Ref } from "vue";
import { merge, cloneDeep } from "lodash-es";
import { nanoid } from "nanoid";
import { usePluginStore, PluginGroups } from "/@/store/plugin";
import { usePluginStore } from "/@/store/plugin";
import { useCompute } from "@fast-crud/fast-crud";
import { useReference } from "/@/use/use-refrence";
import { useSettingStore } from "/@/store/settings";
import { mitter } from "/@/utils/util.mitt";
import { utils } from "/@/utils";
import { useUserStore } from "/@/store/user";
import LocalPluginSelector from "./local-plugin-selector.vue";
import OnlinePluginSelector from "./online-plugin-selector.vue";
defineOptions({
name: "PiStepForm",
});
const props = defineProps({
defineProps({
editMode: {
type: Boolean,
default: true,
},
});
const emit = defineEmits(["update"]);
defineEmits(["update"]);
const pluginStore = usePluginStore();
const userStore = useUserStore();
@@ -171,6 +135,9 @@ function useStepForm() {
});
const stepTypeSelected = (item: any) => {
if (item.__online) {
return;
}
if (item.needPlus && !settingStore.isPlus) {
message.warn("此插件需要开通Certd专业版才能使用");
mitter.emit("openVipModal");
@@ -339,55 +306,24 @@ function useStepForm() {
};
};
const pluginSearch = ref({
keyword: "",
result: [],
});
const pluginGroupActive = ref("all");
const pluginGroup: Ref = ref();
const pluginStore = usePluginStore();
const pluginSourceActive = ref("local");
const handlePluginConfirm = async (item: any) => {
stepTypeSelected(item);
await stepTypeSave();
};
async function loadPluginGroups() {
pluginGroup.value = await pluginStore.getGroups();
}
loadPluginGroups();
const computedPluginGroups: any = computed(() => {
if (!pluginGroup.value) {
return {};
const handleOnlinePluginUninstalled = (plugin: any) => {
if (currentStep.value.type === plugin.fullName) {
currentStep.value.type = undefined;
currentStep.value.title = "新任务";
}
const group = pluginGroup.value as PluginGroups;
const groups = group.groups;
if (pluginSearch.value.keyword) {
const keyword = pluginSearch.value.keyword.toLowerCase();
const list = groups.all.plugins.filter((plugin: any) => {
return plugin.title?.toLowerCase().includes(keyword) || plugin.desc?.toLowerCase().includes(keyword) || plugin.name?.toLowerCase().includes(keyword);
});
return {
search: { key: "search", title: "搜索结果", plugins: list },
};
} else {
return groups;
}
});
watch(
() => {
return pluginSearch.value.keyword;
},
(val: any) => {
if (val) {
pluginGroupActive.value = "search";
} else {
pluginGroupActive.value = "all";
}
}
);
};
return {
pluginGroupActive,
computedPluginGroups,
pluginSearch,
pluginSourceActive,
stepTypeSelected,
handlePluginConfirm,
handleOnlinePluginUninstalled,
stepTypeSave,
stepFormRef,
mode,
@@ -436,34 +372,34 @@ const labelCol = ref({ span: 6 });
const wrapperCol = ref({ span: 16 });
const stepFormRes = useStepForm();
const { pluginGroupActive, computedPluginGroups, pluginSearch, stepTypeSelected, stepTypeSave, stepFormRef, stepDrawerVisible, currentStep, currentPlugin, stepSave, stepDelete, getScopeFunc, fullscreen } = stepFormRes;
const {
pluginSourceActive,
stepTypeSelected,
handlePluginConfirm,
handleOnlinePluginUninstalled,
stepTypeSave,
stepFormRef,
stepDrawerVisible,
currentStep,
currentPlugin,
stepSave,
stepDelete,
getScopeFunc,
fullscreen,
} = stepFormRes;
defineExpose({
...stepFormRes,
});
</script>
<style lang="less">
.cd-step-form-tab-label {
// dropdown
display: flex;
align-items: center;
//width: 120px;
.fs-icon {
display: flex;
align-items: center;
color: #00b7ff;
svg {
vertical-align: middle !important;
display: flex;
align-items: center;
}
}
}
.step-form-drawer {
max-width: 100%;
.ant-drawer-content-wrapper {
max-width: 100vw;
}
.ant-tabs-nav .ant-tabs-tab {
margin-top: 10px !important;
padding: 8px 14px !important;
@@ -502,6 +438,83 @@ defineExpose({
}
.pi-step-form {
.step-plugin-source-pane-local,
.step-plugin-source-pane-online {
display: flex;
height: 100%;
min-height: 0;
flex-direction: column;
}
.step-plugin-search {
flex: none;
padding: 0 0 12px;
}
.step-plugin-selector-tabs {
min-height: 0;
> .ant-tabs-nav {
width: 136px;
flex: 0 0 136px;
overflow: hidden;
}
> .ant-tabs-nav .ant-tabs-nav-wrap,
> .ant-tabs-nav .ant-tabs-nav-list {
width: 100%;
}
> .ant-tabs-nav .ant-tabs-tab {
width: 100%;
box-sizing: border-box;
}
.cd-step-form-tab-label {
display: flex;
align-items: center;
width: 100%;
min-width: 0;
.fs-icon {
display: flex;
align-items: center;
color: #00b7ff;
svg {
vertical-align: middle !important;
display: flex;
align-items: center;
}
}
> div:last-child {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
}
> .ant-tabs-content-holder {
min-width: 0;
min-height: 0;
flex: 1;
overflow-x: hidden;
overflow-y: auto;
padding-right: 10px;
}
> .ant-tabs-content-holder > .ant-tabs-content {
height: auto;
min-height: 100%;
}
> .ant-tabs-content-holder > .ant-tabs-content > .ant-tabs-tabpane {
padding-right: 0 !important;
overflow: visible !important;
}
}
.bottom-button {
padding: 20px;
padding-bottom: 5px;
@@ -514,6 +527,10 @@ defineExpose({
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
width: 22px;
font-size: 22px;
line-height: 22px;
}
.body {
@@ -542,7 +559,9 @@ defineExpose({
.ant-card-meta-title {
display: flex;
flex-direction: row;
align-items: center;
justify-content: flex-start;
min-height: 22px;
}
.ant-avatar {
@@ -558,19 +577,21 @@ defineExpose({
display: block;
overflow: hidden;
text-overflow: ellipsis;
line-height: 22px;
}
}
.ant-card-body {
padding: 14px;
height: 100px;
min-height: 100px;
padding-bottom: 6px;
overflow-y: hidden;
.ant-card-meta-description {
font-size: 12px;
line-height: 20px;
height: 40px;
min-height: 40px;
color: #7f7f7f;
}
}
@@ -0,0 +1,174 @@
<template>
<div class="step-plugin-source-pane-local">
<div class="step-plugin-search">
<a-input-search v-model:value="localPluginSearch.keyword" placeholder="搜索本地插件" :allow-clear="true" :show-search="true"></a-input-search>
</div>
<a-tabs v-model:active-key="pluginGroupActive" tab-position="left" class="step-plugin-selector-tabs flex-1 overflow-hidden h-full">
<a-tab-pane v-for="group of computedLocalPluginGroups" :key="group.key" class="step-plugin-list-pane">
<template #tab>
<div class="cd-step-form-tab-label" @click="handleLocalPluginGroupChange(group.key)">
<fs-icon :icon="group.icon" class="mr-2" />
<div>{{ group.title }}</div>
</div>
</template>
<div v-if="!group.plugins || group.plugins.length === 0" class="step-plugin-empty">没有找到插件</div>
<a-row v-else :gutter="10">
<a-col v-for="item of group.plugins" :key="item.key || item.name" class="step-plugin w-full md:w-[50%]">
<a-card hoverable :class="{ current: item.name === selectedType }" @click="emit('select', item)" @dblclick="emit('confirm', item)">
<a-card-meta>
<template #title>
<fs-icon class="plugin-icon" :icon="item.icon || 'clarity:plugin-line'"></fs-icon>
<span class="title" :title="item.title">{{ item.title }}</span>
<vip-button v-if="item.needPlus" mode="icon" />
</template>
<template #description>
<div class="plugin-card-desc" :title="item.desc" v-html="transformDesc(item.desc)"></div>
</template>
</a-card-meta>
</a-card>
</a-col>
</a-row>
</a-tab-pane>
</a-tabs>
</div>
</template>
<script lang="ts" setup>
import { computed, ref, Ref, watch } from "vue";
import { PluginGroups, usePluginStore } from "/@/store/plugin";
import { useUserStore } from "/@/store/user";
import { utils } from "/@/utils";
defineProps({
selectedType: {
type: String,
default: "",
},
});
const emit = defineEmits<{
(e: "select", plugin: any): void;
(e: "confirm", plugin: any): void;
}>();
const userStore = useUserStore();
const pluginStore = usePluginStore();
const pluginGroupActive = ref("all");
const pluginGroup: Ref<PluginGroups | undefined> = ref();
const localPluginSearch = ref({
keyword: "",
});
function transformDesc(desc: string = "") {
return utils.transformLink(desc);
}
function matchKeyword(plugin: any, keyword: string) {
const fields = [plugin.title, plugin.desc, plugin.name, plugin.fullName, plugin.author, plugin.latest];
return fields.some(field =>
String(field || "")
.toLowerCase()
.includes(keyword)
);
}
async function loadPluginGroups() {
pluginGroup.value = await pluginStore.getGroups();
}
function handleLocalPluginGroupChange(groupKey: string) {
pluginGroupActive.value = groupKey;
localPluginSearch.value.keyword = "";
}
const computedLocalPluginGroups: any = computed(() => {
if (!pluginGroup.value) {
return {};
}
const groups = pluginGroup.value.groups;
const keyword = localPluginSearch.value.keyword.trim().toLowerCase();
const visibleGroups: any = {};
for (const groupKey of Object.keys(groups)) {
if (groupKey === "admin" && !userStore.isAdmin) {
continue;
}
visibleGroups[groupKey] = groups[groupKey];
}
if (!keyword) {
return visibleGroups;
}
const filteredGroups: any = {};
for (const groupKey of Object.keys(visibleGroups)) {
const currentGroup = visibleGroups[groupKey];
filteredGroups[groupKey] = {
...currentGroup,
plugins: currentGroup.plugins.filter((plugin: any) => {
return matchKeyword(plugin, keyword);
}),
};
}
return filteredGroups;
});
watch(
() => {
return localPluginSearch.value.keyword;
},
val => {
if (val) {
pluginGroupActive.value = "all";
}
}
);
loadPluginGroups();
</script>
<style lang="less">
.step-plugin-source-pane-local {
.cd-step-form-tab-label {
display: flex;
align-items: center;
.fs-icon {
display: flex;
align-items: center;
color: #00b7ff;
svg {
vertical-align: middle !important;
display: flex;
align-items: center;
}
}
}
.step-plugin-source-pane {
display: flex;
height: 100%;
min-height: 0;
flex-direction: column;
}
.step-plugin-search {
flex: none;
padding: 0 0 12px;
}
.step-plugin-empty {
display: flex;
min-height: 320px;
align-items: center;
justify-content: center;
color: #7b8794;
font-size: 13px;
}
.plugin-card-desc {
overflow: hidden;
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;
}
}
</style>
@@ -0,0 +1,376 @@
<template>
<div class="step-plugin-source-pane-online">
<div class="step-plugin-search">
<a-input-search v-model:value="onlinePluginSearch.keyword" placeholder="搜索插件市场" :allow-clear="true" :show-search="true" :loading="onlineLoading" @search="handleOnlinePluginSearch"></a-input-search>
</div>
<a-tabs v-model:active-key="onlinePluginGroupActive" tab-position="left" class="step-plugin-selector-tabs step-market-tabs flex-1 overflow-hidden h-full">
<a-tab-pane v-for="group of computedOnlinePluginGroups" :key="group.key" class="step-plugin-list-pane">
<template #tab>
<div class="cd-step-form-tab-label" @click="handleOnlinePluginGroupChange(group.key)">
<fs-icon :icon="group.icon" class="mr-2" />
<div>{{ group.title }}</div>
</div>
</template>
<div v-if="onlineLoading" class="step-market-state">正在加载插件市场...</div>
<div v-else-if="!group.plugins || group.plugins.length === 0" class="step-plugin-empty">没有找到插件</div>
<template v-else>
<div class="step-market-content">
<a-row :gutter="[12, 12]">
<a-col v-for="item of group.plugins" :key="item.key || item.fullName" class="step-plugin market-plugin-col w-full md:w-[50%]">
<PluginItemCard :plugin="item" simple :current="isOnlinePluginCurrent(item)" @click="onlinePluginSelected(item)" @dblclick="handleOnlinePluginCardDblclick(item)" @changed="handleOnlinePluginChanged" />
</a-col>
</a-row>
<div class="online-plugin-pagination">
<a-pagination v-model:current="onlinePage" size="small" :page-size="onlinePageSize" :total="onlineCurrentTotal" :show-size-changer="false" simple />
</div>
</div>
</template>
</a-tab-pane>
</a-tabs>
</div>
</template>
<script lang="ts" setup>
import { computed, ref, Ref, watch } from "vue";
import { PluginGroups, usePluginStore } from "/@/store/plugin";
import { useUserStore } from "/@/store/user";
import PluginItemCard from "/@/views/sys/plugin/components/plugin-item-card.vue";
import * as pluginApi from "/@/views/sys/plugin/api";
import { useI18n } from "/src/locales";
const props = defineProps({
selectedType: {
type: String,
default: "",
},
});
const emit = defineEmits<{
(e: "select", plugin: any): void;
(e: "confirm", plugin: any): void;
(e: "uninstalled", plugin: any): void;
}>();
const { t } = useI18n();
const userStore = useUserStore();
const pluginStore = usePluginStore();
const pluginGroup: Ref<PluginGroups | undefined> = ref();
const onlinePlugins: Ref<pluginApi.OnlinePluginBean[]> = ref([]);
const onlineGroupPlugins: Ref<pluginApi.OnlinePluginBean[]> = ref([]);
const onlineLoading: Ref<boolean> = ref(false);
const onlineGroupLoaded: Ref<boolean> = ref(false);
const onlinePluginSearch = ref({
keyword: "",
});
const onlinePluginQueryKeyword = ref("");
const onlinePluginGroupActive = ref("all");
const onlinePage = ref(1);
const onlinePageSize = 8;
let onlineRequestId = 0;
async function loadPluginGroups() {
pluginGroup.value = await pluginStore.getGroups();
}
function getOnlinePluginListReq(req?: { groupKey?: string; keyword?: string }) {
const groupKey = req?.groupKey ?? onlinePluginGroupActive.value;
const keyword = (req?.keyword ?? onlinePluginQueryKeyword.value).trim();
const query: { pluginType: string; group?: string; keyword?: string } = {
pluginType: "deploy",
};
if (groupKey && groupKey !== "all") {
query.group = groupKey;
}
if (keyword) {
query.keyword = keyword;
}
return query;
}
async function loadOnlinePluginGroups(force = false) {
if (!userStore.isAdmin) {
return [];
}
if (onlineGroupLoaded.value && !force) {
return onlineGroupPlugins.value;
}
const list = await pluginApi.OnlinePluginList({ pluginType: "deploy" });
onlineGroupPlugins.value = list;
onlineGroupLoaded.value = true;
return list;
}
async function loadOnlinePlugins(force = false, options?: { silent?: boolean }) {
if (!userStore.isAdmin) {
return;
}
const requestId = ++onlineRequestId;
if (!options?.silent) {
onlineLoading.value = true;
}
try {
const groupPlugins = await loadOnlinePluginGroups(force);
if (requestId !== onlineRequestId) {
return;
}
const query = getOnlinePluginListReq();
const isFullQuery = !query.group && !query.keyword;
if (isFullQuery) {
onlinePlugins.value = groupPlugins;
} else {
const list = await pluginApi.OnlinePluginList(query);
if (requestId !== onlineRequestId) {
return;
}
onlinePlugins.value = list;
}
} finally {
if (!options?.silent && requestId === onlineRequestId) {
onlineLoading.value = false;
}
}
}
function getOnlinePluginDisplayName(plugin: pluginApi.OnlinePluginBean) {
if (plugin.fullName) {
return plugin.fullName;
}
if (plugin.author && plugin.name) {
return `${plugin.author}/${plugin.name}`;
}
return plugin.name || "";
}
function buildOnlinePluginCard(plugin: pluginApi.OnlinePluginBean) {
const fullName = getOnlinePluginDisplayName(plugin);
return {
...plugin,
key: `online:${fullName}`,
name: fullName,
fullName,
title: plugin.title || plugin.name || fullName,
desc: plugin.desc,
icon: plugin.icon || "clarity:plugin-line",
__online: true,
};
}
function getOnlinePluginGroupKey(plugin: pluginApi.OnlinePluginBean) {
return (plugin.group || "other").trim() || "other";
}
function getOnlinePluginGroupMeta(groupKey: string) {
const localGroups = pluginGroup.value?.groups || {};
const localGroup = localGroups[groupKey];
if (localGroup) {
return {
title: localGroup.title,
icon: localGroup.icon,
order: localGroup.order,
};
}
if (groupKey === "other") {
return {
title: "其他",
icon: "clarity:plugin-line",
order: 9999,
};
}
return {
title: groupKey,
icon: "clarity:plugin-line",
order: 1000,
};
}
function getFilteredOnlinePlugins() {
return onlinePlugins.value.map(plugin => buildOnlinePluginCard(plugin));
}
function getOnlinePluginsByGroup(groupKey: string) {
const list = getFilteredOnlinePlugins();
if (groupKey === "all") {
return list;
}
return list.filter(plugin => getOnlinePluginGroupKey(plugin) === groupKey);
}
function getPagedOnlinePlugins(groupKey: string) {
const list = getOnlinePluginsByGroup(groupKey);
const start = (onlinePage.value - 1) * onlinePageSize;
return list.slice(start, start + onlinePageSize);
}
async function handleOnlinePluginChanged(payload: { plugin: any; action: string }) {
if (payload.action === "uninstall" && props.selectedType === payload.plugin.fullName) {
emit("uninstalled", payload.plugin);
}
if (payload.action === "install" || payload.action === "uninstall") {
await pluginStore.reload();
}
await loadPluginGroups();
await loadOnlinePlugins(true, { silent: true });
}
function getInstalledPlugin(plugin: any) {
if (!plugin.installed || !plugin.fullName) {
return null;
}
const groups = pluginGroup.value;
if (!groups) {
return null;
}
const candidateNames = [plugin.fullName, plugin.name, plugin.author && plugin.name ? `${plugin.author}/${plugin.name}` : ""].filter(Boolean);
for (const name of candidateNames) {
const installedPlugin = groups.get(name);
if (installedPlugin) {
return installedPlugin;
}
}
return groups.groups.all.plugins.find((item: any) => {
if (plugin.localPluginId && item.id === plugin.localPluginId) {
return true;
}
return item.author === plugin.author && item.name === plugin.name;
});
}
function isOnlinePluginCurrent(plugin: any) {
const installedPlugin = getInstalledPlugin(plugin);
return !!installedPlugin && installedPlugin.name === props.selectedType;
}
function onlinePluginSelected(plugin: any) {
const installedPlugin = getInstalledPlugin(plugin);
if (!installedPlugin) {
return;
}
emit("select", installedPlugin);
}
function handleOnlinePluginCardDblclick(plugin: any) {
const installedPlugin = getInstalledPlugin(plugin);
if (!installedPlugin) {
return;
}
emit("confirm", installedPlugin);
}
function handleOnlinePluginGroupChange(groupKey: string) {
onlinePluginGroupActive.value = groupKey;
onlinePluginSearch.value.keyword = "";
onlinePluginQueryKeyword.value = "";
onlinePage.value = 1;
loadOnlinePlugins();
}
function handleOnlinePluginSearch(value: string) {
onlinePluginQueryKeyword.value = (value || "").trim();
onlinePluginGroupActive.value = "all";
onlinePage.value = 1;
loadOnlinePlugins();
}
const computedOnlinePluginGroups: any = computed(() => {
const allPlugins = onlineGroupPlugins.value.map(plugin => buildOnlinePluginCard(plugin));
const groups: any = {
all: {
key: "all",
title: t("certd.all"),
order: 0,
icon: "material-symbols:border-all-rounded",
plugins: getPagedOnlinePlugins("all"),
},
};
const groupKeys = Array.from(new Set(allPlugins.map(plugin => getOnlinePluginGroupKey(plugin))));
groupKeys.sort((left, right) => {
const leftMeta = getOnlinePluginGroupMeta(left);
const rightMeta = getOnlinePluginGroupMeta(right);
return leftMeta.order - rightMeta.order || left.localeCompare(right);
});
for (const groupKey of groupKeys) {
const meta = getOnlinePluginGroupMeta(groupKey);
groups[groupKey] = {
key: groupKey,
title: meta.title,
order: meta.order,
icon: meta.icon,
plugins: getPagedOnlinePlugins(groupKey),
};
}
return groups;
});
const onlineTotalPage = computed(() => {
const total = getOnlinePluginsByGroup(onlinePluginGroupActive.value).length;
return Math.max(1, Math.ceil(total / onlinePageSize));
});
const onlineCurrentTotal = computed(() => {
return getOnlinePluginsByGroup(onlinePluginGroupActive.value).length;
});
watch(
() => {
return onlinePluginGroupActive.value;
},
() => {
onlinePage.value = 1;
}
);
watch(
() => {
return onlineTotalPage.value;
},
totalPage => {
if (onlinePage.value > totalPage) {
onlinePage.value = totalPage;
}
}
);
loadPluginGroups();
loadOnlinePlugins();
</script>
<style lang="less">
.step-plugin-source-pane-online {
.step-market-content {
min-height: 100%;
padding: 2px 2px 12px 0;
}
.step-market-state {
display: flex;
min-height: 320px;
align-items: center;
justify-content: center;
color: #7b8794;
font-size: 13px;
}
.market-plugin-col {
display: flex;
}
.online-plugin-pagination {
display: flex;
align-items: center;
justify-content: flex-end;
min-height: 42px;
padding: 10px 2px 0;
color: #5f6b7a;
font-size: 12px;
font-variant-numeric: tabular-nums;
.ant-pagination {
margin: 0;
}
.ant-pagination-simple-pager {
font-variant-numeric: tabular-nums;
}
}
}
</style>
@@ -1,4 +1,4 @@
<template>
<template>
<div class="dashboard-user">
<div class="header-profile flex-wrap bg-white dark:bg-black">
<div class="flex flex-1">
@@ -23,9 +23,9 @@
<template v-if="userStore.isAdmin">
<a-divider type="vertical" />
<a-badge :dot="hasNewVersion">
<a-tag color="blue" class="flex-inline pointer mr-0" :title="t('certd.dashboard.latestVersion', { version: latestVersion })" @click="openUpgradeUrl()">
<a-tag color="blue" class="flex-inline pointer mr-0" :title="'v' + version + ' ' + (settingsStore.app.releaseMode === 'stable' ? '稳定版' : '')" @click="openUpgradeUrl()">
<fs-icon icon="ion:rocket-outline" class="mr-5"></fs-icon>
v{{ version }}
v{{ version }} {{ settingsStore.app.releaseMode === "stable" ? "stable" : "" }}
</a-tag>
</a-badge>
<a-divider type="vertical" />
@@ -179,7 +179,6 @@ defineOptions({
const version = ref(import.meta.env.VITE_APP_VERSION);
const latestVersion = ref("");
function isNewVersion(version: string, latestVersion: string) {
if (!latestVersion) {
return false;
@@ -13,7 +13,7 @@
<script setup lang="tsx">
import { IframeClient } from "@certd/lib-iframe";
import { computed, onMounted, ref } from "vue";
import { computed, onBeforeUnmount, onMounted, ref } from "vue";
import { useUserStore } from "/@/store/user";
import { useSettingStore } from "/@/store/settings";
import * as api from "./api";
@@ -23,6 +23,7 @@ defineOptions({
name: "AccountBind",
});
const iframeRef = ref();
let iframeClient: IframeClient | undefined;
const userStore = useUserStore();
const settingStore = useSettingStore();
@@ -40,9 +41,10 @@ type SubjectInfo = {
installAt?: number;
vipType?: string;
expiresAt?: number;
userId?: number;
};
onMounted(() => {
const iframeClient = new IframeClient(iframeRef.value, (e: any) => {
iframeClient = new IframeClient(iframeRef.value, (e: any) => {
notification.error({
message: " error",
description: e.message,
@@ -54,6 +56,7 @@ onMounted(() => {
installAt: settingStore.installInfo.installTime,
vipType: settingStore.plusInfo.vipType || "free",
expiresAt: settingStore.plusInfo.expireTime,
userId: settingStore.installInfo.bindUserId || undefined,
};
return subjectInfo;
});
@@ -84,6 +87,11 @@ onMounted(() => {
});
});
});
onBeforeUnmount(() => {
iframeClient?.destroy();
iframeClient = undefined;
});
</script>
<style lang="less">
@@ -0,0 +1,35 @@
import { request } from "/src/api/service";
const apiPrefix = "/sys/audit";
export function createSysAuditApi() {
return {
async GetList(query: any) {
return await request({
url: apiPrefix + "/page",
method: "post",
data: query,
});
},
async DelObj(id: number) {
return await request({
url: apiPrefix + "/delete",
method: "post",
params: { id },
});
},
async Clean(retentionDays: number) {
return await request({
url: apiPrefix + "/clean",
method: "post",
data: { retentionDays },
});
},
async GetDict() {
return await request({
url: apiPrefix + "/dict",
method: "post",
});
},
};
}
@@ -0,0 +1,180 @@
import { CreateCrudOptionsProps, CreateCrudOptionsRet, DelReq, UserPageQuery, UserPageRes, dict } from "@fast-crud/fast-crud";
import { Modal } from "ant-design-vue";
import { useI18n } from "/src/locales";
import { useDicts } from "/@/views/certd/dicts";
const typeDict = dict({
url: "/sys/audit/dict",
getData: async () => {
const { createSysAuditApi } = await import("./api");
const api = createSysAuditApi();
const res = await api.GetDict();
return res.types || [];
},
});
const actionDict = dict({
url: "/sys/audit/dict",
getData: async () => {
const { createSysAuditApi } = await import("./api");
const api = createSysAuditApi();
const res = await api.GetDict();
return res.actions || [];
},
});
export default function ({ crudExpose, context }: CreateCrudOptionsProps): CreateCrudOptionsRet {
const { t } = useI18n();
const { myProjectDict } = useDicts();
const api = context.api;
const pageRequest = async (query: UserPageQuery): Promise<UserPageRes> => {
return await api.GetList(query);
};
const delRequest = async (req: DelReq) => {
return await api.DelObj(req.row.id);
};
const cleanExpired = async () => {
Modal.confirm({
title: "确认清理",
content: "确定要清理90天前的审计日志吗?此操作不可撤销。",
okText: "确认清理",
okType: "danger",
cancelText: "取消",
async onOk() {
await api.Clean(90);
crudExpose.doRefresh();
},
});
};
return {
crudOptions: {
request: { pageRequest, delRequest },
tabs: {
name: "scope",
show: true,
dict: {
data: [
{ value: "system", label: "系统级", color: "red" },
{ value: "user", label: "用户级", color: "blue" },
],
},
},
actionbar: {
buttons: {
add: { show: false },
clean: {
text: "清理过期日志(90天)",
type: "primary",
danger: true,
click: cleanExpired,
},
},
},
rowHandle: {
width: 120,
fixed: "right",
buttons: {
view: { show: false },
edit: { show: false },
remove: { show: true },
copy: { show: false },
},
},
search: {
initialForm: { scope: "system" },
},
columns: {
id: {
title: "ID",
type: "number",
column: { width: 80 },
form: { show: false },
},
createTime: {
title: "操作时间",
type: "datetime",
search: {
show: true,
component: {
name: "a-range-picker",
},
},
column: { width: 170, sorter: true },
form: { show: false },
},
username: {
title: "操作人",
type: "text",
search: { show: true },
column: { width: 120 },
form: { show: false },
},
type: {
title: "类型",
type: "dict-select",
dict: typeDict,
search: { show: true },
column: { width: 120 },
form: { show: false },
},
action: {
title: "操作",
type: "text",
search: { show: true },
column: { width: 200, tooltip: true },
form: { show: false },
},
success: {
title: "结果",
type: "dict-switch",
dict: dict({
data: [
{ value: true, label: "成功", color: "success" },
{ value: false, label: "失败", color: "error" },
],
}),
column: { width: 100, align: "center" },
form: { show: false },
search: { show: true },
},
content: {
title: "备注",
type: "text",
search: { show: true },
column: { width: 500, tooltip: true },
form: { show: false },
},
ipAddress: {
title: "IP地址",
type: "text",
column: { width: 140 },
form: { show: false },
},
projectId: {
title: t("certd.fields.projectName"),
type: "dict-select",
dict: myProjectDict,
form: {
show: false,
},
},
scope: {
title: "范围",
type: "dict-select",
dict: dict({
data: [
{ value: "system", label: "系统级", color: "blue" },
{ value: "user", label: "用户级", color: "green" },
],
}),
search: { show: true },
column: { width: 100 },
form: { show: false },
},
},
},
};
}
@@ -0,0 +1,24 @@
<template>
<fs-page>
<template #header>
<div class="title">
操作日志
<span class="sub">查看所有用户的操作记录</span>
</div>
</template>
<fs-crud ref="crudRef" v-bind="crudBinding" />
</fs-page>
</template>
<script lang="ts" setup>
import { useFs } from "@fast-crud/fast-crud";
import createCrudOptions from "./crud";
import { createSysAuditApi } from "./api";
import { useMounted } from "/@/use/use-mounted";
defineOptions({ name: "SysAuditLog" });
const api = createSysAuditApi();
const { crudBinding, crudRef, crudExpose } = useFs({ createCrudOptions, context: { api } });
useMounted(() => crudExpose.doRefresh());
</script>
@@ -1,75 +1,35 @@
import { request } from "/src/api/service";
const apiPrefix = "/sys/project/provider";
const apiPrefix = "/sys/audit";
export async function GetList(query: any) {
return await request({
url: apiPrefix + "/page",
method: "post",
data: query,
});
}
export async function AddObj(obj: any) {
return await request({
url: apiPrefix + "/add",
method: "post",
data: obj,
});
}
export async function UpdateObj(obj: any) {
return await request({
url: apiPrefix + "/update",
method: "post",
data: obj,
});
}
export async function DelObj(id: any) {
return await request({
url: apiPrefix + "/delete",
method: "post",
params: { id },
});
}
export async function GetObj(id: any) {
return await request({
url: apiPrefix + "/info",
method: "post",
params: { id },
});
}
export async function GetDetail(id: any) {
return await request({
url: apiPrefix + "/detail",
method: "post",
params: { id },
});
}
export async function DeleteBatch(ids: any[]) {
return await request({
url: apiPrefix + "/deleteByIds",
method: "post",
data: { ids },
});
}
export async function SetDefault(id: any) {
return await request({
url: apiPrefix + "/setDefault",
method: "post",
data: { id },
});
}
export async function SetDisabled(id: any, disabled: boolean) {
return await request({
url: apiPrefix + "/setDisabled",
method: "post",
data: { id, disabled },
});
export function createSysAuditApi() {
return {
async GetList(query: any) {
return await request({
url: apiPrefix + "/page",
method: "post",
data: query,
});
},
async DelObj(id: number) {
return await request({
url: apiPrefix + "/delete",
method: "post",
params: { id },
});
},
async Clean(retentionDays: number) {
return await request({
url: apiPrefix + "/clean",
method: "post",
data: { retentionDays },
});
},
async GetDict() {
return await request({
url: apiPrefix + "/dict",
method: "post",
});
},
};
}
@@ -1,252 +1,194 @@
import * as api from "./api";
import { useI18n } from "/src/locales";
import { computed, Ref, ref } from "vue";
import { useRouter } from "vue-router";
import { AddReq, compute, CreateCrudOptionsProps, CreateCrudOptionsRet, DelReq, dict, EditReq, UserPageQuery, UserPageRes, utils } from "@fast-crud/fast-crud";
import { useUserStore } from "/@/store/user";
import { useSettingStore } from "/@/store/settings";
import { ColumnProps, DataFormatterContext, CreateCrudOptionsProps, CreateCrudOptionsRet, DelReq, UserPageQuery, UserPageRes, dict } from "@fast-crud/fast-crud";
import { Modal } from "ant-design-vue";
import { useI18n } from "/src/locales";
import { useDicts } from "/@/views/certd/dicts";
const typeDict = dict({
url: "/sys/audit/dict",
getData: async () => {
const { createSysAuditApi } = await import("./api");
const api = createSysAuditApi();
const res = await api.GetDict();
return res.types || [];
},
});
const actionDict = dict({
url: "/sys/audit/dict",
getData: async () => {
const { createSysAuditApi } = await import("./api");
const api = createSysAuditApi();
const res = await api.GetDict();
return res.actions || [];
},
});
export default function ({ crudExpose, context }: CreateCrudOptionsProps): CreateCrudOptionsRet {
const router = useRouter();
const { t } = useI18n();
const { myProjectDict } = useDicts();
const api = context.api;
const pageRequest = async (query: UserPageQuery): Promise<UserPageRes> => {
return await api.GetList(query);
};
const editRequest = async ({ form, row }: EditReq) => {
form.id = row.id;
const res = await api.UpdateObj(form);
return res;
};
const delRequest = async ({ row }: DelReq) => {
return await api.DelObj(row.id);
const delRequest = async (req: DelReq) => {
return await api.DelObj(req.row.id);
};
const addRequest = async ({ form }: AddReq) => {
const res = await api.AddObj(form);
return res;
const cleanExpired = async () => {
Modal.confirm({
title: "确认清理",
content: "确定要清理90天前的审计日志吗?此操作不可撤销。",
okText: "确认清理",
okType: "danger",
cancelText: "取消",
async onOk() {
await api.Clean(90);
crudExpose.doRefresh();
},
});
};
const userStore = useUserStore();
const settingStore = useSettingStore();
const selectedRowKeys: Ref<any[]> = ref([]);
context.selectedRowKeys = selectedRowKeys;
return {
crudOptions: {
settings: {
plugins: {
//这里使用行选择插件,生成行选择crudOptions配置,最终会与crudOptions合并
rowSelection: {
enabled: true,
order: -2,
before: true,
// handle: (pluginProps,useCrudProps)=>CrudOptions,
props: {
multiple: true,
crossPage: true,
selectedRowKeys,
},
request: { pageRequest, delRequest },
tabs: {
name: "scope",
show: true,
dict: {
data: [
{ value: "system", label: "系统级", color: "red" },
{ value: "user", label: "用户级", color: "blue" },
],
},
},
toolbar: {
buttons: {
export: { show: true },
},
export: {
dataFrom: "search",
columnFilter: (col: ColumnProps) => col.show === true,
dataFormatter: (opts: DataFormatterContext) => {
const { row, originalRow, col } = opts;
const key = col.key;
if (key === "createTime" && originalRow[key]) {
row[key] = new Date(originalRow[key]).toLocaleString();
}
},
},
},
request: {
pageRequest,
addRequest,
editRequest,
delRequest,
actionbar: {
buttons: {
add: { show: false },
clean: {
text: "清理过期日志(90天)",
type: "primary",
danger: true,
click: cleanExpired,
},
},
},
rowHandle: {
minWidth: 200,
width: 120,
fixed: "right",
buttons: {
view: { show: false },
edit: { show: false },
remove: { show: true },
copy: { show: false },
},
},
search: {
initialForm: { scope: "system" },
},
columns: {
id: {
title: "ID",
key: "id",
type: "number",
column: {
width: 100,
},
form: {
show: false,
},
},
domain: {
title: t("certd.cnameDomain"),
type: "text",
editForm: {
component: {
disabled: true,
},
},
search: {
show: true,
},
form: {
component: {
placeholder: t("certd.cnameDomainPlaceholder"),
},
helper: t("certd.cnameDomainHelper"),
rules: [
{ required: true, message: t("certd.requiredField") },
{ pattern: /^[^*]+$/, message: t("certd.cnameDomainPattern") },
],
},
column: {
width: 200,
},
},
dnsProviderType: {
title: t("certd.dnsProvider"),
type: "dict-select",
search: {
show: true,
},
dict: dict({
url: "pi/dnsProvider/list",
value: "key",
label: "title",
}),
form: {
rules: [{ required: true, message: t("certd.requiredField") }],
},
column: {
width: 150,
component: {
color: "auto",
},
},
},
accessId: {
title: t("certd.dnsProviderAuthorization"),
type: "dict-select",
dict: dict({
url: "/pi/access/list",
value: "id",
label: "name",
}),
form: {
component: {
name: "access-selector",
vModel: "modelValue",
type: compute(({ form }) => {
return form.dnsProviderType;
}),
},
rules: [{ required: true, message: t("certd.requiredField") }],
},
column: {
width: 150,
component: {
color: "auto",
},
},
},
isDefault: {
title: t("certd.isDefault"),
type: "dict-switch",
dict: dict({
data: [
{ label: t("certd.yes"), value: true, color: "success" },
{ label: t("certd.no"), value: false, color: "default" },
],
}),
form: {
value: false,
rules: [{ required: true, message: t("certd.selectIsDefault") }],
},
column: {
align: "center",
width: 100,
},
},
setDefault: {
title: t("certd.setDefault"),
type: "text",
form: {
show: false,
},
column: {
width: 100,
align: "center",
conditionalRenderDisabled: true,
cellRender: ({ row }) => {
if (row.isDefault) {
return;
}
const onClick = async () => {
Modal.confirm({
title: t("certd.prompt"),
content: t("certd.confirmSetDefault"),
onOk: async () => {
await api.SetDefault(row.id);
await crudExpose.doRefresh();
},
});
};
return (
<a-button type={"link"} size={"small"} onClick={onClick}>
{t("certd.setAsDefault")}
</a-button>
);
},
},
},
disabled: {
title: t("certd.disabled"),
type: "dict-switch",
dict: dict({
data: [
{ label: t("certd.enabled"), value: false, color: "success" },
{ label: t("certd.disabledLabel"), value: true, color: "error" },
],
}),
form: {
value: false,
},
column: {
width: 100,
component: {
title: t("certd.clickToToggle"),
on: {
async click({ value, row }) {
Modal.confirm({
title: t("certd.prompt"),
content: t("certd.confirmToggleStatus", { action: !value ? t("certd.disable") : t("certd.enable") }),
onOk: async () => {
await api.SetDisabled(row.id, !value);
await crudExpose.doRefresh();
},
});
},
},
},
},
column: { width: 80 },
form: { show: false },
},
createTime: {
title: t("certd.createTime"),
title: "操作时间",
type: "datetime",
search: {
show: true,
component: {
name: "a-range-picker",
},
},
column: { width: 170, sorter: true },
form: { show: false },
},
username: {
title: "操作人",
type: "text",
search: { show: true },
column: { width: 120 },
form: { show: false },
},
type: {
title: "类型",
type: "dict-select",
dict: typeDict,
search: { show: true },
column: { width: 120 },
form: { show: false },
},
action: {
title: "操作",
type: "text",
search: { show: true },
column: { width: 200, tooltip: true },
form: { show: false },
},
success: {
title: "结果",
type: "dict-switch",
dict: dict({
data: [
{ value: true, label: "成功", color: "success" },
{ value: false, label: "失败", color: "error" },
],
}),
column: { width: 100, align: "center" },
form: { show: false },
search: { show: true },
},
content: {
title: "备注",
type: "text",
search: { show: true },
column: { width: 500, tooltip: true },
form: { show: false },
},
ipAddress: {
title: "IP地址",
type: "text",
column: { width: 140 },
form: { show: false },
},
projectId: {
title: t("certd.fields.projectName"),
type: "dict-select",
dict: myProjectDict,
form: {
show: false,
},
column: {
sorter: true,
width: 160,
align: "center",
},
},
updateTime: {
title: t("certd.updateTime"),
type: "datetime",
form: {
show: false,
},
column: {
show: true,
width: 160,
},
scope: {
title: "范围",
type: "dict-select",
dict: dict({
data: [
{ value: "system", label: "系统级", color: "blue" },
{ value: "user", label: "用户级", color: "green" },
],
}),
search: { show: true },
column: { width: 100 },
form: { show: false },
},
},
},

Some files were not shown because too many files have changed in this diff Show More