diff --git a/packages/waybetter/bin/waybetter.mjs b/packages/waybetter/bin/waybetter.mjs index 53704c6..6c496b0 100644 --- a/packages/waybetter/bin/waybetter.mjs +++ b/packages/waybetter/bin/waybetter.mjs @@ -1,16 +1,20 @@ #!/usr/bin/env node -// The `waybetter` command. Today: `waybetter store build|sign|verify` (cli/store.mjs). +// The `waybetter` command: `waybetter store build|sign|verify` (cli/store.mjs) and +// `waybetter release windows|macos` (cli/release.mjs). import { readFileSync } from 'node:fs'; import { STORE_USAGE, storeCommand } from '../cli/store.mjs'; +import { RELEASE_USAGE, releaseCommand } from '../cli/release.mjs'; const [area, ...rest] = process.argv.slice(2); try { if (area === 'store') { for (const line of await storeCommand(rest)) console.log(line); + } else if (area === 'release') { + await releaseCommand(rest); } else if (area === '--version' || area === '-v') { console.log(JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version); } else { - console.log(STORE_USAGE); + console.log(`${STORE_USAGE}\n\n${RELEASE_USAGE}`); if (area && area !== '--help' && area !== '-h') process.exitCode = 1; } } catch (error) { diff --git a/packages/waybetter/build/runtime.mjs b/packages/waybetter/build/runtime.mjs new file mode 100644 index 0000000..2db4bec --- /dev/null +++ b/packages/waybetter/build/runtime.mjs @@ -0,0 +1,80 @@ +// `waybetter/build`: bundles an app's page runtime (or any script native code injects into site +// tabs) into one self-contained IIFE with esbuild, the way every wayBetter app ships it: +// +// import { buildRuntime } from 'waybetter/build'; +// await buildRuntime({ +// entry: 'src/inject/entry.tsx', +// outfile: 'src-tauri/x-runtime.js', +// catalog: 'locales/en.json', // the app's English catalog ({ "messages": { ... } }) +// prefixes: ['x.', 'plugin.'], // only these strings are compiled in (others arrive natively) +// jsx: 'automatic', // any other esbuild option passes through +// }); +// +// - `?inline` CSS imports become strings (Vite semantics); other CSS side-effect imports are +// dropped, because injected UI adopts its stylesheet into a shadow root explicitly +// (`inlineCss: false` turns this off). +// - Imports of `catalog` load only the keys starting with one of `prefixes`: the runtime ships +// English for its own strings; the owner's language arrives natively (i18n_set). +// - esbuild is the app's own dependency (resolved from `cwd`, or pass `esbuild`). +import { readFile } from 'node:fs/promises'; +import { createRequire } from 'node:module'; +import path from 'node:path'; + +/** The CSS plugin: `?inline` imports as text, other CSS imports dropped. */ +export const inlineCssPlugin = { + name: 'waybetter-css', + setup(api) { + api.onResolve({ filter: /\.css(\?inline)?$/ }, args => ({ + path: path.resolve(args.resolveDir, args.path.replace(/\?inline$/, '')), + namespace: args.path.endsWith('?inline') ? 'css-inline' : 'css-drop', + })); + api.onLoad({ filter: /.*/, namespace: 'css-inline' }, async args => ({ contents: await readFile(args.path, 'utf8'), loader: 'text' })); + api.onLoad({ filter: /.*/, namespace: 'css-drop' }, () => ({ contents: '', loader: 'js' })); + }, +}; + +/** The catalog plugin: `catalog` (absolute path) loads as `{ messages }` with only `prefixes` keys. */ +export function catalogPlugin(catalog, prefixes) { + const target = path.resolve(catalog); + return { + name: 'waybetter-strings', + setup(api) { + api.onLoad({ filter: /\.json$/ }, async args => { + if (path.resolve(args.path) !== target) return undefined; + const { messages = {} } = JSON.parse(await readFile(args.path, 'utf8')); + const kept = Object.fromEntries(Object.entries(messages).filter(([key]) => prefixes.some(prefix => key.startsWith(prefix)))); + return { contents: JSON.stringify({ messages: kept }), loader: 'json' }; + }); + }, + }; +} + +/** + * Builds `entry` into `outfile` (paths relative to `cwd`). Defaults: bundled IIFE, es2022, + * minified, no source map, no legal comments. Returns esbuild's result. + * @param {{ entry: string, outfile: string, catalog?: string, prefixes?: string[], cwd?: string, + * inlineCss?: boolean, esbuild?: { build: Function }, plugins?: object[], [option: string]: unknown }} options + */ +export async function buildRuntime(options) { + const { entry, outfile, catalog, prefixes = [], cwd = process.cwd(), inlineCss = true, esbuild, plugins = [], ...rest } = options; + if (!entry || !outfile) throw new Error('buildRuntime: entry and outfile are required'); + if (catalog && !prefixes.length) throw new Error('buildRuntime: a catalog needs the key prefixes the runtime ships'); + const bundler = esbuild ?? createRequire(path.join(path.resolve(cwd), 'package.json'))('esbuild'); + return bundler.build({ + absWorkingDir: path.resolve(cwd), + entryPoints: [entry], + outfile, + bundle: true, + format: 'iife', + target: 'es2022', + minify: true, + sourcemap: false, + legalComments: 'none', + ...rest, + plugins: [ + ...(inlineCss ? [inlineCssPlugin] : []), + ...(catalog ? [catalogPlugin(path.resolve(cwd, catalog), prefixes)] : []), + ...plugins, + ], + }); +} diff --git a/packages/waybetter/cli/release.mjs b/packages/waybetter/cli/release.mjs new file mode 100644 index 0000000..a49e627 --- /dev/null +++ b/packages/waybetter/cli/release.mjs @@ -0,0 +1,289 @@ +// `waybetter release windows|macos`: a signed native release of a wayBetter app and its update +// manifest (`latest.json`). It never uploads anything: it prints the exact upload steps for the +// owner to run. Configured by the app's `waybetter.release.json` (found from the working directory +// up, or `--config `): +// +// { +// "product": "wayBetter for X", // names in messages +// "artifact": "wayBetter-for-X", // space-free file names on the CDN +// "desktopDir": "apps/desktop", // the Tauri app (package.json, src-tauri/) +// "keysDir": "~/.better-twttr-keys", // holds native.key (minisign); never committed +// "keysDirEnv": "BT_KEYS_DIR", // env override of keysDir +// "cdnBase": "https://cdn1.crt.fyi/better-twttr", +// "apiBase": "https://twttr.crt.fyi", // the update API (verification steps) +// "outDir": "releases", // releases/upload (files), releases/native/latest.json +// "manifestValidator": { "module": "packages/contracts/dist/index.js", "export": "NativeRelease", +// "hint": "build packages/contracts first" } // optional, zod-like .parse +// } +// +// The private key is read only into the build's environment (Windows) or handed to the Tauri +// signer by path (macOS). Nothing here prints, copies or moves it. +import { spawnSync } from 'node:child_process'; +import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs'; +import { homedir } from 'node:os'; +import { dirname, isAbsolute, join, relative, resolve } from 'node:path'; +import { pathToFileURL } from 'node:url'; + +export const CONFIG_FILE = 'waybetter.release.json'; + +export const RELEASE_USAGE = `Usage: + waybetter release windows [--skip-build] [--notes "text"] [--config ] + Signed NSIS build (Tauri, updater artifacts), the installer and .sig in /upload, + /native/latest.json (other platforms of the same version kept), upload steps printed. + waybetter release macos --dmg --updater [--arch universal] [--config ] + Signs the updater bundle of a universal macOS build here, copies both into /upload and + adds darwin-aarch64 and darwin-x86_64 to latest.json (run the Windows step first). + +Config: ${CONFIG_FILE} in the app's root (product, artifact, desktopDir, keysDir, keysDirEnv, +cdnBase, apiBase, outDir, optional manifestValidator). Env: CARGO_TARGET_DIR, CDN_BASE, +DEPLOY_TARGET, CDN_DIR, RELEASES_DIR. Nothing is ever uploaded.`; + +class ReleaseError extends Error {} +const fail = message => { throw new ReleaseError(message); }; + +/** Finds and reads the release config: `--config`, else the nearest waybetter.release.json. */ +export function loadReleaseConfig(cwd, file) { + let path = file ? resolve(cwd, file) : undefined; + if (!path) { + for (let dir = resolve(cwd); ; dir = dirname(dir)) { + if (existsSync(join(dir, CONFIG_FILE))) { path = join(dir, CONFIG_FILE); break; } + if (dirname(dir) === dir) fail(`no ${CONFIG_FILE} in ${cwd} or above (or pass --config)`); + } + } + if (!existsSync(path)) fail(`config not found: ${path}`); + let raw; + try { raw = JSON.parse(readFileSync(path, 'utf8')); } catch (error) { fail(`${path}: ${error.message}`); } + return normalizeReleaseConfig(raw, dirname(path)); +} + +const home = value => value.replace(/^~(?=$|[\\/])/, homedir()); + +/** Validated config with absolute paths (`root`: the folder holding the config file). */ +export function normalizeReleaseConfig(raw, root) { + const text = (key, fallback) => { + const value = raw[key] ?? fallback; + if (typeof value !== 'string' || !value.trim()) fail(`${CONFIG_FILE}: "${key}" must be a non-empty string`); + return value.trim(); + }; + const url = key => { + const value = text(key).replace(/\/+$/, ''); + if (!/^https:\/\/[^\s/]+/.test(value)) fail(`${CONFIG_FILE}: "${key}" must be an https URL`); + return value; + }; + const artifact = text('artifact'); + if (!/^[A-Za-z0-9._-]+$/.test(artifact)) fail(`${CONFIG_FILE}: "artifact" must be a space-free file name part`); + const validator = raw.manifestValidator; + if (validator !== undefined && (typeof validator?.module !== 'string' || typeof validator?.export !== 'string')) { + fail(`${CONFIG_FILE}: "manifestValidator" needs "module" and "export"`); + } + const at = value => (isAbsolute(value) ? value : resolve(root, value)); + const desktopDir = at(text('desktopDir')); + return { + root, + product: text('product'), + artifact, + desktopDir, + tauriDir: join(desktopDir, 'src-tauri'), + keysDir: at(home(text('keysDir'))), + keysDirEnv: raw.keysDirEnv === undefined ? undefined : text('keysDirEnv'), + keyFile: text('keyFile', 'native.key'), + cdnBase: url('cdnBase'), + apiBase: url('apiBase'), + outDir: at(text('outDir', 'releases')), + buildCommand: text('buildCommand', 'bun run tauri build'), + manifestValidator: validator && { module: at(validator.module), export: validator.export, hint: validator.hint }, + }; +} + +function keyPath(config, env) { + const dir = (config.keysDirEnv && env[config.keysDirEnv]) || config.keysDir; + return join(home(dir), config.keyFile); +} + +/** The shape every update manifest must have (also when the app adds its own validator). */ +export function checkManifest(manifest) { + if (!/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/.test(manifest.version ?? '')) fail(`manifest: bad version ${manifest.version}`); + if (typeof manifest.notes !== 'string' || typeof manifest.pubDate !== 'string') fail('manifest: notes and pubDate must be strings'); + const platforms = Object.entries(manifest.platforms ?? {}); + if (!platforms.length) fail('manifest: no platforms'); + for (const [key, entry] of platforms) { + if (!/^(windows|darwin|linux)-(x86_64|aarch64|i686|armv7)$/.test(key)) fail(`manifest: unknown platform ${key}`); + if (!/^https:\/\/\S+$/.test(entry?.url ?? '')) fail(`manifest: ${key} url must be https`); + if (typeof entry.signature !== 'string' || !entry.signature.trim()) fail(`manifest: ${key} has no signature`); + } + return manifest; +} + +async function validate(config, manifest) { + checkManifest(manifest); + if (!config.manifestValidator) return manifest; + const { module, export: name, hint } = config.manifestValidator; + const loaded = await import(pathToFileURL(module).href).catch(() => fail(hint || `cannot load ${module}`)); + const schema = loaded[name]; + if (!schema || typeof schema.parse !== 'function') fail(`${module} has no ${name}.parse`); + return schema.parse(manifest); +} + +function readVersion(config) { + const version = JSON.parse(readFileSync(join(config.root, 'package.json'), 'utf8')).version; + const conf = JSON.parse(readFileSync(join(config.tauriDir, 'tauri.conf.json'), 'utf8')); + const cargo = /^version\s*=\s*"([^"]+)"/m.exec(readFileSync(join(config.tauriDir, 'Cargo.toml'), 'utf8'))?.[1]; + const desktop = JSON.parse(readFileSync(join(config.desktopDir, 'package.json'), 'utf8')).version; + const rel = path => relative(config.root, path).replaceAll('\\', '/'); + for (const [name, value] of [ + [rel(join(config.tauriDir, 'tauri.conf.json')), conf.version], + [rel(join(config.tauriDir, 'Cargo.toml')), cargo], + [rel(join(config.desktopDir, 'package.json')), desktop], + ]) { + if (value !== version) fail(`${name} has version ${value}, root package.json has ${version}. Sync them first.`); + } + return { version, productName: conf.productName }; +} + +function option(args, name) { + const i = args.indexOf(name); + return i >= 0 ? args[i + 1] : undefined; +} + +const pubDate = () => new Date().toISOString().replace(/\.\d{3}Z$/, 'Z'); + +/** `waybetter release windows`. */ +export async function releaseWindows(config, args, { env = process.env, log = console.log } = {}) { + const { version, productName } = readVersion(config); + log(`release: ${config.product} ${version}`); + + // Signed build (updater artifacts need the minisign private key; its password is empty). + const targetDir = env.CARGO_TARGET_DIR ? resolve(env.CARGO_TARGET_DIR) : join(config.tauriDir, 'target'); + const bundleDir = join(targetDir, 'release', 'bundle', 'nsis'); + if (!args.includes('--skip-build')) { + const key = keyPath(config, env); + if (!existsSync(key)) fail(`signing key not found at ${key}`); + // A fixed command string from the app's own config (no user input), so the shell is safe. + const result = spawnSync(config.buildCommand, { + cwd: config.desktopDir, + stdio: 'inherit', + shell: true, + env: { ...env, TAURI_SIGNING_PRIVATE_KEY: readFileSync(key, 'utf8').trim(), TAURI_SIGNING_PRIVATE_KEY_PASSWORD: '' }, + }); + if (result.status !== 0) fail(`tauri build failed (exit ${result.status})`); + } + + // The NSIS installer is also the updater payload (createUpdaterArtifacts, v2 format). + if (!existsSync(bundleDir)) fail(`no NSIS bundle folder at ${bundleDir}`); + // Exactly the current productName: the folder may still hold installers built under an older name. + const installer = readdirSync(bundleDir).find(name => name === `${productName}_${version}_x64-setup.exe`); + if (!installer) fail(`no x64 setup.exe for ${version} in ${bundleDir}`); + const sigPath = join(bundleDir, `${installer}.sig`); + if (!existsSync(sigPath)) fail(`missing ${installer}.sig (was TAURI_SIGNING_PRIVATE_KEY set?)`); + + const uploadDir = join(config.outDir, 'upload'); + mkdirSync(join(config.outDir, 'native'), { recursive: true }); + mkdirSync(uploadDir, { recursive: true }); + // Versioned, space-free names: immutable on the CDN and safe in URLs. + const fileName = `${config.artifact}_${version}_x64-setup.exe`; + copyFileSync(join(bundleDir, installer), join(uploadDir, fileName)); + copyFileSync(sigPath, join(uploadDir, `${fileName}.sig`)); + + const cdnBase = (env.CDN_BASE ?? config.cdnBase).replace(/\/+$/, ''); + const manifestPath = join(config.outDir, 'native', 'latest.json'); + // macOS and Linux entries of the same version are kept. + let others = {}; + try { + const previous = JSON.parse(readFileSync(manifestPath, 'utf8')); + if (previous.version === version) others = Object.fromEntries(Object.entries(previous.platforms ?? {}).filter(([key]) => key !== 'windows-x86_64')); + } catch { /* no previous manifest */ } + const manifest = await validate(config, { + version, + notes: option(args, '--notes') ?? '', + pubDate: pubDate(), + platforms: { ...others, 'windows-x86_64': { url: `${cdnBase}/${fileName}`, signature: readFileSync(sigPath, 'utf8').trim() } }, + }); + writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`); + log(`release: wrote ${manifestPath}`); + + // Installer first, manifest last, so clients never see a manifest pointing at a missing file. + const target = env.DEPLOY_TARGET ?? '@'; + const cdnDir = env.CDN_DIR ?? ``; + const releasesDir = env.RELEASES_DIR ?? ''; + const rel = path => relative(config.root, path).replaceAll('\\', '/'); + log(` +Nothing was uploaded. Run these steps yourself, in this order: + + 1. Upload the installer and its signature to the CDN: + scp "${rel(join(uploadDir, fileName))}" "${rel(join(uploadDir, `${fileName}.sig`))}" ${target}:${cdnDir}/ + + 2. Check it is reachable before publishing the manifest: + curl -sSfI ${cdnBase}/${fileName} + + 3. Publish the manifest (the API hot-reloads it by mtime; no restart needed): + scp "${rel(manifestPath)}" ${target}:${releasesDir}/native/latest.json.tmp + ssh ${target} "mv ${releasesDir}/native/latest.json.tmp ${releasesDir}/native/latest.json" + + 4. Verify the update endpoint answers an older client: + curl -sS ${config.apiBase}/v1/updates/windows/x86_64/0.0.0 +`); + return { version, manifestPath, files: [fileName, `${fileName}.sig`] }; +} + +/** `waybetter release macos`: adds a universal macOS build (built unsigned on the Mac) to the release. */ +export async function releaseMacos(config, args, { env = process.env, log = console.log } = {}) { + const version = JSON.parse(readFileSync(join(config.root, 'package.json'), 'utf8')).version; + const dmg = option(args, '--dmg'); + const updater = option(args, '--updater'); + const arch = option(args, '--arch') ?? 'universal'; + if (!dmg || !updater) fail('usage: --dmg --updater [--arch universal]'); + if (arch !== 'universal') fail('only universal builds are supported (one file serves both darwin arches)'); + for (const file of [dmg, updater]) if (!existsSync(file)) fail(`not found: ${file}`); + if (!updater.endsWith('.app.tar.gz')) fail('--updater must be the .app.tar.gz Tauri wrote'); + + const uploadDir = join(config.outDir, 'upload'); + mkdirSync(uploadDir, { recursive: true }); + const dmgName = `${config.artifact}_${version}_${arch}.dmg`; + const updaterName = `${config.artifact}_${version}_${arch}.app.tar.gz`; + copyFileSync(dmg, join(uploadDir, dmgName)); + copyFileSync(updater, join(uploadDir, updaterName)); + + // Sign the copy (the signature's trusted comment names this file and binds the version). + const key = keyPath(config, env); + if (!existsSync(key)) fail(`signing key not found at ${key}`); + const exe = process.platform === 'win32' ? 'tauri.exe' : 'tauri'; + const tauri = [join(config.desktopDir, 'node_modules', '.bin', exe), join(config.root, 'node_modules', '.bin', exe)].find(existsSync); + if (!tauri) fail('Tauri CLI not installed (bun install)'); + const signed = spawnSync(tauri, ['signer', 'sign', '-f', key, '-p', '', '--app-version', version, join(uploadDir, updaterName)], { + stdio: ['ignore', 'ignore', 'inherit'], // stdout would echo the signature; the .sig file holds it + }); + if (signed.status !== 0) fail(`tauri signer sign failed (exit ${signed.status})`); + const sigPath = join(uploadDir, `${updaterName}.sig`); + if (!existsSync(sigPath)) fail(`signer wrote no ${sigPath}`); + + const manifestPath = join(config.outDir, 'native', 'latest.json'); + if (!existsSync(manifestPath)) fail(`no ${relative(config.root, manifestPath)}: run \`waybetter release windows\` first`); + const current = JSON.parse(readFileSync(manifestPath, 'utf8')); + if (current.version !== version) fail(`latest.json is ${current.version}, this build is ${version}`); + const cdnBase = (env.CDN_BASE ?? config.cdnBase).replace(/\/+$/, ''); + const entry = { url: `${cdnBase}/${updaterName}`, signature: readFileSync(sigPath, 'utf8').trim() }; + const manifest = await validate(config, { ...current, platforms: { ...current.platforms, 'darwin-aarch64': entry, 'darwin-x86_64': entry } }); + writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`); + log(`release-macos: ${dmgName}, ${updaterName} (+ .sig) in ${relative(config.root, uploadDir).replaceAll('\\', '/')}; latest.json now has ${Object.keys(manifest.platforms).join(', ')}`); + log(` +Nothing was uploaded. Upload the dmg, the updater bundle and its .sig to the CDN next to the +Windows installer (same target and folder as \`waybetter release windows\` prints), check + curl -sSfI ${cdnBase}/${updaterName} +then publish latest.json the same way (tmp file, then mv), and verify + curl -sS ${config.apiBase}/v1/updates/darwin/aarch64/0.0.0 + curl -sS ${config.apiBase}/v1/updates/darwin/x86_64/0.0.0 +`); + return { version, manifestPath, files: [dmgName, updaterName, `${updaterName}.sig`] }; +} + +/** `waybetter release ...` from the command line (or an app's wrapper script). */ +export async function releaseCommand(args, { cwd = process.cwd(), env = process.env, log = console.log } = {}) { + const [platform, ...rest] = args; + if (platform !== 'windows' && platform !== 'macos') { + log(RELEASE_USAGE); + if (platform && platform !== '--help' && platform !== '-h') fail(`unknown release target ${platform}`); + return undefined; + } + const config = loadReleaseConfig(cwd, option(rest, '--config')); + return platform === 'windows' ? releaseWindows(config, rest, { env, log }) : releaseMacos(config, rest, { env, log }); +} diff --git a/packages/waybetter/package.json b/packages/waybetter/package.json index 9b532bd..b6f83bc 100644 --- a/packages/waybetter/package.json +++ b/packages/waybetter/package.json @@ -1,9 +1,9 @@ { "name": "waybetter", - "version": "0.2.0", + "version": "0.3.0", "license": "GPL-3.0-or-later", "type": "module", - "description": "wayBetter: the framework for apps that run the apps you already use in a light native (Tauri) window and extend them in place. Page runtime (DOM/request hubs, plugins, plugin UI kit with themed dialogs and toasts, theme API and theme JSON Schema, theme color model, link routing, account reporting, deck columns, i18n: ICU-lite messages, locale fallback, plugin strings, catalog checks and JSON Schemas), shell models (address bar, panes, decks, profiles, palette, updates) and the Store: install screen and Store view React components (optional React peer), their state and catalog models, the store catalog JSON Schema and the `waybetter store build|sign|verify` command. No dependencies.", + "description": "wayBetter: the framework for apps that run the apps you already use in a light native (Tauri) window and extend them in place. Page runtime (DOM/request hubs, plugins, plugin UI kit with themed dialogs and toasts, theme API and theme JSON Schema, theme color model, link routing, account reporting, deck columns, i18n: ICU-lite messages, locale fallback, plugin strings, catalog checks and JSON Schemas), shell models (address bar, panes, decks, profiles, palette, updates) and the Store: install screen and Store view React components (optional React peer), their state and catalog models, the store catalog JSON Schema and the `waybetter store build|sign|verify` command, `waybetter release windows|macos` (signed native releases and the update manifest, configured by waybetter.release.json) and `waybetter/build` (the page runtime bundle, with an optional esbuild peer). No dependencies.", "keywords": [ "waybetter", "tauri", @@ -167,11 +167,14 @@ "./theme.schema.json": "./theme.schema.json", "./store-catalog.schema.json": "./store-catalog.schema.json", "./cli/store": "./cli/store.mjs", + "./cli/release": "./cli/release.mjs", + "./build": "./build/runtime.mjs", "./package.json": "./package.json" }, "files": [ "dist", "bin", + "build", "cli", "theme.schema.json", "store-catalog.schema.json", @@ -185,10 +188,14 @@ "node": ">=18.0.0" }, "peerDependencies": { + "esbuild": ">=0.20.0", "react": ">=18.0.0", "react-dom": ">=18.0.0" }, "peerDependenciesMeta": { + "esbuild": { + "optional": true + }, "react": { "optional": true }, diff --git a/packages/waybetter/tests/build.test.mjs b/packages/waybetter/tests/build.test.mjs new file mode 100644 index 0000000..a8d535a --- /dev/null +++ b/packages/waybetter/tests/build.test.mjs @@ -0,0 +1,55 @@ +// `waybetter/build`: the page runtime bundle options and its two esbuild plugins (no esbuild needed: +// the plugins run against a recording stand-in for esbuild's plugin API). +import assert from 'node:assert/strict'; +import { mkdtempSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import test from 'node:test'; +import { buildRuntime, catalogPlugin, inlineCssPlugin } from '../build/runtime.mjs'; + +/** Runs a plugin's setup and returns its onResolve/onLoad handlers. */ +function hooks(plugin) { + const out = { resolve: [], load: [] }; + plugin.setup({ + onResolve: (options, fn) => out.resolve.push({ options, fn }), + onLoad: (options, fn) => out.load.push({ options, fn }), + }); + return out; +} + +test('buildRuntime: an IIFE bundle with the app\'s options on top of the defaults', async () => { + let seen; + const esbuild = { build: async options => { seen = options; return { errors: [] } } }; + await buildRuntime({ entry: 'src/a.ts', outfile: 'out.js', cwd: tmpdir(), esbuild, minify: false, jsx: 'automatic', catalog: 'en.json', prefixes: ['x.'] }); + assert.deepEqual(seen.entryPoints, ['src/a.ts']); + assert.equal(seen.format, 'iife'); + assert.equal(seen.bundle, true); + assert.equal(seen.minify, false); + assert.equal(seen.jsx, 'automatic'); + assert.equal(seen.legalComments, 'none'); + assert.deepEqual(seen.plugins.map(plugin => plugin.name), ['waybetter-css', 'waybetter-strings']); + await buildRuntime({ entry: 'a', outfile: 'b', cwd: tmpdir(), esbuild, inlineCss: false }); + assert.deepEqual(seen.plugins, []); + await assert.rejects(buildRuntime({ entry: 'a', outfile: 'b', esbuild, catalog: 'en.json' }), /prefixes/); + await assert.rejects(buildRuntime({ outfile: 'b', esbuild }), /entry/); +}); + +test('catalog plugin: only the runtime\'s own prefixes, only for that catalog', async () => { + const dir = mkdtempSync(join(tmpdir(), 'wb-build-')); + const catalog = join(dir, 'en.json'); + writeFileSync(catalog, JSON.stringify({ messages: { 'x.a': 'A', 'plugin.b': 'B', 'native.c': 'C', 'kit.d': 'D' } })); + const [{ fn }] = hooks(catalogPlugin(catalog, ['x.', 'plugin.'])).load; + const loaded = await fn({ path: catalog }); + assert.equal(loaded.loader, 'json'); + assert.deepEqual(JSON.parse(loaded.contents), { messages: { 'x.a': 'A', 'plugin.b': 'B' } }); + assert.equal(await fn({ path: join(dir, 'other.json') }), undefined); +}); + +test('css plugin: ?inline imports are text, other CSS imports are dropped', async () => { + const { resolve, load } = hooks(inlineCssPlugin); + const [{ fn: resolveCss }] = resolve; + assert.equal(resolveCss({ path: './a.css?inline', resolveDir: '/x' }).namespace, 'css-inline'); + assert.equal(resolveCss({ path: './a.css', resolveDir: '/x' }).namespace, 'css-drop'); + const drop = load.find(hook => hook.options.namespace === 'css-drop'); + assert.deepEqual(drop.fn({}), { contents: '', loader: 'js' }); +}); diff --git a/packages/waybetter/tests/release-cli.test.mjs b/packages/waybetter/tests/release-cli.test.mjs new file mode 100644 index 0000000..b5357e3 --- /dev/null +++ b/packages/waybetter/tests/release-cli.test.mjs @@ -0,0 +1,118 @@ +// `waybetter release windows|macos`: config, version checks, artifacts, manifest merge, printed steps. +import assert from 'node:assert/strict'; +import { execFileSync } from 'node:child_process'; +import { existsSync, mkdirSync, 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 { checkManifest, loadReleaseConfig, normalizeReleaseConfig, releaseCommand } from '../cli/release.mjs'; + +const BIN = fileURLToPath(new URL('../bin/waybetter.mjs', import.meta.url)); + +const CONFIG = { + product: 'wayBetter for Test', + artifact: 'wayBetter-for-Test', + desktopDir: 'apps/desktop', + keysDir: 'keys-not-here', + keysDirEnv: 'TEST_KEYS_DIR', + cdnBase: 'https://cdn.example.test/app/', + apiBase: 'https://api.example.test', + outDir: 'releases', +}; + +/** A minimal app tree: versions everywhere, a built NSIS bundle in `target`. */ +function app({ version = '1.2.3', cargo = version, config = CONFIG } = {}) { + const root = mkdtempSync(join(tmpdir(), 'wb-release-')); + const tauri = join(root, 'apps/desktop/src-tauri'); + mkdirSync(tauri, { recursive: true }); + writeFileSync(join(root, 'waybetter.release.json'), JSON.stringify(config)); + writeFileSync(join(root, 'package.json'), JSON.stringify({ version })); + writeFileSync(join(root, 'apps/desktop/package.json'), JSON.stringify({ version })); + writeFileSync(join(tauri, 'tauri.conf.json'), JSON.stringify({ version, productName: 'Test App' })); + writeFileSync(join(tauri, 'Cargo.toml'), `[package]\nname = "t"\nversion = "${cargo}"\n`); + const nsis = join(root, 'target/release/bundle/nsis'); + mkdirSync(nsis, { recursive: true }); + writeFileSync(join(nsis, `Test App_${version}_x64-setup.exe`), 'installer'); + writeFileSync(join(nsis, `Test App_${version}_x64-setup.exe.sig`), 'SIGNATURE\n'); + return { root, env: { CARGO_TARGET_DIR: join(root, 'target') } }; +} + +test('config: found from a subfolder, paths resolved, https URLs, safe artifact names', () => { + const { root } = app(); + const config = loadReleaseConfig(join(root, 'apps/desktop')); + assert.equal(config.root, root); + assert.equal(config.tauriDir, join(root, 'apps/desktop/src-tauri')); + assert.equal(config.cdnBase, 'https://cdn.example.test/app'); + assert.equal(config.keyFile, 'native.key'); + assert.throws(() => normalizeReleaseConfig({ ...CONFIG, cdnBase: 'http://cdn.example.test' }, root), /https/); + assert.throws(() => normalizeReleaseConfig({ ...CONFIG, artifact: 'has space' }, root), /artifact/); + assert.throws(() => normalizeReleaseConfig({ ...CONFIG, product: '' }, root), /product/); + assert.throws(() => loadReleaseConfig(tmpdir() + '/definitely-missing-wb', 'nope.json'), /not found/); +}); + +test('windows: copies the signed installer, writes latest.json, keeps other platforms, prints steps only', async () => { + const { root, env } = app(); + mkdirSync(join(root, 'releases/native'), { recursive: true }); + const mac = { url: 'https://cdn.example.test/app/mac.app.tar.gz', signature: 'MAC' }; + writeFileSync(join(root, 'releases/native/latest.json'), JSON.stringify({ version: '1.2.3', notes: '', pubDate: 'x', platforms: { 'darwin-aarch64': mac, 'windows-x86_64': { url: 'https://old', signature: 'OLD' } } })); + const lines = []; + const out = await releaseCommand(['windows', '--skip-build', '--notes', 'Fixes'], { cwd: root, env, log: line => lines.push(line) }); + assert.deepEqual(out.files, ['wayBetter-for-Test_1.2.3_x64-setup.exe', 'wayBetter-for-Test_1.2.3_x64-setup.exe.sig']); + for (const file of out.files) assert.ok(existsSync(join(root, 'releases/upload', file)), file); + const manifest = JSON.parse(readFileSync(join(root, 'releases/native/latest.json'), 'utf8')); + assert.equal(manifest.notes, 'Fixes'); + assert.deepEqual(manifest.platforms['darwin-aarch64'], mac); + assert.deepEqual(manifest.platforms['windows-x86_64'], { url: 'https://cdn.example.test/app/wayBetter-for-Test_1.2.3_x64-setup.exe', signature: 'SIGNATURE' }); + const text = lines.join('\n'); + assert.match(text, /^release: wayBetter for Test 1\.2\.3/); + assert.match(text, /Nothing was uploaded/); + assert.match(text, /curl -sS https:\/\/api\.example\.test\/v1\/updates\/windows\/x86_64\/0\.0\.0/); + assert.match(text, //); +}); + +test('windows: a version mismatch or a missing installer stops before anything is written', async () => { + const mismatch = app({ cargo: '1.2.2' }); + await assert.rejects(releaseCommand(['windows', '--skip-build'], { cwd: mismatch.root, env: mismatch.env, log: () => {} }), /Cargo\.toml has version 1\.2\.2/); + assert.ok(!existsSync(join(mismatch.root, 'releases'))); + const noBundle = app(); + await assert.rejects(releaseCommand(['windows', '--skip-build'], { cwd: noBundle.root, env: {}, log: () => {} }), /no NSIS bundle folder/); +}); + +test('windows: without --skip-build the key must exist (its path is named, never its contents)', async () => { + const { root, env } = app(); + await assert.rejects( + releaseCommand(['windows'], { cwd: root, env: { ...env, TEST_KEYS_DIR: join(root, 'nokeys') }, log: () => {} }), + error => error.message.includes(join(root, 'nokeys', 'native.key')), + ); +}); + +test('windows: the app\'s own manifest validator runs after the built-in shape check', async () => { + const { root, env } = app(); + writeFileSync(join(root, 'validator.mjs'), 'export const Release = { parse: m => ({ ...m, checked: true }) };\n'); + writeFileSync(join(root, 'waybetter.release.json'), JSON.stringify({ ...CONFIG, manifestValidator: { module: 'validator.mjs', export: 'Release' } })); + await releaseCommand(['windows', '--skip-build'], { cwd: root, env, log: () => {} }); + assert.equal(JSON.parse(readFileSync(join(root, 'releases/native/latest.json'), 'utf8')).checked, true); +}); + +test('manifest shape: https URLs, known platforms, signatures', () => { + const ok = { version: '1.0.0', notes: '', pubDate: '2026-01-01T00:00:00Z', platforms: { 'windows-x86_64': { url: 'https://a/b.exe', signature: 's' } } }; + assert.equal(checkManifest(ok), ok); + assert.throws(() => checkManifest({ ...ok, platforms: { 'windows-x86_64': { url: 'http://a/b.exe', signature: 's' } } }), /https/); + assert.throws(() => checkManifest({ ...ok, platforms: { 'amiga-m68k': { url: 'https://a', signature: 's' } } }), /unknown platform/); + assert.throws(() => checkManifest({ ...ok, platforms: { 'windows-x86_64': { url: 'https://a', signature: '' } } }), /signature/); +}); + +test('macos: needs the dmg, the .app.tar.gz and a Windows manifest first', async () => { + const { root } = app(); + await assert.rejects(releaseCommand(['macos'], { cwd: root, log: () => {} }), /usage: --dmg/); + writeFileSync(join(root, 'a.dmg'), 'dmg'); + writeFileSync(join(root, 'a.zip'), 'zip'); + await assert.rejects(releaseCommand(['macos', '--dmg', join(root, 'a.dmg'), '--updater', join(root, 'a.zip')], { cwd: root, log: () => {} }), /\.app\.tar\.gz/); + await assert.rejects(releaseCommand(['macos', '--dmg', 'x', '--updater', 'y', '--arch', 'aarch64'], { cwd: root, log: () => {} }), /universal/); +}); + +test('the bin: usage lists release, an unknown target fails', () => { + assert.match(execFileSync(process.execPath, [BIN, '--help'], { encoding: 'utf8' }), /waybetter release windows/); + assert.throws(() => execFileSync(process.execPath, [BIN, 'release', 'amiga'], { encoding: 'utf8', stdio: 'pipe' }), /unknown release target/); +});