Files
RuneStone/browser-runtime/scripts/stage-runtime.mjs
T

49 lines
2.2 KiB
JavaScript

import { cp, mkdir, access, mkdtemp, rename, rm, lstat, chmod } from 'node:fs/promises';
import { constants } from 'node:fs';
import { resolve, join } from 'node:path';
import { executableName } from './package-target.mjs';
// Copy into a new tree instead of merging Windows and Linux runtime files.
// Retain the previous tree in output/ so a failed switch can be recovered.
export async function stageRuntime({ project, host, platform, arch }) {
const source = resolve(project, `dist/RuneStone-Browser-${platform}-${arch}`);
const executable = join(source, executableName(platform));
const stat = await lstat(executable);
if (!stat.isFile()) throw new Error(`Browser executable is not a regular file: ${executable}`);
await access(executable, platform === 'win32' ? constants.R_OK : constants.R_OK | constants.X_OK);
const parent = resolve(host, 'src-tauri');
await mkdir(parent, { recursive: true });
const destination = join(parent, 'browser-engine');
const temporary = await mkdtemp(join(parent, '.browser-stage-'));
// Copy to a new child so cp preserves the source root mode, not mkdtemp's 0700.
const staged = join(temporary, 'browser-engine');
let backup;
let moved = false;
try {
await cp(source, staged, { recursive: true });
// Electron Packager can leave its temporary root at 0700. Installed resources
// must remain traversable after the package manager changes ownership to root.
if (platform === 'linux') await chmod(staged, 0o755);
await access(join(staged, executableName(platform)), platform === 'win32' ? constants.R_OK : constants.X_OK);
try {
await lstat(destination);
const backups = resolve(host, 'output/browser-stage-backups');
await mkdir(backups, { recursive: true });
backup = join(await mkdtemp(join(backups, 'previous-')), 'browser-engine');
await rename(destination, backup);
moved = true;
} catch (error) {
if (error.code !== 'ENOENT') throw error;
}
try {
await rename(staged, destination);
} catch (error) {
if (moved) await rename(backup, destination);
throw error;
}
return { destination, backup: moved ? backup : undefined };
} finally {
await rm(temporary, { recursive: true, force: true });
}
}