Use the stock Tauri NSIS template with RuneStone installer hooks
Remove the 996-line fork of the Tauri 2.11.4 template and the custom
comparator. src-tauri/windows/hooks.nsh now adds the RuneStone behavior
through bundle.windows.nsis.installerHooks:
- RuneStoneGuiInit (MUI_CUSTOMFUNCTION_GUIINIT) runs before the first
page in interactive and passive setup. It stops a downgrade with exit
code 2. It makes the stock maintenance page skip itself, so that setup
never starts the uninstaller for an upgrade or a reinstall.
- The hidden section RuneStoneVersionCheck runs before the Tauri sections
in all modes. Silent setup shows no pages, so it needs this check.
- NSIS_HOOK_POSTINSTALL writes the release version to DisplayVersion and
RuneStoneReleaseVersion, and the Windows version to
RuneStoneWindowsVersion. Installed apps now show 0.1.23a, not 0.1.23+1.
Setup compares the four-number Windows encoding with ${VersionCompare}.
An unknown installed version stops setup.
buildInstaller.mjs gives the toolchain version to Tauri through a
--config override. It writes tauri.conf.json, Cargo.toml, and Cargo.lock
only after the installer is complete. package.json changes during the
build because the Settings dialog imports its version. A failed build
restores it. Add --dry-run, which prints the plan and changes no file.
The tests compile NSIS programs with the real makensis. They simulate the
installed version in a test-only HKCU key and check /S, /P, /UPDATE, and
interactive setup. A drift check reads the template from the installed
Tauri CLI. The first real installer needs the installer checks in
docs/builds.md.
This commit is contained in:
+145
-86
@@ -1,100 +1,159 @@
|
||||
// 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 root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const exists = file => fs.access(file).then(() => true, () => false);
|
||||
const files = ['package.json', 'src-tauri/tauri.conf.json', 'src-tauri/Cargo.toml', 'src-tauri/Cargo.lock'].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 args = process.argv.slice(2);
|
||||
if (args.length && (args.length !== 2 || args[0] !== '--version')) throw Error('Use --version followed by the release version.');
|
||||
const next = releaseVersion(args[1] ?? 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 platformConfig = JSON.parse(await fs.readFile(path.join(root, 'src-tauri/tauri.windows.conf.json'), 'utf8'));
|
||||
if (platformConfig.bundle.windows.allowDowngrades !== false) throw Error('Downgrade protection must remain enabled.');
|
||||
if (process.platform !== 'win32') throw Error('Build the Windows installer on Windows.');
|
||||
if (!(await exists(path.join(root, 'src-tauri/browser-engine/RuneStone-Browser.exe')))) {
|
||||
throw Error('The browser runtime is not staged. Run pnpm browser:stage first. See docs/development.md#built-in-browser-runtime.');
|
||||
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;
|
||||
}
|
||||
const artifactDir = path.join(root, 'src-tauri/target/release/bundle/nsis');
|
||||
const artifact = path.join(artifactDir, `RuneStone_${next.version}_x64-setup.exe`);
|
||||
const internalArtifact = path.join(artifactDir, `RuneStone_${next.toolchain}_x64-setup.exe`);
|
||||
const releaseDir = path.join(root, 'releases', next.version);
|
||||
const releaseArtifact = path.join(releaseDir, path.basename(artifact));
|
||||
const metadataPath = path.join(releaseDir, 'host.json');
|
||||
for (const file of new Set([artifact, internalArtifact, releaseArtifact, metadataPath])) if (await exists(file)) throw Error('The release file already exists: ' + file);
|
||||
// Each attempt keeps its own backups, so a later attempt cannot replace them.
|
||||
const staging = path.join(root, 'output/installer-build', next.version, new Date().toISOString().replaceAll(':', '-'));
|
||||
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]);
|
||||
let template = await fs.readFile(path.join(root, 'src-tauri/windows/installer.nsi'), 'utf8');
|
||||
for (const [key, value] of Object.entries({ RUNESTONE_VERSION: next.version, RUNESTONE_WINDOWS_VERSION: next.windows,
|
||||
RUNESTONE_COMPARE: path.join(root, 'src-tauri/windows/versionCompare.nsh') })) {
|
||||
if (!template.includes(`@${key}@`)) throw Error('The installer template is missing ' + key);
|
||||
template = template.replaceAll(`@${key}@`, value);
|
||||
|
||||
// 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.');
|
||||
if (!(await exists(path.join(root, 'src-tauri/browser-engine/RuneStone-Browser.exe')))) {
|
||||
throw Error('The browser runtime is not staged. Run pnpm browser:stage first. See docs/development.md#built-in-browser-runtime.');
|
||||
}
|
||||
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 };
|
||||
return { root, files, before, updated, current, next, override, releaseDir, artifacts };
|
||||
}
|
||||
const templatePath = path.join(staging, 'installer.nsi');
|
||||
await fs.writeFile(templatePath, template);
|
||||
const override = path.join(staging, 'config.json');
|
||||
await fs.writeFile(override, JSON.stringify({ bundle: { windows: { allowDowngrades: false, nsis: { template: templatePath } } } }));
|
||||
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 (/\[package\.metadata\.runestone\]/.test(cargo)) {
|
||||
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];
|
||||
const env = { ...process.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 version files are restored.
|
||||
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);
|
||||
|
||||
// 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] },
|
||||
];
|
||||
}
|
||||
let complete = false;
|
||||
try {
|
||||
for (let i = 0; i < files.length; i++) await fs.writeFile(files[i], updated[i]);
|
||||
const cli = path.join(root, 'node_modules/@tauri-apps/cli/tauri.js');
|
||||
await run(process.execPath, [cli, 'build', '--no-bundle', '--', '--locked']);
|
||||
await run('powershell.exe', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', path.join(root, 'scripts/setWindowsVersion.ps1'),
|
||||
'-Path', path.join(root, 'src-tauri/target/release/runestone.exe'), '-Version', next.version, '-NumericVersion', next.windows]);
|
||||
await run(process.execPath, [cli, 'bundle', '--bundles', 'nsis', '--config', override]);
|
||||
await fs.access(internalArtifact);
|
||||
if (internalArtifact !== artifact) await fs.rename(internalArtifact, artifact);
|
||||
await fs.mkdir(releaseDir, { recursive: true });
|
||||
await fs.copyFile(artifact, releaseArtifact, 1);
|
||||
const bytes = await fs.readFile(releaseArtifact);
|
||||
const metadata = { version: next.version, toolchainVersion: next.toolchain, windowsVersion: next.windows,
|
||||
file: path.basename(releaseArtifact), bytes: bytes.length, sha256: createHash('sha256').update(bytes).digest('hex') };
|
||||
await fs.writeFile(metadataPath, JSON.stringify(metadata, null, 2) + '\n', { flag: 'wx' });
|
||||
await fs.unlink(artifact);
|
||||
complete = true;
|
||||
console.log('Installer available: ' + releaseArtifact);
|
||||
} finally {
|
||||
if (!complete) {
|
||||
for (let i = 0; i < files.length; i++) await fs.writeFile(files[i], before[i]);
|
||||
console.error('The build did not complete. The version fields are restored. Backups: ' + staging);
|
||||
for (const file of new Set([artifact, internalArtifact, releaseArtifact, metadataPath])) {
|
||||
if (await exists(file)) await fs.rename(file, path.join(staging, path.basename(file) + '.failed-' + Date.now()));
|
||||
|
||||
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)}`,
|
||||
`1. Write version ${plan.next.version} to package.json. The front-end build reads it. A failed build restores it.`,
|
||||
...buildCommands(plan, overridePath).map((entry, index) => `${index + 2}. ${entry.step}: ${[entry.command, ...entry.args].join(' ')}`),
|
||||
`5. Move the setup file to ${relative(plan.artifacts.release)} and write ${relative(plan.artifacts.metadata)}.`,
|
||||
`6. Write the new version to ${versionFiles.slice(1).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, except package.json during the build.
|
||||
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 {
|
||||
// src/lib/layout/SettingsDialog.svelte imports the version from package.json.
|
||||
await fs.writeFile(files[0], updated[0]);
|
||||
for (const { command, args } of buildCommands(plan, overridePath)) await run(command, args);
|
||||
await fs.access(artifacts.bundled);
|
||||
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 = 1; 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, 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 package.json is restored.
|
||||
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();
|
||||
|
||||
Reference in New Issue
Block a user