runtime-bundle.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import { createReadStream } from "node:fs"
  2. import { readdir, readFile } from "node:fs/promises"
  3. import { createHash } from "node:crypto"
  4. import { join } from "node:path"
  5. export type RuntimeRelease = { protocol: number; revision: string }
  6. export async function runtimeRelease(): Promise<RuntimeRelease> {
  7. const release = JSON.parse(await readFile(new URL("../runtime-release.json", import.meta.url), "utf8"))
  8. if (release.protocol !== 1 || !/^[a-f0-9]{40}$/.test(release.revision)) throw new Error("运行组件版本清单无效。")
  9. return release
  10. }
  11. export async function runtimeFiles(root: string) {
  12. const result: Record<string, string> = {}
  13. const visit = async (relative: string) => {
  14. for (const entry of await readdir(join(root, relative), { withFileTypes: true })) {
  15. const name = relative ? `${relative}/${entry.name}` : entry.name
  16. if (name === "desktop-runtime.json") continue
  17. if (entry.isDirectory()) {
  18. await visit(name)
  19. continue
  20. }
  21. if (!entry.isFile()) throw new Error(`运行组件包含非普通文件:${name}`)
  22. const hash = createHash("sha256")
  23. for await (const chunk of createReadStream(join(root, name))) hash.update(chunk)
  24. result[name] = hash.digest("hex")
  25. }
  26. }
  27. await visit("")
  28. return Object.fromEntries(Object.entries(result).sort(([a], [b]) => a.localeCompare(b)))
  29. }
  30. export async function validateRuntimeBundle(root: string, release?: RuntimeRelease) {
  31. const manifest = JSON.parse(await readFile(join(root, "desktop-runtime.json"), "utf8"))
  32. if (manifest.protocol !== 1 || manifest.platform !== process.platform || manifest.arch !== process.arch)
  33. throw new Error("本地运行组件与打包平台或协议不匹配。")
  34. const binary = process.platform === "win32" ? "agentpaas.exe" : "agentpaas"
  35. const files = await runtimeFiles(root)
  36. if (!manifest.files || !files[binary] || JSON.stringify(files) !== JSON.stringify(manifest.files))
  37. throw new Error("本地运行组件文件校验失败,请重新准备运行组件。")
  38. if (release) {
  39. const info = JSON.parse(await readFile(join(root, "build-info.json"), "utf8"))
  40. if (
  41. info.git_revision !== release.revision ||
  42. info.dirty !== false ||
  43. info.desktop_protocol !== release.protocol ||
  44. info.platform !== manifest.platform ||
  45. info.arch !== manifest.arch
  46. )
  47. throw new Error(`本地运行组件版本不匹配或源码未提交,请使用 ${release.revision} 重新构建。`)
  48. }
  49. return manifest
  50. }