waybetter/packages/waybetter/tests/manifests-cli.test.mjs
CRT 22c09eef4c waybetter manifests: winget, Chocolatey, Homebrew cask and AUR files from one JSON description
Generic (publisher, id, name, version, installer URLs and sha256 or local files, silent switches, licence, homepage). winget: version, installer and locale manifests (validated with the installed winget), Chocolatey: nuspec + install script with checksum (choco pack), Homebrew: a cask for our own tap, AUR: PKGBUILD and .SRCINFO from the .deb or AppImage. waybetter release windows|macos|linux writes them to <outDir>/distribution/<version> once the public download URL is given (--download-base); nothing is submitted.
2026-09-30 16:28:44 +00:00

249 lines
14 KiB
JavaScript

// `waybetter manifests`: winget, Chocolatey, Homebrew and AUR files from a small description.
// Validated offline: the YAML is parsed back and checked against the winget schema's constraints
// (required keys, patterns, enums), the nuspec is checked for well-formedness, PowerShell and Ruby
// syntax-check their files when those tools exist, and the .SRCINFO must agree with the PKGBUILD.
import assert from 'node:assert/strict';
import { execFileSync, spawnSync } from 'node:child_process';
import { existsSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import test from 'node:test';
import { fileURLToPath } from 'node:url';
import { WINGET_MANIFEST_VERSION, buildManifests, resolveSpec, toYaml, writeManifests } from '../cli/manifests.mjs';
const BIN = fileURLToPath(new URL('../bin/waybetter.mjs', import.meta.url));
const SHA = 'a'.repeat(63) + 'B';
const SHA2 = '0123456789abcdef'.repeat(4);
const RAW = {
publisher: 'Example',
id: 'Example.Some-App',
name: 'Some App',
version: '1.2.3',
shortDescription: 'Does: things, "quoted" and #hashed',
description: 'Line one\nLine two',
homepage: 'https://example.test/app',
license: 'GPL-3.0-or-later',
tags: ['a', 'b'],
windows: { url: 'https://dl.example.test/1.2.3/Some-App_1.2.3_x64-setup.exe', sha256: SHA, silentSwitches: '/S' },
macos: { url: 'https://dl.example.test/1.2.3/Some-App_1.2.3.dmg', sha256: SHA2, app: 'Some App.app', zap: ['~/Library/Application Support/x.y'] },
linux: { deb: { url: 'https://dl.example.test/1.2.3/some-app_1.2.3_amd64.deb', sha256: SHA2 }, appImage: { url: 'https://dl.example.test/1.2.3/Some-App.AppImage', sha256: SHA } },
};
/** Parses the YAML subset the emitter writes (maps, lists of maps, lists of scalars, |- blocks). */
function parseYaml(text) {
const lines = text.split('\n').filter(line => line.trim() && !line.trim().startsWith('#'));
let at = 0;
const value = raw => {
if (raw.startsWith('"')) return JSON.parse(raw);
return /^-?\d+(\.\d+)?$/.test(raw) ? Number(raw) : raw;
};
const indentOf = line => line.length - line.trimStart().length;
function block(indent) {
if (lines[at].trimStart().startsWith('- ')) {
const list = [];
while (at < lines.length && indentOf(lines[at]) === indent && lines[at].trimStart().startsWith('- ')) {
const rest = lines[at].trimStart().slice(2);
if (/^[A-Za-z]\w*:( |$)/.test(rest)) {
lines[at] = `${' '.repeat(indent + 2)}${rest}`;
list.push(block(indent + 2));
} else { list.push(value(rest)); at += 1; }
}
return list;
}
const map = {};
while (at < lines.length && indentOf(lines[at]) === indent) {
const [, key, rest] = /^\s*([A-Za-z]\w*):(?: (.*))?$/.exec(lines[at]);
at += 1;
if (rest === '|-') {
const parts = [];
while (at < lines.length && indentOf(lines[at]) > indent) parts.push(lines[at++].slice(indent + 2));
map[key] = parts.join('\n');
} else if (rest === undefined) {
// a nested map is indented by 2; a list of maps by 0 or 2 (we write 0 extra)
map[key] = block(indentOf(lines[at]));
} else map[key] = value(rest);
}
return map;
}
return block(0);
}
function wellFormed(xml) {
const stack = [];
for (const [, close, name, self] of xml.replace(/<\?[\s\S]*?\?>/g, '').matchAll(/<(\/?)([A-Za-z][\w:.-]*)(?:\s[^>]*?)?(\/?)>/g)) {
if (self) continue;
if (!close) stack.push(name);
else assert.equal(stack.pop(), name, `mismatched </${name}>`);
}
assert.deepEqual(stack, []);
assert.doesNotMatch(xml.replace(/&(amp|lt|gt|quot|apos);/g, ''), /&/);
}
test('resolveSpec validates ids, versions, URLs and hashes, and fills the defaults', () => {
const spec = resolveSpec(RAW);
assert.equal(spec.slug, 'some-app');
assert.equal(spec.windows.scope, 'user');
assert.equal(spec.licenseUrl, 'https://spdx.org/licenses/GPL-3.0-or-later.html');
assert.throws(() => resolveSpec({ ...RAW, id: 'NoDot' }), /Publisher\.Package/);
assert.throws(() => resolveSpec({ ...RAW, version: 'v1' }), /version/);
assert.throws(() => resolveSpec({ ...RAW, homepage: 'http://x.test' }), /https/);
assert.throws(() => resolveSpec({ ...RAW, windows: { ...RAW.windows, url: 'http://x.test/a.exe' } }), /https/);
assert.throws(() => resolveSpec({ ...RAW, windows: { ...RAW.windows, sha256: 'abc' } }), /sha256/);
assert.throws(() => resolveSpec({ ...RAW, windows: { sha256: SHA } }), /url/);
assert.throws(() => resolveSpec({ publisher: 'E', id: 'E.A', name: 'A', version: '1.0.0', shortDescription: 's', homepage: 'https://a.test', license: 'MIT' }), /at least one/);
});
test('a file installer is hashed here and its URL comes from the download base, never invented', () => {
const dir = mkdtempSync(join(tmpdir(), 'wb-man-'));
writeFileSync(join(dir, 'Some-App_1.2.3_x64-setup.exe'), 'hello');
const raw = { ...RAW, macos: undefined, linux: undefined, windows: { file: 'Some-App_1.2.3_x64-setup.exe' } };
assert.throws(() => resolveSpec(raw, { baseDir: dir }), /download-base/);
const spec = resolveSpec(raw, { baseDir: dir, downloadBase: 'https://dl.example.test/1.2.3/' });
assert.equal(spec.windows.url, 'https://dl.example.test/1.2.3/Some-App_1.2.3_x64-setup.exe');
assert.equal(spec.windows.sha256, '2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824');
});
test('winget: version, installer and locale manifests match the schema constraints', () => {
const { files } = buildManifests(resolveSpec(RAW), { only: ['winget'] });
const byName = Object.fromEntries(Object.entries(files).map(([path, text]) => [path.replaceAll('\\', '/'), text]));
const base = 'winget/manifests/e/Example/Some-App/1.2.3/Example.Some-App';
assert.deepEqual(Object.keys(byName).sort(), [`${base}.installer.yaml`, `${base}.locale.en-US.yaml`, `${base}.yaml`]);
const version = parseYaml(byName[`${base}.yaml`]);
const installer = parseYaml(byName[`${base}.installer.yaml`]);
const locale = parseYaml(byName[`${base}.locale.en-US.yaml`]);
const idPattern = /^[^.\s\\/:*?"<>|\x01-\x1f]{1,32}(\.[^.\s\\/:*?"<>|\x01-\x1f]{1,32}){1,7}$/;
for (const manifest of [version, installer, locale]) {
assert.match(manifest.PackageIdentifier, idPattern);
assert.equal(manifest.PackageVersion, '1.2.3');
assert.equal(manifest.ManifestVersion, WINGET_MANIFEST_VERSION);
}
assert.deepEqual([version.ManifestType, installer.ManifestType, locale.ManifestType], ['version', 'installer', 'defaultLocale']);
assert.equal(version.DefaultLocale, 'en-US');
assert.equal(locale.PackageLocale, 'en-US');
for (const key of ['Publisher', 'PackageName', 'License', 'ShortDescription']) assert.ok(locale[key], key);
assert.equal(locale.ShortDescription, RAW.shortDescription);
assert.equal(locale.Description, 'Line one\nLine two');
assert.deepEqual(locale.Tags, ['a', 'b']);
assert.ok(installer.Installers.length >= 1);
const [entry] = installer.Installers;
assert.match(entry.Architecture, /^(x86|x64|arm|arm64|neutral)$/);
assert.match(entry.InstallerUrl, /^https:\/\//);
assert.match(entry.InstallerSha256, /^[A-F0-9]{64}$/);
assert.equal(entry.InstallerSha256, SHA.toUpperCase());
assert.equal(installer.InstallerType, 'nullsoft');
assert.equal(installer.InstallerSwitches.Silent, '/S');
assert.match(installer.Scope, /^(user|machine)$/);
assert.ok(installer.InstallModes.every(mode => ['interactive', 'silent', 'silentWithProgress'].includes(mode)));
assert.match(byName[`${base}.yaml`], /^# yaml-language-server: \$schema=https:\/\/aka\.ms\/winget-manifest\.version\.1\.28\.0\.schema\.json$/m);
});
test('toYaml quotes what YAML would misread', () => {
const text = toYaml({ A: 'true', B: '1.0', C: 'a: b', D: '- x', E: '#c', F: 'plain words', G: '' });
const back = parseYaml(text);
assert.equal(back.A, 'true');
assert.equal(back.B, '1.0');
assert.equal(back.C, 'a: b');
assert.equal(back.D, '- x');
assert.equal(back.E, '#c');
assert.equal(back.F, 'plain words');
});
test('chocolatey: the nuspec is well-formed XML and the install script carries the checksum', () => {
const { files } = buildManifests(resolveSpec({ ...RAW, shortDescription: 'A & B <tags> "q"' }), { only: ['chocolatey'] });
const nuspec = files[join('chocolatey', 'some-app', 'some-app.nuspec')];
const script = files[join('chocolatey', 'some-app', 'tools', 'chocolateyInstall.ps1')];
wellFormed(nuspec);
assert.match(nuspec, /<id>some-app<\/id>/);
assert.match(nuspec, /<version>1\.2\.3<\/version>/);
assert.match(nuspec, /A &amp; B &lt;tags&gt; &quot;q&quot;/);
assert.match(script, new RegExp(`checksum64\\s+= '${SHA.toLowerCase()}'`));
assert.match(script, /checksumType64 = 'sha256'/);
assert.match(script, /silentArgs\s+= '\/S'/);
assert.match(script, /url64bit\s+= 'https:\/\/dl\.example\.test\/1\.2\.3\/Some-App_1\.2\.3_x64-setup\.exe'/);
if (process.platform === 'win32') {
const dir = mkdtempSync(join(tmpdir(), 'wb-ps-'));
const file = join(dir, 'chocolateyInstall.ps1');
writeFileSync(file, script);
const run = spawnSync('powershell', ['-NoProfile', '-Command', `$e=$null; [System.Management.Automation.Language.Parser]::ParseFile('${file}',[ref]$null,[ref]$e) | Out-Null; if ($e.Count) { $e | ForEach-Object { $_.Message }; exit 1 }`], { encoding: 'utf8' });
if (!run.error) assert.equal(run.status, 0, run.stdout);
}
});
test('homebrew: a cask with the version interpolated in the URL', () => {
const { files } = buildManifests(resolveSpec(RAW), { only: ['homebrew'] });
const cask = files[join('homebrew', 'Casks', 'some-app.rb')];
assert.match(cask, /^cask "some-app" do$/m);
assert.match(cask, /version "1\.2\.3"/);
assert.match(cask, new RegExp(`sha256 "${SHA2}"`));
assert.match(cask, /url "https:\/\/dl\.example\.test\/#\{version\}\/Some-App_#\{version\}\.dmg"/);
assert.match(cask, /app "Some App\.app"/);
assert.match(cask, /zap trash: \[\n "~\/Library\/Application Support\/x\.y",\n \]/);
assert.match(cask, /end\n$/);
const ruby = spawnSync('ruby', ['-c'], { input: cask, encoding: 'utf8' });
if (!ruby.error) assert.equal(ruby.status, 0, ruby.stderr);
});
test('aur: PKGBUILD from the .deb, and a .SRCINFO that agrees with it', () => {
const { files } = buildManifests(resolveSpec(RAW), { only: ['aur'] });
const pkgbuild = files[join('aur', 'some-app-bin', 'PKGBUILD')];
const srcinfo = files[join('aur', 'some-app-bin', '.SRCINFO')];
assert.match(pkgbuild, /^# Maintainer: Example$/m);
assert.match(pkgbuild, /^pkgname=some-app-bin$/m);
assert.match(pkgbuild, /^pkgver=1\.2\.3$/m);
assert.match(pkgbuild, /^source=\("\$\{pkgname\}-\$\{pkgver\}\.deb::https:\/\/dl\.example\.test\/\$\{pkgver\}\/some-app_\$\{pkgver\}_amd64\.deb"\)$/m);
assert.match(pkgbuild, new RegExp(`^sha256sums=\\('${SHA2}'\\)$`, 'm'));
assert.match(pkgbuild, /bsdtar -xf "\$srcdir"\/data\.tar\.\* -C "\$pkgdir"/);
assert.match(pkgbuild, /^depends=\('webkit2gtk-4\.1' 'gtk3'\)$/m);
const info = Object.fromEntries(srcinfo.split('\n').filter(line => line.includes(' = ')).map(line => line.trim().split(' = ')));
assert.equal(info.pkgbase, 'some-app-bin');
assert.equal(info.pkgver, '1.2.3');
assert.equal(info.source, 'some-app-bin-1.2.3.deb::https://dl.example.test/1.2.3/some-app_1.2.3_amd64.deb');
assert.equal(info.sha256sums, SHA2);
assert.ok(srcinfo.endsWith('pkgname = some-app-bin\n'));
const syntax = spawnSync('bash', ['-n'], { input: pkgbuild, encoding: 'utf8' });
if (!syntax.error) assert.equal(syntax.status, 0, syntax.stderr);
});
test('aur: an AppImage-only package installs under /opt with a launcher', () => {
const { files } = buildManifests(resolveSpec({ ...RAW, linux: { appImage: RAW.linux.appImage } }), { only: ['aur'] });
const pkgbuild = files[join('aur', 'some-app-bin', 'PKGBUILD')];
assert.match(pkgbuild, /^noextract=\("some-app-bin-1\.2\.3\.AppImage"\)$/m);
assert.match(pkgbuild, /install -Dm755 "\$srcdir\/some-app-bin-1\.2\.3\.AppImage" "\$pkgdir\/opt\/some-app\/some-app\.AppImage"/);
assert.doesNotMatch(pkgbuild, /^depends=/m);
});
test('a description without a platform skips its channels; unknown channels fail', () => {
const { files, skipped } = buildManifests(resolveSpec({ ...RAW, macos: undefined, linux: undefined }));
assert.deepEqual(skipped, ['homebrew', 'aur']);
assert.ok(Object.keys(files).some(path => path.includes('winget')));
assert.throws(() => buildManifests(resolveSpec(RAW), { only: ['snap'] }), /unknown channel/);
});
test('the command: writes the tree from a file, LF endings, and prints what it wrote', () => {
const dir = mkdtempSync(join(tmpdir(), 'wb-man-cli-'));
writeFileSync(join(dir, 'app.json'), JSON.stringify(RAW));
const out = execFileSync(process.execPath, [BIN, 'manifests', join(dir, 'app.json'), '--out', join(dir, 'out')], { encoding: 'utf8' });
assert.match(out, /Some-App\.yaml|Example\.Some-App\.yaml/);
const pkgbuild = join(dir, 'out', 'aur', 'some-app-bin', 'PKGBUILD');
assert.ok(existsSync(pkgbuild));
assert.doesNotMatch(readFileSync(pkgbuild, 'utf8'), /\r/);
assert.throws(() => execFileSync(process.execPath, [BIN, 'manifests'], { encoding: 'utf8', stdio: 'pipe' }));
writeManifests(resolveSpec(RAW), join(dir, 'again'), { only: ['homebrew'] });
assert.ok(existsSync(join(dir, 'again', 'homebrew', 'Casks', 'some-app.rb')));
});
test('the real tools accept the files when they are installed: winget validate, choco pack', () => {
const dir = mkdtempSync(join(tmpdir(), 'wb-real-'));
writeManifests(resolveSpec(RAW), dir, { only: ['winget', 'chocolatey'] });
const winget = spawnSync('winget', ['validate', '--manifest', join(dir, 'winget', 'manifests', 'e', 'Example', 'Some-App', '1.2.3')], { encoding: 'utf8' });
if (!winget.error) {
assert.match(winget.stdout, /Manifest validation succeeded/, winget.stdout);
assert.doesNotMatch(winget.stdout, /Manifest Error/);
}
const choco = spawnSync('choco', ['pack', '--limit-output'], { cwd: join(dir, 'chocolatey', 'some-app'), encoding: 'utf8' });
if (!choco.error && choco.status !== null) {
assert.match(choco.stdout, /Successfully created package|some-app/i, choco.stdout + choco.stderr);
assert.ok(existsSync(join(dir, 'chocolatey', 'some-app', 'some-app.1.2.3.nupkg')));
}
});