Files
WT-Offline/scripts/build-windows-installer.ts
T

170 lines
8.1 KiB
TypeScript

import { execFileSync } from 'node:child_process';
import { cp, lstat, mkdir, mkdtemp, readFile, realpath, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { dirname, join, relative, resolve, sep } from 'node:path';
import { Arch, build, Platform } from 'electron-builder';
import { launcherReleaseFiles } from '../apps/launcher/src/shared/schemas/app-update.ts';
import { formatManifest, MANIFEST_FILE, PATCH_PACK_FORMAT, recordedGameVersions } from '../packages/patcher/src/index.ts';
const repository = resolve(import.meta.dirname, '..');
const launcher = join(repository, 'apps', 'launcher');
const modules = join(repository, 'node_modules');
const buildFolder = join(repository, 'build');
const output = join(buildFolder, 'windows-installer');
const workspacePackages = ['apps/server', 'packages/blk', 'packages/exepatch', 'packages/jsonc', 'packages/patcher', 'packages/vromfs'];
interface LauncherManifest {
readonly productName: string;
readonly version: string;
readonly description: string;
readonly main: string;
readonly type: string;
}
interface WorkspaceManifest {
readonly name: string;
readonly exports: { readonly '.': string };
}
async function stageWorkspacePackage(folder: string, resources: string, runtimeModules: string): Promise<void> {
const source = join(repository, folder);
const target = join(resources, 'runtime', folder);
const metadata = JSON.parse(await readFile(join(source, 'package.json'), 'utf8')) as WorkspaceManifest;
await mkdir(target, { recursive: true });
await cp(join(source, 'package.json'), join(target, 'package.json'));
await cp(join(source, 'src'), join(target, 'src'), { recursive: true });
if (metadata.name === '@wto/server' || metadata.name === '@wto/patcher') {
await cp(join(source, 'tuning'), join(target, 'tuning'), { recursive: true });
}
if (metadata.name === '@wto/patcher') {
await mkdir(join(target, 'keys'), { recursive: true });
await cp(join(source, 'keys', 'patch-pack-signing.pub.pem'), join(target, 'keys', 'patch-pack-signing.pub.pem'));
}
// Node resolves the package through a JavaScript entry and loads its TypeScript outside node_modules.
const bridge = join(runtimeModules, metadata.name);
await mkdir(bridge, { recursive: true });
const packagedBridge = join(resources, 'node_modules', metadata.name);
const entry = relative(packagedBridge, join(target, metadata.exports['.'])).split(sep).join('/');
await writeFile(join(bridge, 'package.json'), JSON.stringify({ name: metadata.name, type: 'module', exports: './index.js' }));
await writeFile(join(bridge, 'index.js'), 'export * from ' + JSON.stringify(entry) + ';\n');
}
async function stageInstaller(stage: string, manifest: LauncherManifest): Promise<void> {
const { productName, version, description, main, type } = manifest;
const native = join(stage, 'built-native');
execFileSync('powershell.exe', [
'-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass',
'-File', join(repository, 'native', 'wto-net', 'build.ps1'), '-Out', native,
], { cwd: repository, stdio: 'inherit', windowsHide: true });
await writeFile(join(stage, 'package.json'), JSON.stringify({
name: 'wtoffline-launcher', productName, version, description, main, type, license: 'AGPL-3.0-or-later',
}));
await cp(join(launcher, 'out'), join(stage, 'out'), { recursive: true });
const resources = join(stage, 'installer-resources');
await mkdir(join(resources, 'native'), { recursive: true });
await mkdir(join(stage, 'build'), { recursive: true });
await cp(join(launcher, 'resources', 'icon.ico'), join(stage, 'build', 'icon.ico'));
await cp(join(launcher, 'resources', 'icon.ico'), join(resources, 'icon.ico'));
await cp(join(launcher, 'resources', 'icon.png'), join(resources, 'icon.png'));
await cp(join(repository, 'LICENSE'), join(resources, 'LICENSE-WTOffline'));
await cp(join(native, 'wto_ws.dll'), join(resources, 'native', 'wto_ws.dll'));
for (const folder of ['exe', 'gui', 'native', 'versions']) {
await cp(join(repository, 'patches', folder), join(resources, 'patches', folder), { recursive: true });
}
const now = new Date();
const bundledPackVersion = `${now.getUTCFullYear()}.${String(now.getUTCMonth() + 1).padStart(2, '0')}.${String(now.getUTCDate()).padStart(2, '0')}`;
await writeFile(join(resources, 'patches', MANIFEST_FILE), formatManifest({
format: PATCH_PACK_FORMAT,
version: bundledPackVersion,
minAppVersion: version,
gameVersions: recordedGameVersions(join(resources, 'patches')),
createdAt: now.toISOString(),
}), 'utf8');
const runtimeModules = join(stage, 'installer-modules');
for (const folder of workspacePackages) await stageWorkspacePackage(folder, resources, runtimeModules);
for (const name of ['fflate', 'zod']) {
await cp(join(modules, name), join(runtimeModules, name), { recursive: true });
}
}
async function cleanInstallerOutput(version: string): Promise<void> {
await mkdir(buildFolder, { recursive: true });
if (relative(buildFolder, await realpath(buildFolder)) !== '') throw new Error('The build directory is redirected.');
await mkdir(output, { recursive: true });
const root = await realpath(output);
if (relative(output, root) !== '') throw new Error('The installer output directory is redirected.');
const { installer, manifest, signature } = launcherReleaseFiles(version);
const legacy = `WTOffline Launcher Setup ${version}.exe`;
const names = [installer, installer + '.blockmap', legacy, legacy + '.blockmap', manifest, signature, 'win-unpacked'];
const artifacts = [];
for (const name of names) {
const path = join(root, name);
const entry = await lstat(path).catch((error: NodeJS.ErrnoException) => {
if (error.code === 'ENOENT') return null;
throw error;
});
if (!entry) continue;
const directory = name === 'win-unpacked';
if (relative(path, await realpath(path)) !== '' || !(directory ? entry.isDirectory() : entry.isFile())) {
throw new Error(`Unexpected installer output: ${path}`);
}
artifacts.push({ path, directory });
}
for (const { path, directory } of artifacts) await rm(path, { recursive: directory, force: true });
}
async function main(): Promise<void> {
if (process.platform !== 'win32' || process.arch !== 'x64') throw new Error('The installer build requires Windows x64.');
const temp = await realpath(tmpdir());
const stage = await mkdtemp(join(temp, 'wto-installer-'));
try {
const electron = join(modules, 'electron');
const { version: electronVersion } = JSON.parse(await readFile(join(electron, 'package.json'), 'utf8')) as { version: string };
const manifest = JSON.parse(await readFile(join(launcher, 'package.json'), 'utf8')) as LauncherManifest;
const artifactName = launcherReleaseFiles(manifest.version).installer;
await stageInstaller(stage, manifest);
await cleanInstallerOutput(manifest.version);
const artifacts = await build({
projectDir: stage,
targets: Platform.WINDOWS.createTarget('nsis', Arch.x64),
publish: 'never',
config: {
appId: 'com.wtoffline.launcher',
directories: { output },
electronVersion,
electronDist: join(electron, 'dist'),
asar: false,
npmRebuild: false,
files: ['package.json', 'out/**/*'],
extraResources: [
{ from: 'installer-resources', to: '.', filter: ['**/*'] },
{ from: 'installer-modules', to: 'node_modules', filter: ['**/*'] },
],
win: {
icon: join(stage, 'build', 'icon.ico'),
artifactName,
signExecutable: false,
},
nsis: {
oneClick: false,
perMachine: false,
allowToChangeInstallationDirectory: true,
runAfterFinish: false,
installerIcon: join(stage, 'build', 'icon.ico'),
uninstallerIcon: join(stage, 'build', 'icon.ico'),
installerHeaderIcon: join(stage, 'build', 'icon.ico'),
},
},
});
for (const artifact of artifacts) console.info(artifact);
} finally {
const actual = await realpath(stage);
if (actual === stage && dirname(actual) === temp) await rm(stage, { recursive: true, force: true });
}
}
await main();