mirror of
https://github.com/margrop/wrong-notebook.git
synced 2026-12-02 07:30:03 +08:00
583 lines
30 KiB
JavaScript
583 lines
30 KiB
JavaScript
#!/usr/bin/env node
|
||
/**
|
||
* 全平台安装包构建脚本
|
||
*
|
||
* node scripts/package/build.mjs bundle [--skip-build] 构建通用服务端包 dist/bundle
|
||
* node scripts/package/build.mjs npm 生成 npm 包目录 dist/npm 并 npm pack
|
||
* node scripts/package/build.mjs desktop [electron-builder 参数...]
|
||
* 打包 Windows / macOS / Linux 桌面安装包
|
||
* node scripts/package/build.mjs fnos --arch x86|arm 打包飞牛OS fpk(需要 fnpack)
|
||
* node scripts/package/build.mjs synology 打包群晖 SPK(Docker 套件,无需 bundle;安装时在线拉取镜像)
|
||
* node scripts/package/build.mjs synology --arch x86_64 --image <镜像.tar.gz> 内置镜像的群晖 SPK(arch 取 x86_64 或 arm64,qnap 同)
|
||
* node scripts/package/build.mjs qnap 打包威联通 QPKG(Docker 套件,需要 QDK qbuild)
|
||
* node scripts/package/build.mjs android [--mode standalone|client] [--flavor phone|tablet]
|
||
* 打包安卓 APK(需要 Android SDK 和 Gradle):单机版内置服务端,
|
||
* 需先构建 dist/bundle 和安卓 Prisma 引擎;客户端版连接已部署的服务器
|
||
*
|
||
* 版本号依次取 --version、环境变量 PACKAGE_VERSION、package.json。
|
||
* Prisma 引擎与当前构建机平台一致,因此桌面端、飞牛OS 和原生服务端安装包需在目标平台上构建(见 .github/workflows/packages.yml)。
|
||
* 群晖/威联通套件只管理 Docker 容器,使用 noarch 包,不依赖构建机架构。
|
||
*/
|
||
import fs from 'node:fs';
|
||
import path from 'node:path';
|
||
import crypto from 'node:crypto';
|
||
import { spawnSync } from 'node:child_process';
|
||
import { fileURLToPath } from 'node:url';
|
||
import { buildAndroidRuntime } from './android-runtime.mjs';
|
||
import { androidVersionCode } from './android-version.mjs';
|
||
|
||
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
|
||
const DIST = path.join(ROOT, 'dist');
|
||
const BUNDLE = path.join(DIST, 'bundle');
|
||
const WORK = path.join(DIST, '.work');
|
||
const PACKAGING = path.join(ROOT, 'packaging');
|
||
const rootPkg = readJson(path.join(ROOT, 'package.json'));
|
||
|
||
const [command, ...rest] = process.argv.slice(2);
|
||
const flags = parseFlags(rest);
|
||
const version = String(flags.version || process.env.PACKAGE_VERSION || rootPkg.version).replace(/^v/, '');
|
||
|
||
function parseFlags(args) {
|
||
const out = { _: [] };
|
||
for (let i = 0; i < args.length; i++) {
|
||
const m = /^--(version|arch|flavor|mode|image)(?:=(.*))?$/.exec(args[i]);
|
||
if (m) out[m[1]] = m[2] ?? args[++i];
|
||
else if (args[i] === '--skip-build') out.skipBuild = true;
|
||
else out._.push(args[i]);
|
||
}
|
||
return out;
|
||
}
|
||
|
||
function readJson(file) {
|
||
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
||
}
|
||
|
||
function writeJson(file, data) {
|
||
fs.writeFileSync(file, `${JSON.stringify(data, null, 2)}\n`);
|
||
}
|
||
|
||
function log(message) {
|
||
console.log(`\n[package] ${message}`);
|
||
}
|
||
|
||
function run(cmd, args, options = {}) {
|
||
const result = spawnSync(cmd, args, {
|
||
cwd: ROOT,
|
||
stdio: 'inherit',
|
||
shell: process.platform === 'win32' && !path.isAbsolute(cmd),
|
||
...options,
|
||
env: { ...process.env, NEXT_TELEMETRY_DISABLED: '1', ...options.env },
|
||
});
|
||
if (result.status !== 0) {
|
||
throw new Error(`命令失败(退出码 ${result.status}):${cmd} ${args.join(' ')}`);
|
||
}
|
||
}
|
||
|
||
/** 用当前 Node 运行仓库内依赖的 CLI,避免 Windows 下 npx 的引号问题 */
|
||
function runNodeBin(relPath, args, options) {
|
||
run(process.execPath, [path.join(ROOT, 'node_modules', relPath), ...args], options);
|
||
}
|
||
|
||
function copy(src, dest) {
|
||
fs.cpSync(src, dest, {
|
||
recursive: true,
|
||
force: true,
|
||
verbatimSymlinks: true,
|
||
filter: (file) => path.basename(file) !== '.bin',
|
||
});
|
||
}
|
||
|
||
function rm(target) {
|
||
fs.rmSync(target, { recursive: true, force: true });
|
||
}
|
||
|
||
/** 预置数据库:执行全部迁移并写入系统标签(不含管理员,首次启动用初始化链接创建),与 Docker 镜像内的 prisma/dev.db 一致 */
|
||
function buildSeedDatabase() {
|
||
log('构建预置数据库');
|
||
const seedDb = path.join(WORK, 'seed.db');
|
||
const scriptsOut = path.join(WORK, 'dist-scripts');
|
||
const env = { DATABASE_URL: `file:${seedDb.split(path.sep).join('/')}` };
|
||
runNodeBin('typescript/bin/tsc', [
|
||
'scripts/rebuild-system-tags.ts', 'scripts/seed-chinese-primary.ts', 'scripts/seed-university-grades.ts', '--outDir', scriptsOut,
|
||
'--esModuleInterop', '--resolveJsonModule', '--skipLibCheck', '--module', 'commonjs', '--target', 'ES2022',
|
||
]);
|
||
runNodeBin('prisma/build/index.js', ['migrate', 'deploy'], { env });
|
||
run(process.execPath, ['scripts/seed-admin.js'], { env });
|
||
run(process.execPath, [path.join(scriptsOut, 'scripts', 'rebuild-system-tags.js')], { env });
|
||
return seedDb;
|
||
}
|
||
|
||
/** standalone 只追踪运行时用到的依赖;npm 包据此声明依赖,版本固定为构建时安装的版本 */
|
||
function collectRuntimeDependencies(nodeModules) {
|
||
const declared = { ...rootPkg.devDependencies, ...rootPkg.dependencies };
|
||
const names = [];
|
||
for (const entry of fs.readdirSync(nodeModules)) {
|
||
if (entry.startsWith('.')) continue;
|
||
if (entry.startsWith('@')) {
|
||
for (const sub of fs.readdirSync(path.join(nodeModules, entry))) names.push(`${entry}/${sub}`);
|
||
} else {
|
||
names.push(entry);
|
||
}
|
||
}
|
||
// 未在 package.json 声明、也不是其他已追踪包依赖的包(如 google-auth-library)同样需要声明;
|
||
// @img/* 是 sharp 的平台二进制,交给 npm 按用户平台安装
|
||
const manifests = Object.fromEntries(names.map((n) => [n, readJson(path.join(ROOT, 'node_modules', n, 'package.json'))]));
|
||
const covered = new Set();
|
||
for (const manifest of Object.values(manifests)) {
|
||
for (const field of ['dependencies', 'optionalDependencies', 'peerDependencies']) {
|
||
for (const dep of Object.keys(manifest[field] || {})) covered.add(dep);
|
||
}
|
||
}
|
||
const deps = {};
|
||
for (const name of names.sort()) {
|
||
if (name.startsWith('@img/')) continue;
|
||
if (declared[name] || !covered.has(name)) deps[name] = manifests[name].version;
|
||
}
|
||
deps.prisma = readJson(path.join(ROOT, 'node_modules', 'prisma', 'package.json')).version;
|
||
return deps;
|
||
}
|
||
|
||
/**
|
||
* 精简 Prisma 相关文件,缩小桌面版和飞牛OS 安装包:
|
||
* - 查询引擎只保留本平台的一份(.prisma/client 内),删除其他平台和重复的副本
|
||
* - 删除 Prisma Client 中只用于 Edge / WebAssembly / React Native 的运行时
|
||
* 迁移只需 schema 引擎;Prisma CLI 用到查询引擎时由 launcher.js 通过 PRISMA_QUERY_ENGINE_LIBRARY 指向保留的那一份
|
||
*/
|
||
function pruneBundle() {
|
||
const nodeModules = path.join(BUNDLE, 'node_modules');
|
||
const isQueryEngine = (name) => /^(lib)?query_engine[-_.]/.test(name);
|
||
const native = fs.readdirSync(path.join(ROOT, 'node_modules', '@prisma', 'engines')).find(isQueryEngine);
|
||
if (!native) throw new Error('未找到本平台的 Prisma 查询引擎');
|
||
const before = dirSize(nodeModules);
|
||
|
||
const clientDir = path.join(nodeModules, '.prisma', 'client');
|
||
for (const name of fs.readdirSync(clientDir)) {
|
||
if ((isQueryEngine(name) && name !== native) || name.startsWith('query_engine_bg.')) rm(path.join(clientDir, name));
|
||
}
|
||
for (const dir of [path.join(nodeModules, 'prisma'), path.join(nodeModules, '@prisma', 'engines')]) {
|
||
for (const name of fs.readdirSync(dir)) if (isQueryEngine(name)) rm(path.join(dir, name));
|
||
}
|
||
const runtimeDir = path.join(nodeModules, '@prisma', 'client', 'runtime');
|
||
for (const name of fs.readdirSync(runtimeDir)) {
|
||
if (/\.wasm$|^(edge|edge-esm|wasm|react-native)\.(js|d\.ts)$/.test(name)) rm(path.join(runtimeDir, name));
|
||
}
|
||
for (const pkg of ['adapter-libsql', 'driver-adapter-utils']) rm(path.join(nodeModules, '@prisma', pkg));
|
||
|
||
if (!fs.existsSync(path.join(clientDir, native))) throw new Error(`.prisma/client 中缺少本平台查询引擎 ${native}`);
|
||
const mb = (bytes) => `${(bytes / 1048576).toFixed(0)}MB`;
|
||
log(`精简 node_modules:${mb(before)} → ${mb(dirSize(nodeModules))}`);
|
||
}
|
||
|
||
function dirSize(dir) {
|
||
let total = 0;
|
||
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
||
const full = path.join(dir, entry.name);
|
||
if (entry.isDirectory()) total += dirSize(full);
|
||
else if (entry.isFile()) total += fs.statSync(full).size;
|
||
}
|
||
return total;
|
||
}
|
||
|
||
function buildBundle() {
|
||
rm(WORK);
|
||
fs.mkdirSync(WORK, { recursive: true });
|
||
log('生成 Prisma Client');
|
||
runNodeBin('prisma/build/index.js', ['generate']);
|
||
const seedDb = buildSeedDatabase();
|
||
|
||
if (!flags.skipBuild) {
|
||
log('构建 Next.js 应用');
|
||
// 与 npm run build 的 prebuild 一致:复制 pdfjs 的 CMap 与标准字体到 public/pdfjs
|
||
run(process.execPath, [path.join(ROOT, 'scripts', 'copy-pdfjs-assets.mjs')]);
|
||
runNodeBin('next/dist/bin/next', ['build']);
|
||
}
|
||
const standalone = path.join(ROOT, '.next', 'standalone');
|
||
if (!fs.existsSync(path.join(standalone, 'server.js'))) {
|
||
throw new Error('未找到 .next/standalone/server.js,请先执行 npm run build');
|
||
}
|
||
|
||
log('组装 dist/bundle');
|
||
rm(BUNDLE);
|
||
copy(standalone, BUNDLE);
|
||
// standalone 仅保留运行时必需的顶层项,移除可能带入的本机配置、数据库及开发目录
|
||
const allowedTopLevel = new Set(['server.js', 'package.json', '.next', 'node_modules']);
|
||
for (const entry of fs.readdirSync(BUNDLE)) {
|
||
if (!allowedTopLevel.has(entry)) rm(path.join(BUNDLE, entry));
|
||
}
|
||
// 外部包别名链接由 launcher.js 在运行时解析(见 installExternalAliasResolver)
|
||
rm(path.join(BUNDLE, '.next', 'node_modules'));
|
||
|
||
// npm 包需要的依赖列表,在覆盖 Prisma 目录之前按 standalone 追踪结果计算
|
||
const runtimeDeps = collectRuntimeDependencies(path.join(BUNDLE, 'node_modules'));
|
||
writeJson(path.join(WORK, 'runtime-dependencies.json'), runtimeDeps);
|
||
|
||
copy(path.join(ROOT, '.next', 'static'), path.join(BUNDLE, '.next', 'static'));
|
||
copy(path.join(ROOT, 'public'), path.join(BUNDLE, 'public'));
|
||
fs.mkdirSync(path.join(BUNDLE, 'prisma'), { recursive: true });
|
||
fs.copyFileSync(path.join(ROOT, 'prisma', 'schema.prisma'), path.join(BUNDLE, 'prisma', 'schema.prisma'));
|
||
copy(path.join(ROOT, 'prisma', 'migrations'), path.join(BUNDLE, 'prisma', 'migrations'));
|
||
fs.copyFileSync(seedDb, path.join(BUNDLE, 'prisma', 'seed.db'));
|
||
copy(path.join(WORK, 'dist-scripts'), path.join(BUNDLE, 'dist-scripts'));
|
||
// 运行时迁移需要 Prisma CLI 和本平台的 schema 引擎(与 Dockerfile 一致)
|
||
for (const dir of ['.prisma', 'prisma', '@prisma']) {
|
||
copy(path.join(ROOT, 'node_modules', dir), path.join(BUNDLE, 'node_modules', dir));
|
||
}
|
||
pruneBundle();
|
||
fs.copyFileSync(path.join(PACKAGING, 'runtime', 'launcher.js'), path.join(BUNDLE, 'launcher.js'));
|
||
// MIT 许可证要求随软件分发许可证文本,npm、桌面版和飞牛OS 安装包都基于此目录
|
||
fs.copyFileSync(path.join(ROOT, 'LICENSE'), path.join(BUNDLE, 'LICENSE'));
|
||
|
||
const pkg = readJson(path.join(BUNDLE, 'package.json'));
|
||
writeJson(path.join(BUNDLE, 'package.json'), {
|
||
name: pkg.name,
|
||
version,
|
||
private: true,
|
||
description: '错题本服务端(安装包运行时)',
|
||
});
|
||
log(`dist/bundle 已就绪(v${version}):${fs.readdirSync(BUNDLE).join(', ')}`);
|
||
}
|
||
|
||
function requireBundle() {
|
||
if (!fs.existsSync(path.join(BUNDLE, 'launcher.js'))) {
|
||
throw new Error('未找到 dist/bundle,请先执行 node scripts/package/build.mjs bundle');
|
||
}
|
||
}
|
||
|
||
function buildNpm() {
|
||
requireBundle();
|
||
const out = path.join(DIST, 'npm');
|
||
rm(out);
|
||
fs.mkdirSync(out, { recursive: true });
|
||
log('组装 npm 包');
|
||
for (const entry of fs.readdirSync(BUNDLE)) {
|
||
if (entry === 'node_modules' || entry === 'package.json') continue;
|
||
copy(path.join(BUNDLE, entry), path.join(out, entry));
|
||
}
|
||
copy(path.join(PACKAGING, 'npm', 'bin'), path.join(out, 'bin'));
|
||
fs.copyFileSync(path.join(PACKAGING, 'npm', 'README.md'), path.join(out, 'README.md'));
|
||
// npm 安装时按用户平台生成 Prisma Client,只需本机引擎
|
||
const schemaFile = path.join(out, 'prisma', 'schema.prisma');
|
||
fs.writeFileSync(schemaFile, fs.readFileSync(schemaFile, 'utf8').replace(/^\s*binaryTargets\s*=.*\n/m, ''));
|
||
|
||
writeJson(path.join(out, 'package.json'), {
|
||
name: 'wrong-notebook',
|
||
version,
|
||
description: '错题本:上传题目图片,由 AI 识别、解析并标注知识点,支持练习、统计与打印导出',
|
||
keywords: ['wrong-notebook', 'mistake-notebook', '错题本', 'ai', 'education'],
|
||
homepage: 'https://github.com/margrop/wrong-notebook',
|
||
repository: { type: 'git', url: 'git+https://github.com/margrop/wrong-notebook.git' },
|
||
bugs: 'https://github.com/margrop/wrong-notebook/issues',
|
||
license: 'MIT',
|
||
bin: { 'wrong-notebook': 'bin/wrong-notebook.js' },
|
||
files: ['bin', 'launcher.js', 'server.js', '.next', 'public', 'prisma', 'dist-scripts', 'README.md', 'LICENSE'],
|
||
engines: { node: '>=22.15' },
|
||
scripts: { postinstall: 'node bin/wrong-notebook.js prepare-client' },
|
||
dependencies: readJson(path.join(WORK, 'runtime-dependencies.json')),
|
||
});
|
||
run('npm', ['pack', '--pack-destination', DIST], { cwd: out });
|
||
log(`npm 包已生成:dist/wrong-notebook-${version}.tgz`);
|
||
}
|
||
|
||
function buildDesktop() {
|
||
requireBundle();
|
||
const stage = path.join(DIST, 'desktop');
|
||
rm(stage);
|
||
log('准备桌面端工程');
|
||
copy(path.join(PACKAGING, 'desktop'), stage);
|
||
copy(BUNDLE, path.join(stage, 'server'));
|
||
fs.copyFileSync(path.join(ROOT, 'public', 'icons', 'icon.png'), path.join(stage, 'icon.png'));
|
||
run('npm', ['install', '--no-audit', '--no-fund'], { cwd: stage });
|
||
log('electron-builder 打包');
|
||
run('npx', ['electron-builder', '--publish', 'never', `-c.extraMetadata.version=${version}`, ...flags._], { cwd: stage });
|
||
verifyDesktopOutput(path.join(stage, 'release'));
|
||
}
|
||
|
||
/** electron-builder 的文件过滤规则较多,打包后确认服务端关键文件确实进入安装包 */
|
||
function verifyDesktopOutput(releaseDir) {
|
||
const required = ['launcher.js', 'server.js', '.next/BUILD_ID', 'node_modules/.prisma/client/index.js', 'prisma/seed.db', 'dist-scripts/scripts/seed-chinese-primary.js', 'dist-scripts/scripts/seed-university-grades.js'];
|
||
const roots = [];
|
||
const walk = (dir, depth) => {
|
||
if (depth > 6 || !fs.existsSync(dir)) return;
|
||
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
||
if (!entry.isDirectory()) continue;
|
||
const full = path.join(dir, entry.name);
|
||
if (entry.name === 'server' && /^resources$/i.test(path.basename(dir))) {
|
||
roots.push(full);
|
||
} else {
|
||
walk(full, depth + 1);
|
||
}
|
||
}
|
||
};
|
||
walk(releaseDir, 0);
|
||
if (roots.length === 0) {
|
||
log('未找到解包目录,跳过安装包内容检查');
|
||
return;
|
||
}
|
||
for (const root of roots) {
|
||
const missing = required.filter((file) => !fs.existsSync(path.join(root, file)));
|
||
if (missing.length > 0) throw new Error(`${root} 缺少文件:${missing.join(', ')}`);
|
||
}
|
||
log(`安装包内容检查通过:${roots.map((r) => path.relative(ROOT, r)).join(', ')}`);
|
||
}
|
||
|
||
function buildFnos() {
|
||
requireBundle();
|
||
const arch = flags.arch || (process.arch === 'arm64' ? 'arm' : 'x86');
|
||
if (!['x86', 'arm'].includes(arch)) throw new Error('--arch 只能是 x86 或 arm');
|
||
const stage = path.join(DIST, 'fnos');
|
||
rm(stage);
|
||
log(`准备飞牛OS 打包目录(${arch})`);
|
||
copy(path.join(PACKAGING, 'fnos'), stage);
|
||
copy(BUNDLE, path.join(stage, 'app', 'server'));
|
||
const manifestFile = path.join(stage, 'manifest');
|
||
fs.writeFileSync(manifestFile, fs.readFileSync(manifestFile, 'utf8')
|
||
.replace(/^version\s*=.*$/m, `version = ${version}`)
|
||
.replace(/^platform\s*=.*$/m, `platform = ${arch}`));
|
||
// fnpack 不接受符号链接
|
||
const dropLinks = (dir) => {
|
||
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
||
const full = path.join(dir, entry.name);
|
||
if (entry.isSymbolicLink()) rm(full);
|
||
else if (entry.isDirectory()) dropLinks(full);
|
||
}
|
||
};
|
||
dropLinks(stage);
|
||
for (const file of fs.readdirSync(path.join(stage, 'cmd'))) fs.chmodSync(path.join(stage, 'cmd', file), 0o755);
|
||
|
||
const probe = spawnSync('fnpack', ['--help'], { stdio: 'ignore' });
|
||
if (probe.error) {
|
||
log('未找到 fnpack,已生成打包目录 dist/fnos;在飞牛OS 或 Linux 上执行 fnpack build -d dist/fnos 即可');
|
||
return;
|
||
}
|
||
rm(path.join(stage, 'wrongnotebook.fpk'));
|
||
run('fnpack', ['build', '-d', '.'], { cwd: stage });
|
||
const out = path.join(DIST, `WrongNotebook-FnOS-${version}-${arch}.fpk`);
|
||
fs.renameSync(path.join(stage, 'wrongnotebook.fpk'), out);
|
||
log(`飞牛OS 安装包已生成:${path.relative(ROOT, out)}`);
|
||
}
|
||
|
||
/** 群晖版本号需 [feature]-[build];预览版已有序号,正式版补 -1(镜像标签仍用原始版本) */
|
||
function synologyVersion(value) {
|
||
return value.includes('-') ? value : `${value}-1`;
|
||
}
|
||
|
||
/** QPKG 的 QPKG_VER 最长 10 个字符;去掉年份前缀,镜像标签仍用完整版本 */
|
||
function qnapVersion(value) {
|
||
const short = value.replace(/^20/, '');
|
||
return short.length <= 10 ? short : short.slice(0, 10);
|
||
}
|
||
|
||
/**
|
||
* NAS 套件内置的镜像归档:`docker save` 格式并经 gzip 压缩,其中的镜像名须为
|
||
* ghcr.io/margrop/wrong-notebook:<版本>。内置后套件按 CPU 架构分别出包,安装时不再联网拉取。
|
||
* 未传 --image 时返回 null,生成安装时在线拉取镜像的 noarch 套件。
|
||
*/
|
||
const NAS_IMAGE_ARCHS = {
|
||
// 群晖 INFO 的 arch 要写平台名;同时带上家族名,便于新平台识别
|
||
x86_64: {
|
||
synology: 'x86_64 apollolake avoton braswell broadwell broadwellnk broadwellnkv2 broadwellntb broadwellntbap bromolow cedarview coffeelake denverton epyc7002 geminilake geminilakenk grantley icelaked kvmx64 purley r1000 r1000nk skylaked v1000 v1000nk',
|
||
qnap: 'x86_64',
|
||
},
|
||
arm64: {
|
||
synology: 'armv8 aarch64 rtd1296 rtd1619 rtd1619b armada37xx',
|
||
qnap: 'arm_64',
|
||
},
|
||
};
|
||
|
||
function bundledImage() {
|
||
if (!flags.image) return null;
|
||
const arch = flags.arch;
|
||
if (!NAS_IMAGE_ARCHS[arch]) throw new Error(`内置镜像时需用 --arch 指定 ${Object.keys(NAS_IMAGE_ARCHS).join(' 或 ')}`);
|
||
const file = path.resolve(flags.image);
|
||
const head = Buffer.alloc(2);
|
||
const fd = fs.openSync(file, 'r');
|
||
fs.readSync(fd, head, 0, 2, 0);
|
||
fs.closeSync(fd);
|
||
if (head[0] !== 0x1f || head[1] !== 0x8b) throw new Error(`${flags.image} 不是 gzip 压缩的镜像归档`);
|
||
return { arch, file, ...NAS_IMAGE_ARCHS[arch] };
|
||
}
|
||
|
||
/** qbuild 出错时仍可能返回 0;用尾部标记、体积和文件名确认不是残缺归档 */
|
||
function verifyQpkg(file, expectedName, expectedVersion) {
|
||
if (path.basename(file) !== expectedName) throw new Error(`qbuild 生成的包名不符:${path.basename(file)}`);
|
||
const data = fs.readFileSync(file);
|
||
if (data.length < 16 * 1024) throw new Error(`QPKG 体积过小(${data.length} 字节),可能缺少数据归档`);
|
||
const tail = data.subarray(data.length - 100).toString('latin1');
|
||
if (!tail.includes('QNAPQPKG') || !tail.includes(expectedVersion)) {
|
||
throw new Error(`QPKG 尾部标记或版本不符:${file}`);
|
||
}
|
||
}
|
||
|
||
/** 群晖 SPK 外层必须是未压缩的 tar,gzip 压缩后套件中心会提示「套件文件格式不正确」 */
|
||
function verifySpk(file, required) {
|
||
const head = fs.readFileSync(file).subarray(0, 512);
|
||
if (head[0] === 0x1f && head[1] === 0x8b) throw new Error(`${path.basename(file)} 不能用 gzip 压缩`);
|
||
if (head.subarray(257, 262).toString('latin1') !== 'ustar') throw new Error(`${path.basename(file)} 不是 tar 归档`);
|
||
const listing = spawnSync('tar', ['-tf', file], { encoding: 'utf8' });
|
||
if (listing.status !== 0) throw new Error(`无法读取 ${file}: ${listing.stderr}`);
|
||
const names = new Set(listing.stdout.split('\n').map((line) => line.replace(/^\.\//, '').replace(/\/$/, '')));
|
||
for (const name of required) {
|
||
if (!names.has(name)) throw new Error(`${path.basename(file)} 缺少 ${name}`);
|
||
}
|
||
const stray = [...names].filter((name) => path.basename(name).startsWith('._'));
|
||
if (stray.length > 0) throw new Error(`${path.basename(file)} 混入 macOS 元数据文件:${stray.join(', ')}`);
|
||
}
|
||
|
||
/**
|
||
* 群晖 SPK:Docker 套件,noarch;package.tgz 内只有 compose 项目和说明。
|
||
* DSM 7 不允许第三方套件以 root 运行,容器由 conf/resource 的 docker-project 资源
|
||
* (Container Manager 提供)创建和启停,套件脚本以套件用户运行。
|
||
* INFO 的 adminport/adminurl 让套件中心的「打开」直接指向 http://<NAS>:39300/。
|
||
*/
|
||
async function buildSynology() {
|
||
const stage = path.join(DIST, 'synology');
|
||
rm(stage);
|
||
log('准备群晖 SPK 打包目录');
|
||
copy(path.join(PACKAGING, 'synology'), stage);
|
||
const composeFile = path.join(stage, 'package', 'compose', 'compose.yaml');
|
||
fs.writeFileSync(composeFile, fs.readFileSync(composeFile, 'utf8').replace('__IMAGE_TAG__', version));
|
||
for (const file of fs.readdirSync(path.join(stage, 'scripts'))) fs.chmodSync(path.join(stage, 'scripts', file), 0o755);
|
||
|
||
// 内置镜像:docker-project 在创建项目前加载 target 下的归档,compose 找到本地镜像后不再拉取
|
||
const image = bundledImage();
|
||
if (image) {
|
||
fs.copyFileSync(image.file, path.join(stage, 'package', 'image.tar.gz'));
|
||
const resourceFile = path.join(stage, 'conf', 'resource');
|
||
const resource = readJson(resourceFile);
|
||
resource['docker-project'] = { 'preload-image': 'image.tar.gz', ...resource['docker-project'] };
|
||
writeJson(resourceFile, resource);
|
||
}
|
||
|
||
// 套件图标由 packaging/synology 预置(64×64、256×256),避免构建时引入图像处理依赖
|
||
|
||
// COPYFILE_DISABLE:在 macOS 上构建时不把扩展属性写成 ._ 文件
|
||
const tarEnv = { env: { COPYFILE_DISABLE: '1' } };
|
||
run('tar', ['-czf', 'package.tgz', '-C', 'package', '.'], { cwd: stage, ...tarEnv });
|
||
const checksum = crypto.createHash('md5').update(fs.readFileSync(path.join(stage, 'package.tgz'))).digest('hex');
|
||
const infoFile = path.join(stage, 'INFO');
|
||
fs.writeFileSync(infoFile, fs.readFileSync(infoFile, 'utf8')
|
||
.replace(/^version=.*$/m, `version="${synologyVersion(version)}"`)
|
||
.replace(/^arch=.*$/m, `arch="${image ? image.synology : 'noarch'}"`)
|
||
.replace(/^checksum=.*$/m, `checksum="${checksum}"`));
|
||
|
||
const out = path.join(DIST, `WrongNotebook-Synology-${version}${image ? `-${image.arch}` : ''}.spk`);
|
||
const entries = ['INFO', 'package.tgz', 'scripts', 'conf', 'PACKAGE_ICON.PNG', 'PACKAGE_ICON_256.PNG'];
|
||
run('tar', ['-cf', out, ...entries], { cwd: stage, ...tarEnv });
|
||
verifySpk(out, ['INFO', 'package.tgz', 'scripts/start-stop-status', 'conf/privilege', 'conf/resource', 'PACKAGE_ICON.PNG', 'PACKAGE_ICON_256.PNG']);
|
||
log(`群晖套件已生成:${path.relative(ROOT, out)}`);
|
||
}
|
||
|
||
/**
|
||
* 威联通 QPKG:Docker 套件,noarch;用 QDK qbuild 生成自解压归档。
|
||
* 没有 qbuild 时保留 dist/qnap 打包目录,可在装有 QDK 的机器上继续构建。
|
||
*/
|
||
async function buildQnap() {
|
||
const stage = path.join(DIST, 'qnap');
|
||
rm(stage);
|
||
log('准备威联通 QPKG 打包目录');
|
||
copy(path.join(PACKAGING, 'qnap'), stage);
|
||
copy(path.join(PACKAGING, 'docker', 'docker-container.sh'), path.join(stage, 'shared', 'docker-container.sh'));
|
||
fs.writeFileSync(path.join(stage, 'shared', 'image-tag'), `${version}\n`);
|
||
fs.chmodSync(path.join(stage, 'shared', 'docker-container.sh'), 0o755);
|
||
fs.chmodSync(path.join(stage, 'shared', 'wrongnotebook.sh'), 0o755);
|
||
fs.chmodSync(path.join(stage, 'package_routines'), 0o755);
|
||
|
||
// 内置镜像:放进架构目录,qbuild 只为该架构出包,安装后归档位于 QPKG 安装目录
|
||
const image = bundledImage();
|
||
if (image) {
|
||
fs.mkdirSync(path.join(stage, image.qnap), { recursive: true });
|
||
fs.copyFileSync(image.file, path.join(stage, image.qnap, 'image.tar.gz'));
|
||
}
|
||
|
||
// QPKG 图标由 packaging/qnap/icons 预置(64×64、灰度 64×64、80×80 GIF)
|
||
|
||
const cfgFile = path.join(stage, 'qpkg.cfg');
|
||
fs.writeFileSync(cfgFile, fs.readFileSync(cfgFile, 'utf8')
|
||
.replace(/^QPKG_VER=.*$/m, `QPKG_VER="${qnapVersion(version)}"`));
|
||
|
||
const probe = spawnSync('qbuild', ['--help'], { stdio: 'ignore' });
|
||
if (probe.error) {
|
||
log('未找到 qbuild,已生成打包目录 dist/qnap;安装 QDK 后执行 qbuild 即可');
|
||
return;
|
||
}
|
||
run('qbuild', [], { cwd: stage });
|
||
const built = fs.readdirSync(path.join(stage, 'build')).filter((file) => file.endsWith('.qpkg'));
|
||
if (built.length !== 1) throw new Error(`qbuild 应生成 1 个 qpkg,实际 ${built.length} 个`);
|
||
const builtFile = path.join(stage, 'build', built[0]);
|
||
const expectedName = `wrongnotebook_${qnapVersion(version)}${image ? `_${image.qnap}` : ''}.qpkg`;
|
||
verifyQpkg(builtFile, expectedName, qnapVersion(version));
|
||
// qbuild 会把数据再压缩一遍,QPKG 可能比镜像归档略小;明显偏小才说明归档没有进入安装包
|
||
//(如构建机缺少 rsync 时 qbuild 不报错,只生成几十 KB 的空包)
|
||
if (image && fs.statSync(builtFile).size < fs.statSync(image.file).size * 0.9) {
|
||
throw new Error(`QPKG 远小于内置镜像,镜像归档没有进入安装包:${builtFile}`);
|
||
}
|
||
const out = path.join(DIST, `WrongNotebook-QNAP-${version}${image ? `-${image.arch}` : ''}.qpkg`);
|
||
fs.renameSync(builtFile, out);
|
||
log(`威联通套件已生成:${path.relative(ROOT, out)}`);
|
||
}
|
||
|
||
/**
|
||
* 安卓 APK 有两种模式,各分手机版(竖屏)和平板版(横竖屏):
|
||
* - standalone 单机版:内置 Node.js、Prisma 引擎和 dist/bundle,在手机上运行完整服务端,数据保存在本机
|
||
* - client 客户端版:只是连接已部署服务器的 WebView 外壳
|
||
* 单机版的 Prisma 引擎目录取 ANDROID_PRISMA_ENGINES_DIR,默认 dist/android-prisma-engines
|
||
* (由 build-android-prisma-engines.sh 生成);patchelf 可用 PATCHELF 指定路径。
|
||
* 签名密钥通过环境变量 ANDROID_KEYSTORE_FILE 等传入(见 packaging/android/app/build.gradle),未提供时使用调试签名。
|
||
*/
|
||
async function buildAndroid() {
|
||
const modes = flags.mode ? [flags.mode] : ['standalone', 'client'];
|
||
const flavors = flags.flavor ? [flags.flavor] : ['phone', 'tablet'];
|
||
if (modes.some((mode) => !['standalone', 'client'].includes(mode))) throw new Error('--mode 只能是 standalone 或 client');
|
||
if (flavors.some((flavor) => !['phone', 'tablet'].includes(flavor))) throw new Error('--flavor 只能是 phone 或 tablet');
|
||
if (!process.env.ANDROID_HOME && !process.env.ANDROID_SDK_ROOT) {
|
||
throw new Error('未设置 ANDROID_HOME,请安装 Android SDK(compileSdk 35)');
|
||
}
|
||
const project = path.join(PACKAGING, 'android');
|
||
const runtimeDir = path.join(DIST, 'android-runtime');
|
||
if (modes.includes('standalone')) {
|
||
requireBundle();
|
||
log('组装安卓单机版运行时');
|
||
await buildAndroidRuntime({
|
||
bundleDir: BUNDLE,
|
||
enginesDir: path.resolve(process.env.ANDROID_PRISMA_ENGINES_DIR || path.join(DIST, 'android-prisma-engines')),
|
||
outDir: runtimeDir,
|
||
workDir: path.join(WORK, 'android-runtime'),
|
||
version,
|
||
log,
|
||
});
|
||
}
|
||
|
||
const versionCode = androidVersionCode(version);
|
||
const capitalize = (s) => s[0].toUpperCase() + s.slice(1);
|
||
const variants = modes.flatMap((mode) => flavors.map((flavor) => ({ mode, flavor, name: `${mode}${capitalize(flavor)}` })));
|
||
log(`构建安卓 APK(${variants.map((v) => v.name).join('、')},v${version},versionCode ${versionCode})`);
|
||
run(process.env.GRADLE || 'gradle', [
|
||
'-p', project, '--no-daemon',
|
||
...variants.map((v) => `:app:assemble${capitalize(v.name)}Release`),
|
||
`-PappVersionName=${version}`,
|
||
`-PappVersionCode=${versionCode}`,
|
||
`-PstandaloneRuntimeDir=${runtimeDir}`,
|
||
]);
|
||
fs.mkdirSync(DIST, { recursive: true });
|
||
for (const { mode, flavor, name } of variants) {
|
||
const apk = path.join(project, 'app', 'build', 'outputs', 'apk', name, 'release', `app-${mode}-${flavor}-release.apk`);
|
||
if (!fs.existsSync(apk)) throw new Error(`未找到 ${path.relative(ROOT, apk)}`);
|
||
const prefix = mode === 'client' ? 'WrongNotebook-Android-Client' : 'WrongNotebook-Android';
|
||
const out = path.join(DIST, `${prefix}-${capitalize(flavor)}-${version}.apk`);
|
||
fs.copyFileSync(apk, out);
|
||
log(`安卓安装包已生成:${path.relative(ROOT, out)}`);
|
||
}
|
||
}
|
||
|
||
const commands = { bundle: buildBundle, npm: buildNpm, desktop: buildDesktop, fnos: buildFnos, synology: buildSynology, qnap: buildQnap, android: buildAndroid };
|
||
if (!commands[command]) {
|
||
console.error('用法:node scripts/package/build.mjs <bundle|npm|desktop|fnos|synology|qnap|android> [参数]');
|
||
process.exit(1);
|
||
}
|
||
try {
|
||
await commands[command]();
|
||
} catch (error) {
|
||
console.error(`\n[package] ${error.message}`);
|
||
process.exit(1);
|
||
}
|