Skip to content

A full-featured download manager.

feat(build): optimize Electron package size (#1838)

Dr_rOot227ceb09cd9e
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index f534fa8f..3b81e921 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -134,12 +134,16 @@ jobs:
src/main/bridge/snap-environment.test.ts
tests/scripts/assemble-release-artifacts.test.ts
tests/scripts/before-pack-verify.test.ts
+ tests/scripts/electron-package-contract.test.ts
tests/scripts/flatpak-native-host.test.ts
+ tests/scripts/native-binary-target.test.ts
tests/scripts/release-metadata.test.ts
tests/scripts/snap-artifact.test.ts
tests/scripts/snap-build-set-release.test.ts
tests/scripts/snap-project.test.ts
tests/scripts/snap-store-channel.test.ts
+ tests/scripts/stage-electron-app.test.ts
+ tests/scripts/verify-electron-package.test.ts
tests/scripts/verify-update-artifacts.test.ts
tests/scripts/workflow-release-matrix.test.ts
tests/scripts/workflow-snap.test.ts
@@ -211,6 +215,7 @@ jobs:
rust_target: aarch64-apple-darwin
electron_builder_args: --mac --arm64
resources_dir: release/mac-arm64/Motrix.app/Contents/Resources
+ app_path: release/mac-arm64/Motrix.app
- target: darwin-x64
os: macos-26-intel
platform: darwin
@@ -218,6 +223,7 @@ jobs:
rust_target: x86_64-apple-darwin
electron_builder_args: --mac --x64
resources_dir: release/mac/Motrix.app/Contents/Resources
+ app_path: release/mac/Motrix.app
- target: linux-x64
os: ubuntu-22.04
platform: linux
@@ -225,6 +231,7 @@ jobs:
rust_target: x86_64-unknown-linux-musl
electron_builder_args: --linux --x64
resources_dir: release/linux-unpacked/resources
+ app_path: release/linux-unpacked
- target: linux-arm64
os: ubuntu-22.04-arm
platform: linux
@@ -232,6 +239,7 @@ jobs:
rust_target: aarch64-unknown-linux-musl
electron_builder_args: --linux --arm64
resources_dir: release/linux-arm64-unpacked/resources
+ app_path: release/linux-arm64-unpacked
- target: win32-x64
os: windows-2025
platform: win32
@@ -239,6 +247,7 @@ jobs:
rust_target: x86_64-pc-windows-msvc
electron_builder_args: --win --x64
resources_dir: release/win-unpacked/resources
+ app_path: release/win-unpacked
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
@@ -293,6 +302,12 @@ jobs:
pnpm run build:native-host -- --platform ${{ matrix.platform }} --arch ${{ matrix.arch }}
pnpm run build:electron
+ - name: Stage Electron application
+ run: >-
+ pnpm run stage:electron --
+ --platform ${{ matrix.platform }}
+ --arch ${{ matrix.arch }}
+
- name: Package Flatpak native host companion smoke
if: matrix.platform == 'linux'
shell: bash
@@ -322,6 +337,14 @@ jobs:
--dir
--publish never
+ - name: Verify Electron package
+ run: >-
+ node scripts/verify-electron-package.mjs
+ --app-dir "${{ matrix.app_path }}"
+ --platform ${{ matrix.platform }}
+ --arch ${{ matrix.arch }}
+ --report "release/size-reports/${{ matrix.target }}.json"
+
- name: Verify Windows native host runtime imports
if: matrix.platform == 'win32'
shell: pwsh
@@ -387,3 +410,11 @@ jobs:
throw new Error(`Flatpak-only native host leaked into package: ${file}`)
}
}
+
+ - name: Upload Electron size report
+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
+ with:
+ name: electron-size-report-${{ matrix.target }}-${{ github.run_attempt }}
+ path: release/size-reports/${{ matrix.target }}.json
+ if-no-files-found: error
+ retention-days: 14
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 9d8a6b13..92dc4805 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -110,6 +110,7 @@ jobs:
rust_target: x86_64-unknown-linux-musl
electron_builder_args: --linux deb rpm --x64
resources_dir: release/linux-unpacked/resources
+ app_path: release/linux-unpacked
- target: linux-arm64
os: ubuntu-22.04-arm
platform: linux
@@ -117,6 +118,7 @@ jobs:
rust_target: aarch64-unknown-linux-musl
electron_builder_args: --linux deb rpm --arm64
resources_dir: release/linux-arm64-unpacked/resources
+ app_path: release/linux-arm64-unpacked
- target: win32-x64
os: windows-2025
platform: win32
@@ -124,6 +126,7 @@ jobs:
rust_target: x86_64-pc-windows-msvc
electron_builder_args: --win --x64
resources_dir: release/win-unpacked/resources
+ app_path: release/win-unpacked
# rustc's musl std is self-contained; overriding the linker with Ubuntu's
# musl-gcc mixes CRTs and produces binaries that SIGSEGV at load (see
@@ -242,6 +245,7 @@ jobs:
pnpm run build:builtin
pnpm run build:native-host -- --platform ${{ matrix.platform }} --arch ${{ matrix.arch }}
pnpm run build:electron
+ pnpm run stage:electron -- --platform ${{ matrix.platform }} --arch ${{ matrix.arch }}
# Materialize the private key only after all project-controlled build
# scripts have completed. The path is passed through a step output so the
@@ -300,6 +304,14 @@ jobs:
${{ matrix.electron_builder_args }}
--publish never
+ - name: Verify Electron package
+ run: >-
+ node scripts/verify-electron-package.mjs
+ --app-dir "${{ matrix.app_path }}"
+ --platform ${{ matrix.platform }}
+ --arch ${{ matrix.arch }}
+ --report "release/size-reports/${{ matrix.target }}.json"
+
- name: Verify Windows native host runtime imports
if: matrix.platform == 'win32'
shell: pwsh
@@ -494,6 +506,7 @@ jobs:
release/*.rpm
release/*.tar.gz
release/latest*.yml
+ release/size-reports/${{ matrix.target }}.json
release/*.zip
if-no-files-found: error
retention-days: 7
diff --git a/.github/workflows/snap.yml b/.github/workflows/snap.yml
index d3b972e2..bbb9c51c 100644
--- a/.github/workflows/snap.yml
+++ b/.github/workflows/snap.yml
@@ -179,6 +179,12 @@ jobs:
--arch ${{ matrix.electron_arch }}
pnpm run build:electron
+ - name: Stage Electron application
+ run: >-
+ pnpm run stage:electron --
+ --platform linux
+ --arch ${{ matrix.electron_arch }}
+
- name: Build unpacked Electron application
env:
CSC_IDENTITY_AUTO_DISCOVERY: 'false'
@@ -189,6 +195,14 @@ jobs:
--${{ matrix.electron_arch }}
--publish never
+ - name: Verify Electron package
+ run: >-
+ node scripts/verify-electron-package.mjs
+ --app-dir "${{ matrix.app_dir }}"
+ --platform linux
+ --arch ${{ matrix.electron_arch }}
+ --report "release/size-reports/linux-${{ matrix.electron_arch }}.json"
+
- name: Prepare isolated Snapcraft project
run: >-
node scripts/prepare-snap-project.mjs
@@ -216,7 +230,9 @@ jobs:
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: snap-input-${{ matrix.snap_arch }}
- path: ${{ steps.snapcraft.outputs.snap }}
+ path: |
+ ${{ steps.snapcraft.outputs.snap }}
+ release/size-reports/linux-${{ matrix.electron_arch }}.json
if-no-files-found: error
compression-level: 0
retention-days: 7
diff --git a/electron-builder.json b/electron-builder.json
index e046fcfb..bce95110 100644
--- a/electron-builder.json
+++ b/electron-builder.json
@@ -6,16 +6,33 @@
"asar": true,
"asarUnpack": [
"**/node_modules/{better-sqlite3,bindings,file-uri-to-path}/**",
- "**/node_modules/@resvg/resvg-wasm/**/*.wasm",
"dist/renderer/**"
],
"directories": {
+ "app": "dist/electron-app",
"output": "release",
"buildResources": "build"
},
"files": [
- "dist/**/*",
+ ".motrix-package-stage.json",
+ "dist/core/plugin/host/**",
+ "dist/main/**",
+ "dist/preload/**",
+ "dist/renderer/**",
"package.json",
+ {
+ "from": "node_modules",
+ "to": "node_modules",
+ "filter": [
+ "**/*",
+ "!**/*.map",
+ "!**/*.ts",
+ "!**/*.tsx",
+ "!**/tsconfig*.json",
+ "!**/biome.json",
+ "!**/vite*.config.*"
+ ]
+ },
"!**/*.map",
"!**/*.ts",
"!**/*.tsx",
@@ -202,6 +219,7 @@
"artifactName": "${productName}-${version}.${arch}.${ext}"
},
"beforePack": "./scripts/before-pack-verify.mjs",
+ "beforeBuild": "./scripts/before-build-use-staged-dependencies.mjs",
"detectUpdateChannel": true,
"generateUpdatesFilesForAllChannels": true,
"publish": {
diff --git a/flatpak/app.motrix.native.yml b/flatpak/app.motrix.native.yml
index 133536da..c79d9893 100644
--- a/flatpak/app.motrix.native.yml
+++ b/flatpak/app.motrix.native.yml
@@ -238,6 +238,9 @@ modules:
- pnpm --config.verify-deps-before-run=false run build:builtin
- pnpm --config.verify-deps-before-run=false run build:electron
+ - pnpm --config.verify-deps-before-run=false run stage:electron --
+ --platform linux
+ --arch $npm_config_target_arch
# electronDist reuses the runtime install.js already extracted from
# generated-sources; without it electron-builder re-downloads the dist
# zip and its SHASUMS256.txt from GitHub, which the offline sandbox
@@ -254,6 +257,11 @@ modules:
if [ "$npm_config_target_arch" = arm64 ]; then
unpacked=release/linux-arm64-unpacked
fi
+ node scripts/verify-electron-package.mjs \
+ --app-dir "$unpacked" \
+ --platform linux \
+ --arch "$npm_config_target_arch" \
+ --report "release/size-reports/linux-$npm_config_target_arch.json"
test -x "$unpacked/resources/extra/linux/$npm_config_target_arch/aria2c"
test -x "$unpacked/resources/bin/motrix-native-host"
rm "$unpacked/resources/bin/motrix-native-host"
diff --git a/package.json b/package.json
index accd52c7..d122f6e3 100644
--- a/package.json
+++ b/package.json
@@ -19,6 +19,9 @@
"start": "node scripts/dev.mjs",
"build": "pnpm run build:builtin && pnpm run build:native-host && pnpm build:electron",
"build:electron": "pnpm run build:legal && node scripts/ensure-native-abi.mjs electron && vite build --config vite.main.config.ts && vite build --config vite.preload.config.ts && vite build --config vite.worker.config.ts && vite build --config vite.renderer.config.ts",
+ "stage:electron": "node scripts/stage-electron-app.mjs",
+ "verify:electron-package": "node scripts/verify-electron-package.mjs",
+ "smoke:electron-package": "node scripts/smoke-electron-package.mjs",
"build:server": "pnpm run build:builtin && pnpm run build:legal && vite build --config vite.server.config.ts && vite build --config vite.worker.config.ts && vite build --config vite.renderer.web.config.ts",
"build:builtin": "node scripts/fetch-builtins.mjs",
"build:native-host": "node packages/native-host/build.mjs",
@@ -55,9 +58,9 @@
"fetch:engine": "node scripts/fetch-engine.mjs",
"rebuild:for-node": "pnpm rebuild better-sqlite3",
"rebuild:for-electron": "electron-rebuild --force --only better-sqlite3",
- "pack:mac": "pnpm run check:third-party-notices && pnpm run build:mac-arm64 && CSC_IDENTITY_AUTO_DISCOVERY=false pnpm exec electron-builder --mac --arm64 -c.mac.target=dir && codesign --force --deep --sign - release/mac-arm64/Motrix.app",
- "dist:mac": "pnpm run check:third-party-notices && pnpm run build:mac-arm64 && CSC_IDENTITY_AUTO_DISCOVERY=false pnpm exec electron-builder --mac --arm64 --publish never",
- "release:mac": "pnpm run check:third-party-notices && pnpm run build:mac-arm64 && pnpm exec electron-builder --mac --arm64 --publish never"
+ "pack:mac": "pnpm run check:third-party-notices && pnpm run build:mac-arm64 && pnpm run stage:electron -- --platform darwin --arch arm64 && CSC_IDENTITY_AUTO_DISCOVERY=false pnpm exec electron-builder --mac --arm64 -c.mac.target=dir && codesign --force --deep --sign - release/mac-arm64/Motrix.app",
+ "dist:mac": "pnpm run check:third-party-notices && pnpm run build:mac-arm64 && pnpm run stage:electron -- --platform darwin --arch arm64 && CSC_IDENTITY_AUTO_DISCOVERY=false pnpm exec electron-builder --mac --arm64 --publish never",
+ "release:mac": "pnpm run check:third-party-notices && pnpm run build:mac-arm64 && pnpm run stage:electron -- --platform darwin --arch arm64 && pnpm exec electron-builder --mac --arm64 --publish never"
},
"devDependencies": {
"@biomejs/biome": "^2.5.7",
diff --git a/scripts/before-build-use-staged-dependencies.mjs b/scripts/before-build-use-staged-dependencies.mjs
new file mode 100644
index 00000000..6818fbc5
--- /dev/null
+++ b/scripts/before-build-use-staged-dependencies.mjs
@@ -0,0 +1,20 @@
+import path from 'node:path'
+
+/**
+ * The Electron package stager has already resolved, filtered, and copied the
+ * complete target dependency closure. Returning false tells electron-builder
+ * not to rebuild or independently recollect dependencies from the workspace
+ * root, which would bypass that reviewed staging boundary.
+ */
+export default async function useStagedDependencies(context) {
+ const expectedAppDir = path.resolve(context.appDir)
+ if (
+ path.basename(expectedAppDir) !== 'electron-app' ||
+ path.basename(path.dirname(expectedAppDir)) !== 'dist'
+ ) {
+ throw new Error(
+ '[before-build-use-staged-dependencies] expected appDir to be dist/electron-app'
+ )
+ }
+ return false
+}
diff --git a/scripts/before-pack-verify.mjs b/scripts/before-pack-verify.mjs
index 7ae4ad85..81ecbdab 100644
--- a/scripts/before-pack-verify.mjs
+++ b/scripts/before-pack-verify.mjs
@@ -4,9 +4,11 @@
// extra/<platform>/<arch>/aria2c[.exe] — the download engine
// packages/native-host/dist/<platform>-<arch>/
// motrix-native-host[.exe] — the browser-bridge host
+import { createHash } from 'node:crypto'
import { constants } from 'node:fs'
-import { access, open, stat } from 'node:fs/promises'
+import { access, readFile, stat } from 'node:fs/promises'
import path from 'node:path'
+import { assertNativeBinaryTarget } from './native-binary-target.mjs'
// electron-builder Arch enum ordinals (builder-util/src/arch.ts).
const ARCH_NAMES = {
@@ -17,120 +19,6 @@ const ARCH_NAMES = {
4: 'universal',
}
-const TARGET_MACH_CPU = {
- x64: 0x01000007,
- arm64: 0x0100000c,
-}
-
-const TARGET_ELF_MACHINE = {
- x64: 62,
- arm64: 183,
-}
-
-const TARGET_PE_MACHINE = {
- x64: 0x8664,
- arm64: 0xaa64,
-}
-
-async function readExactlyAt(file, length, position) {
- const bytes = Buffer.alloc(length)
- const { bytesRead } = await file.read(bytes, 0, length, position)
- return bytesRead === length ? bytes : null
-}
-
-function readUInt32(bytes, offset, littleEndian) {
- return littleEndian ? bytes.readUInt32LE(offset) : bytes.readUInt32BE(offset)
-}
-
-async function matchesMachTarget(file, arch) {
- const head = await readExactlyAt(file, 8, 0)
- if (!head) return false
-
- const magic = head.subarray(0, 4).toString('hex')
- const thin =
- magic === 'cffaedfe'
- ? { littleEndian: true }
- : magic === 'feedfacf'
- ? { littleEndian: false }
- : null
- if (thin) {
- return readUInt32(head, 4, thin.littleEndian) === TARGET_MACH_CPU[arch]
- }
-
- const fat =
- magic === 'cafebabe'
- ? { littleEndian: false, entrySize: 20 }
- : magic === 'bebafeca'
- ? { littleEndian: true, entrySize: 20 }
- : magic === 'cafebabf'
- ? { littleEndian: false, entrySize: 32 }
- : magic === 'bfbafeca'
- ? { littleEndian: true, entrySize: 32 }
- : null
- if (!fat) return false
-
- const sliceCount = readUInt32(head, 4, fat.littleEndian)
- if (sliceCount === 0 || sliceCount > 64) return false
- const entries = await readExactlyAt(
- file,
- sliceCount * fat.entrySize,
- head.length
- )
- if (!entries) return false
-
- for (let index = 0; index < sliceCount; index += 1) {
- const offset = index * fat.entrySize
- if (
- readUInt32(entries, offset, fat.littleEndian) === TARGET_MACH_CPU[arch]
- ) {
- return true
- }
- }
- return false
-}
-
-async function matchesElfTarget(file, arch) {
- const head = await readExactlyAt(file, 20, 0)
- if (
- !head?.subarray(0, 4).equals(Buffer.from([0x7f, 0x45, 0x4c, 0x46])) ||
- head[4] !== 2
- ) {
- return false
- }
- const machine =
- head[5] === 1
- ? head.readUInt16LE(18)
- : head[5] === 2
- ? head.readUInt16BE(18)
- : null
- return machine === TARGET_ELF_MACHINE[arch]
-}
-
-async function matchesPeTarget(file, arch) {
- const dosHead = await readExactlyAt(file, 64, 0)
- if (!dosHead?.subarray(0, 2).equals(Buffer.from('MZ'))) {
- return false
- }
- const peOffset = dosHead.readUInt32LE(0x3c)
- const coffHead = await readExactlyAt(file, 6, peOffset)
- return (
- coffHead?.subarray(0, 4).equals(Buffer.from([0x50, 0x45, 0, 0])) === true &&
- coffHead.readUInt16LE(4) === TARGET_PE_MACHINE[arch]
- )
-}
-
-async function matchesExecutableTarget(filePath, platform, arch) {
- const file = await open(filePath, 'r')
- try {
- if (platform === 'darwin') return await matchesMachTarget(file, arch)
- if (platform === 'linux') return await matchesElfTarget(file, arch)
- if (platform === 'win32') return await matchesPeTarget(file, arch)
- return false
- } finally {
- await file.close()
- }
-}
-
async function verifyExecutable(filePath, label, platform, arch) {
let fileStat
try {
@@ -145,7 +33,12 @@ async function verifyExecutable(filePath, label, platform, arch) {
)
}
- if (!(await matchesExecutableTarget(filePath, platform, arch))) {
+ try {
+ await assertNativeBinaryTarget(filePath, platform, arch, {
+ allowUniversal: platform === 'darwin',
+ label,
+ })
+ } catch {
throw new Error(
`[before-pack-verify] ${label} is not a ${platform}-${arch} executable: ${filePath}`
)
@@ -162,6 +55,74 @@ async function verifyExecutable(filePath, label, platform, arch) {
}
}
+async function readJson(filePath, label) {
+ try {
+ return JSON.parse(await readFile(filePath, 'utf8'))
+ } catch (error) {
+ throw new Error(
+ `[before-pack-verify] missing or invalid ${label}: ${filePath}`,
+ {
+ cause: error,
+ }
+ )
+ }
+}
+
+async function verifyStage(projectDir, platform, arch) {
+ const manifestPath = path.join(
+ projectDir,
+ 'dist/electron-app/.motrix-package-stage.json'
+ )
+ const stage = await readJson(manifestPath, 'Electron package stage manifest')
+ const rootManifest = await readJson(
+ path.join(projectDir, 'package.json'),
+ 'root package manifest'
+ )
+ const expectedKey = `${platform}-${arch}`
+ if (
+ stage.schemaVersion !== 1 ||
+ stage.target?.platform !== platform ||
+ stage.target?.arch !== arch ||
+ stage.target?.key !== expectedKey
+ ) {
+ throw new Error(
+ `[before-pack-verify] stage target does not match ${expectedKey}; run "pnpm run stage:electron -- --platform ${platform} --arch ${arch}"`
+ )
+ }
+ if (stage.rootVersion !== rootManifest.version) {
+ throw new Error(
+ `[before-pack-verify] stage version ${stage.rootVersion} does not match root version ${rootManifest.version}`
+ )
+ }
+ if (!Array.isArray(stage.buildOutputs) || stage.buildOutputs.length !== 4) {
+ throw new Error(
+ '[before-pack-verify] stage build-output inventory is missing'
+ )
+ }
+ for (const output of stage.buildOutputs) {
+ if (
+ typeof output.path !== 'string' ||
+ typeof output.sha256 !== 'string' ||
+ !Number.isSafeInteger(output.bytes)
+ ) {
+ throw new Error(
+ '[before-pack-verify] stage build-output inventory is invalid'
+ )
+ }
+ const bytes = await readFile(path.join(projectDir, output.path)).catch(
+ () => null
+ )
+ const sha256 = bytes
+ ? createHash('sha256').update(bytes).digest('hex')
+ : undefined
+ if (bytes?.length !== output.bytes || sha256 !== output.sha256) {
+ throw new Error(
+ `[before-pack-verify] stage is stale for ${output.path}; rerun staging`
+ )
+ }
+ }
+}
+
export default async function beforePack(context) {
const platform = context.electronPlatformName // darwin | win32 | linux
const archName = ARCH_NAMES[context.arch]
@@ -172,10 +133,16 @@ export default async function beforePack(context) {
const projectDir =
context.packager.projectDir ?? context.packager.info.projectDir
+ if (archName === 'universal') {
+ throw new Error(
+ '[before-pack-verify] universal Electron packages are unsupported'
+ )
+ }
+ await verifyStage(projectDir, platform, archName)
const engineBin = platform === 'win32' ? 'aria2c.exe' : 'aria2c'
const hostBin =
platform === 'win32' ? 'motrix-native-host.exe' : 'motrix-native-host'
- const arches = archName === 'universal' ? ['x64', 'arm64'] : [archName]
+ const arches = [archName]
for (const arch of arches) {
const engine = path.join(projectDir, 'extra', platform, arch, engineBin)
diff --git a/scripts/electron-package-runtime-helper.cjs b/scripts/electron-package-runtime-helper.cjs
new file mode 100644
index 00000000..f5e22a46
--- /dev/null
+++ b/scripts/electron-package-runtime-helper.cjs
@@ -0,0 +1,240 @@
+#!/usr/bin/env node
+
+'use strict'
+
+const { createHash } = require('node:crypto')
+const { readFileSync, writeFileSync } = require('node:fs')
+const { Worker } = require('node:worker_threads')
+
+const [, , mode, ...args] = process.argv
+
+function fail(message) {
+ throw new Error(message)
+}
+
+function runDatabaseSmoke(packagePath, databasePath) {
+ const Database = require(packagePath)
+ let database = new Database(databasePath)
+ const schemaVersion = database
+ .prepare('SELECT MAX(version) AS version FROM schema_version')
+ .get().version
+
+ database.exec(`
+ CREATE TABLE IF NOT EXISTS package_runtime_smoke (
+ value TEXT PRIMARY KEY NOT NULL
+ )
+ `)
+ database
+ .prepare('INSERT OR REPLACE INTO package_runtime_smoke (value) VALUES (?)')
+ .run('packaged-native-ok')
+ database.close()
+
+ database = new Database(databasePath, { readonly: true })
+ const reopened = database
+ .prepare('SELECT value FROM package_runtime_smoke WHERE value = ?')
+ .get('packaged-native-ok')
+ database.close()
+
+ return {
+ electronVersion: process.versions.electron,
+ schemaVersion,
+ writeCloseReopen: reopened?.value === 'packaged-native-ok',
+ }
+}
+
+function runQuickJsSmoke(workerPath) {
+ return new Promise((resolve, reject) => {
+ const worker = new Worker(workerPath)
+ const timer = setTimeout(() => {
+ void worker.terminate()
+ reject(new Error('packaged QuickJS worker timed out'))
+ }, 15_000)
+
+ function finish(error, result) {
+ clearTimeout(timer)
+ if (error) {
+ void worker.terminate()
+ reject(error)
+ return
+ }
+ worker.postMessage({ type: 'event', event: 'shutdown' })
+ resolve(result)
+ }
+
+ worker.on('error', (error) => finish(error))
+ worker.on('message', (message) => {
+ if (message.type === 'call') {
+ if (message.capability !== 'crypto' || message.method !== 'hash') {
+ finish(
+ new Error(
+ `unexpected packaged capability call ${message.capability}.${message.method}`
+ )
+ )
+ return
+ }
+ const digest = [
+ ...createHash(message.args[0]).update(message.args[1]).digest(),
+ ]
+ worker.postMessage({
+ type: 'response',
+ id: message.id,
+ ok: true,
+ result: digest,
+ })
+ return
+ }
+ if (message.type === 'ready') {
+ worker.postMessage({
+ type: 'event',
+ event: 'executeCommand',
+ id: 77,
+ commandId: 'package.smoke.hash',
+ args: null,
+ })
+ return
+ }
+ if (message.type === 'fatal') {
+ finish(
+ new Error(
+ `packaged QuickJS worker fatal ${message.code}: ${message.message}`
+ )
+ )
+ return
+ }
+ if (
+ message.type === 'event' &&
+ message.event === 'executeCommandResult'
+ ) {
+ if (!message.ok) {
+ finish(
+ new Error(
+ `packaged QuickJS command failed ${message.errorCode}: ${message.errorMessage}`
+ )
+ )
+ return
+ }
+ finish(undefined, {
+ capability: 'crypto.hash',
+ digestBytes: message.result?.length,
+ digestHex: message.result?.hex,
+ })
+ }
+ })
+
+ worker.postMessage({
+ type: 'init',
+ pluginId: 'package.smoke',
+ manifest: {
+ manifestVersion: 1,
+ id: 'package.smoke',
+ name: 'Package smoke',
+ version: '1.0.0',
+ description: 'Packaged QuickJS runtime smoke',
+ categories: ['integration'],
+ engines: { motrix: '>=2.0.0' },
+ main: 'dist/plugin.js',
+ permissions: [],
+ optionalPermissions: [],
+ hostPermissions: [],
+ activationEvents: ['onCommand:package.smoke.hash'],
+ contributes: {
+ commands: [
+ {
+ id: 'package.smoke.hash',
+ title: 'Package smoke',
+ public: false,
+ },
+ ],
+ },
+ },
+ bundleSource: `
+ const { commands, crypto } = globalThis.__motrix_plugin_api__;
+ commands.register('package.smoke.hash', async () => {
+ const bytes = await crypto.hash('sha256', 'abc');
+ return {
+ length: bytes.length,
+ hex: Array.from(bytes)
+ .map((byte) => byte.toString(16).padStart(2, '0'))
+ .join(''),
+ };
+ });
+ `,
+ app: {
+ version: '2.0.0',
+ platform: process.platform,
+ runtime: 'electron',
+ locale: 'en-US',
+ arch: process.arch,
+ },
+ i18n: {
+ language: 'en-US',
+ dir: 'ltr',
+ currentDict: {},
+ fallbackDict: {},
+ },
+ limits: { heapMB: 32, stackKB: 256 },
+ })
+ })
+}
+
+async function runTraySmoke(packagePath, trayDir, outputPath) {
+ const { initWasm, Resvg } = require(packagePath)
+ const wasm = readFileSync(`${trayDir}/resvg.wasm`)
+ await initWasm(wasm)
+
+ const rawIcon = readFileSync(`${trayDir}/tray.svg`, 'utf8')
+ const icon = rawIcon.replace(/fill="[^"]*"/g, 'fill="black"')
+ const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="134" height="44">
+ <g transform="translate(0,6) scale(1)">${icon}</g>
+ <text x="132" y="20" text-anchor="end" font-family=".SF NS,Helvetica,sans-serif" font-size="18" fill="black">1 MB/s</text>
+ <text x="132" y="38" text-anchor="end" font-family=".SF NS,Helvetica,sans-serif" font-size="18" fill="black">2 MB/s</text>
+ </svg>`
+ const fontBuffers = []
+ for (const fontPath of [
+ `${trayDir}/SFNS-Regular.ttf`,
+ '/System/Library/Fonts/Helvetica.ttc',
+ ]) {
+ try {
+ fontBuffers.push(readFileSync(fontPath))
+ } catch {
+ // The packaged font is required by the verifier; the system fallback is
+ // best-effort so this helper also works on non-macOS hosts.
+ }
+ }
+ const png = Buffer.from(
+ new Resvg(svg, {
+ fitTo: { mode: 'width', value: 134 },
+ font: { fontBuffers, defaultFontFamily: '.SF NS' },
+ })
+ .render()
+ .asPng()
+ )
+ if (png.subarray(1, 4).toString() !== 'PNG') {
+ fail('packaged tray speedometer output is not a PNG')
+ }
+ writeFileSync(outputPath, png)
+ return {
+ pngBytes: png.length,
+ pngSha256: createHash('sha256').update(png).digest('hex'),
+ wasmBytes: wasm.length,
+ }
+}
+
+async function main() {
+ let result
+ if (mode === 'database' && args.length === 2) {
+ result = runDatabaseSmoke(args[0], args[1])
+ } else if (mode === 'quickjs' && args.length === 1) {
+ result = await runQuickJsSmoke(args[0])
+ } else if (mode === 'tray' && args.length === 3) {
+ result = await runTraySmoke(args[0], args[1], args[2])
+ } else {
+ fail('usage: runtime-helper.cjs <database|quickjs|tray> <mode arguments>')
+ }
+ process.stdout.write(`${JSON.stringify(result)}\n`)
+}
+
+main().catch((error) => {
+ process.stderr.write(`${error.stack || error.message}\n`)
+ process.exitCode = 1
+})
diff --git a/scripts/electron-package-size-budgets.json b/scripts/electron-package-size-budgets.json
new file mode 100644
index 00000000..7af58ba8
--- /dev/null
+++ b/scripts/electron-package-size-budgets.json
@@ -0,0 +1,8 @@
+{
+ "schemaVersion": 1,
+ "payloadBytes": 67108864,
+ "betterSqlite3Bytes": 4194304,
+ "unexpectedPackageNames": 0,
+ "foreignBetterSqlite3Prebuilds": 0,
+ "duplicateResvgWasmFiles": 0
+}
diff --git a/scripts/electron-package-utils.mjs b/scripts/electron-package-utils.mjs
new file mode 100644
index 00000000..be99f5b9
--- /dev/null
+++ b/scripts/electron-package-utils.mjs
@@ -0,0 +1,205 @@
+import os from 'node:os'
+import path from 'node:path'
+import { isDeepStrictEqual } from 'node:util'
+
+const RUNTIME_CONTRACT_KEYS = [
+ 'common',
+ 'platforms',
+ 'schemaVersion',
+ 'supportedTargets',
+]
+const PLATFORM_CONTRACT_KEYS = ['optional', 'required']
+const SIZE_BUDGET_KEYS = [
+ 'betterSqlite3Bytes',
+ 'duplicateResvgWasmFiles',
+ 'foreignBetterSqlite3Prebuilds',
+ 'payloadBytes',
+ 'schemaVersion',
+ 'unexpectedPackageNames',
+]
+const SUPPORTED_TARGETS = [
+ 'darwin-arm64',
+ 'darwin-x64',
+ 'linux-arm64',
+ 'linux-x64',
+ 'win32-x64',
+]
+const SUPPORTED_PLATFORMS = ['darwin', 'linux', 'win32']
+const SUPPORTED_ARCHES = ['arm64', 'x64']
+
+function assertRecord(value, label) {
+ if (value === null || Array.isArray(value) || typeof value !== 'object') {
+ throw new Error(`${label} must be an object`)
+ }
+ return value
+}
+
+function assertExactKeys(value, expected, label) {
+ const actual = Object.keys(value).sort()
+ if (!isDeepStrictEqual(actual, [...expected].sort())) {
+ const unknown = actual.filter((key) => !expected.includes(key))
+ const missing = expected.filter((key) => !actual.includes(key))
+ if (unknown.length > 0) {
+ throw new Error(`${label} has unknown key: ${unknown.join(', ')}`)
+ }
+ throw new Error(`${label} is missing key: ${missing.join(', ')}`)
+ }
+}
+
+function assertInteger(value, label) {
+ if (!Number.isSafeInteger(value) || value < 0) {
+ throw new Error(`${label} must be a non-negative safe integer`)
+ }
+ return value
+}
+
+function assertSortedUniqueStrings(value, label) {
+ if (
+ !Array.isArray(value) ||
+ value.some((entry) => typeof entry !== 'string')
+ ) {
+ throw new Error(`${label} must be an array of strings`)
+ }
+ const sorted = [...new Set(value)].sort()
+ if (!isDeepStrictEqual(value, sorted)) {
+ throw new Error(`${label} must contain unique strings in sorted order`)
+ }
+ return value
+}
+
+export function validateRuntimeDependencyContract(value) {
+ const contract = assertRecord(value, 'runtime dependency contract')
+ assertExactKeys(
+ contract,
+ RUNTIME_CONTRACT_KEYS,
+ 'runtime dependency contract'
+ )
+ if (contract.schemaVersion !== 1) {
+ throw new Error('runtime dependency contract schemaVersion must be 1')
+ }
+
+ assertSortedUniqueStrings(contract.supportedTargets, 'supportedTargets')
+ if (!isDeepStrictEqual(contract.supportedTargets, SUPPORTED_TARGETS)) {
+ throw new Error(
+ `supportedTargets must be exactly: ${SUPPORTED_TARGETS.join(', ')}`
+ )
+ }
+ assertSortedUniqueStrings(contract.common, 'common runtime roots')
+
+ const platforms = assertRecord(contract.platforms, 'platforms')
+ assertExactKeys(platforms, SUPPORTED_PLATFORMS, 'platforms')
+ for (const platform of SUPPORTED_PLATFORMS) {
+ const entry = assertRecord(platforms[platform], `platforms.${platform}`)
+ assertExactKeys(entry, PLATFORM_CONTRACT_KEYS, `platforms.${platform}`)
+ assertSortedUniqueStrings(entry.required, `platforms.${platform}.required`)
+ assertSortedUniqueStrings(entry.optional, `platforms.${platform}.optional`)
+ }
+
+ return contract
+}
+
+export function validateSizeBudgetContract(value) {
+ const contract = assertRecord(value, 'size budget contract')
+ assertExactKeys(contract, SIZE_BUDGET_KEYS, 'size budget contract')
+ if (contract.schemaVersion !== 1) {
+ throw new Error('size budget contract schemaVersion must be 1')
+ }
+ for (const key of SIZE_BUDGET_KEYS.filter(
+ (entry) => entry !== 'schemaVersion'
+ )) {
+ assertInteger(contract[key], `size budget contract.${key}`)
+ }
+ return contract
+}
+
+export function targetKey(platform, arch) {
+ return `${platform}-${arch}`
+}
+
+export function parseTarget(options = {}) {
+ const strict = options.strict === true || options.ci === true
+ const platform = options.platform ?? (strict ? undefined : process.platform)
+ const arch = options.arch ?? (strict ? undefined : process.arch)
+
+ if (!platform || !arch) {
+ throw new Error(
+ 'Electron package target requires both --platform and --arch'
+ )
+ }
+ const key = targetKey(platform, arch)
+ if (!SUPPORTED_TARGETS.includes(key)) {
+ throw new Error(
+ `unsupported Electron package target ${key}; expected one of: ${SUPPORTED_TARGETS.join(', ')}`
+ )
+ }
+ return { platform, arch, key }
+}
+
+export function packageNameFromSpecifier(specifier) {
+ if (
+ typeof specifier !== 'string' ||
+ specifier.length === 0 ||
+ specifier.startsWith('.') ||
+ specifier.startsWith('/') ||
+ specifier.startsWith('node:') ||
+ specifier.startsWith('#')
+ ) {
+ return undefined
+ }
+ const parts = specifier.split('/')
+ if (specifier.startsWith('@')) {
+ return parts.length >= 2 && parts[1] ? `${parts[0]}/${parts[1]}` : undefined
+ }
+ return parts[0] || undefined
+}
+
+export function normalizeRelativePath(value, label = 'path') {
+ if (typeof value !== 'string' || value.length === 0) {
+ throw new Error(`${label} must be a non-empty string`)
+ }
+ const portable = value.replaceAll('\\', '/')
+ const normalized = path.posix.normalize(portable)
+ if (
+ path.posix.isAbsolute(normalized) ||
+ normalized === '..' ||
+ normalized.startsWith('../')
+ ) {
+ throw new Error(`${label} must stay within its root: ${value}`)
+ }
+ return normalized.replace(/^\.\//, '')
+}
+
+export function bytesToMiB(bytes) {
+ assertInteger(bytes, 'bytes')
+ return bytes / (1024 * 1024)
+}
+
+export function sortJson(value) {
+ if (Array.isArray(value)) return value.map((entry) => sortJson(entry))
+ if (value && typeof value === 'object') {
+ return Object.fromEntries(
+ Object.keys(value)
+ .sort()
+ .map((key) => [key, sortJson(value[key])])
+ )
+ }
+ return value
+}
+
+export function stringifySortedJson(value) {
+ return `${JSON.stringify(sortJson(value), null, 2)}\n`
+}
+
+export function sanitizeMachinePaths(value, roots = [os.homedir()]) {
+ if (typeof value !== 'string') return value
+ return roots
+ .filter((root) => typeof root === 'string' && root.length > 0)
+ .sort((left, right) => right.length - left.length)
+ .reduce((result, root) => result.replaceAll(root, '<home>'), value)
+}
+
+export const electronPackageTargets = Object.freeze({
+ arches: [...SUPPORTED_ARCHES],
+ platforms: [...SUPPORTED_PLATFORMS],
+ targets: [...SUPPORTED_TARGETS],
+})
diff --git a/scripts/electron-runtime-dependencies.json b/scripts/electron-runtime-dependencies.json
new file mode 100644
index 00000000..2c7a7cef
--- /dev/null
+++ b/scripts/electron-runtime-dependencies.json
@@ -0,0 +1,44 @@
+{
+ "schemaVersion": 1,
+ "supportedTargets": [
+ "darwin-arm64",
+ "darwin-x64",
+ "linux-arm64",
+ "linux-x64",
+ "win32-x64"
+ ],
+ "common": [
+ "@motrix/mdxp",
+ "@motrix/nat",
+ "@motrix/plugin-manifest-schema",
+ "ajv",
+ "better-sqlite3",
+ "chokidar",
+ "electron-updater",
+ "i18next",
+ "libsodium-wrappers",
+ "mmdb-lib",
+ "quickjs-emscripten",
+ "undici",
+ "uuid",
+ "vscode-jsonrpc",
+ "write-file-atomic",
+ "ws",
+ "yauzl",
+ "zod"
+ ],
+ "platforms": {
+ "darwin": {
+ "optional": ["electron-liquid-glass"],
+ "required": ["@resvg/resvg-wasm"]
+ },
+ "linux": {
+ "optional": [],
+ "required": []
+ },
+ "win32": {
+ "optional": [],
+ "required": []
+ }
+ }
+}
diff --git a/scripts/native-binary-target.mjs b/scripts/native-binary-target.mjs
new file mode 100644
index 00000000..a0baa627
--- /dev/null
+++ b/scripts/native-binary-target.mjs
@@ -0,0 +1,145 @@
+import { readFile } from 'node:fs/promises'
+
+const MACH_CPU_ARCHES = new Map([
+ [0x01000007, 'x64'],
+ [0x0100000c, 'arm64'],
+])
+const ELF_MACHINE_ARCHES = new Map([
+ [62, 'x64'],
+ [183, 'arm64'],
+])
+const PE_MACHINE_ARCHES = new Map([
+ [0x8664, 'x64'],
+ [0xaa64, 'arm64'],
+])
+const PLATFORM_FORMATS = {
+ darwin: 'mach-o',
+ linux: 'elf',
+ win32: 'pe',
+}
+
+function readUInt32(bytes, offset, littleEndian) {
+ return littleEndian ? bytes.readUInt32LE(offset) : bytes.readUInt32BE(offset)
+}
+
+function uniqueSorted(values) {
+ return [...new Set(values)].sort()
+}
+
+function detectMach(bytes) {
+ if (bytes.length < 8) return undefined
+ const magic = bytes.subarray(0, 4).toString('hex')
+ const thin =
+ magic === 'cffaedfe'
+ ? { littleEndian: true }
+ : magic === 'feedfacf'
+ ? { littleEndian: false }
+ : undefined
+ if (thin) {
+ const arch = MACH_CPU_ARCHES.get(readUInt32(bytes, 4, thin.littleEndian))
+ return arch ? { format: 'mach-o', arches: [arch] } : undefined
+ }
+
+ const fat =
+ magic === 'cafebabe'
+ ? { littleEndian: false, entrySize: 20 }
+ : magic === 'bebafeca'
+ ? { littleEndian: true, entrySize: 20 }
+ : magic === 'cafebabf'
+ ? { littleEndian: false, entrySize: 32 }
+ : magic === 'bfbafeca'
+ ? { littleEndian: true, entrySize: 32 }
+ : undefined
+ if (!fat) return undefined
+ const count = readUInt32(bytes, 4, fat.littleEndian)
+ if (count === 0 || count > 64 || bytes.length < 8 + count * fat.entrySize) {
+ return undefined
+ }
+ const arches = []
+ for (let index = 0; index < count; index += 1) {
+ const arch = MACH_CPU_ARCHES.get(
+ readUInt32(bytes, 8 + index * fat.entrySize, fat.littleEndian)
+ )
+ if (arch) arches.push(arch)
+ }
+ return arches.length > 0
+ ? { format: 'mach-o', arches: uniqueSorted(arches) }
+ : undefined
+}
+
+function detectElf(bytes) {
+ if (
+ bytes.length < 20 ||
+ !bytes.subarray(0, 4).equals(Buffer.from([0x7f, 0x45, 0x4c, 0x46])) ||
+ bytes[4] !== 2
+ ) {
+ return undefined
+ }
+ const machine =
+ bytes[5] === 1
+ ? bytes.readUInt16LE(18)
+ : bytes[5] === 2
+ ? bytes.readUInt16BE(18)
+ : undefined
+ const arch = ELF_MACHINE_ARCHES.get(machine)
+ return arch ? { format: 'elf', arches: [arch] } : undefined
+}
+
+function detectPe(bytes) {
+ if (bytes.length < 64 || !bytes.subarray(0, 2).equals(Buffer.from('MZ'))) {
+ return undefined
+ }
+ const offset = bytes.readUInt32LE(0x3c)
+ if (
+ offset > bytes.length - 6 ||
+ !bytes.subarray(offset, offset + 4).equals(Buffer.from([0x50, 0x45, 0, 0]))
+ ) {
+ return undefined
+ }
+ const arch = PE_MACHINE_ARCHES.get(bytes.readUInt16LE(offset + 4))
+ return arch ? { format: 'pe', arches: [arch] } : undefined
+}
+
+export function detectNativeBinaryTarget(bytes) {
+ if (!Buffer.isBuffer(bytes)) {
+ throw new Error('native binary input must be a Buffer')
+ }
+ return detectMach(bytes) ?? detectElf(bytes) ?? detectPe(bytes)
+}
+
+export async function readNativeBinaryTarget(filePath) {
+ return detectNativeBinaryTarget(await readFile(filePath))
+}
+
+export async function assertNativeBinaryTarget(
+ filePath,
+ platform,
+ arch,
+ options = {}
+) {
+ const expectedFormat = PLATFORM_FORMATS[platform]
+ if (!expectedFormat || !['arm64', 'x64'].includes(arch)) {
+ throw new Error(`unsupported native binary target ${platform}-${arch}`)
+ }
+ const detected = await readNativeBinaryTarget(filePath)
+ const label = options.label ?? 'native binary'
+ if (
+ !detected ||
+ detected.format !== expectedFormat ||
+ !detected.arches.includes(arch)
+ ) {
+ throw new Error(
+ `${label} has an invalid header; expected ${platform}-${arch}`
+ )
+ }
+ if (
+ detected.format === 'mach-o' &&
+ detected.arches.length > 1 &&
+ options.allowUniversal !== true
+ ) {
+ throw new Error(
+ `${label} is universal Mach-O; universal Mach-O is not allowed`
+ )
+ }
+ return detected
+}
diff --git a/scripts/postinstall.mjs b/scripts/postinstall.mjs
index 84b02f7b..9bce46a3 100644
--- a/scripts/postinstall.mjs
+++ b/scripts/postinstall.mjs
@@ -2,8 +2,8 @@
// scripts/postinstall.mjs
//
// Two independent, per-step env-guarded stages with NO early process.exit:
-// Stage A — `electron-builder install-app-deps` (rebuilds native modules
-// such as better-sqlite3), skipped only by
+// Stage A — `@electron/rebuild` (rebuilds native modules such as
+// better-sqlite3), skipped only by
// MOTRIX_SKIP_ELECTRON_REBUILD=1.
// Stage B — fetch the bundled aria2 binary for the host
// (fetch-engine.mjs, default host mode), skipped only by
@@ -39,16 +39,26 @@ export function classifyRebuildResult(result) {
return { code: result.status ?? 1, reason: null }
}
-function runElectronRebuild() {
- // On Windows the .bin entry is a `electron-builder.cmd` shim, which Node
+export function runElectronRebuild(
+ spawn = spawnSync,
+ platform = process.platform
+) {
+ // On Windows the .bin entry is an `electron-rebuild.cmd` shim, which Node
// refuses to spawn directly (ENOENT/EINVAL since CVE-2024-27980); route it
// through cmd.exe. The argv is a fixed literal, so shell quoting is moot.
- const result = spawnSync('electron-builder', ['install-app-deps'], {
- stdio: 'inherit',
- shell: process.platform === 'win32',
- })
+ // Invoke @electron/rebuild directly so the install-time rebuild targets the
+ // repository root instead of loading electron-builder's staged appDir. The
+ // staged app does not exist until after the build completes.
+ const result = spawn(
+ 'electron-rebuild',
+ ['--module-dir', '.', '--sequential', '--disable-pre-gyp-copy'],
+ {
+ stdio: 'inherit',
+ shell: platform === 'win32',
+ }
+ )
const { code, reason } = classifyRebuildResult(result)
- if (reason) console.error(`[postinstall] electron-builder ${reason}`)
+ if (reason) console.error(`[postinstall] @electron/rebuild ${reason}`)
return code
}
@@ -63,7 +73,7 @@ export async function main(env, deps = defaultDeps) {
// Stage A — electron rebuild (independent SKIP guard).
if (env.MOTRIX_SKIP_ELECTRON_REBUILD === '1') {
deps.log(
- '[postinstall] Stage A: skipping electron-builder install-app-deps ' +
+ '[postinstall] Stage A: skipping @electron/rebuild ' +
'(MOTRIX_SKIP_ELECTRON_REBUILD=1)'
)
} else {
diff --git a/scripts/smoke-electron-package.mjs b/scripts/smoke-electron-package.mjs
new file mode 100644
index 00000000..cd327700
--- /dev/null
+++ b/scripts/smoke-electron-package.mjs
@@ -0,0 +1,398 @@
+#!/usr/bin/env node
+
+import { execFile, spawn } from 'node:child_process'
+import {
+ access,
+ mkdir,
+ mkdtemp,
+ readFile,
+ rm,
+ stat,
+ writeFile,
+} from 'node:fs/promises'
+import net from 'node:net'
+import os from 'node:os'
+import path from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { promisify } from 'node:util'
+import electronPath from 'electron'
+import { chromium } from 'playwright'
+import { parseTarget, stringifySortedJson } from './electron-package-utils.mjs'
+
+const execFileAsync = promisify(execFile)
+const REPOSITORY_ROOT = path.resolve(
+ path.dirname(fileURLToPath(import.meta.url)),
+ '..'
+)
+const RUNTIME_HELPER = path.join(
+ REPOSITORY_ROOT,
+ 'scripts/electron-package-runtime-helper.cjs'
+)
+const RUNTIME_ERROR_PATTERNS = {
+ moduleResolution:
+ /MODULE_NOT_FOUND|Cannot find module|Cannot find package|ERR_MODULE_NOT_FOUND/i,
+ nativeAbi:
+ /NODE_MODULE_VERSION|different Node\.js version|dlopen|wrong architecture|incompatible architecture/i,
+}
+
+export function parseSmokeArguments(argv) {
+ const args = argv[0] === '--' ? argv.slice(1) : [...argv]
+ const options = { adHocSign: false }
+ for (let index = 0; index < args.length; index += 1) {
+ const argument = args[index]
+ if (argument === '--ad-hoc-sign') {
+ options.adHocSign = true
+ continue
+ }
+ if (!argument.startsWith('--')) {
+ throw new Error(`unexpected argument: ${argument}`)
+ }
+ const key = argument.slice(2)
+ if (!['app-dir', 'arch', 'platform', 'report'].includes(key)) {
+ throw new Error(`unknown argument: ${argument}`)
+ }
+ const value = args[index + 1]
+ if (!value || value.startsWith('--')) {
+ throw new Error(`${argument} requires a value`)
+ }
+ options[
+ {
+ 'app-dir': 'appDir',
+ arch: 'arch',
+ platform: 'platform',
+ report: 'report',
+ }[key]
+ ] = value
+ index += 1
+ }
+ if (!options.appDir) throw new Error('--app-dir is required')
+ const target = parseTarget({
+ platform: options.platform,
+ arch: options.arch,
+ strict: true,
+ })
+ return { ...options, ...target }
+}
+
+export function resolvePackagedLayout(appDir, platform) {
+ const absoluteAppDir = path.resolve(appDir)
+ if (platform === 'darwin') {
+ return {
+ appDir: absoluteAppDir,
+ executable: path.join(absoluteAppDir, 'Contents/MacOS/Motrix'),
+ resources: path.join(absoluteAppDir, 'Contents/Resources'),
+ }
+ }
+ if (platform === 'win32') {
+ return {
+ appDir: absoluteAppDir,
+ executable: path.join(absoluteAppDir, 'Motrix.exe'),
+ resources: path.join(absoluteAppDir, 'resources'),
+ }
+ }
+ return {
+ appDir: absoluteAppDir,
+ executable: path.join(absoluteAppDir, 'motrix'),
+ resources: path.join(absoluteAppDir, 'resources'),
+ }
+}
+
+export function scanRuntimeLog(log) {
+ return {
+ moduleResolutionError: RUNTIME_ERROR_PATTERNS.moduleResolution.test(log),
+ nativeAbiError: RUNTIME_ERROR_PATTERNS.nativeAbi.test(log),
+ }
+}
+
+async function getFreePort() {
+ const server = net.createServer()
+ await new Promise((resolve, reject) => {
+ server.once('error', reject)
+ server.listen(0, '127.0.0.1', resolve)
+ })
+ const address = server.address()
+ const port = typeof address === 'object' && address ? address.port : 0
+ await new Promise((resolve, reject) =>
+ server.close((error) => (error ? reject(error) : resolve()))
+ )
+ if (!port) throw new Error('failed to allocate package smoke RPC port')
+ return port
+}
+
+async function runElectronNodeHelper(mode, args) {
+ const child = spawn(electronPath, [RUNTIME_HELPER, mode, ...args], {
+ cwd: REPOSITORY_ROOT,
+ env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' },
+ stdio: ['ignore', 'pipe', 'pipe'],
+ })
+ let stdout = ''
+ let stderr = ''
+ child.stdout.setEncoding('utf8')
+ child.stderr.setEncoding('utf8')
+ child.stdout.on('data', (chunk) => {
+ stdout += chunk
+ })
+ child.stderr.on('data', (chunk) => {
+ stderr += chunk
+ })
+ const exitCode = await new Promise((resolve, reject) => {
+ child.once('error', reject)
+ child.once('exit', (code, signal) => {
+ if (signal) reject(new Error(`${mode} helper exited on ${signal}`))
+ else resolve(code)
+ })
+ })
+ if (exitCode !== 0) {
+ throw new Error(`${mode} helper failed: ${stderr.trim() || stdout.trim()}`)
+ }
+ return JSON.parse(stdout)
+}
+
+async function stopPackagedApp(child) {
+ if (child.exitCode !== null || child.signalCode !== null) return
+ child.kill('SIGTERM')
+ await Promise.race([
+ new Promise((resolve) => child.once('exit', resolve)),
+ new Promise((_, reject) =>
+ setTimeout(
+ () => reject(new Error('packaged app did not stop after SIGTERM')),
+ 15_000
+ )
+ ),
+ ])
+}
+
+async function connectToRenderer(debugPort, child, readStderr) {
+ const endpoint = `http://127.0.0.1:${debugPort}`
+ const deadline = Date.now() + 30_000
+ let lastError
+ while (Date.now() < deadline) {
+ if (child.exitCode !== null || child.signalCode !== null) {
+ throw new Error(
+ `packaged app exited before renderer debugging was ready: ${readStderr()}`
+ )
+ }
+ try {
+ return await chromium.connectOverCDP(endpoint, { timeout: 1000 })
+ } catch (error) {
+ lastError = error
+ await new Promise((resolve) => setTimeout(resolve, 100))
+ }
+ }
+ throw new Error(
+ `packaged renderer debugging did not open within 30000ms: ${lastError?.message ?? 'unknown error'}`
+ )
+}
+
+async function findMainPage(browser) {
+ const deadline = Date.now() + 30_000
+ while (Date.now() < deadline) {
+ const page = browser
+ .contexts()
+ .flatMap((context) => context.pages())
+ .find((candidate) => candidate.url().includes('w=main'))
+ if (page) return page
+ await new Promise((resolve) => setTimeout(resolve, 100))
+ }
+ throw new Error('packaged main renderer did not open within 30000ms')
+}
+
+async function runPackagedApplication(layout, tempDir) {
+ const rpcPort = await getFreePort()
+ const debugPort = await getFreePort()
+ const progressPath = path.join(tempDir, 'runtime-smoke-step.txt')
+ const markProgress = (step) => writeFile(progressPath, `${step}\n`)
+ await writeFile(
+ path.join(tempDir, 'settings.json'),
+ JSON.stringify({
+ version: 8,
+ onboarding: { disclaimerAccepted: true },
+ app: {
+ browserBridgeEnabled: false,
+ checkForUpdatesOnLaunch: false,
+ traySpeedometer: true,
+ warnBeforeQuit: false,
+ },
+ })
+ )
+
+ const rendererErrors = []
+ let browser
+ let stderr = ''
+ const child = spawn(
+ layout.executable,
+ [
+ '--remote-debugging-address=127.0.0.1',
+ `--remote-debugging-port=${debugPort}`,
+ ],
+ {
+ cwd: tempDir,
+ env: {
+ ...process.env,
+ NODE_ENV: 'test',
+ MOTRIX_DEFAULT_SAVE_DIR: path.join(tempDir, 'downloads'),
+ MOTRIX_RPC_PORT: String(rpcPort),
+ MOTRIX_USER_DATA: tempDir,
+ },
+ stdio: ['ignore', 'ignore', 'pipe'],
+ }
+ )
+ child.stderr.setEncoding('utf8')
+ child.stderr.on('data', (chunk) => {
+ stderr += chunk
+ })
+ try {
+ await markProgress('launching')
+ browser = await connectToRenderer(debugPort, child, () => stderr.trim())
+ await markProgress('launched')
+ const page = await findMainPage(browser)
+ await markProgress('first-window')
+ page.on('pageerror', (error) => rendererErrors.push(error.message))
+ page.on('console', (message) => {
+ if (message.type() === 'error') rendererErrors.push(message.text())
+ })
+ await page.waitForLoadState('domcontentloaded')
+ await markProgress('dom-content-loaded')
+ await page.waitForFunction(
+ () => document.documentElement.classList.contains('window-main'),
+ undefined,
+ { timeout: 20_000 }
+ )
+ await markProgress('main-window-ready')
+ await page
+ .locator('[data-sidebar="sidebar"]')
+ .first()
+ .waitFor({ state: 'visible', timeout: 20_000 })
+ await markProgress('sidebar-visible')
+ await new Promise((resolve) => setTimeout(resolve, 1500))
+ return {
+ rendererErrors,
+ title: await page.title(),
+ urlHasMainWindow: page.url().includes('w=main'),
+ windowReady: true,
+ }
+ } finally {
+ await markProgress('stopping')
+ await stopPackagedApp(child)
+ await browser?.close().catch(() => {})
+ await markProgress('stopped')
+ }
+}
+
+async function assertLayout(layout) {
+ for (const required of [
+ layout.executable,
+ path.join(layout.resources, 'app.asar'),
+ path.join(layout.resources, 'app.asar.unpacked'),
+ ]) {
+ await access(required)
+ }
+}
+
+async function main(argv = process.argv.slice(2)) {
+ const options = parseSmokeArguments(argv)
+ if (options.platform !== process.platform || options.arch !== process.arch) {
+ throw new Error(
+ `runtime smoke requires a host-native package; host is ${process.platform}-${process.arch}, target is ${options.key}`
+ )
+ }
+
+ const layout = resolvePackagedLayout(options.appDir, options.platform)
+ await assertLayout(layout)
+ if (options.adHocSign) {
+ if (options.platform !== 'darwin') {
+ throw new Error(
+ '--ad-hoc-sign is supported only for macOS directory output'
+ )
+ }
+ await execFileAsync('codesign', [
+ '--force',
+ '--deep',
+ '--sign',
+ '-',
+ layout.appDir,
+ ])
+ await execFileAsync('codesign', [
+ '--verify',
+ '--deep',
+ '--strict',
+ layout.appDir,
+ ])
+ }
+
+ const tempDir = await mkdtemp(
+ path.join(os.tmpdir(), `motrix-package-${options.key}-`)
+ )
+ try {
+ const application = await runPackagedApplication(layout, tempDir)
+ const log = await readFile(path.join(tempDir, 'logs/motrix.log'), 'utf8')
+ const logScan = scanRuntimeLog(log)
+ if (
+ !application.urlHasMainWindow ||
+ application.rendererErrors.length > 0
+ ) {
+ throw new Error(
+ `packaged renderer failed: ${application.rendererErrors.join('; ')}`
+ )
+ }
+ if (logScan.moduleResolutionError || logScan.nativeAbiError) {
+ throw new Error(
+ 'packaged startup log contains a module resolution or ABI error'
+ )
+ }
+
+ const appAsar = path.join(layout.resources, 'app.asar')
+ const databasePath = path.join(tempDir, 'motrix.db')
+ const database = await runElectronNodeHelper('database', [
+ path.join(appAsar, 'node_modules/better-sqlite3'),
+ databasePath,
+ ])
+ const quickjs = await runElectronNodeHelper('quickjs', [
+ path.join(appAsar, 'dist/core/plugin/host/quick-js-worker.cjs'),
+ ])
+ const tray =
+ options.platform === 'darwin'
+ ? await runElectronNodeHelper('tray', [
+ path.join(appAsar, 'node_modules/@resvg/resvg-wasm'),
+ path.join(layout.resources, 'extra/tray'),
+ path.join(tempDir, 'tray-speedometer.png'),
+ ])
+ : { skipped: true }
+
+ const databaseStat = await stat(databasePath)
+ const report = {
+ schemaVersion: 1,
+ target: options.key,
+ electronVersion: database.electronVersion,
+ application: {
+ ...application,
+ databaseBytes: databaseStat.size,
+ logLines: log.trim().split('\n').length,
+ ...logScan,
+ },
+ database,
+ quickjs,
+ tray,
+ }
+ const reportPath = path.resolve(
+ options.report ??
+ path.join(
+ REPOSITORY_ROOT,
+ `release/size-reports/${options.key}-runtime.json`
+ )
+ )
+ await mkdir(path.dirname(reportPath), { recursive: true })
+ await writeFile(reportPath, stringifySortedJson(report))
+ process.stdout.write(`${stringifySortedJson(report)}`)
+ process.stdout.write(`Runtime smoke report: ${reportPath}\n`)
+ } finally {
+ await rm(tempDir, { recursive: true, force: true })
+ }
+}
+
+if (process.argv[1] === fileURLToPath(import.meta.url)) {
+ main().catch((error) => {
+ process.stderr.write(`${error.stack || error.message}\n`)
+ process.exitCode = 1
+ })
+}
diff --git a/scripts/stage-electron-app.mjs b/scripts/stage-electron-app.mjs
new file mode 100644
index 00000000..2fecb06b
--- /dev/null
+++ b/scripts/stage-electron-app.mjs
@@ -0,0 +1,765 @@
+import { createHash } from 'node:crypto'
+import {
+ chmod,
+ cp,
+ lstat,
+ mkdir,
+ mkdtemp,
+ readdir,
+ readFile,
+ realpath,
+ rename,
+ rm,
+ stat,
+ writeFile,
+} from 'node:fs/promises'
+import { builtinModules, createRequire } from 'node:module'
+import path from 'node:path'
+import { fileURLToPath, pathToFileURL } from 'node:url'
+import {
+ normalizeRelativePath,
+ packageNameFromSpecifier,
+ parseTarget,
+ stringifySortedJson,
+ validateRuntimeDependencyContract,
+} from './electron-package-utils.mjs'
+import { assertNativeBinaryTarget } from './native-binary-target.mjs'
+
+const BUILD_OUTPUTS = [
+ { directory: 'dist/core/plugin/host', entry: 'quick-js-worker.cjs' },
+ { directory: 'dist/main', entry: 'index.cjs' },
+ { directory: 'dist/preload', entry: 'preload.cjs' },
+ { directory: 'dist/renderer', entry: 'index.html' },
+]
+const BUILTIN_MODULES = new Set([
+ ...builtinModules,
+ ...builtinModules.map((name) => `node:${name}`),
+ 'electron',
+])
+const GENERATED_MANIFEST_FIELDS = [
+ 'name',
+ 'productName',
+ 'version',
+ 'description',
+ 'homepage',
+ 'author',
+ 'license',
+ 'type',
+ 'main',
+ 'private',
+]
+
+function isInside(root, candidate) {
+ const relative = path.relative(root, candidate)
+ return (
+ relative.length > 0 &&
+ relative !== '..' &&
+ !relative.startsWith(`..${path.sep}`) &&
+ !path.isAbsolute(relative)
+ )
+}
+
+async function readJson(filePath, label) {
+ try {
+ return JSON.parse(await readFile(filePath, 'utf8'))
+ } catch (error) {
+ throw new Error(`${label} is unreadable: ${filePath}`, { cause: error })
+ }
+}
+
+async function assertBuildOutputs(repoRoot) {
+ for (const output of BUILD_OUTPUTS) {
+ const entry = path.join(repoRoot, output.directory, output.entry)
+ const info = await stat(entry).catch(() => null)
+ if (!info?.isFile()) {
+ throw new Error(`missing Electron build output: ${entry}`)
+ }
+ }
+}
+
+async function fingerprintBuildOutputs(repoRoot) {
+ const fingerprints = []
+ for (const output of BUILD_OUTPUTS) {
+ const relativePath = path.posix.join(output.directory, output.entry)
+ const bytes = await readFile(path.join(repoRoot, relativePath))
+ fingerprints.push({
+ path: relativePath,
+ bytes: bytes.length,
+ sha256: createHash('sha256').update(bytes).digest('hex'),
+ })
+ }
+ return fingerprints.sort((left, right) => left.path.localeCompare(right.path))
+}
+
+function targetList(contract, target) {
+ const platform = contract.platforms[target.platform]
+ return {
+ required: [...contract.common, ...platform.required],
+ optional: [...platform.optional],
+ }
+}
+
+function generatedManifest(rootManifest, contract, target) {
+ const manifest = {}
+ for (const field of GENERATED_MANIFEST_FIELDS) {
+ if (rootManifest[field] !== undefined) manifest[field] = rootManifest[field]
+ }
+
+ const roots = targetList(contract, target)
+ manifest.dependencies = Object.fromEntries(
+ roots.required.map((name) => {
+ const version = rootManifest.dependencies?.[name]
+ if (typeof version !== 'string') {
+ throw new Error(`required runtime root ${name} is not in dependencies`)
+ }
+ return [name, version]
+ })
+ )
+ if (roots.optional.length > 0) {
+ manifest.optionalDependencies = Object.fromEntries(
+ roots.optional.map((name) => {
+ const version = rootManifest.optionalDependencies?.[name]
+ if (typeof version !== 'string') {
+ throw new Error(
+ `optional runtime root ${name} is not in optionalDependencies`
+ )
+ }
+ return [name, version]
+ })
+ )
+ }
+ return manifest
+}
+
+function packageAppliesToTarget(manifest, target) {
+ function matches(values, actual) {
+ if (!Array.isArray(values) || values.length === 0) return true
+ const denied = values.includes(`!${actual}`)
+ const positive = values.filter((entry) => !entry.startsWith('!'))
+ return !denied && (positive.length === 0 || positive.includes(actual))
+ }
+ return (
+ matches(manifest.os, target.platform) && matches(manifest.cpu, target.arch)
+ )
+}
+
+async function resolvePackageInstance(name, fromRoot, canonicalRepoRoot) {
+ const require = createRequire(path.join(fromRoot, 'package.json'))
+ const candidates = []
+ try {
+ candidates.push(require.resolve(`${name}/package.json`))
+ } catch {
+ for (const searchPath of require.resolve.paths(name) ?? []) {
+ candidates.push(path.join(searchPath, name, 'package.json'))
+ }
+ try {
+ let current = path.dirname(require.resolve(name))
+ while (current !== path.dirname(current)) {
+ candidates.push(path.join(current, 'package.json'))
+ current = path.dirname(current)
+ }
+ } catch {
+ // The caller decides whether a missing dependency is optional.
+ }
+ }
+
+ for (const candidate of candidates) {
+ const info = await stat(candidate).catch(() => null)
+ if (!info?.isFile()) continue
+ const manifest = await readJson(candidate, `package ${name}`)
+ if (manifest.name !== name || typeof manifest.version !== 'string') continue
+ const sourceRoot = await realpath(path.dirname(candidate))
+ if (
+ sourceRoot !== canonicalRepoRoot &&
+ !isInside(canonicalRepoRoot, sourceRoot)
+ ) {
+ throw new Error(
+ `resolved package ${name} escapes repository root: ${sourceRoot}`
+ )
+ }
+ return {
+ lexicalRoot: path.dirname(candidate),
+ manifest,
+ sourceRoot,
+ }
+ }
+ return undefined
+}
+
+function nodeLookupDestinations(consumerDestination, name) {
+ const destinations = []
+ let current = consumerDestination
+ while (true) {
+ if (path.posix.basename(current) !== 'node_modules') {
+ destinations.push(path.posix.join(current, 'node_modules', name))
+ }
+ const parent = path.posix.dirname(current)
+ if (parent === current || current === '.') break
+ current = parent
+ }
+ destinations.push(path.posix.join('node_modules', name))
+ return [...new Set(destinations.map((entry) => entry.replace(/^\.\//, '')))]
+}
+
+async function isRootHoisted(repoRoot, name, sourceRoot) {
+ const rootCandidate = path.join(repoRoot, 'node_modules', name)
+ const canonical = await realpath(rootCandidate).catch(() => null)
+ return canonical === sourceRoot
+}
+
+async function assertSafeTree(sourceRoot, canonicalRepoRoot, options = {}) {
+ const visited = new Set()
+
+ async function walk(directory) {
+ const canonical = await realpath(directory)
+ if (visited.has(canonical)) return
+ visited.add(canonical)
+ const entries = await readdir(directory, { withFileTypes: true })
+ for (const entry of entries) {
+ if (options.skipNodeModules && entry.name === 'node_modules') continue
+ const entryPath = path.join(directory, entry.name)
+ if (entry.isSymbolicLink()) {
+ const target = await realpath(entryPath).catch(() => null)
+ if (
+ !target ||
+ (target !== canonicalRepoRoot && !isInside(canonicalRepoRoot, target))
+ ) {
+ throw new Error(
+ `source symlink escapes repository root: ${entryPath}`
+ )
+ }
+ const targetInfo = await stat(target)
+ if (targetInfo.isDirectory()) await walk(target)
+ } else if (entry.isDirectory()) {
+ await walk(entryPath)
+ }
+ }
+ }
+
+ await walk(sourceRoot)
+}
+
+async function normalizeModes(directory) {
+ const entries = await readdir(directory, { withFileTypes: true })
+ for (const entry of entries) {
+ const entryPath = path.join(directory, entry.name)
+ if (entry.isDirectory()) {
+ await chmod(entryPath, 0o755)
+ await normalizeModes(entryPath)
+ } else {
+ const info = await lstat(entryPath)
+ if (info.isSymbolicLink()) {
+ throw new Error(`staging emitted a symlink: ${entryPath}`)
+ }
+ await chmod(entryPath, (info.mode & 0o111) === 0 ? 0o644 : 0o755)
+ }
+ }
+}
+
+async function copyTree(source, destination, canonicalRepoRoot, options = {}) {
+ await assertSafeTree(source, canonicalRepoRoot, options)
+ await mkdir(path.dirname(destination), { recursive: true })
+ await cp(source, destination, {
+ recursive: true,
+ dereference: true,
+ filter: (candidate) => {
+ const relative = path.relative(source, candidate)
+ if (
+ options.skipNodeModules &&
+ (relative === 'node_modules' ||
+ relative.startsWith(`node_modules${path.sep}`))
+ ) {
+ return false
+ }
+ return options.filter ? options.filter(relative) : true
+ },
+ })
+ await normalizeModes(destination)
+}
+
+function packageCopyFilter(name, target) {
+ if (name === 'better-sqlite3') {
+ const selected = path.join('prebuilds', `${target.key}.node`)
+ return (relative) => {
+ if (relative.length === 0) return true
+ const portable = relative.replaceAll(path.sep, '/')
+ return (
+ portable === 'package.json' ||
+ /^LICENSE(?:\..*)?$/i.test(portable) ||
+ portable === 'lib' ||
+ portable.startsWith('lib/') ||
+ portable === 'prebuilds' ||
+ relative === selected
+ )
+ }
+ }
+ if (name === '@resvg/resvg-wasm') {
+ return (relative) => relative.replaceAll(path.sep, '/') !== 'index_bg.wasm'
+ }
+ if (name === 'electron-liquid-glass') {
+ return (relative) => {
+ const portable = relative.replaceAll(path.sep, '/')
+ if (portable === 'prebuilds' || !portable.startsWith('prebuilds/')) {
+ return true
+ }
+ return (
+ portable === `prebuilds/${target.key}` ||
+ portable.startsWith(`prebuilds/${target.key}/`)
+ )
+ }
+ }
+ return undefined
+}
+
+async function collectNativeModules(directory) {
+ const files = []
+ async function walk(current) {
+ for (const entry of await readdir(current, { withFileTypes: true })) {
+ const entryPath = path.join(current, entry.name)
+ if (entry.isDirectory()) await walk(entryPath)
+ else if (entry.name.endsWith('.node')) files.push(entryPath)
+ }
+ }
+ await walk(directory)
+ return files.sort()
+}
+
+async function validateStagedNativeModules(directory, target, packageName) {
+ const nativeModules = await collectNativeModules(directory)
+ for (const file of nativeModules) {
+ await assertNativeBinaryTarget(file, target.platform, target.arch, {
+ label: `${packageName} native module`,
+ })
+ }
+ if (packageName === 'better-sqlite3' && nativeModules.length !== 1) {
+ throw new Error(
+ `better-sqlite3 must stage exactly one ${target.key} prebuild`
+ )
+ }
+}
+
+function readStaticString(source, start) {
+ const quote = source[start]
+ let value = ''
+ for (let index = start + 1; index < source.length; index += 1) {
+ const character = source[index]
+ if (character === quote) return { value, end: index + 1 }
+ if (character === '\\') {
+ index += 1
+ if (index >= source.length) return undefined
+ value += source[index]
+ } else {
+ value += character
+ }
+ }
+ return undefined
+}
+
+export function scanStaticExternals(source) {
+ const specifiers = new Set()
+ let index = 0
+ while (index < source.length) {
+ const character = source[index]
+ const next = source[index + 1]
+ if (character === '/' && next === '/') {
+ index = source.indexOf('\n', index + 2)
+ if (index === -1) break
+ continue
+ }
+ if (character === '/' && next === '*') {
+ const end = source.indexOf('*/', index + 2)
+ index = end === -1 ? source.length : end + 2
+ continue
+ }
+ if (character === '"' || character === "'" || character === '`') {
+ const literal = readStaticString(source, index)
+ index = literal?.end ?? source.length
+ continue
+ }
+
+ const identifier = source.startsWith('require', index)
+ ? 'require'
+ : source.startsWith('import', index)
+ ? 'import'
+ : undefined
+ if (!identifier) {
+ index += 1
+ continue
+ }
+ const before = source[index - 1]
+ const after = source[index + identifier.length]
+ if (/[\w$]/.test(before ?? '') || /[\w$]/.test(after ?? '')) {
+ index += identifier.length
+ continue
+ }
+ let cursor = index + identifier.length
+ while (/\s/.test(source[cursor] ?? '')) cursor += 1
+ if (source[cursor] !== '(') {
+ index += identifier.length
+ continue
+ }
+ cursor += 1
+ while (/\s/.test(source[cursor] ?? '')) cursor += 1
+ if (source[cursor] !== '"' && source[cursor] !== "'") {
+ index = cursor
+ continue
+ }
+ const literal = readStaticString(source, cursor)
+ if (literal) specifiers.add(literal.value)
+ index = literal?.end ?? source.length
+ }
+ return [...specifiers].sort()
+}
+
+async function collectJavaScriptFiles(directory) {
+ const files = []
+ async function walk(current) {
+ for (const entry of await readdir(current, { withFileTypes: true })) {
+ const entryPath = path.join(current, entry.name)
+ if (entry.isDirectory()) await walk(entryPath)
+ else if (/\.(?:c|m)?js$/.test(entry.name)) files.push(entryPath)
+ }
+ }
+ await walk(directory)
+ return files.sort()
+}
+
+async function validateStaticExternals(stageRoot) {
+ const specifiers = new Set()
+ for (const directory of ['dist/main', 'dist/core/plugin/host']) {
+ for (const file of await collectJavaScriptFiles(
+ path.join(stageRoot, directory)
+ )) {
+ const source = await readFile(file, 'utf8')
+ for (const specifier of scanStaticExternals(source)) {
+ if (
+ !BUILTIN_MODULES.has(specifier) &&
+ packageNameFromSpecifier(specifier)
+ ) {
+ specifiers.add(specifier)
+ }
+ }
+ }
+ }
+
+ const require = createRequire(path.join(stageRoot, 'package.json'))
+ for (const specifier of specifiers) {
+ try {
+ require.resolve(specifier)
+ } catch (error) {
+ throw new Error(
+ `staged application cannot resolve external ${specifier}`,
+ { cause: error }
+ )
+ }
+ }
+ return [...specifiers].sort()
+}
+
+async function inventoryTree(directory) {
+ let files = 0
+ let bytes = 0
+ async function walk(current) {
+ for (const entry of await readdir(current, { withFileTypes: true })) {
+ const entryPath = path.join(current, entry.name)
+ if (entry.isDirectory()) await walk(entryPath)
+ else {
+ const info = await stat(entryPath)
+ files += 1
+ bytes += info.size
+ }
+ }
+ }
+ await walk(directory)
+ return { files, bytes }
+}
+
+async function replaceStageAtomically(stageRoot, temporaryRoot) {
+ const backup = `${stageRoot}.previous-${process.pid}-${Date.now()}`
+ let hadPrevious = false
+ try {
+ await rename(stageRoot, backup)
+ hadPrevious = true
+ } catch (error) {
+ if (error?.code !== 'ENOENT') throw error
+ }
+
+ try {
+ await rename(temporaryRoot, stageRoot)
+ } catch (error) {
+ if (hadPrevious) await rename(backup, stageRoot)
+ throw error
+ }
+ if (hadPrevious) await rm(backup, { recursive: true })
+}
+
+export async function stageElectronApp(options = {}) {
+ const repoRoot = path.resolve(
+ options.repoRoot ?? fileURLToPath(new URL('..', import.meta.url))
+ )
+ const canonicalRepoRoot = await realpath(repoRoot)
+ const target = parseTarget({
+ platform: options.platform,
+ arch: options.arch,
+ strict: options.strict,
+ ci: options.ci,
+ })
+ const contract = validateRuntimeDependencyContract(
+ options.contract ??
+ (await readJson(
+ path.join(repoRoot, 'scripts/electron-runtime-dependencies.json'),
+ 'runtime dependency contract'
+ ))
+ )
+ if (!contract.supportedTargets.includes(target.key)) {
+ throw new Error(`unsupported Electron package target ${target.key}`)
+ }
+
+ const requestedStageRoot = path.resolve(
+ options.outputDir ?? path.join(repoRoot, 'dist/electron-app')
+ )
+ const stageRelative = path.relative(repoRoot, requestedStageRoot)
+ if (
+ stageRelative.length === 0 ||
+ stageRelative === '..' ||
+ stageRelative.startsWith(`..${path.sep}`) ||
+ path.isAbsolute(stageRelative)
+ ) {
+ throw new Error(
+ `stage output must stay within repository root: ${requestedStageRoot}`
+ )
+ }
+ const stageRoot = path.join(canonicalRepoRoot, stageRelative)
+ await assertBuildOutputs(repoRoot)
+ const buildOutputs = await fingerprintBuildOutputs(repoRoot)
+
+ const rootManifest = await readJson(
+ path.join(repoRoot, 'package.json'),
+ 'root package manifest'
+ )
+ const appManifest = generatedManifest(rootManifest, contract, target)
+ const temporaryRoot = await mkdtemp(
+ path.join(path.dirname(stageRoot), `.${path.basename(stageRoot)}-`)
+ )
+
+ try {
+ for (const output of BUILD_OUTPUTS) {
+ await copyTree(
+ path.join(repoRoot, output.directory),
+ path.join(temporaryRoot, output.directory),
+ canonicalRepoRoot
+ )
+ }
+ await writeFile(
+ path.join(temporaryRoot, 'package.json'),
+ stringifySortedJson(appManifest)
+ )
+
+ const placements = new Map()
+ const queue = []
+ const optionalOmissions = []
+
+ async function addDependency(name, consumer, optional) {
+ const instance = await resolvePackageInstance(
+ name,
+ consumer.sourceRoot,
+ canonicalRepoRoot
+ )
+ if (!instance) {
+ if (optional) {
+ optionalOmissions.push({
+ name,
+ requestedBy: `${consumer.manifest.name}@${consumer.manifest.version}`,
+ })
+ return
+ }
+ throw new Error(
+ `required dependency ${name} requested by ${consumer.manifest.name}@${consumer.manifest.version} is missing`
+ )
+ }
+ if (!packageAppliesToTarget(instance.manifest, target)) {
+ if (optional) {
+ optionalOmissions.push({
+ name,
+ requestedBy: `${consumer.manifest.name}@${consumer.manifest.version}`,
+ })
+ return
+ }
+ throw new Error(
+ `required dependency ${name} is incompatible with ${target.key}`
+ )
+ }
+
+ const lookup = nodeLookupDestinations(consumer.destination, name)
+ for (const candidate of lookup) {
+ const existing = placements.get(candidate)
+ if (existing?.sourceRoot === instance.sourceRoot) return
+ }
+
+ let destination = path.posix.join(
+ consumer.destination,
+ 'node_modules',
+ name
+ )
+ if (await isRootHoisted(repoRoot, name, instance.sourceRoot)) {
+ destination = path.posix.join('node_modules', name)
+ }
+ destination = normalizeRelativePath(
+ destination,
+ `destination for ${name}`
+ )
+ const conflict = placements.get(destination)
+ if (conflict) {
+ if (conflict.sourceRoot === instance.sourceRoot) return
+ throw new Error(
+ `dependency placement conflict at ${destination}: ${conflict.manifest.version} vs ${instance.manifest.version}`
+ )
+ }
+
+ const placement = { ...instance, destination }
+ placements.set(destination, placement)
+ queue.push(placement)
+ }
+
+ const rootConsumer = {
+ destination: '.',
+ manifest: rootManifest,
+ sourceRoot: canonicalRepoRoot,
+ }
+ const roots = targetList(contract, target)
+ for (const name of roots.required) {
+ await addDependency(name, rootConsumer, false)
+ }
+ for (const name of roots.optional) {
+ await addDependency(name, rootConsumer, true)
+ }
+
+ for (let index = 0; index < queue.length; index += 1) {
+ const placement = queue[index]
+ for (const name of Object.keys(
+ placement.manifest.dependencies ?? {}
+ ).sort()) {
+ await addDependency(name, placement, false)
+ }
+ for (const name of Object.keys(
+ placement.manifest.optionalDependencies ?? {}
+ ).sort()) {
+ await addDependency(name, placement, true)
+ }
+ }
+
+ const packageRecords = [...placements.values()]
+ .sort((left, right) => left.destination.localeCompare(right.destination))
+ .map((placement) => ({
+ destination: placement.destination,
+ name: placement.manifest.name,
+ source: normalizeRelativePath(
+ path.relative(canonicalRepoRoot, placement.sourceRoot),
+ `source for ${placement.manifest.name}`
+ ),
+ version: placement.manifest.version,
+ }))
+
+ for (const placement of [...placements.values()].sort((left, right) =>
+ left.destination.localeCompare(right.destination)
+ )) {
+ const packageFilter = packageCopyFilter(placement.manifest.name, target)
+ await copyTree(
+ placement.sourceRoot,
+ path.join(temporaryRoot, placement.destination),
+ canonicalRepoRoot,
+ { filter: packageFilter, skipNodeModules: true }
+ )
+ await validateStagedNativeModules(
+ path.join(temporaryRoot, placement.destination),
+ target,
+ placement.manifest.name
+ )
+ }
+
+ const externals = await validateStaticExternals(temporaryRoot)
+ optionalOmissions.sort((left, right) =>
+ `${left.name}\0${left.requestedBy}`.localeCompare(
+ `${right.name}\0${right.requestedBy}`
+ )
+ )
+ const inventory = await inventoryTree(temporaryRoot)
+ const resvgPlacement = [...placements.values()].find(
+ (placement) => placement.manifest.name === '@resvg/resvg-wasm'
+ )
+ let resvgWasmSha256
+ if (resvgPlacement) {
+ const resourcePath = path.join(repoRoot, 'extra/tray/resvg.wasm')
+ const resource = await readFile(resourcePath).catch((error) => {
+ throw new Error(`missing macOS resvg resource: ${resourcePath}`, {
+ cause: error,
+ })
+ })
+ resvgWasmSha256 = createHash('sha256').update(resource).digest('hex')
+ }
+ const stageManifest = {
+ schemaVersion: 1,
+ target,
+ rootVersion: rootManifest.version,
+ buildOutputs,
+ externals,
+ packages: packageRecords,
+ optionalOmissions,
+ inventory,
+ ...(resvgWasmSha256 ? { resvgWasmSha256 } : {}),
+ }
+ await writeFile(
+ path.join(temporaryRoot, '.motrix-package-stage.json'),
+ stringifySortedJson(stageManifest)
+ )
+ await replaceStageAtomically(stageRoot, temporaryRoot)
+ return { manifest: stageManifest, stageRoot }
+ } catch (error) {
+ await rm(temporaryRoot, { recursive: true }).catch(() => undefined)
+ throw error
+ }
+}
+
+function parseArguments(argv) {
+ const values = new Map()
+ for (let index = 0; index < argv.length; index += 1) {
+ const option = argv[index]
+ if (option === '--' && index === 0) continue
+ if (option === '--strict') {
+ values.set(option, true)
+ continue
+ }
+ if (!['--platform', '--arch'].includes(option)) {
+ throw new Error(`unknown staging argument: ${option}`)
+ }
+ const value = argv[index + 1]
+ if (!value || value.startsWith('--')) {
+ throw new Error(`missing value for staging argument: ${option}`)
+ }
+ if (values.has(option))
+ throw new Error(`duplicate staging argument: ${option}`)
+ values.set(option, value)
+ index += 1
+ }
+ return values
+}
+
+export async function main(argv = process.argv.slice(2)) {
+ const args = parseArguments(argv)
+ const result = await stageElectronApp({
+ platform: args.get('--platform'),
+ arch: args.get('--arch'),
+ strict: args.has('--strict') || Boolean(process.env.CI),
+ })
+ console.log(
+ `Staged ${result.manifest.target.key} Electron app at ${result.stageRoot}`
+ )
+ return result
+}
+
+if (
+ process.argv[1] &&
+ import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href
+) {
+ await main()
+}
diff --git a/scripts/verify-electron-package.mjs b/scripts/verify-electron-package.mjs
new file mode 100644
index 00000000..fdca7aab
--- /dev/null
+++ b/scripts/verify-electron-package.mjs
@@ -0,0 +1,772 @@
+import { createHash } from 'node:crypto'
+import { constants } from 'node:fs'
+import {
+ access,
+ lstat,
+ mkdir,
+ readdir,
+ readFile,
+ stat,
+ writeFile,
+} from 'node:fs/promises'
+import os from 'node:os'
+import path from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { extractFile, listPackage, statFile } from '@electron/asar'
+import {
+ bytesToMiB,
+ packageNameFromSpecifier,
+ parseTarget,
+ sanitizeMachinePaths,
+ stringifySortedJson,
+ validateSizeBudgetContract,
+} from './electron-package-utils.mjs'
+import { detectNativeBinaryTarget } from './native-binary-target.mjs'
+
+const REPOSITORY_ROOT = path.resolve(
+ path.dirname(fileURLToPath(import.meta.url)),
+ '..'
+)
+const DEFAULT_BUDGETS_PATH = path.join(
+ REPOSITORY_ROOT,
+ 'scripts/electron-package-size-budgets.json'
+)
+const EXPECTED_OUTPUTS = [
+ 'dist/core/plugin/host/quick-js-worker.cjs',
+ 'dist/main/index.cjs',
+ 'dist/preload/preload.cjs',
+ 'dist/renderer/index.html',
+]
+const FORBIDDEN_OUTPUTS = [
+ 'dist/builtin-moext',
+ 'dist/builtin-plugins',
+ 'dist/renderer-web',
+ 'dist/server',
+]
+const LEGAL_RESOURCES = [
+ 'THIRD_PARTY_LICENSES/aria2-COPYING',
+ 'THIRD_PARTY_LICENSES/aria2-LICENSE.OpenSSL',
+ 'THIRD_PARTY_NOTICES.md',
+ 'THIRD_PARTY_NOTICES.zh-CN.md',
+ 'legal/THIRD_PARTY_DEPENDENCIES.md',
+ 'legal/THIRD_PARTY_LICENSES.txt',
+ 'legal/sbom.spdx.json',
+]
+const FORMAT_BY_PLATFORM = {
+ darwin: 'mach-o',
+ linux: 'elf',
+ win32: 'pe',
+}
+
+function sha256(bytes) {
+ return createHash('sha256').update(bytes).digest('hex')
+}
+
+function portable(value) {
+ return value.split(path.sep).join('/')
+}
+
+export function normalizeArchiveEntry(value) {
+ return path.posix.normalize(value.replaceAll('\\', '/')).replace(/^\/+/, '')
+}
+
+function archiveLookupPath(value) {
+ return value.split('/').join(path.sep)
+}
+
+function uniqueSorted(values) {
+ return [...new Set(values)].sort()
+}
+
+async function pathInfo(filePath) {
+ return lstat(filePath).catch(() => null)
+}
+
+async function walkFiles(root) {
+ const result = []
+ async function visit(current, relative) {
+ const entries = await readdir(current, { withFileTypes: true }).catch(
+ () => []
+ )
+ entries.sort((left, right) => left.name.localeCompare(right.name))
+ for (const entry of entries) {
+ const absolute = path.join(current, entry.name)
+ const nextRelative = relative ? `${relative}/${entry.name}` : entry.name
+ if (entry.isDirectory()) await visit(absolute, nextRelative)
+ else if (entry.isFile()) {
+ const info = await stat(absolute)
+ result.push({ absolute, path: nextRelative, bytes: info.size })
+ }
+ }
+ }
+ await visit(root, '')
+ return result
+}
+
+function resourcesDirectory(appDir, platform) {
+ return platform === 'darwin'
+ ? path.join(appDir, 'Contents/Resources')
+ : path.join(appDir, 'resources')
+}
+
+function packageRecordFromManifestPath(relativePath) {
+ const parts = relativePath.split('/')
+ if (parts.at(-1) !== 'package.json') return undefined
+ const nodeModulesIndex = parts.lastIndexOf('node_modules')
+ if (nodeModulesIndex < 0) return undefined
+ const firstNamePart = parts[nodeModulesIndex + 1]
+ if (!firstNamePart) return undefined
+ const manifestIndex = firstNamePart.startsWith('@')
+ ? nodeModulesIndex + 3
+ : nodeModulesIndex + 2
+ if (manifestIndex !== parts.length - 1) return undefined
+ const name = firstNamePart.startsWith('@')
+ ? `${firstNamePart}/${parts[nodeModulesIndex + 2]}`
+ : firstNamePart
+ return {
+ destination: parts.slice(0, manifestIndex).join('/'),
+ name,
+ }
+}
+
+function chooseExportTarget(value) {
+ if (typeof value === 'string') return value
+ if (Array.isArray(value)) {
+ for (const entry of value) {
+ const selected = chooseExportTarget(entry)
+ if (selected) return selected
+ }
+ return undefined
+ }
+ if (value && typeof value === 'object') {
+ for (const condition of ['node', 'require', 'import', 'default']) {
+ const selected = chooseExportTarget(value[condition])
+ if (selected) return selected
+ }
+ }
+ return undefined
+}
+
+function pathExistsInArchive(paths, candidate) {
+ const normalized = path.posix
+ .normalize(candidate.replace(/^\.\//, ''))
+ .replace(/\/$/, '')
+ const candidates = [
+ normalized,
+ `${normalized}.js`,
+ `${normalized}.cjs`,
+ `${normalized}.mjs`,
+ `${normalized}.json`,
+ `${normalized}/index.js`,
+ `${normalized}/index.cjs`,
+ `${normalized}/index.mjs`,
+ `${normalized}/index.json`,
+ ]
+ return candidates.some((entry) => paths.has(entry))
+}
+
+function resolveExternal(external, packages, archivePaths) {
+ const packageName = packageNameFromSpecifier(external)
+ if (!packageName) return false
+ const packageRecord = packages.find(
+ (entry) =>
+ entry.name === packageName &&
+ entry.destination === `node_modules/${packageName}`
+ )
+ if (!packageRecord) return false
+ const subpath = external.slice(packageName.length).replace(/^\//, '')
+ const exportKey = subpath ? `./${subpath}` : '.'
+ const packageExports = packageRecord.manifest.exports
+ const selectedExport =
+ typeof packageExports === 'string' || Array.isArray(packageExports)
+ ? packageExports
+ : packageExports &&
+ Object.keys(packageExports).some((key) => key.startsWith('.'))
+ ? packageExports[exportKey]
+ : packageExports
+ const exportTarget = chooseExportTarget(selectedExport)
+ const target =
+ exportTarget ?? subpath ?? packageRecord.manifest.main ?? 'index.js'
+ return pathExistsInArchive(
+ archivePaths,
+ `${packageRecord.destination}/${target}`
+ )
+}
+
+async function archiveFileBytes(asarPath, relativePath) {
+ return extractFile(asarPath, archiveLookupPath(relativePath))
+}
+
+async function archiveLogicalBytes(asarPath, relativePath) {
+ const info = await statFile(asarPath, archiveLookupPath(relativePath))
+ return info.size ?? 0
+}
+
+async function archiveFileInfo(asarPath, relativePath) {
+ return statFile(asarPath, archiveLookupPath(relativePath))
+}
+
+function nativeTargetMatches(detected, platform, arch, allowUniversal = false) {
+ return Boolean(
+ detected &&
+ detected.format === FORMAT_BY_PLATFORM[platform] &&
+ detected.arches.includes(arch) &&
+ (allowUniversal || detected.arches.length === 1)
+ )
+}
+
+async function readToolVersions() {
+ async function packageVersion(relativePath) {
+ return JSON.parse(
+ await readFile(path.join(REPOSITORY_ROOT, relativePath), 'utf8')
+ ).version
+ }
+ return {
+ asar: await packageVersion(
+ 'node_modules/@electron/asar/package.json'
+ ).catch(() => 'unknown'),
+ electronBuilder: await packageVersion(
+ 'node_modules/electron-builder/package.json'
+ ).catch(() => 'unknown'),
+ node: process.versions.node,
+ }
+}
+
+function sanitizeReport(value, roots) {
+ if (Array.isArray(value))
+ return value.map((entry) => sanitizeReport(entry, roots))
+ if (value && typeof value === 'object') {
+ return Object.fromEntries(
+ Object.entries(value).map(([key, entry]) => [
+ key,
+ sanitizeReport(entry, roots),
+ ])
+ )
+ }
+ return typeof value === 'string' ? sanitizeMachinePaths(value, roots) : value
+}
+
+function parseArguments(argv) {
+ const options = {}
+ for (let index = 0; index < argv.length; index += 1) {
+ const argument = argv[index]
+ if (index === 0 && argument === '--') continue
+ if (!argument.startsWith('--'))
+ throw new Error(`unknown argument: ${argument}`)
+ const key = argument.slice(2)
+ if (!['app-dir', 'arch', 'platform', 'report'].includes(key)) {
+ throw new Error(`unknown option: --${key}`)
+ }
+ const value = argv[index + 1]
+ if (!value || value.startsWith('--')) {
+ throw new Error(`missing value for --${key}`)
+ }
+ options[key] = value
+ index += 1
+ }
+ if (!options['app-dir']) throw new Error('--app-dir is required')
+ return options
+}
+
+export async function verifyElectronPackage(options) {
+ const appDir = path.resolve(options.appDir)
+ const target = parseTarget({
+ platform: options.platform,
+ arch: options.arch,
+ strict: true,
+ })
+ const reportPath = path.resolve(
+ options.reportPath ??
+ path.join(REPOSITORY_ROOT, 'release/size-reports', `${target.key}.json`)
+ )
+ const rawBudgets =
+ options.budgets ?? JSON.parse(await readFile(DEFAULT_BUDGETS_PATH, 'utf8'))
+ const budgets = validateSizeBudgetContract(rawBudgets)
+ const resources = resourcesDirectory(appDir, target.platform)
+ const asarPath = path.join(resources, 'app.asar')
+ const unpackedPath = `${asarPath}.unpacked`
+ const checks = []
+ const errors = []
+ const archivePaths = new Set()
+ let archiveEntries = []
+ let stage
+ let packagedManifest
+ const packages = []
+ const nativeBinaries = []
+ let appFiles = []
+ let unpackedFiles = []
+ let asarBytes = 0
+ let betterSqlite3Bytes = 0
+ let foreignBetterSqlite3Prebuilds = 0
+ let duplicateResvgWasmFiles = 0
+ let unexpectedPackageNames = []
+ const externalResources = {
+ aria2: [],
+ builtins: [],
+ legal: [],
+ nativeHost: [],
+ resvg: [],
+ updateMetadata: [],
+ }
+
+ async function check(id, operation) {
+ try {
+ const message = await operation()
+ checks.push({ id, passed: true, message: message ?? 'passed' })
+ return true
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error)
+ checks.push({ id, passed: false, message })
+ errors.push(`${id}: ${message}`)
+ return false
+ }
+ }
+
+ await check('application-directory', async () => {
+ const info = await pathInfo(appDir)
+ if (!info?.isDirectory())
+ throw new Error('application directory is missing')
+ appFiles = await walkFiles(appDir)
+ return `${appFiles.length} physical files`
+ })
+
+ await check('asar-inventory', async () => {
+ const info = await pathInfo(asarPath)
+ if (!info?.isFile()) throw new Error('resources/app.asar is missing')
+ asarBytes = info.size
+ archiveEntries = await listPackage(asarPath)
+ for (const entry of archiveEntries)
+ archivePaths.add(normalizeArchiveEntry(entry))
+ unpackedFiles = await walkFiles(unpackedPath)
+ return `${archiveEntries.length} archive entries`
+ })
+
+ await check('stage-manifest', async () => {
+ stage = JSON.parse(
+ (
+ await archiveFileBytes(asarPath, '.motrix-package-stage.json')
+ ).toString()
+ )
+ packagedManifest = JSON.parse(
+ (await archiveFileBytes(asarPath, 'package.json')).toString()
+ )
+ if (
+ stage.schemaVersion !== 1 ||
+ stage.target?.platform !== target.platform ||
+ stage.target?.arch !== target.arch ||
+ stage.target?.key !== target.key
+ ) {
+ throw new Error(`packaged stage does not match ${target.key}`)
+ }
+ if (stage.rootVersion !== packagedManifest.version) {
+ throw new Error('packaged stage and package version differ')
+ }
+ if (!Array.isArray(stage.packages) || !Array.isArray(stage.externals)) {
+ throw new Error('packaged stage inventory is invalid')
+ }
+ return `${stage.packages.length} staged packages`
+ })
+
+ await check('required-build-outputs', async () => {
+ if (!stage) throw new Error('stage manifest is unavailable')
+ const actualOutputs = (stage.buildOutputs ?? [])
+ .map((entry) => entry.path)
+ .sort()
+ if (JSON.stringify(actualOutputs) !== JSON.stringify(EXPECTED_OUTPUTS)) {
+ throw new Error(
+ 'stage must contain the exact four Electron build outputs'
+ )
+ }
+ for (const output of stage.buildOutputs) {
+ if (!archivePaths.has(output.path))
+ throw new Error(`missing ${output.path}`)
+ const bytes = await archiveFileBytes(asarPath, output.path)
+ if (bytes.length !== output.bytes || sha256(bytes) !== output.sha256) {
+ throw new Error(`packaged output does not match stage: ${output.path}`)
+ }
+ }
+ return EXPECTED_OUTPUTS.join(', ')
+ })
+
+ await check('forbidden-dist-outputs', async () => {
+ const leaked = FORBIDDEN_OUTPUTS.filter((prefix) =>
+ [...archivePaths].some(
+ (entry) => entry === prefix || entry.startsWith(`${prefix}/`)
+ )
+ )
+ if (leaked.length > 0)
+ throw new Error(`forbidden outputs: ${leaked.join(', ')}`)
+ return 'no server, web, or builtin mirror output'
+ })
+
+ await check('package-inventory', async () => {
+ if (!stage) throw new Error('stage manifest is unavailable')
+ for (const relativePath of [...archivePaths].sort()) {
+ const record = packageRecordFromManifestPath(relativePath)
+ if (!record) continue
+ const manifest = JSON.parse(
+ (await archiveFileBytes(asarPath, relativePath)).toString()
+ )
+ packages.push({ ...record, version: manifest.version, manifest })
+ }
+ packages.sort((left, right) =>
+ left.destination.localeCompare(right.destination)
+ )
+ const expected = stage.packages
+ .map(({ destination, name, version }) => ({ destination, name, version }))
+ .sort((left, right) => left.destination.localeCompare(right.destination))
+ const actual = packages.map(({ destination, name, version }) => ({
+ destination,
+ name,
+ version,
+ }))
+ unexpectedPackageNames = uniqueSorted(
+ actual
+ .filter(
+ (entry) =>
+ !expected.some((candidate) => candidate.name === entry.name)
+ )
+ .map((entry) => entry.name)
+ )
+ if (JSON.stringify(actual) !== JSON.stringify(expected)) {
+ throw new Error(
+ 'packaged package names, versions, or placements differ from stage'
+ )
+ }
+ return `${actual.length} exact package placements`
+ })
+
+ await check('static-externals', async () => {
+ if (!stage) throw new Error('stage manifest is unavailable')
+ const unresolved = stage.externals.filter(
+ (external) => !resolveExternal(external, packages, archivePaths)
+ )
+ if (unresolved.length > 0) {
+ throw new Error(`unresolved externals: ${unresolved.sort().join(', ')}`)
+ }
+ return `${stage.externals.length} externals resolved`
+ })
+
+ await check('native-binaries', async () => {
+ const nativePaths = [...archivePaths]
+ .filter((entry) => entry.endsWith('.node'))
+ .sort()
+ for (const relativePath of nativePaths) {
+ const detected = detectNativeBinaryTarget(
+ await archiveFileBytes(asarPath, relativePath)
+ )
+ nativeBinaries.push({ path: relativePath, ...detected })
+ if (!nativeTargetMatches(detected, target.platform, target.arch)) {
+ throw new Error(`invalid native binary target: ${relativePath}`)
+ }
+ }
+ return `${nativePaths.length} native modules`
+ })
+
+ await check('better-sqlite3-layout', async () => {
+ const sqlitePackages = packages.filter(
+ (entry) => entry.name === 'better-sqlite3'
+ )
+ if (sqlitePackages.length !== 1) {
+ throw new Error('better-sqlite3 must have exactly one package placement')
+ }
+ const root = sqlitePackages[0].destination
+ const files = []
+ for (const entry of [...archivePaths]
+ .filter((candidate) => candidate.startsWith(`${root}/`))
+ .sort()) {
+ const entryInfo = await archiveFileInfo(asarPath, entry)
+ if (!entryInfo.files) files.push(entry)
+ }
+ const leaked = files.filter(
+ (entry) =>
+ entry === `${root}/binding.gyp` ||
+ entry.startsWith(`${root}/deps/`) ||
+ entry.startsWith(`${root}/src/`)
+ )
+ if (leaked.length > 0)
+ throw new Error(`SQLite sources leaked: ${leaked.join(', ')}`)
+ const prebuilds = files.filter(
+ (entry) =>
+ entry.startsWith(`${root}/prebuilds/`) && entry.endsWith('.node')
+ )
+ const expectedPrebuild = `${root}/prebuilds/${target.key}.node`
+ foreignBetterSqlite3Prebuilds = prebuilds.filter(
+ (entry) => entry !== expectedPrebuild
+ ).length
+ if (prebuilds.length !== 1 || prebuilds[0] !== expectedPrebuild) {
+ throw new Error(`expected only ${expectedPrebuild}`)
+ }
+ const detected = detectNativeBinaryTarget(
+ await archiveFileBytes(asarPath, expectedPrebuild)
+ )
+ if (!nativeTargetMatches(detected, target.platform, target.arch)) {
+ foreignBetterSqlite3Prebuilds += 1
+ throw new Error('better-sqlite3 prebuild has an invalid native header')
+ }
+ for (const relativePath of files) {
+ betterSqlite3Bytes += await archiveLogicalBytes(asarPath, relativePath)
+ }
+ return `${prebuilds[0]} (${betterSqlite3Bytes} bytes)`
+ })
+
+ await check('resvg-wasm-placement', async () => {
+ const packageCopies = [...archivePaths].filter(
+ (entry) =>
+ entry.endsWith('node_modules/@resvg/resvg-wasm/index_bg.wasm') ||
+ entry === 'node_modules/@resvg/resvg-wasm/index_bg.wasm'
+ )
+ duplicateResvgWasmFiles = packageCopies.length
+ if (packageCopies.length > 0) {
+ throw new Error(
+ `package resvg WASM leaked: ${packageCopies.sort().join(', ')}`
+ )
+ }
+ const resourcePath = path.join(resources, 'extra/tray/resvg.wasm')
+ const resourceInfo = await pathInfo(resourcePath)
+ if (target.platform !== 'darwin') {
+ if (resourceInfo) throw new Error('resvg WASM resource is macOS-only')
+ return 'non-macOS target has no resvg WASM resource'
+ }
+ if (!resourceInfo?.isFile())
+ throw new Error('macOS resvg WASM resource is missing')
+ const bytes = await readFile(resourcePath)
+ const digest = sha256(bytes)
+ externalResources.resvg.push({
+ path: 'extra/tray/resvg.wasm',
+ bytes: bytes.length,
+ sha256: digest,
+ })
+ if (!stage?.resvgWasmSha256 || digest !== stage.resvgWasmSha256) {
+ throw new Error('macOS resvg WASM hash does not match stage')
+ }
+ return 'single external resvg WASM matches stage'
+ })
+
+ await check('external-resources', async () => {
+ const hostName =
+ target.platform === 'win32'
+ ? 'motrix-native-host.exe'
+ : 'motrix-native-host'
+ const engineName = target.platform === 'win32' ? 'aria2c.exe' : 'aria2c'
+ const required = [
+ {
+ category: 'aria2',
+ path: `extra/${target.platform}/${target.arch}/${engineName}`,
+ executable: true,
+ },
+ { category: 'nativeHost', path: `bin/${hostName}`, executable: true },
+ ...LEGAL_RESOURCES.map((relativePath) => ({
+ category: 'legal',
+ path: relativePath,
+ executable: false,
+ })),
+ ]
+ for (const resource of required) {
+ const absolute = path.join(resources, resource.path)
+ const info = await pathInfo(absolute)
+ if (!info?.isFile() || info.size === 0) {
+ throw new Error(`required resource is missing: ${resource.path}`)
+ }
+ if (resource.executable) {
+ const detected = detectNativeBinaryTarget(await readFile(absolute))
+ if (
+ !nativeTargetMatches(
+ detected,
+ target.platform,
+ target.arch,
+ target.platform === 'darwin'
+ )
+ ) {
+ throw new Error(`resource has invalid target: ${resource.path}`)
+ }
+ if (target.platform !== 'win32') {
+ await access(absolute, constants.X_OK).catch(() => {
+ throw new Error(`resource is not executable: ${resource.path}`)
+ })
+ }
+ }
+ externalResources[resource.category].push({
+ path: resource.path,
+ bytes: info.size,
+ })
+ }
+ for (const forbidden of [
+ 'motrix-flatpak-native-host',
+ 'motrix-flatpak-native-host.exe',
+ 'motrix-native-host-broker',
+ 'motrix-native-host-broker.exe',
+ ]) {
+ if (await pathInfo(path.join(resources, 'bin', forbidden))) {
+ throw new Error(`Flatpak-only native host leaked: bin/${forbidden}`)
+ }
+ }
+ return `${required.length} required resource files`
+ })
+
+ await check('builtin-plugins', async () => {
+ const root = path.join(resources, 'builtin-plugins')
+ const files = await walkFiles(root)
+ const manifests = files
+ .filter((entry) => entry.path.endsWith('/motrix-plugin.json'))
+ .map((entry) => entry.path)
+ .sort()
+ if (manifests.length === 0)
+ throw new Error('builtin plugin manifests are missing')
+ for (const manifest of manifests) {
+ const pluginRoot = path.posix.dirname(manifest)
+ if (
+ !files.some((entry) => entry.path === `${pluginRoot}/dist/plugin.js`)
+ ) {
+ throw new Error(`builtin plugin payload is missing: ${pluginRoot}`)
+ }
+ }
+ externalResources.builtins = files.map(({ path: relativePath, bytes }) => ({
+ path: `builtin-plugins/${portable(relativePath)}`,
+ bytes,
+ }))
+ return `${manifests.length} builtin plugins`
+ })
+
+ await check('update-metadata-policy', async () => {
+ const relativePath = 'app-update.yml'
+ const info = await pathInfo(path.join(resources, relativePath))
+ if (info && (!info.isFile() || info.size === 0)) {
+ throw new Error('app-update.yml exists but is not a non-empty file')
+ }
+ externalResources.updateMetadata = info
+ ? [{ path: relativePath, bytes: info.size, policy: 'distributable' }]
+ : [{ path: relativePath, present: false, policy: 'directory-output' }]
+ return info
+ ? 'distributable update metadata is present'
+ : 'directory output intentionally has no update metadata'
+ })
+
+ const unpackedBytes = unpackedFiles.reduce(
+ (sum, entry) => sum + entry.bytes,
+ 0
+ )
+ const payloadBytes = asarBytes + unpackedBytes
+ const appBytes = appFiles.reduce((sum, entry) => sum + entry.bytes, 0)
+ const localeFiles = appFiles.filter((entry) =>
+ target.platform === 'darwin'
+ ? entry.path.includes('.lproj/')
+ : entry.path.startsWith('locales/')
+ )
+ const localeRoots = uniqueSorted(
+ localeFiles.map((entry) => {
+ const lproj = entry.path.match(/(^|\/)([^/]+\.lproj)\//)
+ if (lproj) return lproj[2]
+ const locale = entry.path.match(/(^|\/)locales\/([^/]+)/)
+ return locale?.[2] ?? entry.path
+ })
+ )
+ const metrics = {
+ betterSqlite3Bytes,
+ duplicateResvgWasmFiles,
+ foreignBetterSqlite3Prebuilds,
+ payloadBytes,
+ unexpectedPackageNames: unexpectedPackageNames.length,
+ }
+
+ for (const [metric, value] of Object.entries(metrics)) {
+ await check(`budget-${metric}`, async () => {
+ const budget = budgets[metric]
+ if (value > budget)
+ throw new Error(`${metric} ${value} exceeds budget ${budget}`)
+ return `${value} <= ${budget}`
+ })
+ }
+
+ const report = sanitizeReport(
+ {
+ schemaVersion: 1,
+ target,
+ passed: checks.every((entry) => entry.passed),
+ tools: await readToolVersions(),
+ inputStage: stage
+ ? {
+ schemaVersion: stage.schemaVersion,
+ target: stage.target,
+ rootVersion: stage.rootVersion,
+ inventory: stage.inventory,
+ packages: stage.packages.map(({ destination, name, version }) => ({
+ destination,
+ name,
+ version,
+ })),
+ externals: [...stage.externals].sort(),
+ optionalOmissions: [...(stage.optionalOmissions ?? [])].sort(),
+ }
+ : null,
+ sizes: {
+ appBytes,
+ appMiB: bytesToMiB(appBytes),
+ asarBytes,
+ asarMiB: bytesToMiB(asarBytes),
+ unpackedBytes,
+ unpackedMiB: bytesToMiB(unpackedBytes),
+ payloadBytes,
+ payloadMiB: bytesToMiB(payloadBytes),
+ localeBytes: localeFiles.reduce((sum, entry) => sum + entry.bytes, 0),
+ localeRoots,
+ },
+ packages: {
+ count: packages.length,
+ names: uniqueSorted(packages.map((entry) => entry.name)),
+ records: packages.map(({ destination, name, version }) => ({
+ destination,
+ name,
+ version,
+ })),
+ betterSqlite3Bytes,
+ unexpectedNames: unexpectedPackageNames,
+ },
+ nativeBinaries,
+ externalResources,
+ budgets,
+ metrics,
+ checks,
+ errors,
+ },
+ [appDir, path.dirname(appDir), os.homedir(), REPOSITORY_ROOT]
+ )
+ await mkdir(path.dirname(reportPath), { recursive: true })
+ await writeFile(reportPath, stringifySortedJson(report))
+ return report
+}
+
+async function main() {
+ const args = parseArguments(process.argv.slice(2))
+ const target = parseTarget({
+ platform: args.platform,
+ arch: args.arch,
+ strict: true,
+ })
+ const report = await verifyElectronPackage({
+ appDir: args['app-dir'],
+ platform: target.platform,
+ arch: target.arch,
+ reportPath: args.report,
+ })
+ const prefix = report.passed ? 'passed' : 'failed'
+ console.log(
+ `[verify-electron-package] ${prefix} ${target.key}: ${report.sizes.payloadBytes} bytes`
+ )
+ if (!report.passed) {
+ for (const error of report.errors) {
+ console.error(`[verify-electron-package] ${error}`)
+ }
+ process.exitCode = 1
+ }
+}
+
+if (
+ process.argv[1] &&
+ path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)
+) {
+ main().catch((error) => {
+ console.error(`[verify-electron-package] ${error.message}`)
+ process.exitCode = 1
+ })
+}
diff --git a/scripts/verify-flatpak-packaging.mjs b/scripts/verify-flatpak-packaging.mjs
index 61f66b7e..d8880c0a 100644
--- a/scripts/verify-flatpak-packaging.mjs
+++ b/scripts/verify-flatpak-packaging.mjs
@@ -266,7 +266,12 @@ export async function verifyFlatpakPackaging(root = REPO_ROOT) {
const brokerBinary = motrixCommands.indexOf(
'/release/motrix-native-host-broker'
)
+ const electronBuild = motrixCommands.indexOf('run build:electron')
+ const electronStage = motrixCommands.indexOf('run stage:electron')
const electronBuilder = motrixCommands.indexOf('electron-builder')
+ const electronPackageVerification = motrixCommands.indexOf(
+ 'verify-electron-package.mjs'
+ )
invariant(
aria2Copy >= 0 && aria2Copy < electronBuilder,
'aria2 must be staged before electron-builder'
@@ -275,6 +280,19 @@ export async function verifyFlatpakPackaging(root = REPO_ROOT) {
nativeHostCopy >= 0 && nativeHostCopy < electronBuilder,
'browser-facing native host must be staged transiently before electron-builder'
)
+ invariant(
+ electronBuild >= 0 &&
+ electronStage > electronBuild &&
+ electronBuilder > electronStage &&
+ electronPackageVerification > electronBuilder &&
+ motrixCommands.includes('--platform linux') &&
+ motrixCommands.includes('--arch $npm_config_target_arch') &&
+ motrixCommands.includes('--app-dir "$unpacked"') &&
+ motrixCommands.includes(
+ '--report "release/size-reports/linux-$npm_config_target_arch.json"'
+ ),
+ 'offline Flatpak build must stage and verify the explicit Electron target'
+ )
invariant(
brokerBinary >= 0 &&
motrixCommands.includes(
@@ -327,7 +345,7 @@ export async function verifyFlatpakPackaging(root = REPO_ROOT) {
)
invariant(
(motrixCommands.match(/pnpm --config\.verify-deps-before-run=false/g) ?? [])
- .length === 5,
+ .length === 6,
'every pnpm run/exec after --ignore-scripts must disable dependency repair'
)
const flatpakScripts = new Map(
@@ -538,6 +556,7 @@ export async function verifyFlatpakPackaging(root = REPO_ROOT) {
cargoSources: cargoSources.length,
builtinSources: builtinSources.length,
brokerCommand: FLATPAK_BROKER_COMMAND,
+ electronPackageVerification: true,
privateProtocolVersion: 1,
}
}
diff --git a/tests/check-third-party-notices.test.ts b/tests/check-third-party-notices.test.ts
index 8d454784..9773a59c 100644
--- a/tests/check-third-party-notices.test.ts
+++ b/tests/check-third-party-notices.test.ts
@@ -227,6 +227,16 @@ function registryPackagesFromCargoLock(
}
describe('third-party graph dependency notices', () => {
+ it('keeps the root manifest as the legal dependency source of truth', async () => {
+ const generator = await readFile(
+ path.join(ROOT, 'scripts/generate-third-party-notices.mjs'),
+ 'utf8'
+ )
+
+ expect(generator).toContain("path.join(resolvedProjectDir, 'package.json')")
+ expect(generator).not.toContain('dist/electron-app/package.json')
+ })
+
it.each(['THIRD_PARTY_NOTICES.md', 'THIRD_PARTY_NOTICES.zh-CN.md'])(
'%s documents the generated runtime inventory',
async (noticeFile) => {
diff --git a/tests/scripts/before-pack-verify.test.ts b/tests/scripts/before-pack-verify.test.ts
index 1a92bae3..e3d40231 100644
--- a/tests/scripts/before-pack-verify.test.ts
+++ b/tests/scripts/before-pack-verify.test.ts
@@ -1,3 +1,4 @@
+import { createHash } from 'node:crypto'
import { chmod, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
@@ -11,6 +12,7 @@ describe('before-pack-verify', () => {
beforeEach(async () => {
projectDir = await mkdtemp(join(tmpdir(), 'motrix-before-pack-'))
+ await writeStage()
})
afterEach(async () => {
@@ -43,6 +45,48 @@ describe('before-pack-verify', () => {
)
}
+ async function writeStage(
+ platform = 'darwin',
+ arch = 'x64',
+ version = '1.2.3'
+ ) {
+ await writeFile(
+ join(projectDir, 'package.json'),
+ `${JSON.stringify({ version })}\n`
+ )
+ const buildOutputs = []
+ for (const relativePath of [
+ 'dist/core/plugin/host/quick-js-worker.cjs',
+ 'dist/main/index.cjs',
+ 'dist/preload/preload.cjs',
+ 'dist/renderer/index.html',
+ ]) {
+ const target = join(projectDir, relativePath)
+ const content = Buffer.from(relativePath)
+ await mkdir(dirname(target), { recursive: true })
+ await writeFile(target, content)
+ buildOutputs.push({
+ path: relativePath,
+ bytes: content.length,
+ sha256: createHash('sha256').update(content).digest('hex'),
+ })
+ }
+ const manifestPath = join(
+ projectDir,
+ 'dist/electron-app/.motrix-package-stage.json'
+ )
+ await mkdir(dirname(manifestPath), { recursive: true })
+ await writeFile(
+ manifestPath,
+ `${JSON.stringify({
+ schemaVersion: 1,
+ target: { platform, arch, key: `${platform}-${arch}` },
+ rootVersion: version,
+ buildOutputs,
+ })}\n`
+ )
+ }
+
async function writeBinary(
filePath: string,
mode = 0o755,
@@ -167,6 +211,7 @@ describe('before-pack-verify', () => {
})
it('accepts Windows .exe files without Unix execute bits', async () => {
+ await writeStage('win32')
await writeBinary(enginePath('win32'), 0o644, 'win32')
await writeBinary(hostPath('win32'), 0o644, 'win32')
@@ -174,6 +219,7 @@ describe('before-pack-verify', () => {
})
it('accepts Windows arm64 PE files for the reserved target contract', async () => {
+ await writeStage('win32', 'arm64')
await writeBinary(enginePath('win32', 'arm64'), 0o644, 'win32', 'arm64')
await writeBinary(hostPath('win32', 'arm64'), 0o644, 'win32', 'arm64')
@@ -181,6 +227,7 @@ describe('before-pack-verify', () => {
})
it('rejects an MZ-only Windows file without a PE/COFF target header', async () => {
+ await writeStage('win32')
await writeBinary(enginePath('win32'), 0o644, 'win32')
await mkdir(dirname(hostPath('win32')), { recursive: true })
await writeFile(hostPath('win32'), Buffer.from('MZ-not-a-PE-file'))
@@ -191,6 +238,7 @@ describe('before-pack-verify', () => {
})
it('accepts executable Linux ELF files', async () => {
+ await writeStage('linux')
await writeBinary(enginePath('linux'), 0o755, 'linux')
await writeBinary(hostPath('linux'), 0o755, 'linux')
@@ -198,6 +246,7 @@ describe('before-pack-verify', () => {
})
it('accepts executable Linux arm64 ELF files', async () => {
+ await writeStage('linux', 'arm64')
await writeBinary(enginePath('linux', 'arm64'), 0o755, 'linux', 'arm64')
await writeBinary(hostPath('linux', 'arm64'), 0o755, 'linux', 'arm64')
@@ -205,6 +254,7 @@ describe('before-pack-verify', () => {
})
it('accepts a universal Mach-O containing the requested target slice', async () => {
+ await writeStage('darwin', 'arm64')
await writeBinary(enginePath('darwin', 'arm64'), 0o755, 'darwin', 'arm64')
await writeUniversalMachBinary(hostPath('darwin', 'arm64'), [
'x64',
@@ -213,4 +263,40 @@ describe('before-pack-verify', () => {
await expect(beforePack(context('darwin', 3))).resolves.toBeUndefined()
})
+
+ it('rejects a missing package stage before checking external resources', async () => {
+ await rm(join(projectDir, 'dist/electron-app/.motrix-package-stage.json'))
+
+ await expect(beforePack(context())).rejects.toThrow(
+ 'missing or invalid Electron package stage manifest'
+ )
+ })
+
+ it('rejects a target-mismatched package stage', async () => {
+ await writeStage('linux')
+
+ await expect(beforePack(context())).rejects.toThrow(
+ 'stage target does not match darwin-x64'
+ )
+ })
+
+ it('rejects a stale package stage', async () => {
+ await writeFile(join(projectDir, 'dist/main/index.cjs'), 'changed')
+
+ await expect(beforePack(context())).rejects.toThrow(
+ 'stage is stale for dist/main/index.cjs'
+ )
+ })
+
+ it('rejects a package stage for another application version', async () => {
+ await writeStage('darwin', 'x64', '1.2.2')
+ await writeFile(
+ join(projectDir, 'package.json'),
+ `${JSON.stringify({ version: '1.2.3' })}\n`
+ )
+
+ await expect(beforePack(context())).rejects.toThrow(
+ 'stage version 1.2.2 does not match root version 1.2.3'
+ )
+ })
})
diff --git a/tests/scripts/electron-package-contract.test.ts b/tests/scripts/electron-package-contract.test.ts
new file mode 100644
index 00000000..7742d0ad
--- /dev/null
+++ b/tests/scripts/electron-package-contract.test.ts
@@ -0,0 +1,261 @@
+import { readFile } from 'node:fs/promises'
+import path from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { describe, expect, it } from 'vitest'
+import {
+ bytesToMiB,
+ packageNameFromSpecifier,
+ parseTarget,
+ sanitizeMachinePaths,
+ stringifySortedJson,
+ validateRuntimeDependencyContract,
+ validateSizeBudgetContract,
+} from '../../scripts/electron-package-utils.mjs'
+import {
+ parseSmokeArguments,
+ resolvePackagedLayout,
+ scanRuntimeLog,
+} from '../../scripts/smoke-electron-package.mjs'
+
+const REPOSITORY_ROOT = path.resolve(
+ path.dirname(fileURLToPath(import.meta.url)),
+ '../..'
+)
+
+async function readJson(relativePath: string): Promise<unknown> {
+ return JSON.parse(
+ await readFile(path.join(REPOSITORY_ROOT, relativePath), 'utf8')
+ )
+}
+
+describe('Electron package contracts', () => {
+ it('packages only the generated staged application', async () => {
+ const config = (await readJson('electron-builder.json')) as {
+ asarUnpack?: string[]
+ beforeBuild?: string
+ directories?: Record<string, string>
+ files?: Array<string | { filter?: string[]; from?: string; to?: string }>
+ }
+ const manifest = (await readJson('package.json')) as {
+ scripts?: Record<string, string>
+ }
+
+ expect(config.directories).toMatchObject({
+ app: 'dist/electron-app',
+ output: 'release',
+ buildResources: 'build',
+ })
+ expect(
+ config.files?.filter(
+ (pattern) => typeof pattern === 'string' && !pattern.startsWith('!')
+ )
+ ).toEqual([
+ '.motrix-package-stage.json',
+ 'dist/core/plugin/host/**',
+ 'dist/main/**',
+ 'dist/preload/**',
+ 'dist/renderer/**',
+ 'package.json',
+ ])
+ expect(config.files).toContainEqual({
+ from: 'node_modules',
+ to: 'node_modules',
+ filter: [
+ '**/*',
+ '!**/*.map',
+ '!**/*.ts',
+ '!**/*.tsx',
+ '!**/tsconfig*.json',
+ '!**/biome.json',
+ '!**/vite*.config.*',
+ ],
+ })
+ expect(config.files).not.toContain('dist/**/*')
+ expect(config.asarUnpack).toContain('dist/renderer/**')
+ expect(config.asarUnpack).not.toContain(
+ '**/node_modules/@resvg/resvg-wasm/**/*.wasm'
+ )
+ expect(config.beforeBuild).toBe(
+ './scripts/before-build-use-staged-dependencies.mjs'
+ )
+
+ expect(manifest.scripts?.['stage:electron']).toBe(
+ 'node scripts/stage-electron-app.mjs'
+ )
+ expect(manifest.scripts?.['verify:electron-package']).toBe(
+ 'node scripts/verify-electron-package.mjs'
+ )
+ for (const name of ['pack:mac', 'dist:mac', 'release:mac']) {
+ const command = manifest.scripts?.[name] ?? ''
+ expect(command).toMatch(
+ /build:mac-arm64 && pnpm run stage:electron -- --platform darwin --arch arm64 && .*electron-builder/
+ )
+ }
+ expect(manifest.scripts?.['build:electron']).not.toContain('stage:electron')
+ })
+
+ it('declares the exact supported runtime roots and targets', async () => {
+ const contract = validateRuntimeDependencyContract(
+ await readJson('scripts/electron-runtime-dependencies.json')
+ )
+ const rootManifest = (await readJson('package.json')) as {
+ dependencies?: Record<string, string>
+ optionalDependencies?: Record<string, string>
+ }
+
+ expect(contract).toEqual({
+ schemaVersion: 1,
+ supportedTargets: [
+ 'darwin-arm64',
+ 'darwin-x64',
+ 'linux-arm64',
+ 'linux-x64',
+ 'win32-x64',
+ ],
+ common: [
+ '@motrix/mdxp',
+ '@motrix/nat',
+ '@motrix/plugin-manifest-schema',
+ 'ajv',
+ 'better-sqlite3',
+ 'chokidar',
+ 'electron-updater',
+ 'i18next',
+ 'libsodium-wrappers',
+ 'mmdb-lib',
+ 'quickjs-emscripten',
+ 'undici',
+ 'uuid',
+ 'vscode-jsonrpc',
+ 'write-file-atomic',
+ 'ws',
+ 'yauzl',
+ 'zod',
+ ],
+ platforms: {
+ darwin: {
+ optional: ['electron-liquid-glass'],
+ required: ['@resvg/resvg-wasm'],
+ },
+ linux: { optional: [], required: [] },
+ win32: { optional: [], required: [] },
+ },
+ })
+
+ const declared = new Set([
+ ...Object.keys(rootManifest.dependencies ?? {}),
+ ...Object.keys(rootManifest.optionalDependencies ?? {}),
+ ])
+ const roots = [
+ ...contract.common,
+ ...Object.values(contract.platforms).flatMap((entry) => [
+ ...entry.required,
+ ...entry.optional,
+ ]),
+ ]
+ expect(roots.every((name) => declared.has(name))).toBe(true)
+ })
+
+ it('declares only controllable-payload hard budgets', async () => {
+ const raw = await readJson('scripts/electron-package-size-budgets.json')
+ const contract = validateSizeBudgetContract(raw)
+
+ expect(contract).toEqual({
+ schemaVersion: 1,
+ payloadBytes: 64 * 1024 * 1024,
+ betterSqlite3Bytes: 4 * 1024 * 1024,
+ unexpectedPackageNames: 0,
+ foreignBetterSqlite3Prebuilds: 0,
+ duplicateResvgWasmFiles: 0,
+ })
+ expect(JSON.stringify(raw)).not.toMatch(/locale|installer|dmg|zip/i)
+ })
+
+ it('rejects unknown contract keys and unsupported targets', () => {
+ expect(() =>
+ validateSizeBudgetContract({
+ schemaVersion: 1,
+ payloadBytes: 1,
+ betterSqlite3Bytes: 1,
+ unexpectedPackageNames: 0,
+ foreignBetterSqlite3Prebuilds: 0,
+ duplicateResvgWasmFiles: 0,
+ localeBytes: 0,
+ })
+ ).toThrow('unknown key')
+ expect(() => parseTarget({ platform: 'darwin', arch: 'ia32' })).toThrow(
+ 'unsupported Electron package target'
+ )
+ })
+
+ it('provides deterministic path-safe reporting helpers', () => {
+ expect(packageNameFromSpecifier('@scope/pkg/subpath')).toBe('@scope/pkg')
+ expect(packageNameFromSpecifier('plain/subpath')).toBe('plain')
+ expect(bytesToMiB(1_572_864)).toBe(1.5)
+ expect(stringifySortedJson({ z: 1, a: { d: 2, b: 3 } })).toBe(
+ '{\n "a": {\n "b": 3,\n "d": 2\n },\n "z": 1\n}\n'
+ )
+ expect(
+ sanitizeMachinePaths('failed at /Users/example/project', [
+ '/Users/example',
+ ])
+ ).toBe('failed at <home>/project')
+ })
+
+ it('defines an explicit host-native packaged runtime smoke contract', async () => {
+ const manifest = (await readJson('package.json')) as {
+ scripts?: Record<string, string>
+ }
+
+ expect(manifest.scripts?.['smoke:electron-package']).toBe(
+ 'node scripts/smoke-electron-package.mjs'
+ )
+ expect(
+ parseSmokeArguments([
+ '--',
+ '--app-dir',
+ 'release/mac-arm64/Motrix.app',
+ '--platform',
+ 'darwin',
+ '--arch',
+ 'arm64',
+ '--ad-hoc-sign',
+ ])
+ ).toMatchObject({
+ adHocSign: true,
+ appDir: 'release/mac-arm64/Motrix.app',
+ key: 'darwin-arm64',
+ })
+ expect(() =>
+ parseSmokeArguments([
+ '--app-dir',
+ 'release/mac-arm64/Motrix.app',
+ '--platform',
+ 'darwin',
+ ])
+ ).toThrow('requires both --platform and --arch')
+ })
+
+ it('resolves packaged layouts and detects startup dependency failures', () => {
+ expect(resolvePackagedLayout('/tmp/Motrix.app', 'darwin')).toEqual({
+ appDir: '/tmp/Motrix.app',
+ executable: '/tmp/Motrix.app/Contents/MacOS/Motrix',
+ resources: '/tmp/Motrix.app/Contents/Resources',
+ })
+ expect(resolvePackagedLayout('/tmp/motrix-unpacked', 'linux')).toEqual({
+ appDir: '/tmp/motrix-unpacked',
+ executable: '/tmp/motrix-unpacked/motrix',
+ resources: '/tmp/motrix-unpacked/resources',
+ })
+ expect(scanRuntimeLog('ready')).toEqual({
+ moduleResolutionError: false,
+ nativeAbiError: false,
+ })
+ expect(scanRuntimeLog("Error: Cannot find module 'zod'")).toMatchObject({
+ moduleResolutionError: true,
+ })
+ expect(
+ scanRuntimeLog('was compiled against a different Node.js version')
+ ).toMatchObject({ nativeAbiError: true })
+ })
+})
diff --git a/tests/scripts/flatpak-packaging.test.ts b/tests/scripts/flatpak-packaging.test.ts
index 2057b6d1..1c6d7d1d 100644
--- a/tests/scripts/flatpak-packaging.test.ts
+++ b/tests/scripts/flatpak-packaging.test.ts
@@ -8,6 +8,7 @@ describe('Flatpak packaging contract', () => {
modules: 4,
builtinSources: 6,
brokerCommand: 'motrix-native-host-broker',
+ electronPackageVerification: true,
privateProtocolVersion: 1,
})
})
diff --git a/tests/scripts/native-binary-target.test.ts b/tests/scripts/native-binary-target.test.ts
new file mode 100644
index 00000000..31b3e47e
--- /dev/null
+++ b/tests/scripts/native-binary-target.test.ts
@@ -0,0 +1,102 @@
+import { mkdtemp, rm, writeFile } from 'node:fs/promises'
+import os from 'node:os'
+import path from 'node:path'
+import { afterEach, describe, expect, it } from 'vitest'
+import {
+ assertNativeBinaryTarget,
+ detectNativeBinaryTarget,
+} from '../../scripts/native-binary-target.mjs'
+
+const temporaryRoots: string[] = []
+
+afterEach(async () => {
+ await Promise.all(
+ temporaryRoots.splice(0).map((root) => rm(root, { recursive: true }))
+ )
+})
+
+function thinMach(arch: 'x64' | 'arm64', littleEndian = true): Buffer {
+ const header = Buffer.alloc(8)
+ header.set(littleEndian ? [0xcf, 0xfa, 0xed, 0xfe] : [0xfe, 0xed, 0xfa, 0xcf])
+ const cpu = arch === 'arm64' ? 0x0100000c : 0x01000007
+ if (littleEndian) header.writeUInt32LE(cpu, 4)
+ else header.writeUInt32BE(cpu, 4)
+ return header
+}
+
+function fatMach(arches: Array<'x64' | 'arm64'>, is64 = false): Buffer {
+ const entrySize = is64 ? 32 : 20
+ const header = Buffer.alloc(8 + arches.length * entrySize)
+ header.set(is64 ? [0xca, 0xfe, 0xba, 0xbf] : [0xca, 0xfe, 0xba, 0xbe])
+ header.writeUInt32BE(arches.length, 4)
+ arches.forEach((arch, index) => {
+ header.writeUInt32BE(
+ arch === 'arm64' ? 0x0100000c : 0x01000007,
+ 8 + index * entrySize
+ )
+ })
+ return header
+}
+
+function elf(arch: 'x64' | 'arm64', bigEndian = false): Buffer {
+ const header = Buffer.alloc(20)
+ header.set([0x7f, 0x45, 0x4c, 0x46])
+ header[4] = 2
+ header[5] = bigEndian ? 2 : 1
+ const machine = arch === 'arm64' ? 183 : 62
+ if (bigEndian) header.writeUInt16BE(machine, 18)
+ else header.writeUInt16LE(machine, 18)
+ return header
+}
+
+function pe(arch: 'x64' | 'arm64'): Buffer {
+ const header = Buffer.alloc(72)
+ header.write('MZ')
+ header.writeUInt32LE(64, 0x3c)
+ header.set([0x50, 0x45, 0, 0], 64)
+ header.writeUInt16LE(arch === 'arm64' ? 0xaa64 : 0x8664, 68)
+ return header
+}
+
+describe('native binary target detection', () => {
+ it.each([
+ [thinMach('x64'), { format: 'mach-o', arches: ['x64'] }],
+ [thinMach('arm64', false), { format: 'mach-o', arches: ['arm64'] }],
+ [fatMach(['x64', 'arm64']), { format: 'mach-o', arches: ['arm64', 'x64'] }],
+ [fatMach(['arm64'], true), { format: 'mach-o', arches: ['arm64'] }],
+ [elf('x64'), { format: 'elf', arches: ['x64'] }],
+ [elf('arm64', true), { format: 'elf', arches: ['arm64'] }],
+ [pe('x64'), { format: 'pe', arches: ['x64'] }],
+ [pe('arm64'), { format: 'pe', arches: ['arm64'] }],
+ ])('detects supported headers', (header, expected) => {
+ expect(detectNativeBinaryTarget(header)).toEqual(expected)
+ })
+
+ it.each([Buffer.alloc(0), Buffer.from('MZ'), fatMach([]), Buffer.alloc(20)])(
+ 'rejects truncated or invalid headers',
+ (header) => {
+ expect(detectNativeBinaryTarget(header)).toBeUndefined()
+ }
+ )
+
+ it('requires an explicit universal Mach-O allowance', async () => {
+ const root = await mkdtemp(path.join(os.tmpdir(), 'motrix-native-test-'))
+ temporaryRoots.push(root)
+ const binary = path.join(root, 'universal.node')
+ await writeFile(binary, fatMach(['x64', 'arm64']))
+
+ await expect(
+ assertNativeBinaryTarget(binary, 'darwin', 'arm64')
+ ).rejects.toThrow('universal Mach-O is not allowed')
+ await expect(
+ assertNativeBinaryTarget(binary, 'darwin', 'arm64', {
+ allowUniversal: true,
+ })
+ ).resolves.toEqual({ format: 'mach-o', arches: ['arm64', 'x64'] })
+ await expect(
+ assertNativeBinaryTarget(binary, 'linux', 'arm64', {
+ allowUniversal: true,
+ })
+ ).rejects.toThrow('expected linux-arm64')
+ })
+})
diff --git a/tests/scripts/postinstall-flow.test.ts b/tests/scripts/postinstall-flow.test.ts
index 4347320f..72497764 100644
--- a/tests/scripts/postinstall-flow.test.ts
+++ b/tests/scripts/postinstall-flow.test.ts
@@ -1,9 +1,13 @@
import { describe, expect, it, vi } from 'vitest'
// @ts-expect-error — .mjs without types
-import { classifyRebuildResult, main } from '../../scripts/postinstall.mjs'
+import {
+ classifyRebuildResult,
+ main,
+ runElectronRebuild,
+} from '../../scripts/postinstall.mjs'
// Stage A (electron rebuild) and Stage B (aria2 fetch) are injected so the
-// test observes control flow without spawning electron-builder or hitting the
+// test observes control flow without spawning the rebuild tool or hitting the
// network. These assertions codify rev-2 constraint 5 plus the code-review
// fixes: the two SKIP guards are independent, but a Stage A FAILURE
// short-circuits with its real exit code and never starts the network Stage B.
@@ -38,6 +42,30 @@ describe('classifyRebuildResult', () => {
})
})
+describe('runElectronRebuild', () => {
+ it('rebuilds root dependencies without loading the staged app config', () => {
+ const spawn = vi.fn(() => ({ status: 0 }))
+
+ expect(runElectronRebuild(spawn, 'linux')).toBe(0)
+ expect(spawn).toHaveBeenCalledWith(
+ 'electron-rebuild',
+ ['--module-dir', '.', '--sequential', '--disable-pre-gyp-copy'],
+ { stdio: 'inherit', shell: false }
+ )
+ })
+
+ it('uses the command shell for the Windows shim', () => {
+ const spawn = vi.fn(() => ({ status: 0 }))
+
+ expect(runElectronRebuild(spawn, 'win32')).toBe(0)
+ expect(spawn).toHaveBeenCalledWith(
+ 'electron-rebuild',
+ ['--module-dir', '.', '--sequential', '--disable-pre-gyp-copy'],
+ { stdio: 'inherit', shell: true }
+ )
+ })
+})
+
describe('postinstall main flow', () => {
it('runs both stages when neither skip var is set', async () => {
const deps = makeDeps()
diff --git a/tests/scripts/stage-electron-app.test.ts b/tests/scripts/stage-electron-app.test.ts
new file mode 100644
index 00000000..0b6e0175
--- /dev/null
+++ b/tests/scripts/stage-electron-app.test.ts
@@ -0,0 +1,516 @@
+import { createHash } from 'node:crypto'
+import {
+ chmod,
+ mkdir,
+ mkdtemp,
+ readdir,
+ readFile,
+ rm,
+ stat,
+ symlink,
+ writeFile,
+} from 'node:fs/promises'
+import os from 'node:os'
+import path from 'node:path'
+import { afterEach, describe, expect, it } from 'vitest'
+import { stageElectronApp } from '../../scripts/stage-electron-app.mjs'
+
+const temporaryRoots: string[] = []
+
+afterEach(async () => {
+ await Promise.all(
+ temporaryRoots.splice(0).map((root) => rm(root, { recursive: true }))
+ )
+})
+
+async function writeFixtureFile(
+ root: string,
+ relativePath: string,
+ content = relativePath
+): Promise<void> {
+ const target = path.join(root, relativePath)
+ await mkdir(path.dirname(target), { recursive: true })
+ await writeFile(target, content)
+}
+
+async function writePackage(
+ root: string,
+ relativePath: string,
+ manifest: {
+ name: string
+ version: string
+ dependencies?: Record<string, string>
+ optionalDependencies?: Record<string, string>
+ }
+): Promise<void> {
+ await writeFixtureFile(
+ root,
+ `${relativePath}/package.json`,
+ `${JSON.stringify({ main: 'index.js', ...manifest }, null, 2)}\n`
+ )
+ await writeFixtureFile(
+ root,
+ `${relativePath}/index.js`,
+ 'module.exports = 1\n'
+ )
+}
+
+function fixtureContract() {
+ return {
+ schemaVersion: 1,
+ supportedTargets: [
+ 'darwin-arm64',
+ 'darwin-x64',
+ 'linux-arm64',
+ 'linux-x64',
+ 'win32-x64',
+ ],
+ common: ['@scope/pkg', 'alpha', 'gamma'],
+ platforms: {
+ darwin: { optional: ['optional-darwin'], required: [] },
+ linux: { optional: [], required: [] },
+ win32: { optional: [], required: [] },
+ },
+ }
+}
+
+function nativeHeader(platform: string, arch: string): Buffer {
+ if (platform === 'win32') {
+ const header = Buffer.alloc(72)
+ header.write('MZ')
+ header.writeUInt32LE(64, 0x3c)
+ header.set([0x50, 0x45, 0, 0], 64)
+ header.writeUInt16LE(arch === 'arm64' ? 0xaa64 : 0x8664, 68)
+ return header
+ }
+ if (platform === 'linux') {
+ const header = Buffer.alloc(20)
+ header.set([0x7f, 0x45, 0x4c, 0x46])
+ header[4] = 2
+ header[5] = 1
+ header.writeUInt16LE(arch === 'arm64' ? 183 : 62, 18)
+ return header
+ }
+ const header = Buffer.alloc(8)
+ header.set([0xcf, 0xfa, 0xed, 0xfe])
+ header.writeUInt32LE(arch === 'arm64' ? 0x0100000c : 0x01000007, 4)
+ return header
+}
+
+async function createNativeFixture(): Promise<string> {
+ const root = await createFixture()
+ const rootManifestPath = path.join(root, 'package.json')
+ const rootManifest = JSON.parse(await readFile(rootManifestPath, 'utf8'))
+ rootManifest.dependencies['@resvg/resvg-wasm'] = '2.6.2'
+ rootManifest.dependencies['better-sqlite3'] = '13.0.3'
+ await writeFile(
+ rootManifestPath,
+ `${JSON.stringify(rootManifest, null, 2)}\n`
+ )
+
+ await writePackage(root, 'node_modules/better-sqlite3', {
+ name: 'better-sqlite3',
+ version: '13.0.3',
+ })
+ const sqliteManifestPath = path.join(
+ root,
+ 'node_modules/better-sqlite3/package.json'
+ )
+ const sqliteManifest = JSON.parse(await readFile(sqliteManifestPath, 'utf8'))
+ sqliteManifest.main = 'lib/index.js'
+ await writeFile(
+ sqliteManifestPath,
+ `${JSON.stringify(sqliteManifest, null, 2)}\n`
+ )
+ await writeFixtureFile(root, 'node_modules/better-sqlite3/LICENSE', 'MIT')
+ await writeFixtureFile(root, 'node_modules/better-sqlite3/lib/index.js')
+ await writeFixtureFile(root, 'node_modules/better-sqlite3/src/leak.cc')
+ await writeFixtureFile(root, 'node_modules/better-sqlite3/deps/leak.c')
+ await writeFixtureFile(root, 'node_modules/better-sqlite3/binding.gyp')
+ for (const target of [
+ 'darwin-arm64',
+ 'darwin-x64',
+ 'linux-arm64',
+ 'linux-x64',
+ 'win32-x64',
+ ]) {
+ const separator = target.lastIndexOf('-')
+ const platform = target.slice(0, separator)
+ const arch = target.slice(separator + 1)
+ await writeFixtureFile(
+ root,
+ `node_modules/better-sqlite3/prebuilds/${target}.node`,
+ nativeHeader(platform, arch).toString('binary')
+ )
+ await writeFile(
+ path.join(root, `node_modules/better-sqlite3/prebuilds/${target}.node`),
+ nativeHeader(platform, arch)
+ )
+ }
+ await writePackage(root, 'node_modules/@resvg/resvg-wasm', {
+ name: '@resvg/resvg-wasm',
+ version: '2.6.2',
+ })
+ await writeFixtureFile(
+ root,
+ 'node_modules/@resvg/resvg-wasm/index_bg.wasm',
+ 'package-copy'
+ )
+ await writeFixtureFile(root, 'extra/tray/resvg.wasm', 'resource-copy')
+ await writeFixtureFile(
+ root,
+ 'dist/main/index.cjs',
+ "require('alpha/subpath')\nrequire('better-sqlite3')\n"
+ )
+ return root
+}
+
+function nativeContract() {
+ const contract = fixtureContract()
+ return {
+ ...contract,
+ common: ['@scope/pkg', 'alpha', 'better-sqlite3', 'gamma'],
+ platforms: {
+ ...contract.platforms,
+ darwin: {
+ optional: ['optional-darwin'],
+ required: ['@resvg/resvg-wasm'],
+ },
+ },
+ }
+}
+
+async function createFixture(): Promise<string> {
+ const root = await mkdtemp(path.join(os.tmpdir(), 'motrix-stage-test-'))
+ temporaryRoots.push(root)
+
+ await writeFixtureFile(
+ root,
+ 'package.json',
+ `${JSON.stringify(
+ {
+ name: 'motrix-fixture',
+ productName: 'Motrix Fixture',
+ version: '1.2.3',
+ description: 'fixture',
+ homepage: 'https://example.test',
+ author: { name: 'Motrix' },
+ license: 'MIT',
+ type: 'module',
+ main: 'dist/main/index.cjs',
+ private: true,
+ scripts: { forbidden: 'true' },
+ devDependencies: { forbidden: '1.0.0' },
+ dependencies: {
+ '@scope/pkg': '1.0.0',
+ alpha: '1.0.0',
+ gamma: '1.0.0',
+ },
+ optionalDependencies: { 'optional-darwin': '1.0.0' },
+ },
+ null,
+ 2
+ )}\n`
+ )
+ await writeFixtureFile(
+ root,
+ 'dist/main/index.cjs',
+ [
+ "const alpha = require('alpha/subpath')",
+ "// require('ignored-comment')",
+ 'const text = "require(\'ignored-string\')"',
+ 'module.exports = { alpha, text }',
+ ].join('\n')
+ )
+ await writeFixtureFile(root, 'dist/preload/preload.cjs')
+ await writeFixtureFile(
+ root,
+ 'dist/core/plugin/host/quick-js-worker.cjs',
+ "require('@scope/pkg')\n"
+ )
+ await writeFixtureFile(root, 'dist/renderer/index.html', '<main>ok</main>')
+
+ await writePackage(root, 'node_modules/alpha', {
+ name: 'alpha',
+ version: '1.0.0',
+ dependencies: { beta: '1.0.0', shared: '1.0.0' },
+ optionalDependencies: { 'missing-native': '1.0.0' },
+ })
+ await writeFixtureFile(
+ root,
+ 'node_modules/alpha/subpath.js',
+ 'module.exports = 1\n'
+ )
+ await writePackage(root, 'node_modules/beta', {
+ name: 'beta',
+ version: '1.0.0',
+ dependencies: { alpha: '1.0.0' },
+ })
+ await writePackage(root, 'node_modules/shared', {
+ name: 'shared',
+ version: '1.0.0',
+ })
+ await writePackage(root, 'node_modules/gamma', {
+ name: 'gamma',
+ version: '1.0.0',
+ dependencies: { shared: '2.0.0' },
+ })
+ await writePackage(root, 'node_modules/gamma/node_modules/shared', {
+ name: 'shared',
+ version: '2.0.0',
+ })
+ await writePackage(root, 'node_modules/@scope/pkg', {
+ name: '@scope/pkg',
+ version: '1.0.0',
+ })
+ return root
+}
+
+describe('stageElectronApp', () => {
+ it('creates a deterministic minimal stage with nested dependency lookup', async () => {
+ const root = await createFixture()
+ await writeFixtureFile(root, 'dist/server/forbidden.mjs')
+ await writeFixtureFile(root, 'dist/renderer-web/forbidden.js')
+ await writeFixtureFile(root, 'dist/builtin-moext/forbidden.moext')
+ await writeFixtureFile(root, 'dist/builtin-plugins/forbidden/index.js')
+ const sourceTimestamp = (await stat(path.join(root, 'node_modules/alpha')))
+ .mtimeMs
+
+ const result = await stageElectronApp({
+ repoRoot: root,
+ platform: 'darwin',
+ arch: 'arm64',
+ strict: true,
+ contract: fixtureContract(),
+ })
+
+ const stageManifest = JSON.parse(
+ await readFile(
+ path.join(root, 'dist/electron-app/.motrix-package-stage.json'),
+ 'utf8'
+ )
+ )
+ const generatedManifest = JSON.parse(
+ await readFile(path.join(root, 'dist/electron-app/package.json'), 'utf8')
+ )
+ expect(result.manifest).toEqual(stageManifest)
+ expect(stageManifest.externals).toEqual(['@scope/pkg', 'alpha/subpath'])
+ expect(
+ stageManifest.packages.map((entry: { version: string }) => entry.version)
+ ).toEqual(expect.arrayContaining(['1.0.0', '2.0.0']))
+ expect(stageManifest.optionalOmissions).toEqual([
+ { name: 'missing-native', requestedBy: '[email protected]' },
+ { name: 'optional-darwin', requestedBy: '[email protected]' },
+ ])
+ expect(generatedManifest).toEqual({
+ name: 'motrix-fixture',
+ productName: 'Motrix Fixture',
+ version: '1.2.3',
+ description: 'fixture',
+ homepage: 'https://example.test',
+ author: { name: 'Motrix' },
+ license: 'MIT',
+ type: 'module',
+ main: 'dist/main/index.cjs',
+ private: true,
+ dependencies: {
+ '@scope/pkg': '1.0.0',
+ alpha: '1.0.0',
+ gamma: '1.0.0',
+ },
+ optionalDependencies: { 'optional-darwin': '1.0.0' },
+ })
+ await expect(
+ stat(
+ path.join(
+ root,
+ 'dist/electron-app/node_modules/gamma/node_modules/shared/package.json'
+ )
+ )
+ ).resolves.toBeDefined()
+ await expect(
+ stat(path.join(root, 'dist/electron-app/dist/server'))
+ ).rejects.toThrow()
+ expect((await stat(path.join(root, 'node_modules/alpha'))).mtimeMs).toBe(
+ sourceTimestamp
+ )
+ expect(JSON.stringify(stageManifest)).not.toContain(root)
+
+ const cleanRoot = await createFixture()
+ const clean = await stageElectronApp({
+ repoRoot: cleanRoot,
+ platform: 'darwin',
+ arch: 'arm64',
+ strict: true,
+ contract: fixtureContract(),
+ })
+ expect(clean.manifest).toEqual(stageManifest)
+ })
+
+ it('keeps the previous stage byte-identical after validation fails', async () => {
+ const root = await createFixture()
+ await stageElectronApp({
+ repoRoot: root,
+ platform: 'darwin',
+ arch: 'arm64',
+ strict: true,
+ contract: fixtureContract(),
+ })
+ const manifestPath = path.join(
+ root,
+ 'dist/electron-app/.motrix-package-stage.json'
+ )
+ const previous = await readFile(manifestPath)
+ await rm(path.join(root, 'dist/main/index.cjs'))
+
+ await expect(
+ stageElectronApp({
+ repoRoot: root,
+ platform: 'darwin',
+ arch: 'arm64',
+ strict: true,
+ contract: fixtureContract(),
+ })
+ ).rejects.toThrow('missing Electron build output')
+ expect(await readFile(manifestPath)).toEqual(previous)
+ })
+
+ it('fails closed for missing dependencies and escaping symlinks', async () => {
+ const missingRoot = await createFixture()
+ await rm(path.join(missingRoot, 'node_modules/beta'), { recursive: true })
+ await expect(
+ stageElectronApp({
+ repoRoot: missingRoot,
+ platform: 'darwin',
+ arch: 'arm64',
+ strict: true,
+ contract: fixtureContract(),
+ })
+ ).rejects.toThrow('required dependency beta')
+
+ const symlinkRoot = await createFixture()
+ const outside = await mkdtemp(
+ path.join(os.tmpdir(), 'motrix-stage-outside-')
+ )
+ temporaryRoots.push(outside)
+ await writeFixtureFile(outside, 'secret.txt', 'secret')
+ await symlink(
+ path.join(outside, 'secret.txt'),
+ path.join(symlinkRoot, 'node_modules/alpha/escape.txt')
+ )
+ await expect(
+ stageElectronApp({
+ repoRoot: symlinkRoot,
+ platform: 'darwin',
+ arch: 'arm64',
+ strict: true,
+ contract: fixtureContract(),
+ })
+ ).rejects.toThrow('escapes repository root')
+ })
+
+ it('requires an explicit supported target in strict mode', async () => {
+ const root = await createFixture()
+ await expect(
+ stageElectronApp({
+ repoRoot: root,
+ strict: true,
+ contract: fixtureContract(),
+ })
+ ).rejects.toThrow('requires both --platform and --arch')
+ await expect(
+ stageElectronApp({
+ repoRoot: root,
+ platform: 'win32',
+ arch: 'arm64',
+ strict: true,
+ contract: fixtureContract(),
+ })
+ ).rejects.toThrow('unsupported Electron package target')
+ })
+
+ it('preserves executable source modes without emitting symlinks', async () => {
+ const root = await createFixture()
+ const executable = path.join(root, 'node_modules/alpha/tool')
+ await writeFixtureFile(root, 'node_modules/alpha/tool', '#!/bin/sh\n')
+ await chmod(executable, 0o755)
+ await stageElectronApp({
+ repoRoot: root,
+ platform: 'darwin',
+ arch: 'arm64',
+ strict: true,
+ contract: fixtureContract(),
+ })
+
+ const copied = await stat(
+ path.join(root, 'dist/electron-app/node_modules/alpha/tool')
+ )
+ expect(copied.mode & 0o111).not.toBe(0)
+ })
+
+ it.each([
+ ['darwin', 'arm64'],
+ ['darwin', 'x64'],
+ ['linux', 'arm64'],
+ ['linux', 'x64'],
+ ['win32', 'x64'],
+ ])('filters native and WASM content for %s-%s', async (platform, arch) => {
+ const root = await createNativeFixture()
+ const result = await stageElectronApp({
+ repoRoot: root,
+ platform,
+ arch,
+ strict: true,
+ contract: nativeContract(),
+ })
+ const sqliteRoot = path.join(
+ root,
+ 'dist/electron-app/node_modules/better-sqlite3'
+ )
+ expect(await readdir(path.join(sqliteRoot, 'prebuilds'))).toEqual([
+ `${platform}-${arch}.node`,
+ ])
+ await expect(stat(path.join(sqliteRoot, 'src'))).rejects.toThrow()
+ await expect(stat(path.join(sqliteRoot, 'deps'))).rejects.toThrow()
+ await expect(stat(path.join(sqliteRoot, 'binding.gyp'))).rejects.toThrow()
+
+ const resvgRoot = path.join(
+ root,
+ 'dist/electron-app/node_modules/@resvg/resvg-wasm'
+ )
+ if (platform === 'darwin') {
+ await expect(
+ stat(path.join(resvgRoot, 'index.js'))
+ ).resolves.toBeDefined()
+ await expect(
+ stat(path.join(resvgRoot, 'index_bg.wasm'))
+ ).rejects.toThrow()
+ expect(result.manifest.resvgWasmSha256).toBe(
+ createHash('sha256').update('resource-copy').digest('hex')
+ )
+ } else {
+ await expect(stat(resvgRoot)).rejects.toThrow()
+ expect(result.manifest.resvgWasmSha256).toBeUndefined()
+ }
+ })
+
+ it('rejects a filename-matched SQLite prebuild with the wrong header', async () => {
+ const root = await createNativeFixture()
+ await writeFile(
+ path.join(
+ root,
+ 'node_modules/better-sqlite3/prebuilds/darwin-arm64.node'
+ ),
+ nativeHeader('darwin', 'x64')
+ )
+ await expect(
+ stageElectronApp({
+ repoRoot: root,
+ platform: 'darwin',
+ arch: 'arm64',
+ strict: true,
+ contract: nativeContract(),
+ })
+ ).rejects.toThrow('expected darwin-arm64')
+ })
+})
diff --git a/tests/scripts/verify-electron-package.test.ts b/tests/scripts/verify-electron-package.test.ts
new file mode 100644
index 00000000..9969c65d
--- /dev/null
+++ b/tests/scripts/verify-electron-package.test.ts
@@ -0,0 +1,595 @@
+import { createHash } from 'node:crypto'
+import {
+ chmod,
+ mkdir,
+ mkdtemp,
+ readFile,
+ rm,
+ stat,
+ unlink,
+ writeFile,
+} from 'node:fs/promises'
+import os from 'node:os'
+import path from 'node:path'
+import { createPackageWithOptions } from '@electron/asar'
+import { afterEach, describe, expect, it } from 'vitest'
+import {
+ normalizeArchiveEntry,
+ verifyElectronPackage,
+} from '../../scripts/verify-electron-package.mjs'
+
+type Target = {
+ platform: 'darwin' | 'linux' | 'win32'
+ arch: 'arm64' | 'x64'
+}
+
+type Fixture = Target & {
+ root: string
+ source: string
+ appDir: string
+ resources: string
+ reportPath: string
+ stage: Record<string, unknown>
+}
+
+const temporaryRoots: string[] = []
+const LARGE_BUDGETS = {
+ schemaVersion: 1,
+ payloadBytes: 64 * 1024 * 1024,
+ betterSqlite3Bytes: 4 * 1024 * 1024,
+ unexpectedPackageNames: 0,
+ foreignBetterSqlite3Prebuilds: 0,
+ duplicateResvgWasmFiles: 0,
+}
+const OUTPUTS = [
+ 'dist/core/plugin/host/quick-js-worker.cjs',
+ 'dist/main/index.cjs',
+ 'dist/preload/preload.cjs',
+ 'dist/renderer/index.html',
+]
+const LEGAL = [
+ 'THIRD_PARTY_LICENSES/aria2-COPYING',
+ 'THIRD_PARTY_LICENSES/aria2-LICENSE.OpenSSL',
+ 'THIRD_PARTY_NOTICES.md',
+ 'THIRD_PARTY_NOTICES.zh-CN.md',
+ 'legal/THIRD_PARTY_DEPENDENCIES.md',
+ 'legal/THIRD_PARTY_LICENSES.txt',
+ 'legal/sbom.spdx.json',
+]
+
+afterEach(async () => {
+ await Promise.all(
+ temporaryRoots
+ .splice(0)
+ .map((root) => rm(root, { recursive: true, force: true }))
+ )
+})
+
+function hash(bytes: Buffer | string): string {
+ return createHash('sha256').update(bytes).digest('hex')
+}
+
+function nativeHeader(target: Target): Buffer {
+ if (target.platform === 'linux') {
+ const header = Buffer.alloc(20)
+ header.set([0x7f, 0x45, 0x4c, 0x46])
+ header[4] = 2
+ header[5] = 1
+ header.writeUInt16LE(target.arch === 'arm64' ? 183 : 62, 18)
+ return header
+ }
+ if (target.platform === 'win32') {
+ const header = Buffer.alloc(72)
+ header.write('MZ')
+ header.writeUInt32LE(64, 0x3c)
+ header.set([0x50, 0x45, 0, 0], 64)
+ header.writeUInt16LE(target.arch === 'arm64' ? 0xaa64 : 0x8664, 68)
+ return header
+ }
+ const header = Buffer.alloc(8)
+ header.set([0xcf, 0xfa, 0xed, 0xfe])
+ header.writeUInt32LE(target.arch === 'arm64' ? 0x0100000c : 0x01000007, 4)
+ return header
+}
+
+async function write(
+ root: string,
+ relativePath: string,
+ content: string | Buffer
+) {
+ const target = path.join(root, relativePath)
+ await mkdir(path.dirname(target), { recursive: true })
+ await writeFile(target, content)
+ return target
+}
+
+async function writeJson(root: string, relativePath: string, value: unknown) {
+ return write(root, relativePath, `${JSON.stringify(value)}\n`)
+}
+
+async function createFixture(
+ target: Target = { platform: 'darwin', arch: 'arm64' },
+ mutate?: (fixture: Fixture) => Promise<void>
+): Promise<Fixture> {
+ const root = await mkdtemp(path.join(os.tmpdir(), 'motrix-package-verify-'))
+ temporaryRoots.push(root)
+ const source = path.join(root, 'source')
+ const appDir = path.join(
+ root,
+ target.platform === 'darwin' ? 'Motrix.app' : 'motrix'
+ )
+ const resources = path.join(
+ appDir,
+ ...(target.platform === 'darwin'
+ ? ['Contents', 'Resources']
+ : ['resources'])
+ )
+ const reportPath = path.join(root, 'report.json')
+ await mkdir(source, { recursive: true })
+ await mkdir(resources, { recursive: true })
+
+ const buildOutputs = []
+ for (const relativePath of OUTPUTS) {
+ const content = Buffer.from(relativePath)
+ await write(source, relativePath, content)
+ buildOutputs.push({
+ path: relativePath,
+ bytes: content.length,
+ sha256: hash(content),
+ })
+ }
+ await writeJson(source, 'package.json', {
+ name: 'motrix-fixture',
+ version: '1.2.3',
+ main: 'dist/main/index.cjs',
+ })
+ await writeJson(source, 'node_modules/better-sqlite3/package.json', {
+ name: 'better-sqlite3',
+ version: '1.0.0',
+ main: 'lib/index.js',
+ })
+ await write(source, 'node_modules/better-sqlite3/LICENSE', 'license')
+ await write(
+ source,
+ 'node_modules/better-sqlite3/lib/index.js',
+ 'module.exports = {}'
+ )
+ await write(
+ source,
+ `node_modules/better-sqlite3/prebuilds/${target.platform}-${target.arch}.node`,
+ nativeHeader(target)
+ )
+ await writeJson(source, 'node_modules/fixture-dep/package.json', {
+ name: 'fixture-dep',
+ version: '2.0.0',
+ exports: {
+ '.': './index.js',
+ './subpath': './subpath.js',
+ },
+ })
+ await write(
+ source,
+ 'node_modules/fixture-dep/index.js',
+ 'export default true'
+ )
+ await write(
+ source,
+ 'node_modules/fixture-dep/subpath.js',
+ 'export default true'
+ )
+
+ const packages = [
+ {
+ destination: 'node_modules/better-sqlite3',
+ name: 'better-sqlite3',
+ version: '1.0.0',
+ },
+ {
+ destination: 'node_modules/fixture-dep',
+ name: 'fixture-dep',
+ version: '2.0.0',
+ },
+ ]
+ const resvg = Buffer.from('fixture-resvg-wasm')
+ if (target.platform === 'darwin') {
+ await writeJson(source, 'node_modules/@resvg/resvg-wasm/package.json', {
+ name: '@resvg/resvg-wasm',
+ version: '3.0.0',
+ main: 'index.js',
+ })
+ await write(
+ source,
+ 'node_modules/@resvg/resvg-wasm/index.js',
+ 'export const ok = true'
+ )
+ packages.push({
+ destination: 'node_modules/@resvg/resvg-wasm',
+ name: '@resvg/resvg-wasm',
+ version: '3.0.0',
+ })
+ await write(resources, 'extra/tray/resvg.wasm', resvg)
+ }
+ packages.sort((left, right) =>
+ left.destination.localeCompare(right.destination)
+ )
+ const stage = {
+ schemaVersion: 1,
+ target: { ...target, key: `${target.platform}-${target.arch}` },
+ rootVersion: '1.2.3',
+ buildOutputs,
+ externals: ['better-sqlite3', 'fixture-dep/subpath'],
+ inventory: { files: 10, bytes: 100 },
+ optionalOmissions: [],
+ packages,
+ ...(target.platform === 'darwin' ? { resvgWasmSha256: hash(resvg) } : {}),
+ }
+ await writeJson(source, '.motrix-package-stage.json', stage)
+
+ const executable = nativeHeader(target)
+ const hostName =
+ target.platform === 'win32'
+ ? 'motrix-native-host.exe'
+ : 'motrix-native-host'
+ const engineName = target.platform === 'win32' ? 'aria2c.exe' : 'aria2c'
+ const host = await write(resources, `bin/${hostName}`, executable)
+ const engine = await write(
+ resources,
+ `extra/${target.platform}/${target.arch}/${engineName}`,
+ executable
+ )
+ await chmod(host, 0o755)
+ await chmod(engine, 0o755)
+ for (const relativePath of LEGAL)
+ await write(resources, relativePath, relativePath)
+ await writeJson(
+ resources,
+ 'builtin-plugins/motrix.fixture/motrix-plugin.json',
+ { id: 'motrix.fixture' }
+ )
+ await write(
+ resources,
+ 'builtin-plugins/motrix.fixture/dist/plugin.js',
+ 'export default true'
+ )
+ if (target.platform === 'darwin') {
+ await write(
+ appDir,
+ 'Contents/Frameworks/Electron Framework.framework/Versions/A/Resources/en.lproj/locale.pak',
+ 'locale'
+ )
+ } else {
+ await write(appDir, 'locales/en-US.pak', 'locale')
+ }
+
+ const fixture: Fixture = {
+ ...target,
+ root,
+ source,
+ appDir,
+ resources,
+ reportPath,
+ stage,
+ }
+ await mutate?.(fixture)
+ await createPackageWithOptions(source, path.join(resources, 'app.asar'), {
+ dot: true,
+ unpackDir: 'dist/renderer',
+ })
+ return fixture
+}
+
+async function verify(
+ fixture: Fixture,
+ budgets = LARGE_BUDGETS,
+ reportPath = fixture.reportPath
+) {
+ return verifyElectronPackage({
+ appDir: fixture.appDir,
+ platform: fixture.platform,
+ arch: fixture.arch,
+ budgets,
+ reportPath,
+ })
+}
+
+function failedCheck(report: Awaited<ReturnType<typeof verify>>, id: string) {
+ return report.checks.find((entry: { id: string }) => entry.id === id)
+}
+
+describe('post-package Electron verification', () => {
+ it('normalizes Windows ASAR listings to portable archive paths', () => {
+ expect(
+ normalizeArchiveEntry(
+ '\\node_modules\\better-sqlite3\\prebuilds\\win32-x64.node'
+ )
+ ).toBe('node_modules/better-sqlite3/prebuilds/win32-x64.node')
+ })
+
+ it('accepts a target-matched ASAR, stage, dependencies, and resources', async () => {
+ const fixture = await createFixture()
+ const report = await verify(fixture)
+
+ expect(report.passed).toBe(true)
+ expect(report.target.key).toBe('darwin-arm64')
+ expect(report.packages.records).toEqual(report.inputStage?.packages)
+ expect(report.metrics).toMatchObject({
+ unexpectedPackageNames: 0,
+ foreignBetterSqlite3Prebuilds: 0,
+ duplicateResvgWasmFiles: 0,
+ })
+ expect(report.externalResources.updateMetadata).toEqual([
+ {
+ path: 'app-update.yml',
+ present: false,
+ policy: 'directory-output',
+ },
+ ])
+ const asarInfo = await stat(path.join(fixture.resources, 'app.asar'))
+ const rendererInfo = await stat(
+ path.join(fixture.resources, 'app.asar.unpacked/dist/renderer/index.html')
+ )
+ expect(report.sizes.payloadBytes).toBe(asarInfo.size + rendererInfo.size)
+ })
+
+ it.each([
+ ['stage manifest', '.motrix-package-stage.json', 'stage-manifest'],
+ ['packaged manifest', 'package.json', 'stage-manifest'],
+ ['main', 'dist/main/index.cjs', 'required-build-outputs'],
+ ['preload', 'dist/preload/preload.cjs', 'required-build-outputs'],
+ [
+ 'worker',
+ 'dist/core/plugin/host/quick-js-worker.cjs',
+ 'required-build-outputs',
+ ],
+ ['renderer', 'dist/renderer/index.html', 'required-build-outputs'],
+ ])('rejects a package missing %s', async (_label, relativePath, checkId) => {
+ const fixture = await createFixture(undefined, async ({ source }) => {
+ await unlink(path.join(source, relativePath))
+ })
+ const report = await verify(fixture)
+ expect(report.passed).toBe(false)
+ expect(failedCheck(report, checkId)?.passed).toBe(false)
+ })
+
+ it('writes a failure report when app.asar is missing', async () => {
+ const fixture = await createFixture()
+ await unlink(path.join(fixture.resources, 'app.asar'))
+ const report = await verify(fixture)
+
+ expect(report.passed).toBe(false)
+ expect(failedCheck(report, 'asar-inventory')?.passed).toBe(false)
+ expect(JSON.parse(await readFile(fixture.reportPath, 'utf8')).passed).toBe(
+ false
+ )
+ })
+
+ it.each([
+ 'dist/server/index.js',
+ 'dist/renderer-web/index.html',
+ 'dist/builtin-plugins/mirror.js',
+ ])('rejects forbidden output %s', async (relativePath) => {
+ const fixture = await createFixture(undefined, async ({ source }) => {
+ await write(source, relativePath, 'forbidden')
+ })
+ const report = await verify(fixture)
+ expect(failedCheck(report, 'forbidden-dist-outputs')?.passed).toBe(false)
+ })
+
+ it('rejects unexpected, nested, mismatched, and unresolved packages', async () => {
+ const unexpected = await createFixture(undefined, async ({ source }) => {
+ await writeJson(source, 'node_modules/unexpected/package.json', {
+ name: 'unexpected',
+ version: '1.0.0',
+ })
+ })
+ const unexpectedReport = await verify(unexpected)
+ expect(failedCheck(unexpectedReport, 'package-inventory')?.passed).toBe(
+ false
+ )
+ expect(unexpectedReport.packages.unexpectedNames).toEqual(['unexpected'])
+
+ const nested = await createFixture(undefined, async ({ source }) => {
+ await writeJson(
+ source,
+ 'node_modules/fixture-dep/node_modules/nested/package.json',
+ { name: 'nested', version: '1.0.0' }
+ )
+ })
+ expect(failedCheck(await verify(nested), 'package-inventory')?.passed).toBe(
+ false
+ )
+
+ const version = await createFixture(undefined, async ({ source }) => {
+ await writeJson(source, 'node_modules/fixture-dep/package.json', {
+ name: 'fixture-dep',
+ version: '9.0.0',
+ exports: { '.': './index.js', './subpath': './subpath.js' },
+ })
+ })
+ expect(
+ failedCheck(await verify(version), 'package-inventory')?.passed
+ ).toBe(false)
+
+ const unresolved = await createFixture(undefined, async (fixture) => {
+ ;(fixture.stage.externals as string[]) = ['fixture-dep/missing']
+ await writeJson(
+ fixture.source,
+ '.motrix-package-stage.json',
+ fixture.stage
+ )
+ })
+ expect(
+ failedCheck(await verify(unresolved), 'static-externals')?.passed
+ ).toBe(false)
+ })
+
+ it.each([
+ [
+ 'zero prebuilds',
+ async (fixture: Fixture) =>
+ unlink(
+ path.join(
+ fixture.source,
+ 'node_modules/better-sqlite3/prebuilds/darwin-arm64.node'
+ )
+ ),
+ ],
+ [
+ 'multiple prebuilds',
+ async (fixture: Fixture) =>
+ write(
+ fixture.source,
+ 'node_modules/better-sqlite3/prebuilds/darwin-x64.node',
+ nativeHeader({ platform: 'darwin', arch: 'x64' })
+ ),
+ ],
+ [
+ 'malformed prebuild',
+ async (fixture: Fixture) =>
+ write(
+ fixture.source,
+ 'node_modules/better-sqlite3/prebuilds/darwin-arm64.node',
+ 'not-native'
+ ),
+ ],
+ [
+ 'source leakage',
+ async (fixture: Fixture) =>
+ write(
+ fixture.source,
+ 'node_modules/better-sqlite3/src/leak.cc',
+ 'source'
+ ),
+ ],
+ ])('rejects better-sqlite3 with %s', async (_label, mutate) => {
+ const fixture = await createFixture(undefined, mutate)
+ const report = await verify(fixture)
+ expect(failedCheck(report, 'better-sqlite3-layout')?.passed).toBe(false)
+ })
+
+ it('enforces resvg placement and hash only on macOS', async () => {
+ const duplicate = await createFixture(undefined, async ({ source }) => {
+ await write(
+ source,
+ 'node_modules/@resvg/resvg-wasm/index_bg.wasm',
+ 'duplicate'
+ )
+ })
+ expect(
+ failedCheck(await verify(duplicate), 'resvg-wasm-placement')?.passed
+ ).toBe(false)
+
+ const missing = await createFixture(undefined, async ({ resources }) => {
+ await unlink(path.join(resources, 'extra/tray/resvg.wasm'))
+ })
+ expect(
+ failedCheck(await verify(missing), 'resvg-wasm-placement')?.passed
+ ).toBe(false)
+
+ const mismatch = await createFixture(undefined, async ({ resources }) => {
+ await write(resources, 'extra/tray/resvg.wasm', 'wrong-hash')
+ })
+ expect(
+ failedCheck(await verify(mismatch), 'resvg-wasm-placement')?.passed
+ ).toBe(false)
+
+ const linux = await createFixture({ platform: 'linux', arch: 'arm64' })
+ expect((await verify(linux)).passed).toBe(true)
+ })
+
+ it('accepts Windows PE binaries and resources', async () => {
+ const windows = await createFixture({ platform: 'win32', arch: 'x64' })
+ expect((await verify(windows)).passed).toBe(true)
+ })
+
+ it.each([
+ 'extra/darwin/arm64/aria2c',
+ 'bin/motrix-native-host',
+ 'builtin-plugins/motrix.fixture/motrix-plugin.json',
+ 'THIRD_PARTY_NOTICES.md',
+ ])('rejects a missing external resource %s', async (relativePath) => {
+ const fixture = await createFixture(undefined, async ({ resources }) => {
+ await unlink(path.join(resources, relativePath))
+ })
+ const report = await verify(fixture)
+ const checkId = relativePath.startsWith('builtin-plugins')
+ ? 'builtin-plugins'
+ : 'external-resources'
+ expect(failedCheck(report, checkId)?.passed).toBe(false)
+ })
+
+ it('validates optional directory update metadata when present', async () => {
+ const fixture = await createFixture(undefined, async ({ resources }) => {
+ await write(resources, 'app-update.yml', '')
+ })
+ expect(
+ failedCheck(await verify(fixture), 'update-metadata-policy')?.passed
+ ).toBe(false)
+ })
+
+ it('enforces the payload budget at the exact byte boundary', async () => {
+ const fixture = await createFixture()
+ const initial = await verify(fixture)
+ const exact = {
+ ...LARGE_BUDGETS,
+ payloadBytes: initial.sizes.payloadBytes,
+ }
+ expect((await verify(fixture, exact)).passed).toBe(true)
+
+ const over = await verify(fixture, {
+ ...exact,
+ payloadBytes: exact.payloadBytes - 1,
+ })
+ expect(failedCheck(over, 'budget-payloadBytes')?.passed).toBe(false)
+ })
+
+ it('keeps locale variation outside optimizer pass/fail metrics', async () => {
+ const small = await createFixture()
+ const large = await createFixture(undefined, async ({ appDir }) => {
+ await write(
+ appDir,
+ 'Contents/Frameworks/Electron Framework.framework/Versions/A/Resources/zh_CN.lproj/locale.pak',
+ Buffer.alloc(4096)
+ )
+ })
+ const smallReport = await verify(small)
+ const largeReport = await verify(large)
+
+ expect(smallReport.passed).toBe(true)
+ expect(largeReport.passed).toBe(true)
+ expect(largeReport.metrics).toEqual(smallReport.metrics)
+ expect(largeReport.sizes.localeBytes).toBeGreaterThan(
+ smallReport.sizes.localeBytes
+ )
+ })
+
+ it('writes deterministic sanitized pass and fail reports', async () => {
+ const fixture = await createFixture()
+ const passPath = path.join(fixture.root, 'pass.json')
+ const failPath = path.join(fixture.root, 'fail.json')
+ const secret = 'motrix-fixture-environment-secret'
+ process.env.MOTRIX_TEST_PACKAGE_SECRET = secret
+ try {
+ await verify(fixture, LARGE_BUDGETS, passPath)
+ await verify(fixture, { ...LARGE_BUDGETS, payloadBytes: 0 }, failPath)
+ } finally {
+ delete process.env.MOTRIX_TEST_PACKAGE_SECRET
+ }
+ const pass = await readFile(passPath, 'utf8')
+ const fail = await readFile(failPath, 'utf8')
+
+ for (const content of [pass, fail]) {
+ expect(content).not.toContain(fixture.root)
+ expect(content).not.toContain(os.homedir())
+ expect(content).not.toContain(secret)
+ }
+ const parsed = JSON.parse(pass)
+ expect(parsed.packages.names).toEqual([...parsed.packages.names].sort())
+ expect(parsed.nativeBinaries).toEqual(
+ [...parsed.nativeBinaries].sort((left, right) =>
+ left.path.localeCompare(right.path)
+ )
+ )
+ expect((await stat(failPath)).isFile()).toBe(true)
+ })
+})
diff --git a/tests/scripts/workflow-release-matrix.test.ts b/tests/scripts/workflow-release-matrix.test.ts
index 759cd2d3..f215fe58 100644
--- a/tests/scripts/workflow-release-matrix.test.ts
+++ b/tests/scripts/workflow-release-matrix.test.ts
@@ -131,6 +131,13 @@ const EXPECTED_TARGETS: ExpectedTarget[] = [
rustTarget: 'x86_64-pc-windows-msvc',
},
]
+const EXPECTED_APP_PATHS = new Map([
+ ['darwin-arm64', 'release/mac-arm64/Motrix.app'],
+ ['darwin-x64', 'release/mac/Motrix.app'],
+ ['linux-arm64', 'release/linux-arm64-unpacked'],
+ ['linux-x64', 'release/linux-unpacked'],
+ ['win32-x64', 'release/win-unpacked'],
+])
const ciSource = readFileSync(
path.join(ROOT, '.github/workflows/ci.yml'),
@@ -216,6 +223,88 @@ describe('CI and release target matrix contract', () => {
}
})
+ it.each([
+ ['CI', ciWorkflow],
+ ['release', releaseWorkflow],
+ ] as const)(
+ '%s stages and verifies every Electron target before artifacts leave the job',
+ (label, workflow) => {
+ const { entries, job } = targetMatrix(workflow)
+ const steps = jobSteps(job)
+ const buildIndex = steps.findIndex((step) =>
+ stringField(step, 'run', '').includes('build:electron')
+ )
+ const stageIndex = steps.findIndex((step) =>
+ stringField(step, 'run', '').includes('stage:electron')
+ )
+ const builderIndices = steps
+ .map((step, index) =>
+ stringField(step, 'run', '').includes('electron-builder') ? index : -1
+ )
+ .filter((index) => index >= 0)
+ const verifierIndex = steps.findIndex((step) =>
+ stringField(step, 'run', '').includes('verify-electron-package.mjs')
+ )
+ const resourceIndex = steps.findIndex(
+ (step) => step.name === 'Verify packaged resources'
+ )
+
+ expect(buildIndex).toBeGreaterThanOrEqual(0)
+ expect(stageIndex).toBeGreaterThanOrEqual(buildIndex)
+ expect(builderIndices.length).toBeGreaterThan(0)
+ for (const builderIndex of builderIndices) {
+ expect(builderIndex).toBeGreaterThan(stageIndex)
+ expect(
+ stringField(steps[builderIndex] as LooseRecord, 'run')
+ ).toContain('--publish never')
+ }
+ expect(verifierIndex).toBeGreaterThan(Math.max(...builderIndices))
+ expect(resourceIndex).toBeGreaterThan(verifierIndex)
+
+ const buildCommand = stringField(steps[buildIndex] as LooseRecord, 'run')
+ const stageCommand = stringField(steps[stageIndex] as LooseRecord, 'run')
+ expect(stageCommand).toContain(`\${{ matrix.platform }}`)
+ expect(stageCommand).toContain(`\${{ matrix.arch }}`)
+ if (buildIndex === stageIndex) {
+ expect(stageCommand.indexOf('stage:electron')).toBeGreaterThan(
+ buildCommand.indexOf('build:electron')
+ )
+ }
+
+ const verifier = stringField(steps[verifierIndex] as LooseRecord, 'run')
+ expect(verifier).toContain(`--app-dir "\${{ matrix.app_path }}"`)
+ expect(verifier).toContain(`--platform \${{ matrix.platform }}`)
+ expect(verifier).toContain(`--arch \${{ matrix.arch }}`)
+ expect(verifier).toContain(
+ `--report "release/size-reports/\${{ matrix.target }}.json"`
+ )
+
+ for (const entry of entries) {
+ const key = `${stringField(entry, 'platform')}-${stringField(
+ entry,
+ 'arch'
+ )}`
+ expect(stringField(entry, 'app_path'), `${label} ${key}`).toBe(
+ EXPECTED_APP_PATHS.get(key)
+ )
+ }
+
+ const upload = steps.find((step) =>
+ label === 'CI'
+ ? step.name === 'Upload Electron size report'
+ : step.name === 'Upload target release input'
+ )
+ const uploadInputs = asRecord(upload?.with, `${label} report upload`)
+ expect(stringField(uploadInputs, 'path')).toContain(
+ `release/size-reports/\${{ matrix.target }}.json`
+ )
+ expect(stringField(uploadInputs, 'if-no-files-found')).toBe('error')
+ expect(steps.indexOf(upload as LooseRecord)).toBeGreaterThan(
+ verifierIndex
+ )
+ }
+ )
+
it('keeps the release assembler on the same target set', () => {
expect(
RELEASE_TARGETS.map((target: { name: string }) => target.name).sort()
@@ -340,6 +429,14 @@ describe('general CI native-host split contract', () => {
expect(contractCommand).toContain(
'tests/scripts/flatpak-native-host.test.ts'
)
+ for (const test of [
+ 'tests/scripts/electron-package-contract.test.ts',
+ 'tests/scripts/native-binary-target.test.ts',
+ 'tests/scripts/stage-electron-app.test.ts',
+ 'tests/scripts/verify-electron-package.test.ts',
+ ]) {
+ expect(contractCommand).toContain(test)
+ }
})
it('compiles every declared native-host binary on host and target runners', () => {
diff --git a/tests/scripts/workflow-snap.test.ts b/tests/scripts/workflow-snap.test.ts
index 21d648ce..b147e115 100644
--- a/tests/scripts/workflow-snap.test.ts
+++ b/tests/scripts/workflow-snap.test.ts
@@ -74,16 +74,53 @@ describe('Snap build workflow contract', () => {
it('builds an unpacked app and never lets electron-builder publish', () => {
const steps = jobSteps(workflowJob(snapWorkflow, 'build'))
+ const stage = steps.find((step) =>
+ stringField(step, 'run', '').includes('stage:electron')
+ )
const builder = steps.find((step) =>
stringField(step, 'run', '').includes('electron-builder')
)
+ const verifier = steps.find((step) =>
+ stringField(step, 'run', '').includes('verify-electron-package.mjs')
+ )
+ const prepare = steps.find(
+ (step) => step.name === 'Prepare isolated Snapcraft project'
+ )
+ expect(stage).toBeDefined()
expect(builder).toBeDefined()
+ expect(verifier).toBeDefined()
const command = stringField(builder as LooseRecord, 'run')
expect(command).toContain('--linux')
expect(command).toContain('--dir')
expect(command).toContain(`--\${{ matrix.electron_arch }}`)
expect(command).toContain('--publish never')
+ const stageCommand = stringField(stage as LooseRecord, 'run')
+ expect(stageCommand).toContain('--platform linux')
+ expect(stageCommand).toContain(`--arch \${{ matrix.electron_arch }}`)
+ const verifyCommand = stringField(verifier as LooseRecord, 'run')
+ expect(verifyCommand).toContain(`--app-dir "\${{ matrix.app_dir }}"`)
+ expect(verifyCommand).toContain('--platform linux')
+ expect(verifyCommand).toContain(`--arch \${{ matrix.electron_arch }}`)
+ expect(verifyCommand).toContain(
+ `--report "release/size-reports/linux-\${{ matrix.electron_arch }}.json"`
+ )
+ expect(steps.indexOf(stage as LooseRecord)).toBeLessThan(
+ steps.indexOf(builder as LooseRecord)
+ )
+ expect(steps.indexOf(builder as LooseRecord)).toBeLessThan(
+ steps.indexOf(verifier as LooseRecord)
+ )
+ expect(steps.indexOf(verifier as LooseRecord)).toBeLessThan(
+ steps.indexOf(prepare as LooseRecord)
+ )
+
+ const upload = steps.find((step) => step.name === 'Upload verified Snap')
+ const uploadInputs = asRecord(upload?.with, 'Snap upload inputs')
+ expect(stringField(uploadInputs, 'path')).toContain(
+ `release/size-reports/linux-\${{ matrix.electron_arch }}.json`
+ )
+ expect(stringField(uploadInputs, 'if-no-files-found')).toBe('error')
const snapcraft = steps.find((step) =>
stringField(step, 'uses', '').startsWith('snapcore/action-build@')