161 lines
9.5 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import fs from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { createReadStream } from 'node:fs';
import { createHash } from 'node:crypto';
import { execFileSync } from 'node:child_process';
import { parseArgs } from 'node:util';
import { maintainAfterPackaging } from './local-build-retention.mjs';
import { assertPiNodeVersion } from '../src/runtime-policy.mjs';
import {
AGENT_DIRECTORIES, BUILD_README, LAUNCHER, NATIVE_FILES, PACKAGE_CHECK_SCRIPT, checkClientPackage, inventoryFiles, regularFile,
} from './client-package-integrity.mjs';
// A local portable build. Never copy a profile, credential, project or request journal.
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
export async function packageClient({
binary, destination, node = process.execPath, nodeLicense,
release = null, sourceRoot = root, nativeRoot = path.resolve(sourceRoot, '../detail-photocraft'),
}) {
if (!binary || !destination) throw Error('指定已验证的原生程序与新的输出目录');
sourceRoot = path.resolve(sourceRoot);
destination = path.resolve(destination);
binary = path.resolve(binary);
node = path.resolve(node);
nodeLicense = path.resolve(nodeLicense || path.join(path.dirname(node), 'LICENSE'));
if (destination === sourceRoot || destination.startsWith(sourceRoot + path.sep)) throw Error('输出目录必须独立于源码');
for (const file of [binary, node, nodeLicense, ...NATIVE_FILES.map(file => path.join(nativeRoot, file))]) await regularFile(file);
const version = execFileSync(node, ['--version'], { encoding: 'utf8', windowsHide: true }).trim();
assertPiNodeVersion(version);
const piPackage = path.join(sourceRoot, 'node_modules/@earendil-works/pi-coding-agent/package.json');
const { version: piVersion } = JSON.parse(await fs.readFile(piPackage, 'utf8'));
await fs.mkdir(path.dirname(destination), { recursive: true });
await fs.mkdir(destination); // Refuse to overwrite an existing client or user data.
await fs.copyFile(binary, path.join(destination, release ? 'XiaoYi.exe' : 'photocraft.exe'));
const agent = path.join(destination, 'agent');
await fs.mkdir(agent);
await fs.copyFile(node, path.join(agent, 'node.exe'));
await fs.copyFile(nodeLicense, path.join(agent, 'LICENSE-Node.txt'));
for (const file of ['package.json', 'package-lock.json']) await fs.copyFile(path.join(sourceRoot, file), path.join(agent, file));
for (const dir of AGENT_DIRECTORIES) await fs.cp(path.join(sourceRoot, dir), path.join(agent, dir), { recursive: true, dereference: true });
if (!release) {
const checkScript = path.join(agent, PACKAGE_CHECK_SCRIPT);
await fs.mkdir(path.dirname(checkScript));
await fs.copyFile(path.join(root, PACKAGE_CHECK_SCRIPT), checkScript);
}
for (const file of NATIVE_FILES) {
const target = path.join(destination, file);
await fs.mkdir(path.dirname(target), { recursive: true });
await fs.copyFile(path.join(nativeRoot, file), target);
}
if (release) {
await fs.writeFile(path.join(destination, 'version.json'), JSON.stringify(release, null, 2));
const files = await inventoryFiles(destination);
await fs.writeFile(path.join(destination, 'build-manifest.json'), JSON.stringify({
...release, files, bytes: files.reduce((sum, file) => sum + file.bytes, 0),
}, null, 2));
return;
}
const launcher = [
'@echo off',
'if /i "%~1"=="--check" goto check',
'start "" "%~dp0photocraft.exe"',
'exit /b %errorlevel%',
':check',
'"%~dp0agent\\node.exe" "%~dp0agent\\' + PACKAGE_CHECK_SCRIPT.replaceAll('/', '\\') + '"',
'exit /b %errorlevel%',
'',
].join('\r\n');
await fs.writeFile(path.join(destination, LAUNCHER), launcher, 'utf8');
const readme = [
'由壹点详情页本地开发构建',
'客户端界面使用 HarmonyOS Sans SC(鸿蒙黑体)。授权条款见 assets/ui-fonts/LICENSE-HarmonyOS-Sans.txt。',
'双击“启动客户端.cmd”。Agent运行组件已随包提供,无需另装Node。',
'账户、个人Key、项目与会话保存在当前Windows用户的独立配置和凭据库,不在本目录内。',
'本包未签名,尚不是正式安装程序。小壹运行组件版本 ' + piVersion + '。',
'',
].join('\r\n');
await fs.writeFile(path.join(destination, BUILD_README), readme, 'utf8');
const files = await inventoryFiles(destination);
const manifest = { at: new Date().toISOString(), kind: 'unsigned-local-development-portable', node: version, pi: piVersion, bytes: files.reduce((sum, file) => sum + file.bytes, 0), files };
await fs.writeFile(path.join(destination, 'build-manifest.json'), JSON.stringify(manifest, null, 2));
return { destination, ...await checkClientPackage({ destination }), node: version, pi: piVersion };
}
// 发布包:安装目录里放带图标的启动程序"小壹.exe"(scripts/windows/build-launcher.mjs 编译),
// 指定 ISCC 时同时编译 Windows 安装程序,桌面和开始菜单的快捷方式都指向这个启动程序。
export async function packageRelease({ binary, destination, node, nodeLicense, version, notes, launcher, iscc, minimum = '0.0.0' }) {
await regularFile(launcher);
const official = (await fs.readFile(path.join(root, '../detail-photocraft/client-version.txt'), 'utf8')).trim();
if (version !== official && version !== official + '-test') throw Error('发布版本与源码版本不一致');
const executable = await fs.readFile(binary);
const prefix = Buffer.from('XIAOYI_BUILD_INFO[');
const start = executable.indexOf(prefix);
const end = executable.indexOf(']', start + prefix.length);
if (start < 0 || end < 0) throw Error('程序缺少构建版本信息');
const [embedded, commit, builtAt, channel] = executable.toString('utf8', start + prefix.length, end).split('|');
if (embedded !== version || !/^[a-f0-9]{40}$/.test(commit) || !Number.isFinite(Date.parse(builtAt)) || channel !== 'stable') {
throw Error('程序构建信息与发布版本不匹配');
}
const release = { version, commit, builtAt, channel };
const releaseNotes = await fs.readFile(notes, 'utf8');
destination = path.resolve(destination);
await fs.mkdir(path.dirname(destination), { recursive: true });
await fs.mkdir(destination);
const install = path.join(destination, '小壹');
await packageClient({ binary, destination: path.join(install, 'versions', version), node, nodeLicense, release });
await fs.writeFile(path.join(install, 'current.txt'), version + '\r\n');
await fs.copyFile(launcher, path.join(install, '小壹.exe'));
await fs.writeFile(path.join(install, '使用说明.txt'), [
'用安装程序安装后,从桌面或开始菜单的“小壹”打开;卸载在 Windows“设置 › 应用”里进行。',
'免安装使用时,把压缩包完整解压到有写入权限的本机目录,双击“小壹.exe”。',
'如果需要打开上一版,先退出小壹,然后运行“小壹.exe --previous”。',
'安装目录和 Windows 用户配置分别保存。更新会保留上一版。', '',
].join('\r\n'));
const name = `小壹-${version}-win-x64.zip`;
const archive = path.join(destination, name);
execFileSync('powershell.exe', [
'-NoProfile', '-NonInteractive', '-Command',
'Add-Type -AssemblyName System.IO.Compression.FileSystem; [IO.Compression.ZipFile]::CreateFromDirectory($env:XIAOYI_ZIP_SOURCE, $env:XIAOYI_ZIP_DESTINATION)',
], {
env: { ...process.env, XIAOYI_ZIP_SOURCE: install, XIAOYI_ZIP_DESTINATION: archive },
windowsHide: true,
});
const hash = createHash('sha256');
for await (const chunk of createReadStream(archive)) hash.update(chunk);
const metadata = {
...release, notes: releaseNotes, minimumVersion: minimum,
file: { name, size: (await fs.stat(archive)).size, sha256: hash.digest('hex') },
};
await fs.writeFile(path.join(destination, 'release.json'), JSON.stringify(metadata, null, 2));
if (!iscc) return metadata;
const installer = `小壹-${version}-安装程序`;
execFileSync(iscc, [
'/Qp', `/DAppVersion=${version}`, `/DSourceDir=${install}`, `/DOutputDir=${destination}`, `/DOutputBaseFilename=${installer}`,
`/DIconFile=${path.join(root, '../detail-photocraft/assets/jiansun/icon.ico')}`, path.join(root, 'scripts/windows/xiaoyi-installer.iss'),
], { windowsHide: true, stdio: ['ignore', 'ignore', 'inherit'] });
return { ...metadata, installer: path.join(destination, installer + '.exe') };
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const { values, positionals } = parseArgs({ allowPositionals: true, options: {
release: { type: 'string' }, notes: { type: 'string' }, launcher: { type: 'string' },
installer: { type: 'string' }, minimum: { type: 'string' },
} });
const [binary, destination, node, nodeLicense] = positionals;
if (values.release !== undefined) {
if (!values.notes || !values.launcher) {
throw Error('发布模式需要 --release <版本> --notes <说明文件> --launcher <小壹.exe> [--installer <ISCC.exe>] [--minimum <最低可用版本>]');
}
console.log(JSON.stringify(await packageRelease({
binary, destination, node, nodeLicense, version: values.release, notes: values.notes,
launcher: values.launcher, iscc: values.installer, minimum: values.minimum,
})));
} else {
const result = await packageClient({ binary, destination, node, nodeLicense });
const cleanup = await maintainAfterPackaging(result.destination, path.resolve(binary));
console.log(JSON.stringify({ ...result, cleanup }));
}
}