feat: 展示小程序构建过程和日志

This commit is contained in:
que01 committed 2026-10-13 20:20:13 +08:00
1 parent 8b4d27b0ee
commit 998e32e49c
7 files changed
+182 -14

No files matched your search

@@ -89,6 +89,12 @@ export function PublicationPage({ canManageTemplate }: { canManageTemplate: bool
privateKey: "",
});
}, [miniAppSettings.data, miniAppSettingsForm]);
useEffect(() => {
const building = miniAppReleases.data?.find((task) => task.status === "building");
if (!building) return;
const timer = setInterval(() => void miniAppReleases.refetch(), 1500);
return () => clearInterval(timer);
}, [miniAppReleases.data, miniAppReleases]);
const refresh = () => {
for (const key of [
"publication-brand",
@@ -532,9 +538,11 @@ export function PublicationPage({ canManageTemplate }: { canManageTemplate: bool
color={
task.status === "published"
? "green"
: task.status === "failed"
: task.status === "failed" || task.status === "build_failed"
? "red"
: "blue"
: task.status === "building"
? "orange"
: "blue"
}
>
{task.status}
@@ -545,7 +553,27 @@ export function PublicationPage({ canManageTemplate }: { canManageTemplate: bool
</Typography.Text>
)}
{task.error && <Typography.Text type="danger">{task.error}</Typography.Text>}
{task.status === "built" && (
{task.status === "building" && (
<Typography.Text type="secondary">正在构建微信小程序...</Typography.Text>
)}
{task.status === "build_failed" && (
<Typography.Text type="secondary">微信小程序构建失败</Typography.Text>
)}
{task.buildLogs?.length ? (
<Space direction="vertical" style={{ width: "100%" }}>
{task.buildLogs.slice(-8).map((log, index) => (
<Typography.Paragraph
key={`${log.at}-${index}`}
type={log.stream === "stderr" ? "danger" : "secondary"}
style={{ marginBottom: 0, whiteSpace: "pre-wrap", fontSize: 12 }}
code
>
{log.message}
</Typography.Paragraph>
))}
</Space>
) : null}
{(task.status === "built" || task.status === "build_failed") && (
<Button
size="small"
loading={uploadMiniAppRelease.isPending}
@@ -0,0 +1,3 @@
ALTER TYPE "MiniAppReleaseStatus" ADD VALUE 'building' AFTER 'built';
ALTER TYPE "MiniAppReleaseStatus" ADD VALUE 'build_failed' AFTER 'building';
ALTER TABLE "MiniAppReleaseTask" ADD COLUMN "buildLogs" JSONB;
+3
View File
@@ -102,6 +102,8 @@ model CapabilityInstallation {
enum MiniAppReleaseStatus {
built
building
build_failed
uploaded
under_review
rejected
@@ -119,6 +121,7 @@ model MiniAppReleaseTask {
version Int
status MiniAppReleaseStatus @default(built)
artifactPath String?
buildLogs Json?
actorId String
error String?
weappUploadId String?
@@ -10,6 +10,7 @@ import {
} from "@nestjs/common";
import type { FastifyRequest } from "fastify";
import { existsSync } from "node:fs";
import { spawn } from "node:child_process";
import { resolve } from "node:path";
import { Prisma } from "@prisma/client";
import { getTemplatePackageManifest, templatePackageRegistry } from "@personal-brand/config";
@@ -52,6 +53,18 @@ interface MiniprogramCi {
}) => Promise<Record<string, unknown>>;
}
interface BuildLog {
at: string;
message: string;
stream: "stdout" | "stderr";
}
interface BuildProcess {
stdout: NodeJS.ReadableStream;
stderr: NodeJS.ReadableStream;
on: (event: "close" | "error", listener: (code: number | null) => void) => void;
}
@Controller("admin/miniapp-releases")
export class AdminMiniAppReleaseController {
constructor(
@@ -170,10 +183,58 @@ export class AdminMiniAppReleaseController {
const templateKey = miniAppTemplateKey(brand.templateKey);
if (!templateKey) throw new BadRequestException("当前品牌模板没有可上传的小程序包");
const projectPath = resolve(MINIAPP_ARTIFACT_ROOT, templateKey, "weapp");
if (!existsSync(projectPath) || !existsSync(resolve(projectPath, "app.json")))
throw new BadRequestException(
`小程序构建产物不存在:${projectPath},请先执行对应模板的微信小程序构建`,
);
const buildLogs: BuildLog[] = [
{
at: new Date().toISOString(),
message: `开始构建 ${templateKey} 微信小程序`,
stream: "stdout",
},
];
await this.releases.updateStatus(identity.brandId, identity.subject, taskId, {
status: "building",
buildLogs,
});
const result = await this.buildWeApp(templateKey, (message, stream) => {
buildLogs.push({ at: new Date().toISOString(), message, stream });
void this.releases
.updateStatus(identity.brandId, identity.subject, taskId, { status: "building", buildLogs })
.catch(() => undefined);
});
if (result.exitCode !== 0) {
buildLogs.push({
at: new Date().toISOString(),
message: `构建失败,退出码 ${result.exitCode}`,
stream: "stderr",
});
await this.releases.updateStatus(identity.brandId, identity.subject, taskId, {
status: "build_failed",
error: `小程序构建失败,请查看构建日志`,
buildLogs,
});
throw new BadRequestException("小程序构建失败,请查看构建日志");
}
if (!existsSync(projectPath) || !existsSync(resolve(projectPath, "app.json"))) {
buildLogs.push({
at: new Date().toISOString(),
message: `构建完成但缺少产物:${projectPath}/app.json`,
stream: "stderr",
});
await this.releases.updateStatus(identity.brandId, identity.subject, taskId, {
status: "build_failed",
error: "小程序构建产物缺少 app.json",
buildLogs,
});
throw new BadRequestException("小程序构建产物缺少 app.json");
}
buildLogs.push({
at: new Date().toISOString(),
message: "构建完成,开始上传微信",
stream: "stdout",
});
await this.releases.updateStatus(identity.brandId, identity.subject, taskId, {
status: "built",
buildLogs,
});
const ci = (await import("miniprogram-ci")) as unknown as MiniprogramCi;
const project = new ci.Project({
projectPath,
@@ -182,7 +243,7 @@ export class AdminMiniAppReleaseController {
privateKey,
});
try {
const result = await ci.upload({
const uploadResult = await ci.upload({
project,
version: body.version ?? String(task.version),
desc: body.desc ?? `brand content v${task.version}`,
@@ -191,14 +252,16 @@ export class AdminMiniAppReleaseController {
});
return this.releases.updateStatus(identity.brandId, identity.subject, taskId, {
status: "uploaded",
buildLogs,
weappUploadId:
typeof result.strUint64Version === "string"
? result.strUint64Version
typeof uploadResult.strUint64Version === "string"
? uploadResult.strUint64Version
: String(task.version),
});
} catch (error) {
await this.releases.updateStatus(identity.brandId, identity.subject, taskId, {
status: "failed",
buildLogs,
error: error instanceof Error ? error.message : "微信代码上传失败",
});
throw error;
@@ -226,6 +289,34 @@ export class AdminMiniAppReleaseController {
return value;
}
private buildWeApp(
templateKey: string,
onLog: (message: string, stream: "stdout" | "stderr") => void,
): Promise<{ exitCode: number }> {
return new Promise((resolvePromise, rejectPromise) => {
const child = spawn("pnpm", ["--filter", "@personal-brand/taro", "build:weapp"], {
cwd: resolve(process.cwd(), "../.."),
env: { ...process.env, TEMPLATE_KEY: templateKey, TARO_ENV: "weapp" },
shell: process.platform === "win32",
}) as BuildProcess;
const readStream = (stream: NodeJS.ReadableStream, name: "stdout" | "stderr") => {
let buffer = "";
stream.on("data", (chunk: Buffer | string) => {
buffer += chunk.toString();
for (const message of buffer.split("\n").slice(0, -1)) onLog(message, name);
buffer = buffer.slice(buffer.lastIndexOf("\n") + 1);
});
stream.on("end", () => {
if (buffer) onLog(buffer, name);
});
};
readStream(child.stdout, "stdout");
readStream(child.stderr, "stderr");
child.on("close", (code) => resolvePromise({ exitCode: code ?? 1 }));
child.on("error", () => rejectPromise(new Error("小程序构建进程启动失败")));
});
}
private jsonObject(value: unknown): Record<string, unknown> {
return value && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
@@ -8,8 +8,27 @@ export class CreateMiniAppReleaseDto {
}
export class UpdateMiniAppReleaseStatusDto {
@IsIn(["uploaded", "under_review", "approved", "rejected", "failed", "built", "published"])
status!: "uploaded" | "under_review" | "approved" | "rejected" | "failed" | "built" | "published";
@IsIn([
"uploaded",
"under_review",
"approved",
"rejected",
"failed",
"built",
"building",
"build_failed",
"published",
])
status!:
| "uploaded"
| "under_review"
| "approved"
| "rejected"
| "failed"
| "built"
| "building"
| "build_failed"
| "published";
@IsOptional()
@IsString()
@@ -9,6 +9,8 @@ import { PrismaService } from "../../prisma.service.js";
const transitions: Record<string, string[]> = {
built: ["uploaded", "under_review", "failed"],
building: ["built", "build_failed"],
build_failed: ["built"],
uploaded: ["under_review", "failed"],
under_review: ["approved", "rejected", "failed"],
approved: ["published", "failed"],
@@ -64,9 +66,18 @@ export class AdminMiniAppReleaseService {
taskId: string,
input: {
status:
"uploaded" | "under_review" | "approved" | "rejected" | "failed" | "built" | "published";
| "uploaded"
| "under_review"
| "approved"
| "rejected"
| "failed"
| "built"
| "building"
| "build_failed"
| "published";
error?: string;
weappUploadId?: string;
buildLogs?: unknown;
},
): Promise<unknown> {
return this.prisma.$transaction(
@@ -89,6 +100,9 @@ export class AdminMiniAppReleaseService {
status: input.status,
error: input.error ?? null,
...(input.weappUploadId ? { weappUploadId: input.weappUploadId } : {}),
...(input.buildLogs !== undefined
? { buildLogs: input.buildLogs as Prisma.InputJsonValue }
: {}),
audit,
},
});
+11 -1
View File
@@ -51,8 +51,18 @@ export interface BrandReleaseSummary {
export interface MiniAppReleaseTask {
id: string;
version: number;
status: "built" | "uploaded" | "under_review" | "rejected" | "approved" | "published" | "failed";
status:
| "built"
| "building"
| "build_failed"
| "uploaded"
| "under_review"
| "rejected"
| "approved"
| "published"
| "failed";
artifactPath?: string | null;
buildLogs?: Array<{ at: string; message: string; stream: "stdout" | "stderr" }> | null;
error?: string | null;
weappUploadId?: string | null;
createdAt: string;