import { BadRequestException, Body, Controller, Get, Param, Patch, Post, Req, } 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"; import { AdminAccessService } from "../../admin-access.service.js"; import { PrismaService } from "../../prisma.service.js"; import { AdminMiniAppReleaseService } from "./admin-miniapp-release.service.js"; import { UpdateMiniAppSettingsDto } from "./admin-miniapp-settings.dto.js"; import { decryptMiniAppCredential, encryptMiniAppCredential } from "./miniapp-credential-crypto.js"; import { CreateMiniAppReleaseDto, UpdateMiniAppReleaseStatusDto, UploadMiniAppReleaseDto, } from "./admin-miniapp-release.dto.js"; const MINIAPP_ARTIFACT_ROOT = process.env.MINIAPP_ARTIFACT_ROOT ?? "apps/taro/dist"; function miniAppTemplateKey(industryTemplateKey: string): string | null { return ( getTemplatePackageManifest(industryTemplateKey)?.packageKey ?? templatePackageRegistry.find((item) => item.supportedIndustryTemplates.includes(industryTemplateKey), )?.packageKey ?? null ); } interface MiniprogramCi { Project: new (options: { projectPath: string; type: "miniProgram"; appid: string; privateKey: string; }) => unknown; upload: (options: { project: unknown; version: string; desc: string; robot: number; setting: { es6: boolean; minified: boolean }; }) => Promise>; } 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( private readonly access: AdminAccessService, private readonly releases: AdminMiniAppReleaseService, private readonly prisma: PrismaService, ) {} @Get("latest") async latest(@Req() request: FastifyRequest): Promise { const identity = await this.identity(request); const task = await this.prisma.miniAppReleaseTask.findFirst({ where: { brandId: identity.brandId }, orderBy: { createdAt: "desc" }, }); return task ?? null; } @Get("settings") async settings(@Req() request: FastifyRequest): Promise { const identity = await this.identity(request); const brand = await this.prisma.brandProfile.findUnique({ where: { id: identity.brandId }, select: { miniAppSettings: true }, }); const settings = this.jsonObject(brand?.miniAppSettings); return { appId: "", artifactPath: MINIAPP_ARTIFACT_ROOT, build: {}, ...settings, privateKey: undefined, credential: settings.credential ? { algorithm: "aes-256-gcm" } : null, hasStoredCredentials: Boolean(settings.credential), }; } @Patch("settings") async updateSettings( @Req() request: FastifyRequest, @Body() body: UpdateMiniAppSettingsDto & { privateKey?: string }, ): Promise { const identity = await this.identity(request); await this.access.requireRole(request, ["owner", "admin", "platform-admin"]); if (body.privateKey !== undefined && !body.privateKey.startsWith("-----BEGIN")) throw new BadRequestException("上传私钥格式无效"); const brand = await this.prisma.brandProfile.findUniqueOrThrow({ where: { id: identity.brandId }, select: { miniAppSettings: true }, }); const current = this.jsonObject(brand.miniAppSettings); const credential = body.privateKey === undefined ? current.credential : encryptMiniAppCredential(body.privateKey); const settings = { ...current, appId: body.appId ?? current.appId ?? "", build: { ...this.jsonObject(current.build), ...this.jsonObject(body.build), } as Prisma.InputJsonObject, ...(credential ? { credential } : {}), templateKey: current.templateKey ?? null, } satisfies Prisma.InputJsonObject; await this.prisma.brandProfile.update({ where: { id: identity.brandId }, data: { miniAppSettings: settings }, }); return { appId: settings.appId, artifactPath: MINIAPP_ARTIFACT_ROOT, build: settings.build, credential: settings.credential ? { algorithm: "aes-256-gcm" } : null, hasStoredCredentials: Boolean(settings.credential), }; } @Get() list(@Req() request: FastifyRequest): Promise { return this.identity(request).then(({ brandId }) => this.releases.list(brandId)); } @Post() create(@Req() request: FastifyRequest, @Body() body: CreateMiniAppReleaseDto): Promise { return this.identity(request).then(({ brandId, subject }) => this.releases.create(brandId, subject, body), ); } @Post(":id/upload") async upload( @Req() request: FastifyRequest, @Param("id") taskId: string, @Body() body: UploadMiniAppReleaseDto, ): Promise { const identity = await this.identity(request); const task = await this.prisma.miniAppReleaseTask.findFirst({ where: { id: taskId, brandId: identity.brandId }, }); if (!task) throw new BadRequestException("小程序发布任务不存在"); if (task.status !== "built" && task.status !== "failed") throw new BadRequestException("当前小程序发布任务不能重复上传"); const brand = await this.prisma.brandProfile.findUniqueOrThrow({ where: { id: identity.brandId }, select: { miniAppSettings: true, templateKey: true }, }); const settings = this.jsonObject(brand.miniAppSettings); const appid = typeof settings.appId === "string" && settings.appId ? settings.appId : this.requiredEnv("WECHAT_APP_ID"); const privateKey = settings.credential ? decryptMiniAppCredential(settings.credential) : this.requiredEnv("WECHAT_UPLOAD_PRIVATE_KEY"); const templateKey = miniAppTemplateKey(brand.templateKey); if (!templateKey) throw new BadRequestException("当前品牌模板没有可上传的小程序包"); const projectPath = resolve(MINIAPP_ARTIFACT_ROOT, templateKey, "weapp"); 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, type: "miniProgram", appid, privateKey, }); try { const uploadResult = await ci.upload({ project, version: body.version ?? String(task.version), desc: body.desc ?? `brand content v${task.version}`, robot: body.robot ?? 1, setting: { es6: false, minified: true }, }); return this.releases.updateStatus(identity.brandId, identity.subject, taskId, { status: "uploaded", buildLogs, weappUploadId: 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; } } @Patch(":id/status") async updateStatus( @Req() request: FastifyRequest, @Param("id") taskId: string, @Body() body: UpdateMiniAppReleaseStatusDto, ): Promise { const identity = await this.identity(request); return this.releases.updateStatus(identity.brandId, identity.subject, taskId, body); } private async identity(request: FastifyRequest): Promise<{ subject: string; brandId: string }> { const { subject, brandId } = await this.access.requireBrand(request); return { subject, brandId }; } private requiredEnv(name: string): string { const value = process.env[name]; if (!value) throw new BadRequestException(`${name} 未配置`); 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 { return value && typeof value === "object" && !Array.isArray(value) ? (value as Record) : {}; } }