RuneStone 1.0.0

This commit is contained in:
Knotty Wyvern
2026-11-16 04:21:21 -07:00
commit b52eeb14a1
827 changed files with 241421 additions and 0 deletions
+161
View File
@@ -0,0 +1,161 @@
// Builds the Windows installer. See docs/builds.md#build-the-windows-installer.
// Usage: node scripts/buildInstaller.mjs [--version <version>] [--dry-run]
import fs from 'node:fs/promises';
import path from 'node:path';
import { spawn } from 'node:child_process';
import { realpathSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { createHash } from 'node:crypto';
import { releaseVersion } from './releaseVersion.mjs';
const exists = file => fs.access(file).then(() => true, () => false);
export const versionFiles = ['package.json', 'src-tauri/tauri.conf.json', 'src-tauri/Cargo.toml', 'src-tauri/Cargo.lock'];
export function parseArguments(args) {
const options = { version: undefined, dryRun: false };
for (let i = 0; i < args.length; i++) {
if (args[i] === '--dry-run') options.dryRun = true;
else if (args[i] === '--version' && args[i + 1] && !options.version) options.version = args[++i];
else throw Error('Use --version followed by the release version, and optionally --dry-run.');
}
return options;
}
// Reads the version fields, checks the build preconditions, and returns the build plan. Changes no file.
export async function planInstallerBuild(root, requestedVersion) {
const files = versionFiles.map(file => path.join(root, file));
const before = await Promise.all(files.map(file => fs.readFile(file, 'utf8')));
const current = releaseVersion(JSON.parse(before[0]).version);
const next = releaseVersion(requestedVersion ?? current.version);
const config = JSON.parse(before[1]);
const cargoVersion = /^version = "([^"]+)"/m.exec(before[2])?.[1];
const lockedVersion = /name = "runestone"\r?\nversion = "([^"]+)"/.exec(before[3])?.[1];
if ([config.version, cargoVersion, lockedVersion].some(value => value !== current.toolchain)) throw Error('The release version fields do not match.');
const cargoRelease = /\[package\.metadata\.runestone\]\r?\nversion = "([^"]+)"/.exec(before[2])?.[1];
if (cargoRelease && cargoRelease !== current.version) throw Error('The Cargo release metadata does not match.');
if (config.bundle?.windows?.allowDowngrades === true) throw Error('Downgrade protection must remain enabled.');
const windowsConfig = JSON.parse(await fs.readFile(path.join(root, 'src-tauri/tauri.windows.conf.json'), 'utf8')).bundle?.windows;
if (windowsConfig?.allowDowngrades !== false) throw Error('Downgrade protection must remain enabled.');
const hooks = windowsConfig?.nsis?.installerHooks;
if (!hooks || !(await exists(path.join(root, 'src-tauri', hooks)))) throw Error('The installer hooks file is not configured. See src-tauri/tauri.windows.conf.json.');
// The browser engine is a separate download. See docs/builds.md#build-the-browser-engine.
if (JSON.stringify(config.bundle?.resources ?? {}).includes('browser-engine')) throw Error('The installer must not bundle the browser engine.');
const bundleDir = path.join(root, 'src-tauri/target/release/bundle/nsis');
const releaseDir = path.join(root, 'releases', next.version);
const artifacts = {
bundled: path.join(bundleDir, `RuneStone_${next.toolchain}_x64-setup.exe`),
renamed: path.join(bundleDir, `RuneStone_${next.version}_x64-setup.exe`),
release: path.join(releaseDir, `RuneStone_${next.version}_x64-setup.exe`),
metadata: path.join(releaseDir, 'host.json'),
};
for (const file of new Set(Object.values(artifacts))) if (await exists(file)) throw Error('The release file already exists: ' + file);
const packageJson = JSON.parse(before[0]);
packageJson.version = next.version;
config.version = next.toolchain;
let cargo = before[2].replace(/^version = "[^"]+"/m, `version = "${next.toolchain}"`);
if (cargoRelease) cargo = cargo.replace(/(\[package\.metadata\.runestone\]\r?\nversion = ")[^"]+"/, `$1${next.version}"`);
else cargo += `\n[package.metadata.runestone]\nversion = "${next.version}"\n`;
const lock = before[3].replace(/(name = "runestone"\r?\nversion = ")[^"]+"/, `$1${next.toolchain}"`);
const updated = [JSON.stringify(packageJson, null, 2) + '\n', JSON.stringify(config, null, 2) + '\n', cargo, lock];
// Tauri merges this override into tauri.conf.json for the build script, the app, and the bundler.
const override = { version: next.toolchain };
// vite.config.js gives this version to the front end, so package.json can wait until the build completes.
const env = { RUNESTONE_VERSION: next.version };
// The core installer is about 10 MB. A larger file means that something such as the engine got into the bundle.
const maxSetupBytes = 30 * 1024 * 1024;
return { root, files, before, updated, current, next, override, env, releaseDir, artifacts, maxSetupBytes };
}
// The commands of a build, in order. overridePath is the file with plan.override.
export function buildCommands(plan, overridePath) {
const cli = path.join(plan.root, 'node_modules/@tauri-apps/cli/tauri.js');
return [
{ step: 'compile', command: process.execPath, args: [cli, 'build', '--no-bundle', '--config', overridePath, '--', '--locked'] },
{ step: 'version-resource', command: 'powershell.exe', args: ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File',
path.join(plan.root, 'scripts/setWindowsVersion.ps1'), '-Path', path.join(plan.root, 'src-tauri/target/release/runestone.exe'),
'-Version', plan.next.version, '-NumericVersion', plan.next.windows] },
{ step: 'bundle', command: process.execPath, args: [cli, 'bundle', '--bundles', 'nsis', '--config', overridePath] },
];
}
export function describePlan(plan, overridePath = '<attempt folder>/tauri.version.json') {
const relative = file => path.relative(plan.root, file);
return [
`Release version: ${plan.next.version} (current ${plan.current.version})`,
`Toolchain version: ${plan.next.toolchain}. Windows version: ${plan.next.windows}.`,
`Configuration override: ${JSON.stringify(plan.override)}`,
`Environment: ${Object.entries(plan.env).map(([key, value]) => `${key}=${value}`).join(' ')}`,
...buildCommands(plan, overridePath).map((entry, index) => `${index + 1}. ${entry.step}: ${[entry.command, ...entry.args].join(' ')}`),
`4. Move the setup file to ${relative(plan.artifacts.release)} and write ${relative(plan.artifacts.metadata)}.`,
`5. Write the new version to ${versionFiles.join(', ')}.`,
].join('\n');
}
// Runs the build. run(command, args) must reject when a command fails.
// The tracked version files change only when the build completes.
export async function runInstallerBuild(plan, run, staging) {
const { files, before, updated, artifacts } = plan;
await fs.mkdir(staging, { recursive: true });
for (let i = 0; i < files.length; i++) await fs.writeFile(path.join(staging, path.basename(files[i]) + '.before'), before[i]);
const overridePath = path.join(staging, 'tauri.version.json');
await fs.writeFile(overridePath, JSON.stringify(plan.override, null, 2) + '\n');
let complete = false;
try {
for (const { command, args } of buildCommands(plan, overridePath)) await run(command, args);
const size = (await fs.stat(artifacts.bundled)).size;
if (size > plan.maxSetupBytes) throw Error(`The setup file has ${size} bytes, more than the limit of ${plan.maxSetupBytes}. Make sure that the bundle does not include the browser engine.`);
if (artifacts.bundled !== artifacts.renamed) await fs.rename(artifacts.bundled, artifacts.renamed);
await fs.mkdir(plan.releaseDir, { recursive: true });
await fs.copyFile(artifacts.renamed, artifacts.release, fs.constants.COPYFILE_EXCL);
const bytes = await fs.readFile(artifacts.release);
const metadata = { version: plan.next.version, toolchainVersion: plan.next.toolchain, windowsVersion: plan.next.windows,
file: path.basename(artifacts.release), bytes: bytes.length, sha256: createHash('sha256').update(bytes).digest('hex') };
await fs.writeFile(artifacts.metadata, JSON.stringify(metadata, null, 2) + '\n', { flag: 'wx' });
await fs.unlink(artifacts.renamed);
for (let i = 0; i < files.length; i++) await fs.writeFile(files[i], updated[i]);
complete = true;
return artifacts.release;
} finally {
if (!complete) {
for (let i = 0; i < files.length; i++) {
if ((await fs.readFile(files[i], 'utf8').catch(() => null)) !== before[i]) await fs.writeFile(files[i], before[i]);
}
for (const file of new Set(Object.values(artifacts))) {
if (await exists(file)) await fs.rename(file, path.join(staging, path.basename(file) + '.failed-' + Date.now()));
}
console.error('The build did not complete. The version fields are restored. Backups: ' + staging);
}
}
}
async function main() {
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const options = parseArguments(process.argv.slice(2));
const plan = await planInstallerBuild(root, options.version);
if (options.dryRun) {
console.log(describePlan(plan));
return;
}
if (process.platform !== 'win32') throw Error('Build the Windows installer on Windows.');
const env = { ...process.env, ...plan.env, GIT_CONFIG_COUNT: '1', GIT_CONFIG_KEY_0: 'safe.directory', GIT_CONFIG_VALUE_0: root.replaceAll('\\', '/') };
// Ctrl+C also stops the child build. Keep this process alive so that the cleanup runs.
let interrupted = false;
for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) process.on(signal, () => { interrupted = true; process.exitCode = 130; });
async function run(command, parameters) {
if (interrupted) throw Error('The build was interrupted.');
console.log(command + ' ' + parameters.join(' '));
const code = await new Promise((resolve, reject) => {
const child = spawn(command, parameters, { cwd: root, env, stdio: 'inherit', windowsHide: true });
child.on('error', reject); child.on('exit', resolve);
});
if (interrupted) throw Error('The build was interrupted.');
if (code !== 0) throw Error('The build command failed with exit code ' + code);
}
// Each attempt keeps its own backups, so a later attempt cannot replace them.
const staging = path.join(root, 'output/installer-build', plan.next.version, new Date().toISOString().replaceAll(':', '-'));
const installer = await runInstallerBuild(plan, run, staging);
console.log('Installer available: ' + installer);
}
if (process.argv[1] && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url))) await main();