Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
build: shrink the Windows and macOS downloads and strip release sidecars
Cursor Agent97b54a5b5d17
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 258bee48b..031071929 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -50,6 +50,7 @@ jobs:- 'scripts/build-macos-packages*'- 'scripts/bundle-gpui*'- 'scripts/finalize-linux-*'+ - 'scripts/finalize-macos-*'- 'scripts/linux-bundle-config*'- 'scripts/prepare-gpui-dependency*'- 'scripts/run-gpui-build*'@@ -274,7 +275,7 @@ jobs:uses: actions/checkout@v4- name: Test desktop build preparation- run: node --test scripts/prepare-gpui-dependency.test.mjs scripts/build-macos-packages.test.mjs scripts/bundle-gpui.test.mjs+ run: node --test scripts/prepare-gpui-dependency.test.mjs scripts/build-macos-packages.test.mjs scripts/bundle-gpui.test.mjs scripts/finalize-macos-packages.test.mjs- name: Install Linux desktop dependenciesif: ${{ runner.os == 'Linux' }}diff --git a/.github/workflows/desktop-release.yml b/.github/workflows/desktop-release.ymlindex 11142a366..2217437a8 100644--- a/.github/workflows/desktop-release.yml+++ b/.github/workflows/desktop-release.yml@@ -231,7 +231,7 @@ jobs:run: node --test scripts/prepare-gpui-dependency.test.mjs- name: Test desktop packaging scripts- run: node --test scripts/build-macos-packages.test.mjs scripts/bundle-gpui.test.mjs+ run: node --test scripts/build-macos-packages.test.mjs scripts/bundle-gpui.test.mjs scripts/finalize-macos-packages.test.mjs- name: Install Linux desktop dependenciesif: ${{ runner.os == 'Linux' }}@@ -402,6 +402,22 @@ jobs:TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}RUST_TARGET_TRIPLE: ${{ matrix.settings.target }}+ # Same bytes, smaller downloads: zopfli for the updater archive, which+ # every install (0.6.0's Tauri updater included) still unpacks as gzip,+ # and LZMA for the disk image, which macOS 10.15+ mounts natively.+ - name: Shrink macOS packages+ if: ${{ runner.os == 'macOS' }}+ shell: bash+ run: |+ brew install pigz+ node scripts/finalize-macos-packages.mjs "$CAP_BUNDLE"+ env:+ HOMEBREW_NO_AUTO_UPDATE: "1"+ APPLE_SIGNING_IDENTITY: ${{ secrets.APPLE_SIGNING_IDENTITY }}+ APPLE_KEYCHAIN: ${{ format('{0}/build.keychain', runner.temp) }}+ TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}+ TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}+# Sign Cap's prebuilt binary and its sidecars in one request, then bundle# the installer from the signed payload.- name: Stage Windows payload for Authenticode signingdiff --git a/apps/desktop-gpui/packaging/windows/installer-hooks.nsh b/apps/desktop-gpui/packaging/windows/installer-hooks.nshindex 42749c420..6ef08c2eb 100644--- a/apps/desktop-gpui/packaging/windows/installer-hooks.nsh+++ b/apps/desktop-gpui/packaging/windows/installer-hooks.nsh@@ -1,3 +1,8 @@+; Tauri includes this file right after `SetCompressor /SOLID lzma`, before any+; data is compressed. A 128 MB window lets LZMA match cap-cli.exe against+; Cap.exe, which share most of their code; the default 8 MB window cannot.+SetCompressorDictSize 128+!macro NSIS_HOOK_POSTINSTALLDelete "$INSTDIR\cap-gpui.exe"Delete "$INSTDIR\cap-exporter.exe"diff --git a/apps/desktop-gpui/tauri.conf.json b/apps/desktop-gpui/tauri.conf.jsonindex bd7d7b2ea..b5f4be441 100644--- a/apps/desktop-gpui/tauri.conf.json+++ b/apps/desktop-gpui/tauri.conf.json@@ -71,7 +71,8 @@"headerImage": "../desktop/src-tauri/assets/nsis-header.bmp","sidebarImage": "../desktop/src-tauri/assets/nsis-sidebar.bmp","installerIcon": "../desktop/src-tauri/icons/icon.ico",- "installerHooks": "packaging/windows/installer-hooks.nsh"+ "installerHooks": "packaging/windows/installer-hooks.nsh",+ "compression": "lzma"},"webviewInstallMode": {"type": "skip"diff --git a/scripts/bundle-gpui.test.mjs b/scripts/bundle-gpui.test.mjsindex a7acc0ad3..367ff895e 100644--- a/scripts/bundle-gpui.test.mjs+++ b/scripts/bundle-gpui.test.mjs@@ -116,6 +116,22 @@ test("the GPUI bundle ships one CLI sidecar instead of two identical copies", ());});+test("the Windows installer compresses with a window large enough to span both binaries", () => {+ assert.equal(gpuiConfig.bundle.windows.nsis.compression, "lzma");+ const hooks = readFileSync(+ path.join(gpuiDirectory, gpuiConfig.bundle.windows.nsis.installerHooks),+ "utf8",+ );+ const directives = hooks+ .split(/\r?\n/)+ .filter((line) => line.trim() && !line.trim().startsWith(";"));+ assert.equal(directives[0], "SetCompressorDictSize 128");+ assert.ok(+ directives.indexOf("SetCompressorDictSize 128") <+ directives.findIndex((line) => line.startsWith("!macro")),+ );+});+test("platform resources point at the shared native dependencies", () => {assert.deepEqual(gpuiPlatformConfig("darwin"), {bundle: {diff --git a/scripts/finalize-macos-packages.mjs b/scripts/finalize-macos-packages.mjsnew file mode 100644index 000000000..340841d1c--- /dev/null+++ b/scripts/finalize-macos-packages.mjs@@ -0,0 +1,178 @@+import { mkdtemp, readdir, rename, rm, stat } from "node:fs/promises";+import path from "node:path";+import { setTimeout as wait } from "node:timers/promises";+import { pathToFileURL } from "node:url";+import { runCommand, signUpdaterArtifact } from "./finalize-linux-appimage.mjs";++const captured = (env) => ({+ env: { ...env, LC_ALL: "C" },+ encoding: "utf8",+ stdio: ["ignore", "pipe", "inherit"],+});++async function tarDigest(archive, env, run) {+ const result = await run(+ "bash",+ [+ "-c",+ 'set -euo pipefail; pigz -dc -- "$1" | shasum -a 256',+ "bash",+ archive,+ ],+ captured(env),+ );+ const digest = /^([0-9a-f]{64})\b/.exec(result.stdout ?? "")?.[1];+ if (!digest) throw new Error(`Could not read ${archive}`);+ return digest;+}++export async function recompressUpdaterArchive(+ filename,+ { unsigned = false, env = process.env, run = runCommand } = {},+) {+ const archive = path.resolve(filename);+ if (!archive.endsWith(".tar.gz")) {+ throw new Error("Expected a .tar.gz updater archive");+ }+ if (!unsigned && !env.TAURI_SIGNING_PRIVATE_KEY) {+ throw new Error(+ "TAURI_SIGNING_PRIVATE_KEY is required to sign the updater archive",+ );+ }+ const work = await mkdtemp(path.join(path.dirname(archive), ".cap-update-"));+ try {+ const output = path.join(work, path.basename(archive));+ await run(+ "bash",+ [+ "-c",+ 'set -euo pipefail; pigz -dc -- "$1" | pigz -11 -n -c > "$2"',+ "bash",+ archive,+ output,+ ],+ { env },+ );+ if (+ (await tarDigest(archive, env, run)) !==+ (await tarDigest(output, env, run))+ ) {+ throw new Error("The recompressed updater archive changed its contents");+ }+ const [before, after] = await Promise.all([stat(archive), stat(output)]);+ if (after.size >= before.size) {+ return { before: before.size, after: before.size };+ }+ if (!unsigned) await signUpdaterArtifact(output, { env, run });+ await rename(output, archive);+ if (unsigned) await rm(`${archive}.sig`, { force: true });+ else await rename(`${output}.sig`, `${archive}.sig`);+ return { before: before.size, after: after.size };+ } finally {+ await rm(work, { recursive: true, force: true });+ }+}++async function signDiskImage(dmg, env, run, delay) {+ const keychain = env.APPLE_KEYCHAIN ? ["--keychain", env.APPLE_KEYCHAIN] : [];+ for (let attempt = 0; ; attempt++) {+ try {+ await run(+ "codesign",+ [+ "--force",+ "--timestamp",+ "--sign",+ env.APPLE_SIGNING_IDENTITY,+ ...keychain,+ dmg,+ ],+ { env },+ );+ await run("codesign", ["--verify", dmg], { env });+ return;+ } catch (error) {+ if (attempt === 2) throw error;+ await delay(15_000 * (attempt + 1));+ }+ }+}++export async function convertDiskImage(+ filename,+ {+ env = process.env,+ run = runCommand,+ delay = wait,+ warn = (message) => console.warn(message),+ } = {},+) {+ const dmg = path.resolve(filename);+ if (!dmg.endsWith(".dmg")) throw new Error("Expected a .dmg disk image");+ if (!env.APPLE_SIGNING_IDENTITY) {+ throw new Error(+ "APPLE_SIGNING_IDENTITY is required to sign the disk image",+ );+ }+ const work = await mkdtemp(path.join(path.dirname(dmg), ".cap-dmg-"));+ try {+ const output = path.join(work, path.basename(dmg));+ try {+ await run("hdiutil", ["convert", dmg, "-format", "ULMO", "-o", output], {+ env,+ });+ await run("hdiutil", ["verify", output], { env });+ await signDiskImage(output, env, run, delay);+ } catch (error) {+ warn(+ `::warning::Keeping the zlib disk image; LZMA conversion failed: ${error instanceof Error ? error.message : error}`,+ );+ return null;+ }+ const [before, after] = await Promise.all([stat(dmg), stat(output)]);+ if (after.size >= before.size) {+ return { before: before.size, after: before.size };+ }+ await rename(output, dmg);+ return { before: before.size, after: after.size };+ } finally {+ await rm(work, { recursive: true, force: true });+ }+}++async function single(directory, extension) {+ const files = (await readdir(directory)).filter((file) =>+ file.endsWith(extension),+ );+ if (files.length !== 1) {+ throw new Error(+ `Expected one ${extension} in ${directory}, found ${files.length}`,+ );+ }+ return path.join(directory, files[0]);+}++export async function finalizeMacosPackages(bundleRoot, options = {}) {+ const archive = await single(path.join(bundleRoot, "macos"), ".app.tar.gz");+ const dmg = await single(path.join(bundleRoot, "dmg"), ".dmg");+ return {+ archive: await recompressUpdaterArchive(archive, options),+ dmg: await convertDiskImage(dmg, options),+ };+}++if (+ process.argv[1] &&+ import.meta.url === pathToFileURL(process.argv[1]).href+) {+ const [bundleRoot] = process.argv.slice(2);+ if (process.platform !== "darwin" || !bundleRoot) {+ throw new Error(+ "Run on macOS: node scripts/finalize-macos-packages.mjs <bundle directory>",+ );+ }+ const { archive, dmg } = await finalizeMacosPackages(bundleRoot);+ console.log(+ `Updater archive ${archive.before} -> ${archive.after} bytes; disk image ${dmg ? `${dmg.before} -> ${dmg.after} bytes` : "unchanged"}`,+ );+}diff --git a/scripts/finalize-macos-packages.test.mjs b/scripts/finalize-macos-packages.test.mjsnew file mode 100644index 000000000..5aaf43d3f--- /dev/null+++ b/scripts/finalize-macos-packages.test.mjs@@ -0,0 +1,208 @@+import assert from "node:assert/strict";+import { spawnSync } from "node:child_process";+import {+ mkdir,+ mkdtemp,+ readdir,+ readFile,+ rm,+ stat,+ writeFile,+} from "node:fs/promises";+import { tmpdir } from "node:os";+import path from "node:path";+import { test } from "node:test";+import { runCommand } from "./finalize-linux-appimage.mjs";+import {+ convertDiskImage,+ finalizeMacosPackages,+ recompressUpdaterArchive,+} from "./finalize-macos-packages.mjs";++const available = (command) =>+ spawnSync("sh", ["-c", `command -v ${command}`]).status === 0;+const zopfli = available("pigz") && available("shasum");++async function workspace(t) {+ const root = await mkdtemp(path.join(tmpdir(), "cap-macos-packages-"));+ t.after(() => rm(root, { recursive: true, force: true }));+ return root;+}++async function updaterArchive(root) {+ const app = path.join(root, "app/Cap.app/Contents/MacOS");+ await mkdir(app, { recursive: true });+ const line = "Cap records your screen, camera and microphone.\n";+ await writeFile(path.join(app, "Cap"), line.repeat(20_000), { mode: 0o755 });+ const archive = path.join(root, "Cap.app.tar.gz");+ runCommand("bash", [+ "-c",+ 'tar -C "$1" -cf - Cap.app | gzip -1 > "$2"',+ "bash",+ path.join(root, "app"),+ archive,+ ]);+ await writeFile(`${archive}.sig`, "original signature");+ return archive;+}++const tarBytes = (archive) =>+ spawnSync("bash", ["-c", 'gzip -dc "$1"', "bash", archive]).stdout;++test(+ "the updater archive is recompressed with identical contents and signed again",+ { skip: !zopfli },+ async (t) => {+ const root = await workspace(t);+ const archive = await updaterArchive(root);+ const original = tarBytes(archive);+ const before = (await stat(archive)).size;+ const signed = [];+ const result = await recompressUpdaterArchive(archive, {+ env: { ...process.env, TAURI_SIGNING_PRIVATE_KEY: "key" },+ run: async (command, args, options) => {+ if (command !== "bun") return runCommand(command, args, options);+ assert.deepEqual(args.slice(0, 4), ["run", "tauri", "signer", "sign"]);+ signed.push(await readFile(args[4]));+ await writeFile(`${args[4]}.sig`, "zopfli signature");+ return {};+ },+ });+ assert.ok(result.after < before, `${result.after} >= ${before}`);+ assert.equal((await stat(archive)).size, result.after);+ assert.deepEqual(tarBytes(archive), original);+ assert.deepEqual(signed, [await readFile(archive)]);+ assert.equal(await readFile(`${archive}.sig`, "utf8"), "zopfli signature");+ },+);++test("an updater archive whose contents change is left untouched", async (t) => {+ const root = await workspace(t);+ const archive = path.join(root, "Cap.app.tar.gz");+ await writeFile(archive, "original");+ await writeFile(`${archive}.sig`, "original signature");+ let digests = 0;+ await assert.rejects(+ recompressUpdaterArchive(archive, {+ env: { TAURI_SIGNING_PRIVATE_KEY: "key" },+ run: async (command, args) => {+ assert.equal(command, "bash");+ if (args[1].includes("pigz -11")) {+ await writeFile(args[4], "smaller");+ return {};+ }+ digests += 1;+ return { stdout: `${String(digests).repeat(64)} -\n` };+ },+ }),+ /changed its contents/,+ );+ assert.equal(await readFile(archive, "utf8"), "original");+ assert.equal(await readFile(`${archive}.sig`, "utf8"), "original signature");+});++function diskImageHarness({ convertedSize, failAt = new Set() }) {+ const calls = [];+ let codesignFailures = failAt.has("codesign") ? 1 : 0;+ const run = async (command, args) => {+ calls.push([command, args[0]]);+ if (failAt.has(`${command} ${args[0]}`)) {+ throw new Error(`${command} ${args[0]} failed`);+ }+ if (command === "hdiutil" && args[0] === "convert") {+ assert.deepEqual(args.slice(2, 4), ["-format", "ULMO"]);+ await writeFile(args[5], Buffer.alloc(convertedSize, 1));+ }+ if (command === "codesign" && args[0] === "--force") {+ if (codesignFailures > 0) {+ codesignFailures -= 1;+ throw new Error("The timestamp service is not available.");+ }+ assert.deepEqual(args.slice(0, 5), [+ "--force",+ "--timestamp",+ "--sign",+ "Developer ID Application: Cap",+ "--keychain",+ ]);+ }+ return {};+ };+ return { calls, run };+}++for (const scenario of [+ { name: "smaller", convertedSize: 10, replaced: true },+ { name: "larger", convertedSize: 400, replaced: false },+ {+ name: "failed",+ convertedSize: 10,+ failAt: new Set(["hdiutil verify"]),+ replaced: false,+ },+ {+ name: "retried",+ convertedSize: 10,+ failAt: new Set(["codesign"]),+ replaced: true,+ },+]) {+ test(`a ${scenario.name} LZMA disk image ${scenario.replaced ? "replaces" : "keeps"} the original`, async (t) => {+ const root = await workspace(t);+ const dmg = path.join(root, "Cap_0.6.1_aarch64.dmg");+ await writeFile(dmg, Buffer.alloc(100, 7));+ const { calls, run } = diskImageHarness(scenario);+ const delays = [];+ const warnings = [];+ const result = await convertDiskImage(dmg, {+ env: {+ APPLE_SIGNING_IDENTITY: "Developer ID Application: Cap",+ APPLE_KEYCHAIN: "/tmp/build.keychain",+ },+ run,+ delay: async (milliseconds) => delays.push(milliseconds),+ warn: (message) => warnings.push(message),+ });+ const contents = await readFile(dmg);+ if (scenario.replaced) {+ assert.deepEqual(contents, Buffer.alloc(10, 1));+ assert.deepEqual(result, { before: 100, after: 10 });+ } else {+ assert.deepEqual(contents, Buffer.alloc(100, 7));+ }+ if (scenario.name === "failed") {+ assert.equal(result, null);+ assert.match(warnings[0], /Keeping the zlib disk image/);+ }+ if (scenario.name === "retried") assert.deepEqual(delays, [15_000]);+ assert.deepEqual(calls[0], ["hdiutil", "convert"]);+ assert.ok(+ !(await readdir(root)).some((file) => file.startsWith(".cap-dmg-")),+ );+ });+}++test("disk image conversion needs a signing identity before touching the image", async (t) => {+ const root = await workspace(t);+ const dmg = path.join(root, "Cap.dmg");+ await writeFile(dmg, "original");+ await assert.rejects(+ convertDiskImage(dmg, {+ env: {},+ run: () => assert.fail("no command should run"),+ }),+ /APPLE_SIGNING_IDENTITY/,+ );+ assert.equal(await readFile(dmg, "utf8"), "original");+});++test("macOS packages are located once each inside the bundle", async (t) => {+ const root = await workspace(t);+ await mkdir(path.join(root, "macos"));+ await mkdir(path.join(root, "dmg"));+ await writeFile(path.join(root, "dmg/Cap_0.6.1_aarch64.dmg"), "dmg");+ await assert.rejects(+ finalizeMacosPackages(root, { env: {}, run: () => assert.fail() }),+ /Expected one \.app\.tar\.gz/,+ );+});