RuneStone 1.0.0
This commit is contained in:
@@ -0,0 +1,193 @@
|
||||
// Builds the browser engine ZIP and pins it in the host. See docs/builds.md#build-the-browser-engine.
|
||||
// Usage: node scripts/buildBrowserEngine.mjs --release-url <folder URL> [--version <version>] [--dry-run]
|
||||
import fs from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import zlib from 'node:zlib';
|
||||
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 engineFiles = ['browser-runtime/package.json', 'browser-runtime/package-lock.json', 'src-tauri/browser-engine.json'];
|
||||
|
||||
export function parseArguments(args) {
|
||||
const options = { version: undefined, releaseUrl: 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 if (args[i] === '--release-url' && args[i + 1] && !options.releaseUrl) options.releaseUrl = args[++i];
|
||||
else throw Error('Use --release-url followed by the release folder URL, optionally --version followed by the engine version, and optionally --dry-run.');
|
||||
}
|
||||
if (!options.releaseUrl) throw Error('Use --release-url followed by the URL of the folder that will hold the engine ZIP.');
|
||||
return options;
|
||||
}
|
||||
|
||||
/** The platform key of the host manifest, as `browser_engine::platform()` in Rust writes it. */
|
||||
export function platformKey(platform, arch) {
|
||||
const system = { win32: 'windows', linux: 'linux', darwin: 'macos' }[platform];
|
||||
const processor = { x64: 'x86_64', arm64: 'aarch64' }[arch];
|
||||
if (!system || !processor) throw Error(`Unsupported engine platform: ${platform}-${arch}`);
|
||||
return `${system}-${processor}`;
|
||||
}
|
||||
|
||||
// Reads the version fields, checks the preconditions, and returns the build plan. Changes no file.
|
||||
/** @param {string} root @param {{ version?: string, releaseUrl: string }} options @param {{ platform: string, arch: string }} [target] */
|
||||
export async function planEngineBuild(root, { version, releaseUrl }, target = process) {
|
||||
const files = engineFiles.map(file => path.join(root, file));
|
||||
const before = await Promise.all(files.map(file => fs.readFile(file, 'utf8')));
|
||||
const [packageJson, lock, manifest] = before.map(text => JSON.parse(text));
|
||||
const current = releaseVersion(packageJson.version).version;
|
||||
const next = releaseVersion(version ?? current).version;
|
||||
if (lock.version !== current || lock.packages?.['']?.version !== current) throw Error('The engine version fields do not match.');
|
||||
const protocol = Number(/pub const PROTOCOL: u64 = (\d+);/.exec(await fs.readFile(path.join(root, 'src-tauri/src/browser_engine.rs'), 'utf8'))?.[1]);
|
||||
const sent = Number(/event: 'ready', protocol: (\d+)/.exec(await fs.readFile(path.join(root, 'browser-runtime/src/engine-main.mjs'), 'utf8'))?.[1]);
|
||||
if (!protocol || protocol !== sent) throw Error('The engine protocol in browser_engine.rs and engine-main.mjs differs.');
|
||||
const folder = new URL(releaseUrl.endsWith('/') ? releaseUrl : releaseUrl + '/');
|
||||
if (folder.protocol !== 'https:' || folder.username || folder.password || folder.search || folder.hash) {
|
||||
throw Error('Use an HTTPS release URL without credentials, a query, or a fragment.');
|
||||
}
|
||||
const { platform, arch } = target;
|
||||
const file = `RuneStone-Browser_${next}_${platform}-${arch}.zip`;
|
||||
const releaseDir = path.join(root, 'releases', 'browser-engine', next);
|
||||
const artifacts = { archive: path.join(releaseDir, file), metadata: path.join(releaseDir, 'engine.json') };
|
||||
for (const artifact of Object.values(artifacts)) if (await exists(artifact)) throw Error('The release file already exists: ' + artifact);
|
||||
const dist = path.join(root, 'browser-runtime', 'dist', `RuneStone-Browser-${platform}-${arch}`);
|
||||
return { root, files, before, current, next, protocol, platform, arch, key: platformKey(platform, arch), file,
|
||||
url: new URL(file, folder).href, dist, releaseDir, artifacts };
|
||||
}
|
||||
|
||||
export function buildCommands(plan) {
|
||||
// The same script as `npm --prefix browser-runtime run package`, without a shell.
|
||||
return [{ step: 'package', command: process.execPath,
|
||||
args: [path.join(plan.root, 'browser-runtime/scripts/package.mjs'), `--platform=${plan.platform}`, `--arch=${plan.arch}`] }];
|
||||
}
|
||||
|
||||
export function describePlan(plan) {
|
||||
const relative = file => path.relative(plan.root, file);
|
||||
return [
|
||||
`Engine version: ${plan.next} (current ${plan.current}). Protocol: ${plan.protocol}. Platform: ${plan.key}.`,
|
||||
`1. Write ${plan.next} to ${engineFiles.slice(0, 2).join(' and ')}.`,
|
||||
...buildCommands(plan).map((entry, index) => `${index + 2}. ${entry.step}: ${[entry.command, ...entry.args].join(' ')}`),
|
||||
`3. Write ${relative(plan.artifacts.archive)} from ${relative(plan.dist)}, and ${relative(plan.artifacts.metadata)}.`,
|
||||
`4. Pin ${plan.url} in ${engineFiles[2]}.`,
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
async function listFiles(folder, prefix = '') {
|
||||
const result = [];
|
||||
const entries = (await fs.readdir(path.join(folder, prefix), { withFileTypes: true })).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
|
||||
for (const entry of entries) {
|
||||
const name = prefix ? `${prefix}/${entry.name}` : entry.name;
|
||||
if (entry.isDirectory()) result.push(...await listFiles(folder, name));
|
||||
else if (entry.isFile()) result.push(name);
|
||||
else throw Error(`The engine folder contains a link or a special file: ${name}`);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** A ZIP of the files in `folder`, at the archive root, in name order, with a fixed time. The same files give the same bytes. */
|
||||
export async function zipFolder(folder) {
|
||||
const chunks = [], central = [];
|
||||
let offset = 0;
|
||||
const names = await listFiles(folder);
|
||||
if (names.length > 65535) throw Error('The engine has too many files for a ZIP without ZIP64.');
|
||||
for (const name of names) {
|
||||
const full = path.join(folder, ...name.split('/'));
|
||||
const [data, stat] = await Promise.all([fs.readFile(full), fs.stat(full)]);
|
||||
const deflated = zlib.deflateRawSync(data, { level: 9 });
|
||||
const stored = deflated.length >= data.length;
|
||||
const body = stored ? data : deflated;
|
||||
const crc = zlib.crc32(data);
|
||||
const nameBytes = Buffer.from(name, 'utf8');
|
||||
if (data.length >= 0xffffffff || offset + 30 + nameBytes.length + body.length >= 0xffffffff) throw Error('The engine is too large for a ZIP without ZIP64.');
|
||||
// Version 2.0, UTF-8 names, no data descriptor, and the DOS date 1980-01-01 00:00.
|
||||
const local = Buffer.alloc(30);
|
||||
local.writeUInt32LE(0x04034b50, 0); local.writeUInt16LE(20, 4); local.writeUInt16LE(0x0800, 6); local.writeUInt16LE(stored ? 0 : 8, 8);
|
||||
local.writeUInt16LE(0, 10); local.writeUInt16LE(0x21, 12); local.writeUInt32LE(crc, 14); local.writeUInt32LE(body.length, 18);
|
||||
local.writeUInt32LE(data.length, 22); local.writeUInt16LE(nameBytes.length, 26); local.writeUInt16LE(0, 28);
|
||||
const mode = 0o100000 | (process.platform === 'win32' ? 0o644 : stat.mode & 0o755);
|
||||
const entry = Buffer.alloc(46);
|
||||
entry.writeUInt32LE(0x02014b50, 0); entry.writeUInt16LE((3 << 8) | 20, 4); entry.writeUInt16LE(20, 6); entry.writeUInt16LE(0x0800, 8);
|
||||
entry.writeUInt16LE(stored ? 0 : 8, 10); entry.writeUInt16LE(0, 12); entry.writeUInt16LE(0x21, 14); entry.writeUInt32LE(crc, 16);
|
||||
entry.writeUInt32LE(body.length, 20); entry.writeUInt32LE(data.length, 24); entry.writeUInt16LE(nameBytes.length, 28);
|
||||
entry.writeUInt32LE(mode * 0x10000, 38); entry.writeUInt32LE(offset, 42);
|
||||
chunks.push(local, nameBytes, body);
|
||||
central.push(entry, nameBytes);
|
||||
offset += local.length + nameBytes.length + body.length;
|
||||
}
|
||||
const directory = Buffer.concat(central);
|
||||
const end = Buffer.alloc(22);
|
||||
end.writeUInt32LE(0x06054b50, 0); end.writeUInt16LE(names.length, 8); end.writeUInt16LE(names.length, 10);
|
||||
end.writeUInt32LE(directory.length, 12); end.writeUInt32LE(offset, 16);
|
||||
return Buffer.concat([...chunks, directory, end]);
|
||||
}
|
||||
|
||||
// Runs the build. run(command, args) must reject when a command fails.
|
||||
// On failure, the version fields and the pin get their previous contents back.
|
||||
export async function runEngineBuild(plan, run, staging) {
|
||||
const { files, before, 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]);
|
||||
let complete = false;
|
||||
try {
|
||||
// Electron reports this version with app.getVersion(), so it goes into the package first.
|
||||
const packageJson = JSON.parse(before[0]);
|
||||
packageJson.version = plan.next;
|
||||
const lock = JSON.parse(before[1]);
|
||||
lock.version = plan.next; lock.packages[''].version = plan.next;
|
||||
await fs.writeFile(files[0], JSON.stringify(packageJson, null, 2) + '\n');
|
||||
await fs.writeFile(files[1], JSON.stringify(lock, null, 2) + '\n');
|
||||
for (const { command, args } of buildCommands(plan)) await run(command, args);
|
||||
const executable = plan.platform === 'win32' ? 'RuneStone-Browser.exe' : 'RuneStone-Browser';
|
||||
if (!(await exists(path.join(plan.dist, executable)))) throw Error('The packaged engine has no engine program: ' + plan.dist);
|
||||
const archive = await zipFolder(plan.dist);
|
||||
await fs.mkdir(plan.releaseDir, { recursive: true });
|
||||
await fs.writeFile(artifacts.archive, archive, { flag: 'wx' });
|
||||
const sha256 = createHash('sha256').update(archive).digest('hex');
|
||||
const metadata = { version: plan.next, protocol: plan.protocol, platform: plan.key, file: plan.file, url: plan.url, bytes: archive.length, sha256 };
|
||||
await fs.writeFile(artifacts.metadata, JSON.stringify(metadata, null, 2) + '\n', { flag: 'wx' });
|
||||
const previous = JSON.parse(before[2]);
|
||||
// The packages of other platforms stay only when they have the same engine version.
|
||||
const platforms = previous.version === plan.next ? { ...previous.platforms } : {};
|
||||
platforms[plan.key] = { url: plan.url, bytes: archive.length, sha256 };
|
||||
await fs.writeFile(files[2], JSON.stringify({ version: plan.next, protocol: plan.protocol, platforms }, null, 2) + '\n');
|
||||
complete = true;
|
||||
return { archive: artifacts.archive, ...metadata };
|
||||
} 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 Object.values(artifacts)) {
|
||||
if (await exists(file)) await fs.rename(file, path.join(staging, path.basename(file) + '.failed-' + Date.now()));
|
||||
}
|
||||
console.error('The engine build did not complete. The version fields and the pin 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 planEngineBuild(root, options);
|
||||
if (options.dryRun) {
|
||||
console.log(describePlan(plan));
|
||||
return;
|
||||
}
|
||||
if (process.platform !== 'win32') throw Error('Build the browser engine on Windows. The other platforms have no published engine yet.');
|
||||
async function run(command, parameters) {
|
||||
console.log(command + ' ' + parameters.join(' '));
|
||||
const code = await new Promise((resolve, reject) => {
|
||||
const child = spawn(command, parameters, { cwd: root, stdio: 'inherit', windowsHide: true });
|
||||
child.on('error', reject); child.on('exit', resolve);
|
||||
});
|
||||
if (code !== 0) throw Error('The engine build command failed with exit code ' + code);
|
||||
}
|
||||
const staging = path.join(root, 'output/browser-engine-build', plan.next, new Date().toISOString().replaceAll(':', '-'));
|
||||
const result = await runEngineBuild(plan, run, staging);
|
||||
console.log(`Engine available: ${result.archive}\n${result.bytes} bytes, SHA-256 ${result.sha256}\nUpload it to ${result.url}`);
|
||||
}
|
||||
|
||||
if (process.argv[1] && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url))) await main();
|
||||
@@ -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();
|
||||
@@ -0,0 +1,43 @@
|
||||
// Builds the plugin SDK package into packages/plugin-sdk/dist. See docs/development.md#plugin-sdk.
|
||||
// Usage: node scripts/buildSdk.mjs
|
||||
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';
|
||||
|
||||
export const sdkFolder = 'packages/plugin-sdk';
|
||||
|
||||
// Runs a command and rejects when it fails.
|
||||
export function runCommand(command, args, options = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const child = spawn(command, args, { stdio: 'inherit', windowsHide: true, ...options });
|
||||
child.on('error', reject);
|
||||
child.on('exit', code => code === 0 ? resolve() : reject(Error(`${path.basename(command)} ${args.join(' ')} failed with exit code ${code}.`)));
|
||||
});
|
||||
}
|
||||
|
||||
// The declaration files keep the `.ts` import paths of the source. Older TypeScript versions need `.js` paths.
|
||||
export function declarationImports(text) {
|
||||
return text.replace(/(\bfrom\s+["'])(\.{1,2}\/[^"']+)\.ts(["'])/g, '$1$2.js$3').replace(/(\bimport\(\s*["'])(\.{1,2}\/[^"']+)\.ts(["']\s*\))/g, '$1$2.js$3');
|
||||
}
|
||||
|
||||
// Removes dist/, compiles the package with the TypeScript compiler of this repository, and returns the dist/ path.
|
||||
export async function buildSdk(root, run = runCommand) {
|
||||
const folder = path.join(root, sdkFolder);
|
||||
const dist = path.join(folder, 'dist');
|
||||
await fs.rm(dist, { recursive: true, force: true });
|
||||
await run(process.execPath, [path.join(root, 'node_modules/typescript/bin/tsc'), '-p', path.join(folder, 'tsconfig.json')], { cwd: root });
|
||||
for (const name of await fs.readdir(dist)) {
|
||||
if (!name.endsWith('.d.ts')) continue;
|
||||
const file = path.join(dist, name);
|
||||
await fs.writeFile(file, declarationImports(await fs.readFile(file, 'utf8')));
|
||||
}
|
||||
await fs.access(path.join(dist, 'index.js'));
|
||||
return dist;
|
||||
}
|
||||
|
||||
if (process.argv[1] && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url))) {
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
console.log('SDK build: ' + await buildSdk(root));
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
// Check the build output for the native features (src/lib/features/).
|
||||
// Each feature module must load only through its dynamic import in `src/lib/features/loader.ts`.
|
||||
// The check fails when a feature folder, or a library that only a feature needs, is in an entry chunk
|
||||
// or in a chunk that an entry chunk imports statically. It also reports the size of each feature chunk.
|
||||
//
|
||||
// Usage: node scripts/featureChunks.mjs (also `pnpm check:features`)
|
||||
// It runs a full build with Vite, so it takes about a minute.
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
/** The feature folders. The runtime files directly in `src/lib/features/` stay in the main bundle. */
|
||||
export const FEATURE_FOLDERS = ["git", "background", "terminal", "pdf", "pm"];
|
||||
/** Libraries that only features need. */
|
||||
export const FEATURE_LIBRARIES = ["@xterm", "pdfjs-dist", "yaml"];
|
||||
|
||||
const normal = id => id.replaceAll("\\", "/");
|
||||
|
||||
/** The chunk names that the entry chunks load, directly or through static imports. */
|
||||
export function staticClosure(chunks) {
|
||||
const byName = new Map(chunks.map(chunk => [chunk.fileName, chunk]));
|
||||
const seen = new Set();
|
||||
const queue = chunks.filter(chunk => chunk.isEntry).map(chunk => chunk.fileName);
|
||||
while (queue.length) {
|
||||
const name = queue.pop();
|
||||
if (seen.has(name)) continue;
|
||||
seen.add(name);
|
||||
for (const next of byName.get(name)?.imports ?? []) queue.push(next);
|
||||
}
|
||||
return seen;
|
||||
}
|
||||
|
||||
/** True when a module belongs to a feature folder or to a feature library. */
|
||||
export function featureModule(id, folders = FEATURE_FOLDERS, libraries = FEATURE_LIBRARIES) {
|
||||
const path = normal(id);
|
||||
return folders.some(folder => path.includes(`/src/lib/features/${folder}/`))
|
||||
|| libraries.some(library => path.includes(`/node_modules/${library}/`) || path.includes(`/node_modules/.pnpm/${library.replace("/", "+")}`));
|
||||
}
|
||||
|
||||
/**
|
||||
* Check the chunks of one client build. `chunks` has the Rollup fields `fileName`, `isEntry`, `isDynamicEntry`,
|
||||
* `facadeModuleId`, `imports`, `moduleIds`, and `size`. Returns the problems and the size of each feature chunk.
|
||||
*/
|
||||
export function checkChunks(chunks, folders = FEATURE_FOLDERS) {
|
||||
const problems = [];
|
||||
const closure = staticClosure(chunks);
|
||||
for (const chunk of chunks) {
|
||||
if (!closure.has(chunk.fileName)) continue;
|
||||
for (const id of chunk.moduleIds ?? []) {
|
||||
if (featureModule(id, folders)) problems.push(`${chunk.fileName} loads at start and contains ${normal(id).replace(/^.*?\/(src|node_modules)\//, "$1/")}`);
|
||||
}
|
||||
}
|
||||
const sizes = {};
|
||||
for (const folder of folders) {
|
||||
const entry = chunks.find(chunk => chunk.facadeModuleId && normal(chunk.facadeModuleId).endsWith(`/src/lib/features/${folder}/index.ts`));
|
||||
if (!entry) { problems.push(`No chunk starts at src/lib/features/${folder}/index.ts.`); continue; }
|
||||
if (!entry.isDynamicEntry || entry.isEntry) problems.push(`src/lib/features/${folder}/index.ts must be a dynamic entry only.`);
|
||||
sizes[folder] = entry.size;
|
||||
}
|
||||
return { problems, sizes };
|
||||
}
|
||||
|
||||
async function main() {
|
||||
// The client build of SvelteKit runs as a nested Vite build, so the report comes from a plugin in vite.config.js.
|
||||
const report = path.join(mkdtempSync(path.join(tmpdir(), "runestone-chunks-")), "chunks.json");
|
||||
const vite = fileURLToPath(new URL("../node_modules/vite/bin/vite.js", import.meta.url));
|
||||
execFileSync(process.execPath, [vite, "build", "--logLevel", "warn"], { stdio: ["ignore", "ignore", "inherit"], env: { ...process.env, RUNESTONE_FEATURE_CHUNKS: report } });
|
||||
const chunks = JSON.parse(readFileSync(report, "utf8"));
|
||||
rmSync(path.dirname(report), { recursive: true, force: true });
|
||||
const { problems, sizes } = checkChunks(chunks);
|
||||
for (const [folder, size] of Object.entries(sizes)) console.log(`${folder}: ${(size / 1024).toFixed(1)} KiB in its own chunk`);
|
||||
if (problems.length) {
|
||||
for (const problem of problems) console.error(`FAIL: ${problem}`);
|
||||
process.exitCode = 1;
|
||||
} else console.log(`PASS: ${FEATURE_FOLDERS.length} feature module(s) load only at first need.`);
|
||||
}
|
||||
|
||||
if (process.argv[1] === fileURLToPath(import.meta.url)) await main();
|
||||
@@ -0,0 +1,76 @@
|
||||
// Check the translation catalog (src/lib/i18n/messages.ts) against the code:
|
||||
// - unknown: the code translates a key that the catalog does not have,
|
||||
// - unused: the catalog has a key that the code never translates,
|
||||
// - untranslated: a catalog row has an empty or missing translation.
|
||||
// The code translates a key with `$t("…")` in Svelte, `tr("…")` in TypeScript, or marks it with `message("…")`
|
||||
// when a variable carries it to the translation call later. Every string literal in the first argument counts,
|
||||
// so `tr(open ? "Close" : "Open")` uses both keys.
|
||||
import { readdir, readFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath, pathToFileURL } from "node:url";
|
||||
|
||||
const root = fileURLToPath(new URL("../", import.meta.url));
|
||||
const catalogFile = path.join(root, "src/lib/i18n/messages.ts");
|
||||
const calls = /(?:\$t|\btr|\bmessage)\(/g;
|
||||
|
||||
async function sources(dir) {
|
||||
const entries = await readdir(dir, { withFileTypes: true });
|
||||
const nested = await Promise.all(entries.map(entry => entry.isDirectory()
|
||||
? sources(path.join(dir, entry.name))
|
||||
: /\.(svelte|ts)$/.test(entry.name) ? [path.join(dir, entry.name)] : []));
|
||||
return nested.flat();
|
||||
}
|
||||
|
||||
/** The string literals of the first argument that starts at `start`. A literal in a comparison is not a key. */
|
||||
function argumentKeys(source, start) {
|
||||
const keys = [];
|
||||
let depth = 0;
|
||||
for (let index = start; index < source.length; index++) {
|
||||
const char = source[index];
|
||||
if (char === "\"" || char === "'" || char === "`") {
|
||||
let value = "", end = index + 1, dynamic = false;
|
||||
for (; end < source.length && source[end] !== char; end++) {
|
||||
if (source[end] === "\\") { value += source[++end]; continue; }
|
||||
if (char === "`" && source[end] === "$" && source[end + 1] === "{") dynamic = true;
|
||||
value += source[end];
|
||||
}
|
||||
const compared = /[=!]==?\s*$/.test(source.slice(start, index)) || /^\s*[=!]==?/.test(source.slice(end + 1));
|
||||
if (!dynamic && !compared) keys.push(value);
|
||||
index = end;
|
||||
} else if ("([{".includes(char)) depth++;
|
||||
else if (")]}".includes(char)) { if (depth === 0) break; depth--; }
|
||||
else if (char === "," && depth === 0) break;
|
||||
}
|
||||
return keys;
|
||||
}
|
||||
|
||||
export async function auditCatalog() {
|
||||
const { messageRows } = await import(pathToFileURL(catalogFile).href);
|
||||
const catalog = new Map(messageRows.map(row => [row[0], row]));
|
||||
const used = new Set();
|
||||
const failures = [];
|
||||
for (const file of await sources(path.join(root, "src"))) {
|
||||
if (file === catalogFile) continue;
|
||||
const source = await readFile(file, "utf8");
|
||||
for (const match of source.matchAll(calls)) {
|
||||
for (const key of argumentKeys(source, match.index + match[0].length)) {
|
||||
used.add(key);
|
||||
if (!catalog.has(key)) {
|
||||
const line = source.slice(0, match.index).split("\n").length;
|
||||
failures.push(`Unknown key: ${path.relative(root, file).replaceAll("\\", "/")}:${line}: ${key}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const [key, row] of catalog) {
|
||||
if (!used.has(key)) failures.push(`Unused key: ${key}`);
|
||||
if (row.length < 4 || row.slice(1).some(value => !value?.trim())) failures.push(`Untranslated key: ${key}`);
|
||||
}
|
||||
return { failures, keys: catalog.size, used: used.size };
|
||||
}
|
||||
|
||||
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||
const { failures, keys } = await auditCatalog();
|
||||
if (failures.length) { console.error(failures.join("\n")); process.exitCode = 1; }
|
||||
else console.log(`PASS: the code uses all ${keys} catalog keys, and each key has every translation.`);
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
// Start the test build, attach to its WebView2 through CDP, read the metrics, and stop only the started process tree.
|
||||
import { spawn } from "node:child_process";
|
||||
import { existsSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { setTimeout as sleep } from "node:timers/promises";
|
||||
import { playwright } from "../../tests/smoke/_harness/index.mjs";
|
||||
import { processTree } from "./core.mjs";
|
||||
import { listProcesses, stopTree } from "./processes.mjs";
|
||||
import { TABLE } from "./scenarios.mjs";
|
||||
|
||||
const isMainPage = page => { try { const url = new URL(page.url()); return url.pathname === "/" && !url.search && url.protocol.startsWith("http"); } catch { return false; } };
|
||||
|
||||
async function cdpResponds(port) {
|
||||
try {
|
||||
const response = await fetch(`http://127.0.0.1:${port}/json/version`, { signal: AbortSignal.timeout(1000) });
|
||||
return response.ok;
|
||||
} catch { return false; }
|
||||
}
|
||||
|
||||
/** Call a Rust command from the page. */
|
||||
export function invoke(page, command, args = {}) {
|
||||
return page.evaluate(([command, args]) => window.__TAURI_INTERNALS__.invoke(command, args), [command, args]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Start `exe` with remote debugging on `port` and attach to its main page.
|
||||
* Refuse when another program already answers on the port, because the tool must not drive a foreign browser.
|
||||
*/
|
||||
export async function launch({ exe, port, timeout = 90000 }) {
|
||||
if (await cdpResponds(port)) throw new Error(`Port ${port} already answers CDP requests. Stop that program or choose another --port.`);
|
||||
const env = { ...process.env, WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS: `--remote-debugging-port=${port}`, NO_PROXY: "127.0.0.1,localhost", no_proxy: "127.0.0.1,localhost" };
|
||||
const started = performance.now();
|
||||
const startedAt = Date.now();
|
||||
const child = spawn(exe, [], { env, cwd: path.dirname(exe), stdio: "ignore", windowsHide: false });
|
||||
let exited = null;
|
||||
child.on("exit", code => { exited = code ?? -1; });
|
||||
child.on("error", error => { exited = String(error); });
|
||||
await new Promise(resolve => child.once("spawn", resolve).once("error", resolve));
|
||||
const app = { child, pid: child.pid, started, startedAt, browser: null, page: null, cdpMs: null };
|
||||
if (!app.pid) throw new Error(`Cannot start ${exe}: ${exited}`);
|
||||
try {
|
||||
const { chromium } = playwright();
|
||||
while (!app.browser) {
|
||||
if (exited !== null) throw new Error(`The app stopped during the start (exit ${exited}).`);
|
||||
if (performance.now() - started > timeout) throw new Error("CDP did not answer during the start.");
|
||||
if (await cdpResponds(port)) app.browser = await chromium.connectOverCDP(`http://127.0.0.1:${port}`, { timeout: 10000 });
|
||||
else await sleep(50);
|
||||
}
|
||||
app.cdpMs = performance.now() - started;
|
||||
while (!app.page) {
|
||||
if (performance.now() - started > timeout) throw new Error("The main window page did not open.");
|
||||
app.page = app.browser.contexts().flatMap(context => context.pages()).find(isMainPage) ?? null;
|
||||
if (!app.page) await sleep(50);
|
||||
}
|
||||
app.page.setDefaultTimeout(30000);
|
||||
return app;
|
||||
} catch (error) {
|
||||
await stop(app);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/** Wait for the known tree row. Return the start time in milliseconds from the spawn, and page timing values. */
|
||||
export async function waitForWorkbench(app, timeout = 60000) {
|
||||
await app.page.locator(TABLE.knownRow).waitFor({ state: "visible", timeout });
|
||||
const startMs = performance.now() - app.started;
|
||||
const timing = await app.page.evaluate(() => ({ timeOrigin: performance.timeOrigin, domContentLoaded: performance.getEntriesByType("navigation")[0]?.domContentLoadedEventEnd ?? null, tabs: document.querySelectorAll('[role="tab"]').length }));
|
||||
return { startMs, navigationMs: timing.timeOrigin - app.startedAt, domContentLoadedMs: timing.domContentLoaded === null ? null : timing.timeOrigin + timing.domContentLoaded - app.startedAt, tabsAtStart: timing.tabs };
|
||||
}
|
||||
|
||||
/** Start a long task observer in the page. */
|
||||
export function observeLongTasks(page) {
|
||||
return page.evaluate(() => {
|
||||
const state = { count: 0, max: 0 };
|
||||
const record = entries => { for (const entry of entries) { state.count++; state.max = Math.max(state.max, entry.duration); } };
|
||||
const observer = new PerformanceObserver(list => record(list.getEntries()));
|
||||
observer.observe({ type: "longtask" });
|
||||
window.__rsLongTasks = { state, observer, record };
|
||||
});
|
||||
}
|
||||
|
||||
/** Stop the long task observer. Return the count and the longest duration. */
|
||||
export function collectLongTasks(page) {
|
||||
return page.evaluate(() => {
|
||||
const tasks = window.__rsLongTasks;
|
||||
if (!tasks) return null;
|
||||
tasks.record(tasks.observer.takeRecords());
|
||||
tasks.observer.disconnect();
|
||||
return { count: tasks.state.count, maxMs: Math.round(tasks.state.max) };
|
||||
});
|
||||
}
|
||||
|
||||
/** Collect garbage in the main page, wait, and read the heap and the process tree. */
|
||||
export async function readMemory(app, { settleMs = 5000 } = {}) {
|
||||
const cdp = await app.page.context().newCDPSession(app.page);
|
||||
try {
|
||||
await cdp.send("HeapProfiler.collectGarbage");
|
||||
await sleep(settleMs);
|
||||
const heap = await cdp.send("Runtime.getHeapUsage");
|
||||
const tree = processTree(await listProcesses(), app.pid);
|
||||
return {
|
||||
heapMB: heap.usedSize / 1048576,
|
||||
heapTotalMB: heap.totalSize / 1048576,
|
||||
privateMB: tree.privateBytes / 1048576,
|
||||
workingSetMB: tree.workingSet / 1048576,
|
||||
processCount: tree.count,
|
||||
processNames: tree.names,
|
||||
processes: tree.processes.map(item => ({ pid: item.ProcessId, parent: item.ParentProcessId, name: item.Name, privateMB: +(item.PrivatePageCount / 1048576).toFixed(1), workingSetMB: +(item.WorkingSetSize / 1048576).toFixed(1), created: item.Created })),
|
||||
};
|
||||
} finally { await cdp.detach().catch(() => {}); }
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear the open tabs and the layout in the page storage, so the next start restores no tab and shows the file tree.
|
||||
* Chromium writes local storage to disk after a delay, so the function waits before it returns.
|
||||
*/
|
||||
export async function clearViewState(page, flushMs = 6000) {
|
||||
await page.evaluate(layout => {
|
||||
for (const key of Object.keys(localStorage)) if (key.startsWith("runestone.document-session.")) localStorage.removeItem(key);
|
||||
localStorage.setItem("runestone.workbenchLayout", JSON.stringify(layout));
|
||||
}, TABLE.layout);
|
||||
await sleep(flushMs);
|
||||
}
|
||||
|
||||
/** Stop the started process tree and make sure that none of its processes remain. */
|
||||
export async function stop(app) {
|
||||
if (!app?.pid) return { stopped: false };
|
||||
const before = processTree(await listProcesses().catch(() => []), app.pid).processes;
|
||||
const result = await stopTree(app.pid);
|
||||
await app.browser?.close().catch(() => {});
|
||||
for (let attempt = 0; attempt < 50; attempt++) {
|
||||
const now = await listProcesses().catch(() => []);
|
||||
const left = before.filter(item => now.some(other => other.ProcessId === item.ProcessId && other.Created === item.Created));
|
||||
if (!left.length) return { ...result, remaining: [] };
|
||||
if (attempt === 10) for (const item of left) await stopTree(item.ProcessId);
|
||||
await sleep(200);
|
||||
}
|
||||
throw new Error(`Processes of the stopped app remain: ${before.map(item => item.ProcessId).join(", ")}.`);
|
||||
}
|
||||
|
||||
/** The WebView2 folder of the test identity. It exists after the first start of a build with that identifier. */
|
||||
export function webviewFolder(localData) {
|
||||
return path.join(localData, "EBWebView");
|
||||
}
|
||||
export const hasWebviewFolder = localData => existsSync(webviewFolder(localData));
|
||||
@@ -0,0 +1,157 @@
|
||||
// Pure parts of the feature measurement tool: arguments, safety refusals, statistics, the process tree, and the report table.
|
||||
import path from "node:path";
|
||||
|
||||
export const FEATURES = ["git", "background", "terminal", "pdf", "pm"];
|
||||
export const MODES = ["plugin", "native"];
|
||||
export const SCENARIOS = ["on-idle", "in-use", "after-off"];
|
||||
/** The app that the owner installed. The tool never starts it, stops it, or touches its data. */
|
||||
export const INSTALLED_EXE = "D:\\Users\\KnottyWyvern\\AppData\\Local\\RuneStone\\runestone.exe";
|
||||
export const INSTALLED_IDENTIFIER = "com.runestone.app";
|
||||
|
||||
export const USAGE = "Usage: node scripts/measureFeatures.mjs --exe <path> --identifier com.runestone.<name> --stage <name> --mode plugin|native --features git,background,terminal,pdf,pm [--runs 3] [--port 9241] [--fresh-fixture] [--only base,<feature>:<scenario>,...] [--skip-base]";
|
||||
|
||||
/** Read the command line. Throw an error with the usage text for a missing or unknown argument. */
|
||||
export function parseArguments(args) {
|
||||
const options = { exe: undefined, identifier: undefined, stage: undefined, mode: undefined, features: undefined, runs: 3, port: 9241, freshFixture: false, only: undefined, skipBase: false };
|
||||
const values = { "--exe": "exe", "--identifier": "identifier", "--stage": "stage", "--mode": "mode", "--features": "features", "--runs": "runs", "--port": "port", "--only": "only" };
|
||||
const seen = new Set();
|
||||
for (let index = 0; index < args.length; index++) {
|
||||
const arg = args[index];
|
||||
if (arg === "--fresh-fixture") { options.freshFixture = true; continue; }
|
||||
if (arg === "--skip-base") { options.skipBase = true; continue; }
|
||||
const key = values[arg];
|
||||
if (!key) throw new Error(`Unknown argument ${arg}. ${USAGE}`);
|
||||
if (seen.has(arg)) throw new Error(`Give ${arg} one time only. ${USAGE}`);
|
||||
seen.add(arg);
|
||||
const value = args[++index];
|
||||
if (value === undefined || value.startsWith("--")) throw new Error(`${arg} needs a value. ${USAGE}`);
|
||||
options[key] = value;
|
||||
}
|
||||
for (const key of ["exe", "identifier", "stage", "mode", "features"]) if (options[key] === undefined) throw new Error(`--${key} is required. ${USAGE}`);
|
||||
if (!MODES.includes(options.mode)) throw new Error(`--mode must be plugin or native. ${USAGE}`);
|
||||
if (!/^[a-z0-9][a-z0-9._-]{0,63}$/i.test(options.stage)) throw new Error("--stage must be a simple folder name.");
|
||||
const features = options.features.split(",").map(feature => feature.trim()).filter(Boolean);
|
||||
const unknown = features.filter(feature => !FEATURES.includes(feature));
|
||||
if (!features.length || unknown.length) throw new Error(`Unknown feature ${unknown.join(", ") || "(none)"}. Use ${FEATURES.join(", ")}.`);
|
||||
options.features = [...new Set(features)];
|
||||
for (const key of ["runs", "port"]) {
|
||||
const number = Number(options[key]);
|
||||
if (typeof options[key] === "string" && !/^\d+$/.test(options[key])) throw new Error(`--${key} must be a whole number.`);
|
||||
options[key] = number;
|
||||
}
|
||||
if (options.runs < 1 || options.runs > 20) throw new Error("--runs must be from 1 to 20.");
|
||||
if (options.port < 1024 || options.port > 65535) throw new Error("--port must be from 1024 to 65535.");
|
||||
if (options.only !== undefined) {
|
||||
options.only = options.only.split(",").map(item => item.trim()).filter(Boolean);
|
||||
for (const item of options.only) {
|
||||
const [feature, scenario] = item.split(":");
|
||||
if (!(item === "base" || (options.features.includes(feature) && SCENARIOS.includes(scenario)))) throw new Error(`--only takes base or <feature>:<scenario>, not ${item}.`);
|
||||
}
|
||||
}
|
||||
return options;
|
||||
}
|
||||
|
||||
function samePath(a, b) {
|
||||
return path.win32.resolve(a).toLowerCase() === path.win32.resolve(b).toLowerCase();
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuse an unsafe target. The executable must not be the installed app or be in its folder.
|
||||
* The identifier must start with `com.runestone.` and must not be the identifier of the installed app.
|
||||
* `env` supplies LOCALAPPDATA and APPDATA. Return the two data folders that the tool may reset.
|
||||
*/
|
||||
export function checkTarget({ exe, identifier }, env = process.env) {
|
||||
const installed = [INSTALLED_EXE];
|
||||
if (env.LOCALAPPDATA) installed.push(path.win32.join(env.LOCALAPPDATA, "RuneStone", "runestone.exe"));
|
||||
const resolved = path.win32.resolve(exe);
|
||||
for (const target of installed) {
|
||||
if (samePath(resolved, target) || samePath(path.win32.dirname(resolved), path.win32.dirname(target)))
|
||||
throw new Error(`Refusing to run the installed RuneStone (${target}). Give a copy of a test build.`);
|
||||
}
|
||||
if (typeof identifier !== "string" || identifier.toLowerCase() === INSTALLED_IDENTIFIER)
|
||||
throw new Error(`Refusing the identifier ${identifier}. It belongs to the installed RuneStone.`);
|
||||
if (!/^com\.runestone\.[a-z0-9][a-z0-9-]*$/.test(identifier))
|
||||
throw new Error(`Refusing the identifier ${identifier}. A test identifier starts with com.runestone. and has lowercase letters, digits, and hyphens.`);
|
||||
if (!env.APPDATA || !env.LOCALAPPDATA) throw new Error("APPDATA and LOCALAPPDATA must be set.");
|
||||
return { roaming: path.win32.join(env.APPDATA, identifier), local: path.win32.join(env.LOCALAPPDATA, identifier) };
|
||||
}
|
||||
|
||||
/** The median of the finite numbers in `values`, or null when there is none. */
|
||||
export function median(values) {
|
||||
const numbers = values.filter(value => typeof value === "number" && Number.isFinite(value)).sort((a, b) => a - b);
|
||||
if (!numbers.length) return null;
|
||||
const middle = Math.floor(numbers.length / 2);
|
||||
return numbers.length % 2 ? numbers[middle] : (numbers[middle - 1] + numbers[middle]) / 2;
|
||||
}
|
||||
|
||||
/**
|
||||
* Walk the descendants of `rootPid` in a process list from Win32_Process.
|
||||
* A child counts only when it started after its parent, so a reused parent process ID does not add a stranger.
|
||||
* Return the processes of the tree, with the root first, and the sums of the private bytes and the working sets.
|
||||
*/
|
||||
export function processTree(list, rootPid) {
|
||||
const byParent = new Map();
|
||||
for (const item of list) {
|
||||
if (!byParent.has(item.ParentProcessId)) byParent.set(item.ParentProcessId, []);
|
||||
byParent.get(item.ParentProcessId).push(item);
|
||||
}
|
||||
const root = list.find(item => item.ProcessId === rootPid);
|
||||
if (!root) return { processes: [], privateBytes: 0, workingSet: 0, count: 0, names: {} };
|
||||
const processes = [root];
|
||||
const seen = new Set([rootPid]);
|
||||
for (let index = 0; index < processes.length; index++) {
|
||||
const parent = processes[index];
|
||||
for (const child of byParent.get(parent.ProcessId) ?? []) {
|
||||
if (seen.has(child.ProcessId)) continue;
|
||||
if (typeof child.Created === "number" && typeof parent.Created === "number" && child.Created < parent.Created) continue;
|
||||
seen.add(child.ProcessId);
|
||||
processes.push(child);
|
||||
}
|
||||
}
|
||||
const names = {};
|
||||
for (const item of processes) names[item.Name] = (names[item.Name] ?? 0) + 1;
|
||||
return {
|
||||
processes,
|
||||
privateBytes: processes.reduce((sum, item) => sum + Number(item.PrivatePageCount ?? 0), 0),
|
||||
workingSet: processes.reduce((sum, item) => sum + Number(item.WorkingSetSize ?? 0), 0),
|
||||
count: processes.length,
|
||||
names,
|
||||
};
|
||||
}
|
||||
|
||||
export const METRICS = ["privateMB", "workingSetMB", "heapMB", "startMs", "firstNeedMs", "longTaskCount", "longTaskMaxMs", "processCount"];
|
||||
|
||||
/** The median of each metric over the samples that did not fail. */
|
||||
export function summarize(samples) {
|
||||
const good = samples.filter(sample => !sample.error);
|
||||
const result = { runs: samples.length, failed: samples.length - good.length };
|
||||
for (const metric of METRICS) result[metric] = median(good.map(sample => sample[metric]));
|
||||
return result;
|
||||
}
|
||||
|
||||
const fixed = (value, digits = 1) => value === null || value === undefined ? "–" : Number(value).toFixed(digits);
|
||||
|
||||
/** The Markdown report: one table row for each feature and scenario. */
|
||||
export function markdownTable(report) {
|
||||
const lines = [
|
||||
`# Feature memory: ${report.stage}`,
|
||||
"",
|
||||
`Build: \`${report.build}\` (${report.identifier}), mode ${report.mode}, ${report.runs} runs for each scenario, ${report.date}.`,
|
||||
`Machine: ${report.machine.cpu}, ${fixed(report.machine.ramGB)} GB RAM, ${report.machine.windows}.`,
|
||||
"Each value is the median of the runs. Private and working set are sums over the process tree of the app.",
|
||||
"",
|
||||
"| Feature | Scenario | Private MB | Working set MB | JS heap MB | Start ms | First need ms | Long tasks (count / longest ms) |",
|
||||
"| --- | --- | ---: | ---: | ---: | ---: | ---: | ---: |",
|
||||
];
|
||||
for (const row of report.rows) {
|
||||
const m = row.median;
|
||||
if (!m || m.runs === m.failed) {
|
||||
lines.push(`| ${row.feature} | ${row.scenario} | failed | | | | | ${row.reason ? row.reason.replace(/\|/g, "/").slice(0, 160) : ""} |`);
|
||||
continue;
|
||||
}
|
||||
const failed = m.failed ? ` (${m.failed} of ${m.runs} runs failed)` : "";
|
||||
lines.push(`| ${row.feature} | ${row.scenario}${failed} | ${fixed(m.privateMB)} | ${fixed(m.workingSetMB)} | ${fixed(m.heapMB)} | ${fixed(m.startMs, 0)} | ${fixed(m.firstNeedMs, 0)} | ${fixed(m.longTaskCount, 0)} / ${fixed(m.longTaskMaxMs, 0)} |`);
|
||||
}
|
||||
if (report.notes?.length) lines.push("", "Notes:", "", ...report.notes.map(note => `- ${note}`));
|
||||
return lines.join("\n") + "\n";
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
// The fixture workspace: a Git repository with history and changes, a 50-page PDF, background images, and a Project Management store.
|
||||
// It lives in the system temporary folder, outside the repository, so the file watcher of the app does not see the worktree.
|
||||
import { execFile } from "node:child_process";
|
||||
import { createHash } from "node:crypto";
|
||||
import { existsSync, realpathSync } from "node:fs";
|
||||
import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
import { encodePng, gradientPixel } from "./png.mjs";
|
||||
import { writePdf } from "./pdf.mjs";
|
||||
|
||||
const run = promisify(execFile);
|
||||
export const FIXTURE_VERSION = 1;
|
||||
export const COMMITS = 30;
|
||||
export const TEXT_FILES = 50;
|
||||
export const PDF_PAGES = 50;
|
||||
export const BOARDS = 8;
|
||||
export const CARDS_PER_BOARD = 50;
|
||||
export const IMAGES = 5;
|
||||
export const IMAGE_SIZE = { width: 1920, height: 1080 };
|
||||
/** A file at the workspace root that the tree shows at once. The start time waits for its row. */
|
||||
export const KNOWN_ROW = "sample.pdf";
|
||||
|
||||
export const fixtureRoot = () => path.join(tmpdir(), "runestone-phase7-fixture");
|
||||
|
||||
/** A UUID with the version 4 layout, made from `seed`, so each fixture build has the same IDs. */
|
||||
export function seededUuid(seed) {
|
||||
const hex = createHash("sha256").update(seed).digest("hex");
|
||||
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-4${hex.slice(13, 16)}-${"89ab"[parseInt(hex[16], 16) % 4]}${hex.slice(17, 20)}-${hex.slice(20, 32)}`;
|
||||
}
|
||||
|
||||
/** The card file name: the hex of the UTF-8 card ID, then `.md`. */
|
||||
export const cardFileName = id => `${Buffer.from(id, "utf8").toString("hex")}.md`;
|
||||
|
||||
/** An order key that sorts in the same order as `index`. */
|
||||
const orderKey = index => `a${String.fromCharCode(97 + Math.floor(index / 26))}${String.fromCharCode(97 + (index % 26))}`;
|
||||
|
||||
const textName = index => `note-${String(index + 1).padStart(2, "0")}.txt`;
|
||||
|
||||
function git(cwd, args, env = {}) {
|
||||
const config = ["-c", "user.name=RuneStone Fixture", "-c", "[email protected]", "-c", "commit.gpgsign=false", "-c", "core.autocrlf=false", "-c", "init.defaultBranch=main"];
|
||||
return run("git", ["-C", cwd, ...config, ...args], { env: { ...process.env, GIT_TERMINAL_PROMPT: "0", ...env }, windowsHide: true, maxBuffer: 16 * 1024 * 1024 });
|
||||
}
|
||||
|
||||
const LISTS = [
|
||||
{ id: "backlog", name: "Backlog", status: null },
|
||||
{ id: "todo", name: "To do", status: "todo" },
|
||||
{ id: "doing", name: "In progress", status: "doing" },
|
||||
{ id: "done", name: "Done", status: "done" },
|
||||
];
|
||||
|
||||
/** The Project Management store: `workspace.json`, the card files, and the two `.gitignore` files. */
|
||||
export function pmFiles() {
|
||||
const files = new Map();
|
||||
files.set(".runestone/pm/.gitignore", "# RuneStone PM local data\n*\n");
|
||||
files.set(".runestone/pm/cards/.gitignore", "*\n");
|
||||
const boards = [];
|
||||
for (let b = 0; b < BOARDS; b++) {
|
||||
const id = seededUuid(`board-${b}`);
|
||||
boards.push({
|
||||
name: `Fixture board ${b + 1}`,
|
||||
value: {
|
||||
schema: 1, kind: "board", id,
|
||||
lists: LISTS.map(list => ({ id: list.id, name: list.name, status: list.status, collapsed: false })),
|
||||
defaults: { todo: "todo", doing: "doing", done: "done" },
|
||||
},
|
||||
});
|
||||
for (let c = 0; c < CARDS_PER_BOARD; c++) {
|
||||
const cardId = seededUuid(`card-${b}-${c}`);
|
||||
const list = LISTS[c % LISTS.length];
|
||||
const status = list.status ?? "todo";
|
||||
const source = [
|
||||
"---",
|
||||
"runestone_pm:",
|
||||
" schema: 1",
|
||||
` id: ${cardId}`,
|
||||
" kind: task",
|
||||
` status: ${status}`,
|
||||
" tags: []",
|
||||
" sessions: []",
|
||||
" archived: false",
|
||||
` order: ${orderKey(b * CARDS_PER_BOARD + c)}`,
|
||||
" placements:",
|
||||
` ${id}:`,
|
||||
` listId: ${list.id}`,
|
||||
` order: ${orderKey(c)}`,
|
||||
` title: Fixture card ${c + 1} on board ${b + 1}`,
|
||||
` priority: ${["low", "medium", "high"][c % 3]}`,
|
||||
"---",
|
||||
"",
|
||||
`This card is fixture data for the memory measurement. Board ${b + 1}, card ${c + 1}.`,
|
||||
"",
|
||||
].join("\n");
|
||||
files.set(`.runestone/pm/cards/${cardFileName(cardId)}`, source);
|
||||
}
|
||||
}
|
||||
files.set(".runestone/pm/workspace.json", JSON.stringify({ schema: 1, boards, deletedBoardIds: [] }, null, 2) + "\n");
|
||||
return files;
|
||||
}
|
||||
|
||||
const COLORS = [
|
||||
[[16, 42, 120], [220, 90, 40], 0.3],
|
||||
[[10, 110, 80], [240, 220, 60], 1.2],
|
||||
[[120, 20, 90], [40, 200, 230], 2.1],
|
||||
[[30, 30, 30], [200, 200, 210], 0],
|
||||
[[200, 40, 40], [20, 60, 160], Math.PI / 2],
|
||||
];
|
||||
|
||||
async function writeFiles(root, files) {
|
||||
for (const [rel, contents] of files) {
|
||||
const target = path.join(root, ...rel.split("/"));
|
||||
await mkdir(path.dirname(target), { recursive: true });
|
||||
await writeFile(target, contents);
|
||||
}
|
||||
}
|
||||
|
||||
/** Build the fixture in `root`. The caller removes an old fixture first. */
|
||||
export async function buildFixture(root) {
|
||||
const workspace = path.join(root, "workspace");
|
||||
const backgrounds = path.join(root, "backgrounds");
|
||||
await mkdir(workspace, { recursive: true });
|
||||
await mkdir(backgrounds, { recursive: true });
|
||||
for (const [index, [from, to, angle]] of COLORS.entries()) {
|
||||
const { width, height } = IMAGE_SIZE;
|
||||
await writeFile(path.join(backgrounds, `background-${index + 1}.png`), encodePng(width, height, gradientPixel(width, height, from, to, angle)));
|
||||
}
|
||||
await git(workspace, ["init", "-q"]);
|
||||
await writeFile(path.join(workspace, ".gitignore"), ".runestone/\n");
|
||||
await writeFile(path.join(workspace, "sample.pdf"), writePdf(Array.from({ length: PDF_PAGES }, (_, index) => `Page ${index + 1}`)));
|
||||
const line = (file, version) => `Fixture file ${file + 1}, version ${version}.\n`;
|
||||
const versions = Array(TEXT_FILES).fill(0);
|
||||
for (let file = 0; file < TEXT_FILES; file++) await writeFile(path.join(workspace, textName(file)), line(file, 0));
|
||||
for (let commit = 0; commit < COMMITS; commit++) {
|
||||
if (commit > 0) {
|
||||
// Each later commit changes five files, so the graph and the diffs have content.
|
||||
for (let k = 0; k < 5; k++) {
|
||||
const file = (commit * 7 + k * 11) % TEXT_FILES;
|
||||
versions[file]++;
|
||||
await writeFile(path.join(workspace, textName(file)), Array.from({ length: versions[file] + 1 }, (_, v) => line(file, v)).join(""));
|
||||
}
|
||||
}
|
||||
await git(workspace, ["add", "-A"]);
|
||||
const date = new Date(Date.UTC(2026, 0, 1 + commit, 12)).toISOString();
|
||||
await git(workspace, ["commit", "-q", "--no-verify", "-m", commit === 0 ? "Add the fixture files" : `Change fixture files, step ${commit}`], { GIT_AUTHOR_DATE: date, GIT_COMMITTER_DATE: date });
|
||||
}
|
||||
for (let file = 0; file < TEXT_FILES; file++) {
|
||||
const target = path.join(workspace, textName(file));
|
||||
await writeFile(target, (await readFile(target, "utf8")) + `Changed after the last commit (file ${file + 1}).\n`);
|
||||
}
|
||||
await writeFiles(workspace, pmFiles());
|
||||
await writeFile(path.join(root, "fixture.json"), JSON.stringify({ version: FIXTURE_VERSION, commits: COMMITS, changes: TEXT_FILES, pages: PDF_PAGES, boards: BOARDS, cards: BOARDS * CARDS_PER_BOARD, images: IMAGES }, null, 2) + "\n");
|
||||
}
|
||||
|
||||
/** Check that the fixture in `root` is complete and unchanged. Return a list of problems, empty when it matches. */
|
||||
export async function checkFixture(root) {
|
||||
const problems = [];
|
||||
const workspace = path.join(root, "workspace");
|
||||
try {
|
||||
const record = JSON.parse(await readFile(path.join(root, "fixture.json"), "utf8"));
|
||||
if (record.version !== FIXTURE_VERSION) problems.push(`fixture version ${record.version}`);
|
||||
} catch { problems.push("no fixture.json"); return problems; }
|
||||
for (let index = 0; index < IMAGES; index++) if (!existsSync(path.join(root, "backgrounds", `background-${index + 1}.png`))) problems.push(`no background ${index + 1}`);
|
||||
if (!existsSync(path.join(workspace, "sample.pdf"))) problems.push("no sample.pdf");
|
||||
try {
|
||||
const status = (await git(workspace, ["status", "--porcelain"])).stdout.split("\n").filter(Boolean);
|
||||
if (status.length !== TEXT_FILES || status.some(entry => !entry.startsWith(" M "))) problems.push(`git status shows ${status.length} entries, not ${TEXT_FILES} changed files`);
|
||||
const count = Number((await git(workspace, ["rev-list", "--count", "HEAD"])).stdout.trim());
|
||||
if (count !== COMMITS) problems.push(`${count} commits, not ${COMMITS}`);
|
||||
} catch (error) { problems.push(`git: ${error.message}`); }
|
||||
for (const [rel, contents] of pmFiles()) {
|
||||
const target = path.join(workspace, ...rel.split("/"));
|
||||
if (!existsSync(target)) { problems.push(`no ${rel}`); break; }
|
||||
if (rel.endsWith("workspace.json") && (await readFile(target, "utf8")) !== contents) problems.push("workspace.json changed");
|
||||
}
|
||||
return problems;
|
||||
}
|
||||
|
||||
/** Reuse the fixture when it matches, or build it again. Return the canonical paths. */
|
||||
export async function prepareFixture({ fresh = false, root = fixtureRoot(), log = () => {} } = {}) {
|
||||
let problems = fresh ? ["--fresh-fixture"] : await checkFixture(root);
|
||||
if (problems.length) {
|
||||
log(`Building the fixture in ${root} (${problems.join(", ")}).`);
|
||||
// The fixture folder belongs to this tool. It is in the system temporary folder.
|
||||
if (path.basename(root) !== "runestone-phase7-fixture") throw new Error(`Refusing to remove ${root}.`);
|
||||
await rm(root, { recursive: true, force: true });
|
||||
await buildFixture(root);
|
||||
problems = await checkFixture(root);
|
||||
if (problems.length) throw new Error(`The new fixture does not match: ${problems.join(", ")}.`);
|
||||
} else log(`Reusing the fixture in ${root}.`);
|
||||
// The canonical path expands short 8.3 names, so the app and the grants see the same path.
|
||||
const real = realpathSync.native(root);
|
||||
return { root: real, workspace: path.join(real, "workspace"), backgrounds: path.join(real, "backgrounds") };
|
||||
}
|
||||
|
||||
/** Run the read-only Project Management helper of the skill. Return the number of boards that it lists. */
|
||||
export async function inspectPmBoards(workspace, helper = path.join(process.env.USERPROFILE ?? "", ".claude", "skills", "runestone-project-management", "scripts", "inspect.mjs")) {
|
||||
if (!existsSync(helper)) return { checked: false, reason: `no helper at ${helper}` };
|
||||
const { stdout } = await run(process.execPath, [helper, "boards", "--workspace", workspace], { windowsHide: true, maxBuffer: 16 * 1024 * 1024 });
|
||||
return { checked: true, output: stdout };
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
// A local fake Gitea release server. The host installs plugin ZIPs through its Gitea path from this server.
|
||||
import { createServer } from "node:http";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
|
||||
/**
|
||||
* Serve the releases in `packages`: a list of `{ repo, tag, file }`, with `file` the path of a plugin ZIP.
|
||||
* The server answers `GET /api/v1/repos/test/<repo>/releases/tags/<tag>` and serves the ZIP at its download link.
|
||||
* Return the base URL, the repository link of each package, the request log, and `close`.
|
||||
*/
|
||||
export async function startGiteaServer(packages, owner = "test") {
|
||||
const bodies = new Map();
|
||||
for (const item of packages) bodies.set(item.repo, { ...item, name: path.basename(item.file), bytes: await readFile(item.file) });
|
||||
const requests = [];
|
||||
const server = createServer((request, response) => {
|
||||
const url = new URL(request.url, "http://127.0.0.1");
|
||||
requests.push(`${request.method} ${url.pathname}`);
|
||||
const release = /^\/api\/v1\/repos\/([^/]+)\/([^/]+)\/releases\/tags\/([^/]+)$/.exec(url.pathname);
|
||||
const download = /^\/download\/([^/]+)\/([^/]+)$/.exec(url.pathname);
|
||||
if (request.method === "GET" && release && release[1] === owner && bodies.get(release[2])?.tag === decodeURIComponent(release[3])) {
|
||||
const item = bodies.get(release[2]);
|
||||
const body = JSON.stringify({
|
||||
tag_name: item.tag, draft: false,
|
||||
assets: [{ name: item.name, size: item.bytes.length, browser_download_url: `${base}/download/${item.repo}/${encodeURIComponent(item.name)}` }],
|
||||
});
|
||||
response.writeHead(200, { "content-type": "application/json", "content-length": Buffer.byteLength(body) });
|
||||
response.end(body);
|
||||
return;
|
||||
}
|
||||
if (request.method === "GET" && download && bodies.get(download[1])?.name === decodeURIComponent(download[2])) {
|
||||
const item = bodies.get(download[1]);
|
||||
response.writeHead(200, { "content-type": "application/zip", "content-length": item.bytes.length });
|
||||
response.end(item.bytes);
|
||||
return;
|
||||
}
|
||||
response.writeHead(404, { "content-type": "text/plain" });
|
||||
response.end("not found");
|
||||
});
|
||||
await new Promise((resolve, reject) => { server.once("error", reject); server.listen(0, "127.0.0.1", resolve); });
|
||||
const base = `http://127.0.0.1:${server.address().port}`;
|
||||
return {
|
||||
base,
|
||||
requests,
|
||||
repository: repo => `${base}/${owner}/${repo}`,
|
||||
close: () => new Promise(resolve => server.close(() => resolve())),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
// A small PDF writer for the fixture document: one page for each text, in Helvetica, with a correct cross-reference table.
|
||||
|
||||
function escapeText(text) {
|
||||
return text.replace(/[\\()]/g, match => `\\${match}`);
|
||||
}
|
||||
|
||||
/** Write a PDF with one US Letter page for each entry of `texts`. Return the bytes. */
|
||||
export function writePdf(texts) {
|
||||
if (!texts.length) throw new Error("A PDF needs at least one page.");
|
||||
// Object numbers: 1 catalog, 2 page tree, 3 font, then a page and its content stream for each text.
|
||||
const pageIds = texts.map((_, index) => 4 + index * 2);
|
||||
const objects = [
|
||||
"<< /Type /Catalog /Pages 2 0 R >>",
|
||||
`<< /Type /Pages /Kids [${pageIds.map(id => `${id} 0 R`).join(" ")}] /Count ${texts.length} >>`,
|
||||
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>",
|
||||
];
|
||||
for (const [index, text] of texts.entries()) {
|
||||
const stream = `BT /F1 48 Tf 72 680 Td (${escapeText(text)}) Tj ET\nBT /F1 14 Tf 72 640 Td (RuneStone measurement fixture, page ${index + 1} of ${texts.length}) Tj ET\n`;
|
||||
objects.push(`<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 3 0 R >> >> /Contents ${pageIds[index] + 1} 0 R >>`);
|
||||
objects.push(`<< /Length ${Buffer.byteLength(stream, "latin1")} >>\nstream\n${stream}endstream`);
|
||||
}
|
||||
let body = "%PDF-1.4\n%\xe2\xe3\xcf\xd3\n";
|
||||
const offsets = [];
|
||||
for (const [index, object] of objects.entries()) {
|
||||
offsets.push(Buffer.byteLength(body, "latin1"));
|
||||
body += `${index + 1} 0 obj\n${object}\nendobj\n`;
|
||||
}
|
||||
const xref = Buffer.byteLength(body, "latin1");
|
||||
// Each entry is exactly 20 bytes, with a space and a line feed at the end.
|
||||
body += `xref\n0 ${objects.length + 1}\n0000000000 65535 f \n`;
|
||||
for (const offset of offsets) body += `${String(offset).padStart(10, "0")} 00000 n \n`;
|
||||
body += `trailer\n<< /Size ${objects.length + 1} /Root 1 0 R >>\nstartxref\n${xref}\n%%EOF\n`;
|
||||
return Buffer.from(body, "latin1");
|
||||
}
|
||||
|
||||
/** Read the cross-reference table of a PDF from `writePdf`. Return `startxref` and the offsets of the objects in use. */
|
||||
export function readPdfXref(bytes) {
|
||||
const text = bytes.toString("latin1");
|
||||
const start = Number(/startxref\n(\d+)\n%%EOF\n?$/.exec(text)?.[1]);
|
||||
if (!Number.isInteger(start) || !text.startsWith("xref\n", start)) throw new Error("The startxref offset does not point to the xref table.");
|
||||
const lines = text.slice(start).split("\n");
|
||||
const [, count] = lines[1].split(" ").map(Number);
|
||||
const entries = lines.slice(2, 2 + count).map(line => ({ line, offset: Number(line.slice(0, 10)), used: line.slice(17, 18) === "n" }));
|
||||
return { start, count, entries };
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
// A small PNG encoder for the fixture images. It writes 8-bit RGB images without a dependency.
|
||||
import { deflateSync } from "node:zlib";
|
||||
|
||||
const CRC_TABLE = (() => {
|
||||
const table = new Uint32Array(256);
|
||||
for (let n = 0; n < 256; n++) {
|
||||
let c = n;
|
||||
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
|
||||
table[n] = c >>> 0;
|
||||
}
|
||||
return table;
|
||||
})();
|
||||
|
||||
/** The CRC-32 of `bytes`, as PNG and ZIP use it. */
|
||||
export function crc32(bytes) {
|
||||
let crc = 0xffffffff;
|
||||
for (const byte of bytes) crc = CRC_TABLE[(crc ^ byte) & 0xff] ^ (crc >>> 8);
|
||||
return (crc ^ 0xffffffff) >>> 0;
|
||||
}
|
||||
|
||||
export const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
|
||||
|
||||
function chunk(type, data) {
|
||||
const length = Buffer.alloc(4);
|
||||
length.writeUInt32BE(data.length);
|
||||
const body = Buffer.concat([Buffer.from(type, "ascii"), data]);
|
||||
const crc = Buffer.alloc(4);
|
||||
crc.writeUInt32BE(crc32(body));
|
||||
return Buffer.concat([length, body, crc]);
|
||||
}
|
||||
|
||||
/** Encode an RGB image. `pixel(x, y)` returns `[r, g, b]` with values from 0 to 255. */
|
||||
export function encodePng(width, height, pixel) {
|
||||
if (!Number.isInteger(width) || !Number.isInteger(height) || width < 1 || height < 1) throw new Error("The image size must be positive whole numbers.");
|
||||
const stride = width * 3 + 1;
|
||||
const raw = Buffer.alloc(stride * height);
|
||||
for (let y = 0; y < height; y++) {
|
||||
const row = y * stride;
|
||||
raw[row] = 0; // Filter type None.
|
||||
for (let x = 0; x < width; x++) {
|
||||
const [r, g, b] = pixel(x, y);
|
||||
const at = row + 1 + x * 3;
|
||||
raw[at] = r; raw[at + 1] = g; raw[at + 2] = b;
|
||||
}
|
||||
}
|
||||
const header = Buffer.alloc(13);
|
||||
header.writeUInt32BE(width, 0);
|
||||
header.writeUInt32BE(height, 4);
|
||||
header[8] = 8; // Bit depth.
|
||||
header[9] = 2; // Color type RGB.
|
||||
header[10] = 0; header[11] = 0; header[12] = 0;
|
||||
return Buffer.concat([PNG_SIGNATURE, chunk("IHDR", header), chunk("IDAT", deflateSync(raw, { level: 6 })), chunk("IEND", Buffer.alloc(0))]);
|
||||
}
|
||||
|
||||
/** Read the chunks of a PNG file. Each chunk has its type, data, stored CRC, and computed CRC. */
|
||||
export function readPngChunks(bytes) {
|
||||
if (!bytes.subarray(0, 8).equals(PNG_SIGNATURE)) throw new Error("The file has no PNG signature.");
|
||||
const chunks = [];
|
||||
let at = 8;
|
||||
while (at < bytes.length) {
|
||||
const length = bytes.readUInt32BE(at);
|
||||
const type = bytes.toString("ascii", at + 4, at + 8);
|
||||
const data = bytes.subarray(at + 8, at + 8 + length);
|
||||
const stored = bytes.readUInt32BE(at + 8 + length);
|
||||
chunks.push({ type, data, stored, computed: crc32(bytes.subarray(at + 4, at + 8 + length)) });
|
||||
at += 12 + length;
|
||||
}
|
||||
return chunks;
|
||||
}
|
||||
|
||||
/** A diagonal gradient between two colors. Each fixture image uses a different pair and angle. */
|
||||
export function gradientPixel(width, height, from, to, angle) {
|
||||
const dx = Math.cos(angle), dy = Math.sin(angle);
|
||||
const span = Math.abs(dx) * width + Math.abs(dy) * height;
|
||||
const origin = Math.min(0, dx * width) + Math.min(0, dy * height);
|
||||
return (x, y) => {
|
||||
const t = (x * dx + y * dy - origin) / span;
|
||||
return [0, 1, 2].map(i => Math.round(from[i] + (to[i] - from[i]) * t));
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
// Process sampling and the stop of one process tree. The tool never stops a process by its image name.
|
||||
import { execFile } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
const run = promisify(execFile);
|
||||
|
||||
const LIST = "Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,Name,PrivatePageCount,WorkingSetSize,@{n='Created';e={if ($_.CreationDate) { $_.CreationDate.ToFileTimeUtc() } else { $null }}} | ConvertTo-Json -Compress";
|
||||
|
||||
/** List all processes one time, with the private bytes and the working set of each. */
|
||||
export async function listProcesses() {
|
||||
const { stdout } = await run("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", LIST], { maxBuffer: 64 * 1024 * 1024, windowsHide: true });
|
||||
const value = JSON.parse(stdout);
|
||||
return (Array.isArray(value) ? value : [value]).map(item => ({ ...item, PrivatePageCount: Number(item.PrivatePageCount ?? 0), WorkingSetSize: Number(item.WorkingSetSize ?? 0) }));
|
||||
}
|
||||
|
||||
/** Stop the process tree of `pid` with taskkill. Errors are returned, not thrown, because the tree can be gone already. */
|
||||
export async function stopTree(pid) {
|
||||
if (!Number.isInteger(pid) || pid <= 4) throw new Error(`Refusing to stop process ID ${pid}.`);
|
||||
try {
|
||||
const { stdout } = await run("taskkill.exe", ["/PID", String(pid), "/T", "/F"], { windowsHide: true });
|
||||
return { stopped: true, output: stdout.trim() };
|
||||
} catch (error) {
|
||||
return { stopped: false, output: String(error.stderr || error.message).trim() };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
// The scenario table: the selectors, names, and feature switches of both modes, and the in-use action of each feature.
|
||||
// A value with `plugin` and `native` keys differs between the modes. Change the table when a stage changes a name.
|
||||
|
||||
const PLUGIN_RELEASES = "D:/Users/KnottyWyvern/Documents";
|
||||
|
||||
export const TABLE = {
|
||||
/** The start time ends when this tree row is visible. */
|
||||
knownRow: '[data-tree-rel="sample.pdf"]',
|
||||
/** The command palette. */
|
||||
palette: { shortcut: "Control+Shift+P", input: "Find a command" },
|
||||
/** The layout that the cleanup writes, so each start shows the file tree. */
|
||||
layout: { leftOpen: true, rightOpen: true, leftWidth: 260, rightWidth: 240, leftView: "files" },
|
||||
/** The settings section of the native feature switches. */
|
||||
featuresSection: "features",
|
||||
features: {
|
||||
git: {
|
||||
plugin: { id: "runestone.git", repo: "runestone-git", tag: "v0.1.10", zip: `${PLUGIN_RELEASES}/RuneStone_Git/releases/runestone.git-0.1.10.zip` },
|
||||
nativeKey: "git",
|
||||
navigation: "Source control",
|
||||
changeRow: { plugin: ".rs-git-row", native: ".source-control .row" },
|
||||
changeCount: 50,
|
||||
changeFile: { plugin: ".rs-git-file", native: ".source-control .file" },
|
||||
diffTab: "Git diff",
|
||||
diffText: "Changed after the last commit",
|
||||
graphCommand: "Show Git graph",
|
||||
/** Where the command is: `palette`, or `menu:<ribbon menu name>`. Master lists plugin view commands only in the Plug-in views menu. */
|
||||
graphCommandIn: { plugin: "menu:Plug-in views", native: "palette" },
|
||||
graphTab: "Git graph",
|
||||
graphText: "Change fixture files, step 29",
|
||||
},
|
||||
background: {
|
||||
plugin: { id: "runestone.bg-slideshow", repo: "runestone-bg-slideshow", tag: "v0.0.11", zip: `${PLUGIN_RELEASES}/RuneStone_Background_Slideshow/releases/runestone.bg-slideshow-0.0.11.zip` },
|
||||
nativeKey: "background",
|
||||
/**
|
||||
* The style property of the body that holds the current background image. The action counts its changes.
|
||||
* Native: `backgroundHub.applyApp` (src/lib/plugins/backgrounds.ts) sets it for each new image of Background.
|
||||
*/
|
||||
imageProperty: { plugin: "--rs-background-image", native: "--rs-background-image" },
|
||||
changes: 3,
|
||||
seconds: 10,
|
||||
},
|
||||
terminal: {
|
||||
plugin: { id: "runestone.terminal", repo: "runestone-terminal", tag: "v0.1.11", zip: `${PLUGIN_RELEASES}/RuneStone_Terminal/releases/runestone.terminal-0.1.11.zip` },
|
||||
nativeKey: "terminal",
|
||||
/**
|
||||
* Both modes use the same names. Native: the ribbon button comes from the feature switch, and the first click loads
|
||||
* the Terminal feature and xterm (src/lib/features/TerminalHost.svelte), so the action includes that load.
|
||||
*/
|
||||
ribbon: ".plugin-ribbon",
|
||||
button: "Terminal",
|
||||
surface: ".xterm",
|
||||
rows: ".xterm-rows",
|
||||
prompt: "PS [A-Za-z]:\\\\",
|
||||
command: '1..10000 | % { "line $_" }',
|
||||
readyText: "line 10000",
|
||||
},
|
||||
pdf: {
|
||||
plugin: { id: "runestone.pdf-viewer", repo: "runestone-pdf-viewer", tag: "v0.0.5", zip: `${PLUGIN_RELEASES}/RuneStone_PDF_Viewer/releases/runestone.pdf-viewer-0.0.5.zip` },
|
||||
nativeKey: "pdf",
|
||||
/**
|
||||
* Both modes use the same names. Native: the tree row opens a PDF tab, and the first tab loads the PDF Viewer feature
|
||||
* and PDF.js (src/lib/features/pdf/), so the action includes that load. Each page canvas is an image named "PDF page N",
|
||||
* and the page field is a spin button named "Page number". Enter in the field goes to the page.
|
||||
*/
|
||||
row: '[data-tree-rel="sample.pdf"]',
|
||||
firstPage: "PDF page 1",
|
||||
pageInput: "Page number",
|
||||
target: 25,
|
||||
targetPage: "PDF page 25",
|
||||
},
|
||||
pm: {
|
||||
plugin: { id: "runestone.pm", repo: "runestone-pm", tag: "v0.2.49", zip: `${PLUGIN_RELEASES}/RuneStone_Project_Management/releases/runestone.pm-0.2.49.zip` },
|
||||
nativeKey: "pm",
|
||||
/**
|
||||
* Where the view opens: `palette`, `menu:<ribbon menu name>`, or `ribbon:<ribbon button name>`. Native: the static
|
||||
* ribbon button opens the default board or All tasks, and the first click loads the feature (src/lib/features/pm/).
|
||||
*/
|
||||
openIn: { plugin: "menu:Plug-in views", native: "ribbon:Project Management" },
|
||||
title: "Project Management",
|
||||
card: { plugin: ".pm-card", native: ".pm-card" },
|
||||
minCards: 50,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
/** The value of a table entry for `mode`. */
|
||||
export const pick = (value, mode) => value && typeof value === "object" && !Array.isArray(value) && ("plugin" in value || "native" in value) ? value[mode] : value;
|
||||
|
||||
const escape = text => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
const starts = text => new RegExp(`^${escape(text)}`);
|
||||
|
||||
/** Wait until the page has at least `count` elements for `selector`. The predicate is synchronous on purpose. */
|
||||
export function waitForCount(page, selector, count, timeout = 60000) {
|
||||
return page.waitForFunction(([selector, count]) => document.querySelectorAll(selector).length >= count, [selector, count], { timeout, polling: 100 });
|
||||
}
|
||||
|
||||
/** Open a command from the command palette by its exact title. */
|
||||
export async function runPaletteCommand(page, title) {
|
||||
await page.keyboard.press(TABLE.palette.shortcut);
|
||||
const input = page.getByRole("textbox", { name: TABLE.palette.input, exact: true });
|
||||
await input.waitFor({ timeout: 10000 });
|
||||
await input.fill(title);
|
||||
await page.getByRole("button", { name: starts(title) }).first().waitFor({ timeout: 10000 });
|
||||
await input.press("Enter");
|
||||
}
|
||||
|
||||
/**
|
||||
* Run a command from the palette, from a ribbon menu, or from a ribbon button.
|
||||
* `where` is `palette`, `menu:<menu name>`, or `ribbon:<button name>`.
|
||||
*/
|
||||
export async function runCommand(page, where, title) {
|
||||
if (where === "palette") return runPaletteCommand(page, title);
|
||||
const button = /^ribbon:(.+)$/.exec(where)?.[1];
|
||||
if (button) return page.locator(".plugin-ribbon").getByRole("button", { name: button, exact: true }).click();
|
||||
const menu = /^menu:(.+)$/.exec(where)?.[1];
|
||||
if (!menu) throw new Error(`Unknown command place ${where}.`);
|
||||
await page.locator(".plugin-ribbon").getByRole("button", { name: menu, exact: true }).click();
|
||||
await page.getByRole("menuitem", { name: starts(title) }).first().click();
|
||||
}
|
||||
|
||||
/**
|
||||
* The in-use action of each feature. Each action returns when its ready condition is true.
|
||||
* `ctx` has `mode` and `log`. Some actions return details for the sample.
|
||||
*/
|
||||
export const ACTIONS = {
|
||||
async git(page, { mode }) {
|
||||
const git = TABLE.features.git;
|
||||
await page.getByRole("button", { name: git.navigation, exact: true }).first().click();
|
||||
await waitForCount(page, pick(git.changeRow, mode), git.changeCount);
|
||||
await page.locator(pick(git.changeFile, mode)).first().click();
|
||||
await page.getByRole("tab", { name: starts(git.diffTab) }).first().waitFor({ timeout: 30000 });
|
||||
await page.getByText(git.diffText).first().waitFor({ timeout: 30000 });
|
||||
await runCommand(page, pick(git.graphCommandIn, mode), git.graphCommand);
|
||||
await page.getByRole("tab", { name: starts(git.graphTab) }).first().waitFor({ timeout: 30000 });
|
||||
await page.getByText(git.graphText, { exact: true }).first().waitFor({ timeout: 30000 });
|
||||
return { changeRows: await page.locator(pick(git.changeRow, mode)).count() };
|
||||
},
|
||||
async background(page, { mode }) {
|
||||
const background = TABLE.features.background;
|
||||
const property = pick(background.imageProperty, mode);
|
||||
const started = Date.now();
|
||||
// Count the changes in the page, so a short image does not slip between two Node polls.
|
||||
await page.evaluate(property => {
|
||||
const state = { values: [], times: [] };
|
||||
const sample = () => {
|
||||
const value = document.body.style.getPropertyValue(property);
|
||||
if (value && value !== state.values.at(-1)) { state.values.push(value); state.times.push(performance.now()); }
|
||||
};
|
||||
sample();
|
||||
state.timer = setInterval(sample, 100);
|
||||
window.__rsBackgroundProbe = state;
|
||||
}, property);
|
||||
const timeout = (background.changes + 2) * background.seconds * 1000 + 30000;
|
||||
await page.waitForFunction(changes => (window.__rsBackgroundProbe?.values.length ?? 0) >= changes + 1, background.changes, { timeout, polling: 250 });
|
||||
const result = await page.evaluate(() => {
|
||||
const state = window.__rsBackgroundProbe;
|
||||
clearInterval(state.timer);
|
||||
return { images: state.values.length, intervalsMs: state.times.slice(1).map((time, index) => Math.round(time - state.times[index])) };
|
||||
});
|
||||
return { ...result, waitedMs: Date.now() - started };
|
||||
},
|
||||
async terminal(page) {
|
||||
const terminal = TABLE.features.terminal;
|
||||
await page.locator(terminal.ribbon).getByRole("button", { name: terminal.button, exact: true }).click();
|
||||
await page.locator(terminal.surface).first().waitFor({ timeout: 30000 });
|
||||
await page.waitForFunction(([rows, prompt]) => new RegExp(prompt).test((document.querySelector(rows)?.textContent ?? "").replace(/\u00a0/g, " ")), [terminal.rows, terminal.prompt], { timeout: 60000, polling: 100 });
|
||||
await page.locator(terminal.surface).first().click();
|
||||
await page.keyboard.type(terminal.command);
|
||||
await page.keyboard.press("Enter");
|
||||
await page.waitForFunction(([rows, text]) => (document.querySelector(rows)?.textContent ?? "").replace(/\u00a0/g, " ").includes(text), [terminal.rows, terminal.readyText], { timeout: 120000, polling: 100 });
|
||||
},
|
||||
async pdf(page) {
|
||||
const pdf = TABLE.features.pdf;
|
||||
await page.locator(pdf.row).click();
|
||||
await page.getByRole("img", { name: pdf.firstPage, exact: true }).waitFor({ timeout: 60000 });
|
||||
const input = page.getByRole("textbox", { name: pdf.pageInput, exact: true }).or(page.getByRole("spinbutton", { name: pdf.pageInput, exact: true })).first();
|
||||
await input.fill(String(pdf.target));
|
||||
await input.press("Enter");
|
||||
await page.getByRole("img", { name: pdf.targetPage, exact: true }).waitFor({ timeout: 60000 });
|
||||
},
|
||||
async pm(page, { mode }) {
|
||||
const pm = TABLE.features.pm;
|
||||
await runCommand(page, pick(pm.openIn, mode), pm.title);
|
||||
await waitForCount(page, pick(pm.card, mode), pm.minCards);
|
||||
return { cards: await page.locator(pick(pm.card, mode)).count() };
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,279 @@
|
||||
#!/usr/bin/env node
|
||||
// Measure the RAM and the response times of the optional features, each feature off and on.
|
||||
// The tool starts a test build with an isolated identifier, drives it through CDP, and stops only the process tree that it started.
|
||||
// Run `node scripts/measureFeatures.mjs --help` for the arguments. The results go to output/phase-7/<stage>/.
|
||||
import { existsSync } from "node:fs";
|
||||
import { realpathSync } from "node:fs";
|
||||
import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { setTimeout as sleep } from "node:timers/promises";
|
||||
import { fileURLToPath, pathToFileURL } from "node:url";
|
||||
import { checkTarget, FEATURES, markdownTable, parseArguments, SCENARIOS, summarize, USAGE } from "./measure/core.mjs";
|
||||
import { inspectPmBoards, prepareFixture } from "./measure/fixture.mjs";
|
||||
import { startGiteaServer } from "./measure/giteaServer.mjs";
|
||||
import { ACTIONS, TABLE } from "./measure/scenarios.mjs";
|
||||
|
||||
const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const IDLE_MS = 15000;
|
||||
const GC_SETTLE_MS = 5000;
|
||||
// Plugins load after the workbench shows. Each run waits this long after the start, so the action measures the feature and not the plugin load.
|
||||
const START_SETTLE_MS = 5000;
|
||||
const log = message => console.log(`[${new Date().toISOString().slice(11, 19)}] ${message}`);
|
||||
|
||||
async function machine() {
|
||||
return { cpu: os.cpus()[0]?.model?.trim() ?? "unknown", cores: os.cpus().length, ramGB: os.totalmem() / 1024 ** 3, windows: `${os.version()} ${os.release()}`, node: process.version };
|
||||
}
|
||||
|
||||
/** Remove the data folders of the test identity. `checkTarget` made the paths from the test identifier. */
|
||||
async function resetData(folders, identifier) {
|
||||
for (const folder of [folders.roaming, folders.local]) {
|
||||
if (path.win32.basename(folder) !== identifier) throw new Error(`Refusing to remove ${folder}.`);
|
||||
for (let attempt = 0; ; attempt++) {
|
||||
try { await rm(folder, { recursive: true, force: true }); break; } catch (error) {
|
||||
if (attempt >= 20) throw new Error(`Cannot reset ${folder}: ${error.message}`);
|
||||
await sleep(500);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Write the folder grant and the settings of Background Slideshow before the first start. */
|
||||
async function seedBackgroundPlugin(folders, backgrounds) {
|
||||
const id = TABLE.features.background.plugin.id;
|
||||
const folder = path.join(folders.roaming, "plugin-data", id);
|
||||
await mkdir(folder, { recursive: true });
|
||||
const grant = "6f0c7a8e-5b1d-4c2e-9a3f-2d7b8e1c4a90";
|
||||
await writeFile(path.join(folder, "folder-grants.json"), JSON.stringify({ schema: 1, grants: [{ id: grant, path: backgrounds }] }, null, 2));
|
||||
await writeFile(path.join(folder, "settings.json"), JSON.stringify({ grant, folder: backgrounds, seconds: TABLE.features.background.seconds, order: "name", enabled: true, targets: ["app"], overlay: 0, position: "center", size: "cover" }));
|
||||
}
|
||||
|
||||
/**
|
||||
* Write the `background` settings and the host folder file of the native Background before the first start
|
||||
* (src/lib/features/backgroundSettings.ts and src-tauri/src/backgrounds.rs). The settings file has no other section,
|
||||
* so the first start keeps it and migrates only the feature switches.
|
||||
*/
|
||||
async function seedBackgroundNative(folders, backgrounds) {
|
||||
await mkdir(folders.roaming, { recursive: true });
|
||||
const background = { source: "folder", seconds: TABLE.features.background.seconds, order: "name", paused: false, targets: ["app"], overlay: 0, position: "center", size: "cover" };
|
||||
await writeFile(path.join(folders.roaming, "settings.json"), JSON.stringify({ schema: 1, revision: 1, background }, null, 2) + "\n");
|
||||
// The host accepts the folder only at its resolved path.
|
||||
await writeFile(path.join(folders.roaming, "background-folder.json"), JSON.stringify({ schema: 1, path: realpathSync.native(backgrounds) }, null, 2));
|
||||
}
|
||||
|
||||
/** The features that are on in the running app. */
|
||||
async function readState(app, mode, invoke) {
|
||||
if (mode === "plugin") {
|
||||
const snapshot = await invoke(app.page, "plugins_snapshot");
|
||||
return new Set(FEATURES.filter(feature => snapshot.plugins.some(row => row.manifest.id === TABLE.features[feature].plugin.id && row.enabled)));
|
||||
}
|
||||
const file = await invoke(app.page, "settings_read");
|
||||
const section = file?.sections?.[TABLE.featuresSection] ?? {};
|
||||
return new Set(FEATURES.filter(feature => section[TABLE.features[feature].nativeKey] === true));
|
||||
}
|
||||
|
||||
/** Turn on exactly the features in `enabled`, and turn off the others. */
|
||||
async function applyState(app, mode, enabled, invoke) {
|
||||
if (mode === "plugin") {
|
||||
const snapshot = await invoke(app.page, "plugins_snapshot");
|
||||
for (const row of snapshot.plugins) {
|
||||
const feature = FEATURES.find(item => TABLE.features[item].plugin.id === row.manifest.id);
|
||||
const want = feature ? enabled.has(feature) : false;
|
||||
if (row.enabled !== want) await invoke(app.page, "plugins_set_enabled", { id: row.manifest.id, enabled: want, hash: want ? row.hash : null });
|
||||
}
|
||||
return;
|
||||
}
|
||||
const file = await invoke(app.page, "settings_read");
|
||||
const value = { ...(file?.sections?.[TABLE.featuresSection] ?? {}) };
|
||||
for (const feature of FEATURES) value[TABLE.features[feature].nativeKey] = enabled.has(feature);
|
||||
await invoke(app.page, "settings_write", { section: TABLE.featuresSection, value });
|
||||
}
|
||||
|
||||
const sameSet = (a, b) => a.size === b.size && [...a].every(item => b.has(item));
|
||||
|
||||
/** Install the plugins of `features` from the fake Gitea server. */
|
||||
async function installPlugins(app, features, invoke) {
|
||||
const packages = features.map(feature => TABLE.features[feature].plugin);
|
||||
for (const item of packages) if (!existsSync(item.zip)) throw new Error(`No plugin ZIP at ${item.zip}.`);
|
||||
const server = await startGiteaServer(packages.map(item => ({ repo: item.repo, tag: item.tag, file: item.zip })));
|
||||
try {
|
||||
for (const item of packages) {
|
||||
const rows = await invoke(app.page, "plugins_from_git", { url: server.repository(item.repo), tag: item.tag, token: null });
|
||||
if (rows.length !== 1 || rows[0].error || !rows[0].token) throw new Error(`plugins_from_git for ${item.repo}: ${JSON.stringify(rows)}`);
|
||||
if (rows[0].manifest?.id !== item.id) throw new Error(`The ZIP of ${item.repo} has the ID ${rows[0].manifest?.id}, not ${item.id}.`);
|
||||
const results = await invoke(app.page, "plugins_install", { tokens: [rows[0].token], enabled: true });
|
||||
if (results.some(result => result.error)) throw new Error(`plugins_install for ${item.id}: ${JSON.stringify(results)}`);
|
||||
log(`Installed ${item.id} from ${server.repository(item.repo)}.`);
|
||||
}
|
||||
} finally { await server.close(); }
|
||||
const snapshot = await invoke(app.page, "plugins_snapshot");
|
||||
const missing = packages.filter(item => !snapshot.plugins.some(row => row.manifest.id === item.id && !row.error));
|
||||
if (missing.length) throw new Error(`Plugins missing after the install: ${missing.map(item => item.id).join(", ")}.`);
|
||||
return snapshot.plugins.map(row => ({ id: row.manifest.id, version: row.manifest.version, hash: row.hash }));
|
||||
}
|
||||
|
||||
export async function main(argv = process.argv.slice(2)) {
|
||||
if (argv.includes("--help")) { console.log(USAGE); return; }
|
||||
const options = parseArguments(argv);
|
||||
const exe = path.resolve(options.exe);
|
||||
const folders = checkTarget({ exe, identifier: options.identifier });
|
||||
if (!existsSync(exe)) throw new Error(`No executable at ${exe}.`);
|
||||
// Load the app module after the refusals, so the refusals work without Playwright.
|
||||
const app = await import("./measure/app.mjs");
|
||||
const output = path.join(repoRoot, "output", "phase-7", options.stage);
|
||||
await mkdir(output, { recursive: true });
|
||||
const fixture = await prepareFixture({ fresh: options.freshFixture, log });
|
||||
const pm = await inspectPmBoards(fixture.workspace);
|
||||
if (pm.checked && JSON.parse(pm.output).workspaces[0].boards.length !== 8) throw new Error("The Project Management fixture does not show 8 boards.");
|
||||
|
||||
const reportPath = path.join(output, "memory.json");
|
||||
const previous = options.only && existsSync(reportPath) ? JSON.parse(await readFile(reportPath, "utf8")) : null;
|
||||
const report = {
|
||||
stage: options.stage, mode: options.mode, build: exe, identifier: options.identifier, date: new Date().toISOString(), runs: options.runs,
|
||||
machine: await machine(), fixture, method: {
|
||||
idleMs: IDLE_MS, gcSettleMs: GC_SETTLE_MS, startSettleMs: START_SETTLE_MS,
|
||||
action: "Each run waits startSettleMs after the start, then starts the action. First need is the time from the start of the action to its ready condition.",
|
||||
memory: "Win32_Process PrivatePageCount and WorkingSetSize, summed over the descendants of the started process.",
|
||||
heap: "CDP Runtime.getHeapUsage usedSize of the main page after HeapProfiler.collectGarbage. Workers and other pages are not included.",
|
||||
start: `From the spawn to the visible tree row ${TABLE.knownRow}.`,
|
||||
longTasks: "PerformanceObserver longtask in the main page, from the start of the action to its end. For on-idle and base, over the idle wait.",
|
||||
},
|
||||
plugins: previous?.plugins ?? null, setup: {}, rows: previous?.rows ?? [], notes: previous?.notes ?? [],
|
||||
};
|
||||
const save = async () => {
|
||||
report.date = new Date().toISOString();
|
||||
await writeFile(reportPath, JSON.stringify(report, null, 2) + "\n");
|
||||
await writeFile(path.join(output, "memory.md"), markdownTable(report));
|
||||
};
|
||||
const wanted = (feature, scenario) => !options.only || options.only.includes(feature === "base" ? "base" : `${feature}:${scenario}`);
|
||||
|
||||
// The plan: base runs with every feature off, then each feature scenario with only that feature on.
|
||||
const plan = [];
|
||||
if (wanted("base") && !options.skipBase) for (let run = 1; run <= options.runs; run++) plan.push({ feature: "base", scenario: "base", run, enabled: new Set() });
|
||||
const featurePlan = [];
|
||||
for (const feature of options.features) for (const scenario of SCENARIOS) if (wanted(feature, scenario)) for (let run = 1; run <= options.runs; run++) featurePlan.push({ feature, scenario, run, enabled: new Set([feature]) });
|
||||
|
||||
log(`Resetting ${folders.roaming} and ${folders.local}.`);
|
||||
await resetData(folders, options.identifier);
|
||||
if (options.mode === "plugin" && options.features.includes("background")) await seedBackgroundPlugin(folders, fixture.backgrounds);
|
||||
if (options.mode === "native" && options.features.includes("background")) await seedBackgroundNative(folders, fixture.backgrounds);
|
||||
|
||||
// The setup start opens the workspace. It also proves the test identity.
|
||||
let session = await app.launch({ exe, port: options.port });
|
||||
try {
|
||||
if (!app.hasWebviewFolder(folders.local)) throw new Error(`${app.webviewFolder(folders.local)} does not exist. The executable does not use the identifier ${options.identifier}.`);
|
||||
const snapshot = await app.invoke(session.page, "plugins_snapshot");
|
||||
if (!path.resolve(snapshot.root).toLowerCase().startsWith(path.resolve(folders.roaming).toLowerCase())) throw new Error(`The app data folder ${snapshot.root} is not in ${folders.roaming}.`);
|
||||
report.setup.identity = { webview: app.webviewFolder(folders.local), pluginRoot: snapshot.root };
|
||||
await app.invoke(session.page, "workspace_open", { path: fixture.workspace });
|
||||
await session.page.evaluate(layout => localStorage.setItem("runestone.workbenchLayout", JSON.stringify(layout)), TABLE.layout);
|
||||
await session.page.reload();
|
||||
await session.page.locator(TABLE.knownRow).waitFor({ timeout: 60000 });
|
||||
if (options.mode === "native") await applyState(session, "native", new Set(), app.invoke);
|
||||
await app.clearViewState(session.page);
|
||||
} finally { await app.stop(session); }
|
||||
log("Setup done: workspace open, identity confirmed.");
|
||||
|
||||
const rowFor = (feature, scenario) => {
|
||||
let row = report.rows.find(item => item.feature === feature && item.scenario === scenario);
|
||||
if (!row) { row = { feature, scenario, samples: [], median: null }; report.rows.push(row); }
|
||||
return row;
|
||||
};
|
||||
for (const item of [...plan, ...featurePlan]) {
|
||||
const row = rowFor(item.feature, item.scenario);
|
||||
if (item.run === 1) { row.samples = []; row.median = null; delete row.reason; }
|
||||
}
|
||||
// Keep the row order stable: base first, then each feature in the order of FEATURES and SCENARIOS.
|
||||
const rank = row => row.feature === "base" ? -1 : FEATURES.indexOf(row.feature) * 10 + SCENARIOS.indexOf(row.scenario);
|
||||
report.rows.sort((a, b) => rank(a) - rank(b));
|
||||
await save();
|
||||
|
||||
let installed = options.mode === "native";
|
||||
const runAll = async list => {
|
||||
for (const [index, item] of list.entries()) {
|
||||
const next = list[index + 1];
|
||||
const row = rowFor(item.feature, item.scenario);
|
||||
log(`${item.feature} ${item.scenario}, run ${item.run} of ${options.runs}.`);
|
||||
const sample = await measure(item, next, options.mode).catch(error => ({ run: item.run, error: String(error?.stack ?? error).split("\n").slice(0, 3).join(" | ") }));
|
||||
if (sample.error) log(` failed: ${sample.error}`);
|
||||
else log(` private ${sample.privateMB.toFixed(1)} MB, working set ${sample.workingSetMB.toFixed(1)} MB, heap ${sample.heapMB.toFixed(1)} MB, start ${Math.round(sample.startMs)} ms, first need ${sample.firstNeedMs === null ? "–" : Math.round(sample.firstNeedMs)} ms`);
|
||||
row.samples.push(sample);
|
||||
row.median = summarize(row.samples);
|
||||
if (row.median.failed === row.median.runs) row.reason = row.samples.find(item => item.error)?.error;
|
||||
else delete row.reason;
|
||||
await save();
|
||||
}
|
||||
};
|
||||
|
||||
/** One measured run in a new app process. Before the stop, it prepares the feature state of `next`. */
|
||||
async function measure(item, next, mode, retry = true) {
|
||||
const session = await app.launch({ exe, port: options.port });
|
||||
const sample = { run: item.run, pid: session.pid, cdpMs: Math.round(session.cdpMs) };
|
||||
let prepared = false;
|
||||
try {
|
||||
Object.assign(sample, await app.waitForWorkbench(session));
|
||||
const state = await readState(session, mode, app.invoke);
|
||||
if (!sameSet(state, item.enabled)) {
|
||||
// A failed run can leave another state. Fix it and start again.
|
||||
if (!retry) throw new Error(`The feature state is ${[...state].join(",") || "none"}, not ${[...item.enabled].join(",") || "none"}.`);
|
||||
await applyState(session, mode, item.enabled, app.invoke);
|
||||
await app.clearViewState(session.page);
|
||||
prepared = true;
|
||||
await app.stop(session);
|
||||
return measure(item, next, mode, false);
|
||||
}
|
||||
await sleep(START_SETTLE_MS);
|
||||
await app.observeLongTasks(session.page);
|
||||
sample.firstNeedMs = null;
|
||||
if (item.scenario === "in-use" || item.scenario === "after-off") {
|
||||
const begin = performance.now();
|
||||
sample.details = await ACTIONS[item.feature](session.page, { mode, log }) ?? null;
|
||||
sample.firstNeedMs = performance.now() - begin;
|
||||
if (item.scenario === "after-off") await applyState(session, mode, new Set(), app.invoke);
|
||||
const tasks = await app.collectLongTasks(session.page);
|
||||
await sleep(IDLE_MS);
|
||||
Object.assign(sample, { longTaskCount: tasks?.count ?? null, longTaskMaxMs: tasks?.maxMs ?? null });
|
||||
} else {
|
||||
await sleep(IDLE_MS);
|
||||
const tasks = await app.collectLongTasks(session.page);
|
||||
Object.assign(sample, { longTaskCount: tasks?.count ?? null, longTaskMaxMs: tasks?.maxMs ?? null });
|
||||
}
|
||||
Object.assign(sample, await app.readMemory(session, { settleMs: GC_SETTLE_MS }));
|
||||
return sample;
|
||||
} catch (error) {
|
||||
const shot = path.join(output, `failure-${item.feature}-${item.scenario}-${item.run}.png`);
|
||||
await session.page.screenshot({ path: shot }).catch(() => {});
|
||||
throw error;
|
||||
} finally {
|
||||
if (!prepared) {
|
||||
try {
|
||||
await applyState(session, mode, next?.enabled ?? new Set(), app.invoke);
|
||||
await app.clearViewState(session.page);
|
||||
} catch (error) { log(` cleanup: ${error.message}`); }
|
||||
await app.stop(session);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await runAll(plan);
|
||||
if (featurePlan.length && !installed) {
|
||||
session = await app.launch({ exe, port: options.port });
|
||||
try {
|
||||
await session.page.locator(TABLE.knownRow).waitFor({ timeout: 60000 });
|
||||
report.plugins = await installPlugins(session, options.features, app.invoke);
|
||||
await session.page.reload();
|
||||
await session.page.locator(TABLE.knownRow).waitFor({ timeout: 60000 });
|
||||
await applyState(session, "plugin", featurePlan[0].enabled, app.invoke);
|
||||
await app.clearViewState(session.page);
|
||||
} finally { await app.stop(session); }
|
||||
installed = true;
|
||||
await save();
|
||||
}
|
||||
await runAll(featurePlan);
|
||||
await save();
|
||||
log(`Wrote ${reportPath} and ${path.join(output, "memory.md")}.`);
|
||||
}
|
||||
|
||||
if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {
|
||||
main().catch(error => { console.error(error?.stack ?? String(error)); process.exitCode = 1; });
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { readdir, readFile } from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const root = fileURLToPath(new URL('../', import.meta.url));
|
||||
const pluginRepos = process.env.RUNESTONE_PLUGIN_REPOS || path.resolve(root, '..');
|
||||
export const projects = ['RuneStone', 'RuneStone_Local_Autocomplete', 'RuneStone_CSV_Viewer'];
|
||||
const patterns = {
|
||||
action: /\b(?:showActionMenu|actionMenu)\s*\(/g,
|
||||
svelteMenu: /<ContextMenu\b/g,
|
||||
nativeChoice: /<select\b|(?:createElement|el)\(\s*['"]select['"]/g,
|
||||
picker: /rs-picker(?:[\s"']|$)|role=['"]listbox['"]|setAttribute\(\s*['"]role['"],\s*['"]listbox['"]/g,
|
||||
localPopup: /(?:class|className)\s*=\s*['"][^'"\n]*(?:menu|picker|popup)|\.popover\s*=/g,
|
||||
};
|
||||
async function files(dir) {
|
||||
const entries = await readdir(dir, { withFileTypes: true });
|
||||
const results = await Promise.all(entries.filter(entry => !entry.isSymbolicLink()).map(entry => entry.isDirectory()
|
||||
? files(path.join(dir, entry.name)) : /\.(svelte|[cm]?[jt]s)$/.test(entry.name) ? [path.join(dir, entry.name)] : []));
|
||||
return results.flat();
|
||||
}
|
||||
export async function discover() {
|
||||
const surfaces = {}, missing = [];
|
||||
for (const project of projects) {
|
||||
const base = project === 'RuneStone' ? root : path.resolve(pluginRepos, project);
|
||||
let sources;
|
||||
try { sources = await files(path.join(base, 'src')); } catch (error) { if (error.code === 'ENOENT') { missing.push(project); continue; } throw error; }
|
||||
// The plugin SDK declares the public menu API of RuneStone.
|
||||
if (project === 'RuneStone') sources.push(...await files(path.join(base, 'packages/plugin-sdk/src')));
|
||||
for (const file of sources) {
|
||||
const source = await readFile(file, 'utf8');
|
||||
const counts = Object.fromEntries(Object.entries(patterns).map(([name, pattern]) => [name, [...source.matchAll(pattern)].length]).filter(([, count]) => count));
|
||||
if (Object.keys(counts).length) surfaces[`${project}/${path.relative(base, file).replaceAll('\\', '/')}`] = counts;
|
||||
}
|
||||
}
|
||||
return { surfaces, missing };
|
||||
}
|
||||
export async function checkInventory() {
|
||||
const { surfaces, missing } = await discover();
|
||||
const inventory = JSON.parse(await readFile(path.join(root, 'docs/menu-surfaces.json'), 'utf8'));
|
||||
const failures = missing.map(project => `Missing checkout: ${project}`);
|
||||
for (const [file, counts] of Object.entries(surfaces)) {
|
||||
const entry = inventory.surfaces[file];
|
||||
if (!entry) failures.push(`Unreviewed surface: ${file}`);
|
||||
else if (JSON.stringify(counts) !== JSON.stringify(entry.counts)) failures.push(`Changed entry points: ${file}`);
|
||||
else if (!entry.design || !entry.check) failures.push(`Missing design or check: ${file}`);
|
||||
}
|
||||
for (const file of Object.keys(inventory.surfaces)) if (!(file in surfaces)) failures.push(`Stale inventory: ${file}`);
|
||||
if (failures.length) { console.error(failures.join('\n')); return false; }
|
||||
console.log(`PASS: ${Object.keys(surfaces).length} source files across ${projects.length} projects match the reviewed menu inventory. Runtime checks remain separate.`);
|
||||
return true;
|
||||
}
|
||||
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||
if (process.argv.includes('--discover')) console.log(JSON.stringify(await discover(), null, 2));
|
||||
else if (!await checkInventory()) process.exitCode = 1;
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
import { lstat, readdir, readFile, mkdir, writeFile, realpath, link, unlink } from "node:fs/promises";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { resolve, relative, isAbsolute, join, dirname } from "node:path";
|
||||
import { pathToFileURL } from "node:url";
|
||||
import { crc32, deflateRawSync } from "node:zlib";
|
||||
|
||||
const MiB = 1024 * 1024;
|
||||
const device = /^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])$/i;
|
||||
function validPath(name) {
|
||||
return name.length <= 180 && name.split("/").every(part =>
|
||||
part.length > 0 && part.length <= 120 && /^[a-zA-Z0-9._-]+$/.test(part)
|
||||
&& !part.endsWith(".") && !device.test(part.split(".")[0]));
|
||||
}
|
||||
function requireValue(condition, message) {
|
||||
if (!condition) throw new Error(message);
|
||||
}
|
||||
|
||||
// ZIP32 with DEFLATE, fixed timestamps, and sorted paths gives repeatable release files.
|
||||
function zip(files) {
|
||||
const local = [], central = [];
|
||||
let offset = 0, centralSize = 0;
|
||||
for (const [path, bytes] of files) {
|
||||
const name = Buffer.from(path);
|
||||
const compressed = deflateRawSync(bytes, { level: 9 });
|
||||
const header = Buffer.alloc(30);
|
||||
header.writeUInt32LE(0x04034b50, 0);
|
||||
header.writeUInt16LE(20, 4);
|
||||
header.writeUInt16LE(8, 8);
|
||||
header.writeUInt16LE(33, 12); // January 1, 1980.
|
||||
header.writeUInt32LE(crc32(bytes), 14);
|
||||
header.writeUInt32LE(compressed.length, 18);
|
||||
header.writeUInt32LE(bytes.length, 22);
|
||||
header.writeUInt16LE(name.length, 26);
|
||||
local.push(header, name, compressed);
|
||||
const record = Buffer.alloc(46);
|
||||
record.writeUInt32LE(0x02014b50, 0);
|
||||
record.writeUInt16LE(20, 4);
|
||||
header.copy(record, 6, 4, 30);
|
||||
record.writeUInt32LE(offset, 42);
|
||||
central.push(record, name);
|
||||
offset += header.length + name.length + compressed.length;
|
||||
centralSize += record.length + name.length;
|
||||
}
|
||||
const end = Buffer.alloc(22);
|
||||
end.writeUInt32LE(0x06054b50, 0);
|
||||
end.writeUInt16LE(files.length, 8);
|
||||
end.writeUInt16LE(files.length, 10);
|
||||
end.writeUInt32LE(centralSize, 12);
|
||||
end.writeUInt32LE(offset, 16);
|
||||
return Buffer.concat([...local, ...central, end]);
|
||||
}
|
||||
|
||||
export async function packagePlugin(source, destination) {
|
||||
const input = resolve(source);
|
||||
let project = input;
|
||||
if (!destination) {
|
||||
while (true) {
|
||||
try { await readFile(join(project, "package.json")); break; }
|
||||
catch (error) {
|
||||
if (error.code !== "ENOENT") throw error;
|
||||
const parent = dirname(project);
|
||||
requireValue(parent !== project, "Pass an output folder when the compiled folder has no project root.");
|
||||
project = parent;
|
||||
}
|
||||
}
|
||||
}
|
||||
const output = resolve(destination ?? join(project, "releases"));
|
||||
const inputMeta = await lstat(input);
|
||||
requireValue(inputMeta.isDirectory() && !inputMeta.isSymbolicLink(), "Select a compiled plugin folder.");
|
||||
const files = [], names = new Set();
|
||||
let total = 0, count = 0;
|
||||
async function walk(directory, prefix = "") {
|
||||
for (const entry of (await readdir(directory)).sort()) {
|
||||
const name = prefix + entry;
|
||||
requireValue(validPath(name), `Invalid package path: ${name}`);
|
||||
requireValue(!names.has(name.toLowerCase()), `Duplicate package path: ${name}`);
|
||||
names.add(name.toLowerCase());
|
||||
requireValue(++count <= 5000, "The package exceeds 5,000 entries.");
|
||||
const path = join(directory, entry), meta = await lstat(path);
|
||||
requireValue(!meta.isSymbolicLink(), `Remove the link from the package: ${name}`);
|
||||
if (meta.isDirectory()) await walk(path, name + "/");
|
||||
else {
|
||||
requireValue(meta.isFile() && meta.size <= 25 * MiB, `Invalid or oversized package file: ${name}`);
|
||||
const bytes = await readFile(path);
|
||||
requireValue(bytes.length <= 25 * MiB, `The file exceeds 25 MiB: ${name}`);
|
||||
total += bytes.length;
|
||||
requireValue(total <= 100 * MiB, "The package exceeds 100 MiB of expanded data.");
|
||||
files.push([name, bytes]);
|
||||
}
|
||||
}
|
||||
}
|
||||
await walk(input);
|
||||
const manifestBytes = files.find(([name]) => name === "plugin.json")?.[1];
|
||||
requireValue(manifestBytes && manifestBytes.length <= 64 * 1024, "The package needs plugin.json at its root, within 64 KiB.");
|
||||
const manifest = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(manifestBytes));
|
||||
requireValue(typeof manifest.id === "string" && validPath(manifest.id) && /^[a-z][a-z0-9.-]*$/.test(manifest.id), "The plugin ID is invalid.");
|
||||
requireValue(manifest.schemaVersion === 1 && manifest.apiVersion === 1 && manifest.access === "full-app", "Unsupported schema, API version, or access mode.");
|
||||
for (const key of ["name", "author", "description", "version"]) {
|
||||
requireValue(typeof manifest[key] === "string" && manifest[key].trim() && Buffer.byteLength(manifest[key]) <= 1000, `The manifest needs a valid ${key}.`);
|
||||
}
|
||||
requireValue(/^\d+\.\d+\.\d+[a-z]*$/.test(manifest.version), "Use a plugin version such as 1.0.0 or 1.0.0a.");
|
||||
requireValue(typeof manifest.entry === "string" && validPath(manifest.entry) && /\.m?js$/.test(manifest.entry), "The entry must be a compiled JavaScript module.");
|
||||
const entry = files.find(([name]) => name === manifest.entry)?.[1];
|
||||
requireValue(entry, "The entry module is missing.");
|
||||
new TextDecoder("utf-8", { fatal: true }).decode(entry);
|
||||
const filename = `${manifest.id}-${manifest.version}.zip`;
|
||||
requireValue(filename.length <= 240, "The release filename is too long.");
|
||||
await mkdir(output, { recursive: true });
|
||||
const target = join(await realpath(output), filename);
|
||||
const within = relative(await realpath(input), target);
|
||||
requireValue(isAbsolute(within) || within === ".." || within.startsWith("../") || within.startsWith("..\\"), "Choose an output folder outside the plugin folder.");
|
||||
const archive = zip(files.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0));
|
||||
requireValue(archive.length <= 100 * MiB, "The archive exceeds 100 MiB.");
|
||||
const temporary = `${target}.${randomUUID()}.tmp`;
|
||||
try {
|
||||
await writeFile(temporary, archive, { flag: "wx" });
|
||||
try {
|
||||
await link(temporary, target);
|
||||
} catch (error) {
|
||||
if (error.code !== "EEXIST") throw error;
|
||||
requireValue((await readFile(target)).equals(archive), "The release file already contains different contents: " + target);
|
||||
}
|
||||
} finally {
|
||||
await unlink(temporary).catch(error => { if (error.code !== "ENOENT") throw error; });
|
||||
}
|
||||
return target;
|
||||
}
|
||||
|
||||
if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
|
||||
try {
|
||||
requireValue(process.argv[2] && process.argv.length <= 4, "Usage: node scripts/packagePlugin.mjs <compiled-folder> [output-folder]");
|
||||
console.log(await packagePlugin(process.argv[2], process.argv[3]));
|
||||
} catch (error) {
|
||||
console.error(error.message);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
// Packs the plugin SDK into a release file that plugins install from its URL. See docs/releases.md#sdk-releases.
|
||||
// Usage: node scripts/releaseSdk.mjs --release-url <folder URL> --version <version> [--dry-run]
|
||||
// The script writes releases/plugin-sdk/<version>/. It never uploads. It prints the dependency line for plugins.
|
||||
import fs from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import zlib from 'node:zlib';
|
||||
import { execFile } from 'node:child_process';
|
||||
import { realpathSync } from 'node:fs';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { compareReleases, releaseVersion } from './releaseVersion.mjs';
|
||||
import { buildSdk, sdkFolder } from './buildSdk.mjs';
|
||||
|
||||
const exists = file => fs.access(file).then(() => true, () => false);
|
||||
export const packageName = '@runestone/plugin-sdk';
|
||||
// The files beside dist/ and package.json in the package. LICENSE and README.md are required. NOTICE is optional.
|
||||
export const packageFiles = ['README.md', 'LICENSE', 'NOTICE'];
|
||||
// The fixed file time of npm packages, 1985-10-26 08:15 UTC, in seconds.
|
||||
export const packageTime = 499162500;
|
||||
|
||||
export function parseArguments(args) {
|
||||
const options = { version: undefined, releaseUrl: 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 if (args[i] === '--release-url' && args[i + 1] && !options.releaseUrl) options.releaseUrl = args[++i];
|
||||
else throw Error('Use --release-url followed by the release folder URL, --version followed by the SDK version, and optionally --dry-run.');
|
||||
}
|
||||
if (!options.releaseUrl) throw Error('Use --release-url followed by the URL of the folder that will hold the SDK package.');
|
||||
if (!options.version) throw Error('Use --version followed by the SDK version, for example --version 0.1.2.');
|
||||
return options;
|
||||
}
|
||||
|
||||
// Runs git in a folder and returns its output without the final line break. Rejects when git fails.
|
||||
export function git(cwd, args) {
|
||||
return new Promise((resolve, reject) => {
|
||||
execFile('git', ['-C', cwd, ...args], { windowsHide: true, maxBuffer: 16 * 1024 * 1024 }, (error, stdout, stderr) => {
|
||||
if (error) reject(Error(`git ${args.join(' ')} failed in ${cwd}: ${String(stderr || error.message).trim()}`));
|
||||
else resolve(stdout.replace(/\r?\n$/, ''));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// The package.json of the release: the source fields with the new version, without build scripts or development dependencies.
|
||||
export function releasePackageJson(source, version) {
|
||||
const { scripts, devDependencies, ...rest } = source;
|
||||
const result = { ...rest, version };
|
||||
for (const field of ['types', 'exports', 'files', 'license']) if (!result[field]) throw Error(`The SDK package.json has no "${field}" field.`);
|
||||
return result;
|
||||
}
|
||||
|
||||
/** The file name that `npm pack` gives a package: `@scope/name` becomes `scope-name-<version>.tgz`. */
|
||||
export function packageFileName(name, version) {
|
||||
return `${name.replace(/^@/, '').replace('/', '-')}-${version}.tgz`;
|
||||
}
|
||||
|
||||
/** A gzip tar of the entries under `package/`, in name order, with a fixed time and mode. The same entries give the same bytes. */
|
||||
export function packEntries(entries) {
|
||||
const blocks = [];
|
||||
const sorted = [...entries].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
|
||||
for (let i = 1; i < sorted.length; i++) if (sorted[i].name === sorted[i - 1].name) throw Error('The SDK package has two files with the name ' + sorted[i].name);
|
||||
for (const { name, data } of sorted) {
|
||||
const full = Buffer.from('package/' + name, 'utf8');
|
||||
if (full.length > 100) throw Error('The SDK has a file name that is too long for the package: ' + name);
|
||||
if (data.length >= 8 ** 11) throw Error('The SDK has a file that is too large for the package: ' + name);
|
||||
// A ustar header: name, mode, owner, group, size, time, checksum, type, and the magic value.
|
||||
const header = Buffer.alloc(512);
|
||||
full.copy(header, 0);
|
||||
const octal = (value, offset, size) => header.write(value.toString(8).padStart(size - 1, '0') + '\0', offset, size, 'ascii');
|
||||
octal(0o644, 100, 8); octal(0, 108, 8); octal(0, 116, 8); octal(data.length, 124, 12); octal(packageTime, 136, 12);
|
||||
header.write(' ', 148, 8, 'ascii');
|
||||
header.write('0', 156, 1, 'ascii');
|
||||
header.write('ustar\0' + '00', 257, 8, 'ascii');
|
||||
let sum = 0;
|
||||
for (const byte of header) sum += byte;
|
||||
header.write(sum.toString(8).padStart(6, '0') + '\0 ', 148, 8, 'ascii');
|
||||
blocks.push(header, data, Buffer.alloc((512 - data.length % 512) % 512));
|
||||
}
|
||||
blocks.push(Buffer.alloc(1024));
|
||||
return zlib.gzipSync(Buffer.concat(blocks), { level: 9 });
|
||||
}
|
||||
|
||||
/** The SHA-512 value that npm and pnpm record in a lock file. */
|
||||
export const integrity = data => 'sha512-' + createHash('sha512').update(data).digest('base64');
|
||||
|
||||
async function listFiles(folder, prefix = '') {
|
||||
const result = [];
|
||||
for (const entry of await fs.readdir(path.join(folder, prefix), { withFileTypes: true })) {
|
||||
const name = prefix ? `${prefix}/${entry.name}` : entry.name;
|
||||
if (entry.isDirectory()) result.push(...await listFiles(folder, name));
|
||||
else if (entry.isFile()) result.push(name);
|
||||
else throw Error('The SDK build contains a link or a special file: ' + name);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// Checks the preconditions and returns the release plan. Changes no file.
|
||||
/** @param {string} root @param {{ version: string, releaseUrl: string }} options */
|
||||
export async function planSdkRelease(root, { version, releaseUrl }) {
|
||||
const next = releaseVersion(version);
|
||||
const packageDir = path.join(root, sdkFolder);
|
||||
const sourceFile = path.join(packageDir, 'package.json');
|
||||
const source = JSON.parse(await fs.readFile(sourceFile, 'utf8'));
|
||||
if (source.name !== packageName) throw Error(`${sourceFile} is not the ${packageName} package.`);
|
||||
const current = releaseVersion(source.version);
|
||||
if (compareReleases(next.version, current.version) <= 0) throw Error(`The SDK version must be greater than the current version ${current.version}.`);
|
||||
for (const file of ['README.md', 'LICENSE']) {
|
||||
if (!(await exists(path.join(packageDir, file)))) throw Error(`The SDK package has no ${file} file. Add ${path.join(sdkFolder, file)} before a release.`);
|
||||
}
|
||||
const copies = [];
|
||||
for (const file of packageFiles) if (await exists(path.join(packageDir, file))) copies.push(file);
|
||||
if ((await git(root, ['status', '--porcelain', '--untracked-files=all', '--', sdkFolder])) !== '') {
|
||||
throw Error(`${sdkFolder} has changes that are not committed. Commit them first, so that the release has a source commit.`);
|
||||
}
|
||||
const folder = new URL(releaseUrl.endsWith('/') ? releaseUrl : releaseUrl + '/');
|
||||
if (folder.protocol !== 'https:' || folder.username || folder.password || folder.search || folder.hash) {
|
||||
throw Error('Use an HTTPS release URL without credentials, a query, or a fragment.');
|
||||
}
|
||||
const file = packageFileName(packageName, next.version);
|
||||
const releaseDir = path.join(root, 'releases', 'plugin-sdk', next.version);
|
||||
const artifacts = { archive: path.join(releaseDir, file), metadata: path.join(releaseDir, 'sdk.json') };
|
||||
for (const artifact of Object.values(artifacts)) if (await exists(artifact)) throw Error('The release file already exists: ' + artifact);
|
||||
return {
|
||||
root, packageDir, sourceFile, source, current, next, copies, file, releaseDir, artifacts,
|
||||
url: new URL(file, folder).href,
|
||||
hostCommit: await git(root, ['rev-parse', 'HEAD']),
|
||||
packageJson: releasePackageJson(source, next.version),
|
||||
};
|
||||
}
|
||||
|
||||
export function describePlan(plan) {
|
||||
const relative = file => path.relative(plan.root, file);
|
||||
return [
|
||||
`SDK version: ${plan.next.version} (current ${plan.current.version})`,
|
||||
`Source: ${relative(plan.packageDir) || '.'} at RuneStone ${plan.hostCommit}`,
|
||||
`1. Build ${sdkFolder}/dist.`,
|
||||
`2. Write ${relative(plan.artifacts.archive)} with dist, package.json, ${plan.copies.join(', ')}, and ${relative(plan.artifacts.metadata)}.`,
|
||||
`3. Write the version ${plan.next.version} to ${sdkFolder}/package.json.`,
|
||||
`Plugins then use: "${packageName}": "${plan.url}"`,
|
||||
'The script does not upload the file.',
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
// Runs the release. build(root) returns the dist folder. The source version changes only when the release files exist.
|
||||
export async function runSdkRelease(plan, build = buildSdk) {
|
||||
const before = await fs.readFile(plan.sourceFile, 'utf8');
|
||||
const written = [];
|
||||
let complete = false;
|
||||
try {
|
||||
const dist = await build(plan.root);
|
||||
for (const file of ['index.js', 'index.d.ts']) await fs.access(path.join(dist, file));
|
||||
const entries = [{ name: 'package.json', data: Buffer.from(JSON.stringify(plan.packageJson, null, 2) + '\n') }];
|
||||
for (const file of plan.copies) entries.push({ name: file, data: await fs.readFile(path.join(plan.packageDir, file)) });
|
||||
for (const file of await listFiles(dist)) entries.push({ name: 'dist/' + file, data: await fs.readFile(path.join(dist, ...file.split('/'))) });
|
||||
const archive = packEntries(entries);
|
||||
await fs.mkdir(plan.releaseDir, { recursive: true });
|
||||
await fs.writeFile(plan.artifacts.archive, archive, { flag: 'wx' });
|
||||
written.push(plan.artifacts.archive);
|
||||
const metadata = {
|
||||
name: packageName, version: plan.next.version, file: plan.file, url: plan.url, bytes: archive.length,
|
||||
sha256: createHash('sha256').update(archive).digest('hex'), integrity: integrity(archive), source: plan.hostCommit,
|
||||
};
|
||||
await fs.writeFile(plan.artifacts.metadata, JSON.stringify(metadata, null, 2) + '\n', { flag: 'wx' });
|
||||
written.push(plan.artifacts.metadata);
|
||||
await fs.writeFile(plan.sourceFile, before.replace(/("version":\s*")[^"]+(")/, `$1${plan.next.version}$2`));
|
||||
if (JSON.parse(await fs.readFile(plan.sourceFile, 'utf8')).version !== plan.next.version) throw Error('The SDK version field did not change.');
|
||||
complete = true;
|
||||
return { archive: plan.artifacts.archive, ...metadata };
|
||||
} finally {
|
||||
if (!complete) {
|
||||
if ((await fs.readFile(plan.sourceFile, 'utf8').catch(() => null)) !== before) await fs.writeFile(plan.sourceFile, before);
|
||||
// Only the files of this attempt go. A failed attempt does not use up the version.
|
||||
for (const file of written) await fs.rm(file, { force: true });
|
||||
await fs.rmdir(plan.releaseDir).catch(() => {});
|
||||
console.error('The SDK release did not complete. The version is restored, and the files of this attempt are removed.');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const options = parseArguments(process.argv.slice(2));
|
||||
const plan = await planSdkRelease(root, options);
|
||||
console.log(describePlan(plan));
|
||||
if (options.dryRun) {
|
||||
console.log('Dry run: no file changed.');
|
||||
return;
|
||||
}
|
||||
const result = await runSdkRelease(plan);
|
||||
console.log(`\nSDK package: ${result.archive}\n${result.bytes} bytes, SHA-256 ${result.sha256}\nIntegrity: ${result.integrity}`);
|
||||
console.log(`Upload it to ${result.url}`);
|
||||
console.log(`Plugins use: "${packageName}": "${result.url}"`);
|
||||
console.log(`Then commit the new version in ${sdkFolder}/package.json in RuneStone.`);
|
||||
}
|
||||
|
||||
if (process.argv[1] && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url))) {
|
||||
try { await main(); } catch (error) { console.error(error instanceof Error ? error.message : error); process.exitCode = 1; }
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
export function releaseVersion(value) {
|
||||
const match = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)([a-z]*)$/.exec(value);
|
||||
if (!match) throw Error('Use a release version such as 0.1.23 or 0.1.23a.');
|
||||
const parts = match.slice(1, 4).map(Number);
|
||||
let revision = 0;
|
||||
for (const letter of match[4]) revision = revision * 26 + letter.charCodeAt(0) - 96;
|
||||
if (parts.some(part => part > 65535) || revision > 65535) throw Error('The Windows version exceeds 65535.');
|
||||
const base = parts.join('.');
|
||||
return { version: value, base, suffix: match[4], revision,
|
||||
toolchain: revision ? `${base}+${revision}` : base, windows: `${base}.${revision}` };
|
||||
}
|
||||
|
||||
export function nextHotfix(value) {
|
||||
const parsed = releaseVersion(value);
|
||||
let revision = parsed.revision + 1;
|
||||
let suffix = '';
|
||||
while (revision) {
|
||||
revision--;
|
||||
suffix = String.fromCharCode(97 + revision % 26) + suffix;
|
||||
revision = Math.floor(revision / 26);
|
||||
}
|
||||
return releaseVersion(parsed.base + suffix).version;
|
||||
}
|
||||
|
||||
export function compareReleases(left, right) {
|
||||
const a = releaseVersion(left).windows.split('.').map(Number);
|
||||
const b = releaseVersion(right).windows.split('.').map(Number);
|
||||
for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return Math.sign(a[i] - b[i]);
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
param(
|
||||
[Parameter(Mandatory)][string]$Path,
|
||||
[Parameter(Mandatory)][string]$Version,
|
||||
[Parameter(Mandatory)][string]$NumericVersion
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Add-Type -TypeDefinition @'
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Diagnostics;
|
||||
using System.ComponentModel;
|
||||
using System.Runtime.InteropServices;
|
||||
public static class RuneStoneVersionResource {
|
||||
[DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)]
|
||||
static extern IntPtr BeginUpdateResource(string path, bool deleteExisting);
|
||||
[DllImport("kernel32.dll", SetLastError=true)]
|
||||
static extern bool UpdateResource(IntPtr handle, IntPtr type, IntPtr name, ushort language, byte[] data, uint size);
|
||||
[DllImport("kernel32.dll", SetLastError=true)]
|
||||
static extern bool EndUpdateResource(IntPtr handle, bool discard);
|
||||
static void Align(BinaryWriter writer) { while (writer.BaseStream.Position % 4 != 0) writer.Write((byte)0); }
|
||||
static byte[] Text(string value) { return Encoding.Unicode.GetBytes(value + "\0"); }
|
||||
static byte[] Block(string key, ushort type, byte[] value, ushort valueLength, params byte[][] children) {
|
||||
using (var stream = new MemoryStream()) using (var writer = new BinaryWriter(stream)) {
|
||||
writer.Write((ushort)0); writer.Write(valueLength); writer.Write(type);
|
||||
writer.Write(Text(key)); Align(writer); writer.Write(value);
|
||||
foreach (var child in children) { Align(writer); writer.Write(child); }
|
||||
long length = stream.Length; stream.Position = 0; writer.Write(checked((ushort)length));
|
||||
return stream.ToArray();
|
||||
}
|
||||
}
|
||||
static byte[] StringValue(string key, string value) {
|
||||
var bytes = Text(value); return Block(key, 1, bytes, checked((ushort)(bytes.Length / 2)));
|
||||
}
|
||||
public static void Set(string path, string version, string numeric) {
|
||||
var p = Array.ConvertAll(numeric.Split('.'), UInt16.Parse);
|
||||
if (p.Length != 4) throw new ArgumentException("Use four Windows version parts.");
|
||||
var previous = FileVersionInfo.GetVersionInfo(path);
|
||||
byte[] fixedInfo;
|
||||
using (var stream = new MemoryStream()) using (var writer = new BinaryWriter(stream)) {
|
||||
uint high = ((uint)p[0] << 16) | p[1], low = ((uint)p[2] << 16) | p[3];
|
||||
foreach (uint value in new uint[] { 0xFEEF04BD, 0x10000, high, low, high, low, 0x3F, 0, 4, 1, 0, 0, 0 }) writer.Write(value);
|
||||
fixedInfo = stream.ToArray();
|
||||
}
|
||||
var strings = Block("StringFileInfo", 1, new byte[0], 0,
|
||||
Block("040904B0", 1, new byte[0], 0,
|
||||
StringValue("CompanyName", previous.CompanyName ?? "RuneStone"),
|
||||
StringValue("FileDescription", previous.FileDescription ?? "RuneStone"),
|
||||
StringValue("ProductName", "RuneStone"),
|
||||
StringValue("OriginalFilename", "runestone.exe"),
|
||||
StringValue("FileVersion", version), StringValue("ProductVersion", version)));
|
||||
var vars = Block("VarFileInfo", 1, new byte[0], 0,
|
||||
Block("Translation", 0, new byte[] { 9, 4, 0xB0, 4 }, 4));
|
||||
var data = Block("VS_VERSION_INFO", 0, fixedInfo, 52, strings, vars);
|
||||
var handle = BeginUpdateResource(path, false);
|
||||
if (handle == IntPtr.Zero) throw new Win32Exception();
|
||||
if (!UpdateResource(handle, (IntPtr)16, (IntPtr)1, 0, data, (uint)data.Length)) {
|
||||
var error = new Win32Exception(); EndUpdateResource(handle, true); throw error;
|
||||
}
|
||||
if (!EndUpdateResource(handle, false)) throw new Win32Exception();
|
||||
}
|
||||
}
|
||||
'@
|
||||
$resolvedPath = (Resolve-Path -LiteralPath $Path).Path
|
||||
[RuneStoneVersionResource]::Set($resolvedPath, $Version, $NumericVersion)
|
||||
$actual = [Diagnostics.FileVersionInfo]::GetVersionInfo($resolvedPath)
|
||||
if ($actual.ProductVersion -ne $Version -or $actual.FileVersion -ne $Version) {
|
||||
throw 'The executable version resource does not match the release version.'
|
||||
}
|
||||
$actual | Select-Object FileVersion, ProductVersion, FileMajorPart, FileMinorPart, FileBuildPart, FilePrivatePart
|
||||
@@ -0,0 +1,237 @@
|
||||
// Run the browser smoke tests in tests/smoke/. See docs/development.md#browser-smoke-tests.
|
||||
//
|
||||
// pnpm smoke [filter...] [--list] [--jobs N] [--timeout seconds] [--retries N] [--no-serve] [--csp]
|
||||
//
|
||||
// A filter selects the tests whose path contains it, for example `tabs` or `tables/drag`.
|
||||
// After the parallel run, the runner runs each failed test again, one at a time (--retries, default 1).
|
||||
// A test that passes on a retry counts as "flaky". The summary lists it, but the run does not fail.
|
||||
// A test declares what it needs on a line near the top:
|
||||
// // @requires repo:RuneStone_Local_Autocomplete/src electron
|
||||
// The runner skips a test, with the reason, when a requirement is missing.
|
||||
// A test that fails because of a known app defect states it near the top:
|
||||
// // @known-issue <the defect>
|
||||
// It still runs. A failure counts as "known". A pass counts as a failure, so remove the stale line.
|
||||
// --csp runs the tests under the app's content security policy (RUNESTONE_CSP=1). A test fails on any violation.
|
||||
import { spawn } from "node:child_process";
|
||||
import { createWriteStream, existsSync } from "node:fs";
|
||||
import { mkdir, readdir, readFile } from "node:fs/promises";
|
||||
import { createRequire } from "node:module";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const root = fileURLToPath(new URL("../", import.meta.url));
|
||||
const smokeRoot = path.join(root, "tests", "smoke");
|
||||
const logRoot = path.join(root, "output", "smoke", "logs");
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
const option = (name, fallback) => {
|
||||
const index = args.indexOf(name);
|
||||
if (index < 0) return fallback;
|
||||
const [value] = args.splice(index, 2).slice(1);
|
||||
return value;
|
||||
};
|
||||
const flag = name => {
|
||||
const index = args.indexOf(name);
|
||||
if (index >= 0) args.splice(index, 1);
|
||||
return index >= 0;
|
||||
};
|
||||
const list = flag("--list");
|
||||
const serve = !flag("--no-serve");
|
||||
const jobs = Math.max(1, Number(option("--jobs", "4")));
|
||||
const timeoutMs = Math.max(10, Number(option("--timeout", "180"))) * 1000;
|
||||
const retries = Math.max(0, Number(option("--retries", "1")));
|
||||
const csp = flag("--csp");
|
||||
const filters = args;
|
||||
|
||||
const env = { ...process.env, SMOKE_URL: process.env.SMOKE_URL || "http://127.0.0.1:1420" };
|
||||
if (csp) env.RUNESTONE_CSP = "1";
|
||||
const pluginRepos = env.RUNESTONE_PLUGIN_REPOS || path.join(root, "..");
|
||||
|
||||
async function findTests(dir) {
|
||||
const result = [];
|
||||
for (const entry of await readdir(dir, { withFileTypes: true })) {
|
||||
const full = path.join(dir, entry.name);
|
||||
if (entry.isDirectory() && !entry.name.startsWith("_")) result.push(...await findTests(full));
|
||||
else if (entry.isFile() && entry.name.endsWith(".smoke.mjs")) result.push(full);
|
||||
}
|
||||
return result.sort();
|
||||
}
|
||||
|
||||
async function header(file) {
|
||||
const head = (await readFile(file, "utf8")).split("\n").slice(0, 10).join("\n");
|
||||
return {
|
||||
needs: head.match(/@requires\s+([^\r\n]+)/)?.[1].trim().split(/\s+/) ?? [],
|
||||
knownIssue: head.match(/@known-issue\s+([^\r\n]+)/)?.[1].trim(),
|
||||
};
|
||||
}
|
||||
|
||||
function missing(requirement) {
|
||||
const [kind, value = ""] = requirement.split(/:(.*)/s);
|
||||
if (kind === "repo") {
|
||||
const target = path.join(pluginRepos, value);
|
||||
return existsSync(target) ? null : `${target} is missing; set RUNESTONE_PLUGIN_REPOS to the folder of the plugin checkouts`;
|
||||
}
|
||||
if (kind === "electron") {
|
||||
return existsSync(path.join(root, "browser-runtime", "node_modules", "electron")) ? null : "Electron is missing; run npm ci --prefix browser-runtime";
|
||||
}
|
||||
return `unknown requirement "${requirement}"`;
|
||||
}
|
||||
|
||||
function findChrome() {
|
||||
if (env.CHROME_PATH || env.PLAYWRIGHT_MODULE) return;
|
||||
try {
|
||||
const bundled = createRequire(import.meta.url)("playwright").chromium.executablePath();
|
||||
if (existsSync(bundled)) return;
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
const candidates = {
|
||||
win32: [
|
||||
path.join(env.PROGRAMFILES || "C:\\Program Files", "Google\\Chrome\\Application\\chrome.exe"),
|
||||
path.join(env["PROGRAMFILES(X86)"] || "C:\\Program Files (x86)", "Microsoft\\Edge\\Application\\msedge.exe"),
|
||||
path.join(env.PROGRAMFILES || "C:\\Program Files", "Microsoft\\Edge\\Application\\msedge.exe"),
|
||||
],
|
||||
darwin: ["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", "/Applications/Chromium.app/Contents/MacOS/Chromium"],
|
||||
linux: ["/usr/bin/google-chrome", "/usr/bin/chromium", "/usr/bin/chromium-browser"],
|
||||
}[process.platform] ?? [];
|
||||
const found = candidates.find(existsSync);
|
||||
if (found) env.CHROME_PATH = found;
|
||||
else console.warn("No Chromium found. Run `pnpm exec playwright install chromium`, or set CHROME_PATH.");
|
||||
}
|
||||
|
||||
async function reachable(url) {
|
||||
try {
|
||||
await fetch(url, { signal: AbortSignal.timeout(2000) });
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** True when the server sends the content security policy with the app page (see vite.config.js). */
|
||||
async function sendsPolicy(url) {
|
||||
try {
|
||||
const response = await fetch(url, { headers: { accept: "text/html" }, signal: AbortSignal.timeout(10000) });
|
||||
return response.headers.has("content-security-policy");
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function startServer() {
|
||||
const vite = path.join(root, "node_modules", "vite", "bin", "vite.js");
|
||||
// Serve on the port in SMOKE_URL, so that two checkouts can run their tests at the same time.
|
||||
const port = new URL(env.SMOKE_URL).port || "1420";
|
||||
const server = spawn(process.execPath, [vite, "dev", "--port", port, "--strictPort"], { cwd: root, env, stdio: "ignore", windowsHide: true });
|
||||
for (let waited = 0; waited < 60000; waited += 500) {
|
||||
if (await reachable(env.SMOKE_URL)) return server;
|
||||
await new Promise(resolve => setTimeout(resolve, 500));
|
||||
}
|
||||
server.kill();
|
||||
throw new Error(`The dev server did not start at ${env.SMOKE_URL}.`);
|
||||
}
|
||||
|
||||
function run(file, knownIssue, logSuffix = "") {
|
||||
const name = path.relative(smokeRoot, file).replace(/\\/g, "/").replace(/\.smoke\.mjs$/, "");
|
||||
const log = path.join(logRoot, name.replaceAll("/", "__") + logSuffix + ".log");
|
||||
const started = Date.now();
|
||||
return new Promise(resolve => {
|
||||
const out = createWriteStream(log);
|
||||
const child = spawn(process.execPath, [file], { cwd: root, env, stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
|
||||
child.stdout.pipe(out, { end: false });
|
||||
child.stderr.pipe(out, { end: false });
|
||||
const timer = setTimeout(() => child.kill(), timeoutMs);
|
||||
child.on("close", code => {
|
||||
clearTimeout(timer);
|
||||
out.end();
|
||||
const seconds = ((Date.now() - started) / 1000).toFixed(1);
|
||||
let status = code === 0 ? "pass" : Date.now() - started >= timeoutMs ? "timeout" : "fail";
|
||||
if (knownIssue) status = status === "pass" ? "unexpected-pass" : "known";
|
||||
resolve({ name, status, detail: status === "known" ? knownIssue : `${seconds}s`, log });
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
const tests = (await findTests(smokeRoot)).filter(file => {
|
||||
const rel = path.relative(smokeRoot, file).replace(/\\/g, "/");
|
||||
return !filters.length || filters.some(filter => rel.includes(filter));
|
||||
});
|
||||
if (!tests.length) {
|
||||
console.error(`No smoke tests match: ${filters.join(" ")}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const plan = [];
|
||||
for (const file of tests) {
|
||||
const { needs, knownIssue } = await header(file);
|
||||
const reasons = needs.map(missing).filter(Boolean);
|
||||
plan.push({ file, needs, reasons, knownIssue });
|
||||
}
|
||||
|
||||
if (list) {
|
||||
for (const { file, needs, reasons } of plan) {
|
||||
const name = path.relative(smokeRoot, file).replace(/\\/g, "/");
|
||||
console.log(`${reasons.length ? "skip" : "run "} ${name}${needs.length ? ` [${needs.join(" ")}]` : ""}${reasons.length ? ` (${reasons.join("; ")})` : ""}`);
|
||||
}
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
findChrome();
|
||||
// Tests that load plugin source resolve "@runestone/plugin-sdk" to this build.
|
||||
if (!existsSync(path.join(root, "packages", "plugin-sdk", "dist", "index.js"))) {
|
||||
console.log("Building the plugin SDK...");
|
||||
const build = spawn(process.execPath, [path.join(root, "scripts", "buildSdk.mjs")], { cwd: root, stdio: "inherit", windowsHide: true });
|
||||
const code = await new Promise(resolve => build.on("close", resolve));
|
||||
if (code !== 0) throw new Error("The plugin SDK build failed. Run pnpm sdk:build.");
|
||||
}
|
||||
await mkdir(logRoot, { recursive: true });
|
||||
let server;
|
||||
if (!(await reachable(env.SMOKE_URL))) {
|
||||
if (!serve) {
|
||||
console.error(`Nothing serves ${env.SMOKE_URL}. Start pnpm dev, or run without --no-serve.`);
|
||||
process.exit(1);
|
||||
}
|
||||
console.log(`Starting the dev server at ${env.SMOKE_URL}${csp ? " in CSP mode" : ""}...`);
|
||||
server = await startServer();
|
||||
}
|
||||
if (csp && !(await sendsPolicy(env.SMOKE_URL))) {
|
||||
server?.kill();
|
||||
console.error(`The server at ${env.SMOKE_URL} does not send a content security policy. Stop it, or set SMOKE_URL to a free port, so that --csp can start a server with RUNESTONE_CSP=1.`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const results = [];
|
||||
const queue = plan.filter(item => !item.reasons.length);
|
||||
for (const item of plan.filter(item => item.reasons.length)) {
|
||||
results.push({ name: path.relative(smokeRoot, item.file).replace(/\\/g, "/").replace(/\.smoke\.mjs$/, ""), status: "skip", detail: item.reasons.join("; ") });
|
||||
}
|
||||
async function worker() {
|
||||
while (queue.length) {
|
||||
const { file, knownIssue } = queue.shift();
|
||||
const result = { ...await run(file, knownIssue), file };
|
||||
results.push(result);
|
||||
console.log(`${result.status.padEnd(7)} ${result.name} (${result.detail})`);
|
||||
}
|
||||
}
|
||||
try {
|
||||
await Promise.all(Array.from({ length: Math.min(jobs, queue.length || 1) }, worker));
|
||||
for (let attempt = 1; attempt <= retries; attempt++) {
|
||||
for (const result of results.filter(item => ["fail", "timeout"].includes(item.status))) {
|
||||
const retry = await run(result.file, undefined, `.retry${attempt}`);
|
||||
console.log(`retry ${retry.name}: ${retry.status} (${retry.detail})`);
|
||||
if (retry.status === "pass") result.status = "flaky";
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
server?.kill();
|
||||
}
|
||||
|
||||
const count = status => results.filter(result => result.status === status).length;
|
||||
console.log("");
|
||||
for (const result of results.filter(item => item.status !== "pass").sort((a, b) => a.name.localeCompare(b.name))) {
|
||||
const detail = ["skip", "known"].includes(result.status) ? result.detail : path.relative(root, result.log);
|
||||
console.log(`${result.status.padEnd(7)} ${result.name}: ${detail}`);
|
||||
}
|
||||
const failed = count("fail") + count("timeout") + count("unexpected-pass");
|
||||
console.log(`\n${count("pass")} passed, ${count("flaky")} flaky, ${failed} failed, ${count("known")} known issues, ${count("skip")} skipped. Logs: ${path.relative(root, logRoot)}`);
|
||||
process.exitCode = failed ? 1 : 0;
|
||||
Reference in New Issue
Block a user