import { createHash } from "node:crypto"; import { existsSync } from "node:fs"; import { cp, mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { spawnSync } from "node:child_process"; import { createRequire } from "node:module"; import { checkPackage } from "./check-package.mjs"; const require = createRequire(import.meta.url); const { findLeaks, loadConfig } = require("../../apps/taro/config/mask-taro.cjs"); const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../.."); const timestamp = new Date().toISOString().replace(/\D/g, "").slice(0, 14); const git = spawnSync("git", ["rev-parse", "--short=12", "HEAD"], { cwd: root, encoding: "utf8" }); if (git.status !== 0) throw new Error("Cannot determine source revision"); const revision = git.stdout.trim(); const version = process.env.RELEASE_VERSION ?? timestamp + "-" + revision; const output = path.join(root, "dist/releases", version); const archive = path.join(root, "dist/releases", "personal-brand-" + version + ".tar.gz"); function run(command, args) { const result = spawnSync(command, args, { cwd: root, stdio: "inherit" }); if (result.status !== 0) process.exit(result.status ?? 1); } /** 发布产物对外可下载,出现框架指纹即视为发布配置错误。 */ function assertNoStackFingerprint(directory) { const config = loadConfig(); if (!config.enabled) return; const leaks = findLeaks(path.join(root, directory), config); if (!leaks.length) return; throw new Error( `${directory} 仍含技术栈指纹,请通过包内构建脚本产出:\n` + leaks .slice(0, 10) .map((leak) => " - " + leak) .join("\n"), ); } async function listFiles(directory, prefix = "") { const files = []; for (const entry of await readdir(directory, { withFileTypes: true })) { const relative = path.posix.join(prefix, entry.name); if (entry.isDirectory()) files.push(...(await listFiles(path.join(directory, entry.name), relative))); else if (entry.isFile()) files.push(relative); else throw new Error("Unsupported release file: " + relative); } return files.sort(); } async function verifyStaticEntry(dist, entry, prefix) { const html = await readFile(path.join(dist, entry), "utf8"); for (const match of html.matchAll(/(?:src|href)=["']([^"']+)["']/g)) { const reference = match[1]; if (!/\.(?:js|css)(?:[?#]|$)/.test(reference)) continue; const url = new URL(reference, "https://release.invalid" + prefix); if (url.origin !== "https://release.invalid" || !url.pathname.startsWith(prefix)) { throw new Error("Invalid static base path in " + entry + ": " + reference); } const relative = decodeURIComponent(url.pathname.slice(prefix.length)); const base = entry === "index.html" ? dist : path.join(dist, "template-preview"); await readFile(path.join(base, relative)); } } async function copyWorkspace(workspace) { const source = path.join(root, workspace); const target = path.join(output, workspace); await mkdir(target, { recursive: true }); await cp(path.join(source, "package.json"), path.join(target, "package.json")); for (const directory of ["src", "dist"]) { if (!existsSync(path.join(source, directory))) continue; await cp(path.join(source, directory), path.join(target, directory), { recursive: true }); } if (existsSync(path.join(source, "tsconfig.json"))) { await cp(path.join(source, "tsconfig.json"), path.join(target, "tsconfig.json")); } if (workspace === "apps/api") { await cp(path.join(source, "prisma/schema.prisma"), path.join(target, "prisma/schema.prisma")); await cp(path.join(source, "prisma/migrations"), path.join(target, "prisma/migrations"), { recursive: true, }); } } async function copyTaroWorkspace() { const source = path.join(root, "apps/taro"); const target = path.join(output, "apps/taro"); await mkdir(target, { recursive: true }); await cp(path.join(source, "package.json"), path.join(target, "package.json")); await cp(path.join(source, "src"), path.join(target, "src"), { recursive: true }); await cp(path.join(source, "config"), path.join(target, "config"), { recursive: true }); await cp(path.join(source, "tsconfig.json"), path.join(target, "tsconfig.json")); } function sha256File(file) { return readFile(file).then((content) => createHash("sha256").update(content).digest("hex")); } async function discoverTemplatePackages() { const packages = []; for (const entry of await readdir(path.join(root, "packages"), { withFileTypes: true })) { const templateDirectory = path.join(root, "packages", entry.name); if ( entry.isDirectory() && entry.name.startsWith("template-") && existsSync(path.join(templateDirectory, "template.json")) && existsSync(path.join(templateDirectory, "taro/index.tsx")) ) { packages.push({ directoryName: entry.name, manifest: JSON.parse(await readFile(path.join(templateDirectory, "template.json"), "utf8")), }); } } return packages.sort((left, right) => left.manifest.packageKey.localeCompare(right.manifest.packageKey), ); } async function buildTemplateCatalog() { const packedRoot = path.join(root, "dist/template-packages"); await rm(packedRoot, { recursive: true, force: true }); const packages = []; for (const template of await discoverTemplatePackages()) { const { packageKey, version } = template.manifest; if (typeof packageKey !== "string" || typeof version !== "string") throw new Error("Template manifest must declare packageKey and version"); run("node", ["scripts/template-pack.cjs", "--template", packageKey, "--out", packedRoot]); const packedDirectory = path.join(packedRoot, `${packageKey}-${version}`); const checksums = JSON.parse( await readFile(path.join(packedDirectory, "checksums.json"), "utf8"), ); const archiveSource = packedDirectory + ".tar.gz"; const archiveChecksum = await sha256File(archiveSource); const archivePath = path.posix.join( "template-artifacts", packageKey, version, archiveChecksum + ".tar.gz", ); const archiveTarget = path.join(output, archivePath); await mkdir(path.dirname(archiveTarget), { recursive: true }); await cp(archiveSource, archiveTarget); const target = path.join(output, "packages", template.directoryName); await cp(packedDirectory, target, { recursive: true }); packages.push({ packageKey, version, displayName: template.manifest.displayName, supportedIndustryTemplates: template.manifest.supportedIndustryTemplates, manifest: template.manifest, validationReport: { formatVersion: "1", errors: [], fileCount: checksums.files.length, extractedBytes: checksums.files.reduce((total, file) => total + file.bytes, 0), files: checksums.files, }, contentChecksum: checksums.contentChecksum, archiveChecksum, archivePath, }); } await writeFile( path.join(output, "template-catalog.json"), JSON.stringify({ formatVersion: "1", packages }, null, 2) + "\n", ); return packages; } async function main() { if (!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,100}$/.test(version)) throw new Error("Invalid release version"); const adminDist = path.join(root, "apps/admin/dist"); await verifyStaticEntry(adminDist, "index.html", "/admin/"); await verifyStaticEntry(adminDist, "template-preview/index.html", "/template-preview/"); await mkdir(path.dirname(output), { recursive: true }); await mkdir(output, { recursive: false }); for (const file of [ "package.json", "pnpm-lock.yaml", "pnpm-workspace.yaml", "tsconfig.base.json", ]) { await cp(path.join(root, file), path.join(output, file)); } await cp(path.join(root, "patches"), path.join(output, "patches"), { recursive: true }); for (const workspace of [ "apps/api", "packages/config", "packages/template-contract", "packages/types", "packages/validation", ]) { await copyWorkspace(workspace); } await copyTaroWorkspace(); await cp(adminDist, path.join(output, "apps/admin/dist"), { recursive: true }); const templateCatalog = await buildTemplateCatalog(); if (!templateCatalog.length) throw new Error("Release contains no template package"); await cp(path.join(root, "apps/api/prisma/assets"), path.join(output, "seed-media"), { recursive: true, }); await cp(path.join(root, "deploy"), path.join(output, "deploy"), { recursive: true }); for (const file of ["check-package.mjs", "verify-public-release.mjs"]) { await mkdir(path.join(output, "scripts/deploy"), { recursive: true }); await cp(path.join(root, "scripts/deploy", file), path.join(output, "scripts/deploy", file)); } const validationPath = path.join(output, "packages/validation/package.json"); const validation = JSON.parse(await readFile(validationPath, "utf8")); validation.exports["."].import = "./dist/index.js"; validation.exports["."].types = "./dist/index.d.ts"; await writeFile(validationPath, JSON.stringify(validation, null, 2) + "\n"); const schemaPath = path.join(output, "apps/api/prisma/schema.prisma"); const schema = await readFile(schemaPath, "utf8"); await writeFile( schemaPath, schema.replace(/binaryTargets\s*=\s*\[[^\]]*\]/, 'binaryTargets = ["native"]'), ); const status = spawnSync("git", ["status", "--porcelain"], { cwd: root, encoding: "utf8" }); if (status.status !== 0) throw new Error("Cannot determine working tree state"); const manifest = { version, revision, dirty: Boolean(status.stdout.trim()), createdAt: new Date().toISOString(), nodeMajor: 24, packageManager: "pnpm@9.15.0", files: [], }; for (const file of await listFiles(output)) { if (/(?:^|\/)\.env(?:\.|$)/.test(file) && !file.endsWith(".example")) { throw new Error("Refusing to package environment file: " + file); } const content = await readFile(path.join(output, file)); manifest.files.push({ path: file, bytes: content.byteLength, sha256: createHash("sha256").update(content).digest("hex"), }); } await writeFile(path.join(output, "manifest.json"), JSON.stringify(manifest, null, 2) + "\n"); await checkPackage(output); run("tar", ["-czf", archive, "-C", output, "."]); const checksum = createHash("sha256") .update(await readFile(archive)) .digest("hex"); await writeFile(archive + ".sha256", checksum + " " + path.basename(archive) + "\n"); console.log("release: " + version); console.log("files: " + manifest.files.length); console.log("archive: " + path.relative(root, archive)); console.log("checksum: " + path.relative(root, archive + ".sha256")); } run("pnpm", ["build:admin:preview"]); assertNoStackFingerprint("apps/admin/dist"); run("pnpm", ["--filter", "@personal-brand/config", "build"]); run("pnpm", ["--filter", "@personal-brand/types", "build"]); run("pnpm", ["--filter", "@personal-brand/validation", "build"]); run("pnpm", ["--filter", "@personal-brand/api", "exec", "prisma", "generate"]); run("pnpm", ["--filter", "@personal-brand/api", "build"]); await main();