Skip to content

Build your personal knowledge base with Trilium Notes

12.6 KB
Raw Blame
import type { ForgeConfig } from "@electron-forge/shared-types";
import { FuseV1Options } from "@electron/fuses";
import { FUSES } from "./flip-fuses.js";
import { trimElectronLocales } from "./trim-locales.js";
import { copyFileSync, existsSync, mkdirSync, readFileSync, renameSync } from "fs";
import path, { join } from "path";

import packageJson from "../package.json" with { type: "json" };
import { PRODUCT_NAME } from "../src/app-info.js";

const ELECTRON_FORGE_DIR = __dirname;

const EXECUTABLE_NAME = "trilium"; // keep in sync with server's package.json -> packagerConfig.executableName
const APP_ICON_PATH = path.join(ELECTRON_FORGE_DIR, "app-icon");

const extraResourcesForPlatform = getExtraResourcesForPlatform();
const baseLinuxMakerConfigOptions = {
    name: EXECUTABLE_NAME,
    bin: EXECUTABLE_NAME,
    productName: PRODUCT_NAME,
    icon: path.join(APP_ICON_PATH, "png/128x128.png"),
    desktopTemplate: path.resolve(path.join(ELECTRON_FORGE_DIR, "desktop.ejs")),
    categories: ["Office", "Utility"]
};
const windowsSignConfiguration = process.env.WINDOWS_SIGN_EXECUTABLE ? {
    hookModulePath: path.join(ELECTRON_FORGE_DIR, "sign-windows.cjs")
} : undefined;
const macosSignConfiguration = process.env.APPLE_ID ? {
    osxSign: {},
    osxNotarize: {
        appleId: process.env.APPLE_ID!,
        appleIdPassword: process.env.APPLE_ID_PASSWORD!,
        teamId: process.env.APPLE_TEAM_ID!
    }
} : undefined;
const isNightly = packageJson.version.includes("test");

const config: ForgeConfig = {
    outDir: "out",
    // Documentation of `packagerConfig` options: https://electron.github.io/packager/main/interfaces/Options.html
    packagerConfig: {
        executableName: EXECUTABLE_NAME,
        name: PRODUCT_NAME,
        appVersion: packageJson.version,
        overwrite: true,
        asar: {
            // The shared libraries beside sherpa-onnx's addon (onnxruntime) are loaded by the OS,
            // which cannot read them from inside the archive. auto-unpack-natives adds `*.node`.
            unpack: "**/node_modules/sherpa-onnx-*-*/**"
        },
        icon: path.join(APP_ICON_PATH, isNightly ? "icon-dev" : "icon"),
        ...macosSignConfiguration,
        windowsSign: windowsSignConfiguration,
        extraResource: [
            // All resources should stay in Resources directory for macOS
            ...(process.platform === "darwin" ? [] : extraResourcesForPlatform)
        ],
        prune: false,
        afterComplete: [
            ({ buildPath, platform }) => {
                // Only move resources on non-macOS platforms
                if (platform === "darwin") return;

                for (const resource of extraResourcesForPlatform) {
                    const baseName = path.basename(resource);
                    const sourcePath = path.join(buildPath, "resources", baseName);

                    // prettier-ignore
                    const destPath = (baseName !== "256x256.png")
                        ? path.join(buildPath, baseName)
                        : path.join(buildPath, "icon.png");

                    renameSync(sourcePath, destPath);
                }
            }
        ]
    },
    makers: [
        {
            name: "@electron-forge/maker-deb",
            config: {
                options: baseLinuxMakerConfigOptions
            }
        },
        {
            name: "@electron-forge/maker-flatpak",
            config: {
                options: {
                    ...baseLinuxMakerConfigOptions,
                    icon: {
                        "128x128": path.join(APP_ICON_PATH, isNightly ? "png/128x128-dev.png" : "png/128x128.png"),
                    },
                    id: "com.triliumnext.notes",
                    runtimeVersion: "24.08",
                    base: "org.electronjs.Electron2.BaseApp",
                    baseVersion: "24.08",
                    baseFlatpakref: "https://flathub.org/repo/flathub.flatpakrepo",
                    finishArgs: [
                        // Wayland/X11 Rendering
                        "--socket=fallback-x11",
                        "--socket=wayland",
                        "--share=ipc",
                        // Open GL
                        "--device=dri",
                        // Audio output
                        "--socket=pulseaudio",
                        // Read/write home directory access
                        "--filesystem=home",
                        // Allow communication with network
                        "--share=network",
                        // System notifications with libnotify
                        "--talk-name=org.freedesktop.Notifications",
                        // System tray
                        "--talk-name=org.kde.StatusNotifierWatcher"
                    ],
                    modules: [
                        {
                            name: "zypak",
                            sources: {
                                type: "git",
                                url: "https://github.com/refi64/zypak",
                                tag: "v2024.01.17"
                            }
                        }
                    ]
                },
            }
        },
        {
            name: "@electron-forge/maker-rpm",
            config: {
                options: baseLinuxMakerConfigOptions
            }
        },
        {
            name: "@electron-forge/maker-squirrel",
            config: {
                name: EXECUTABLE_NAME,
                productName: PRODUCT_NAME,
                iconUrl: `https://raw.githubusercontent.com/TriliumNext/Trilium/refs/heads/main/apps/desktop/electron-forge/app-icon/${isNightly ? "icon-dev" : "icon"}.ico`,
                setupIcon: path.join(ELECTRON_FORGE_DIR, isNightly ? "setup-icon/setup-dev.ico" : "setup-icon/setup.ico"),
                loadingGif: path.join(ELECTRON_FORGE_DIR, isNightly ? "setup-icon/setup-banner-dev.gif" : "setup-icon/setup-banner.gif"),
                windowsSign: windowsSignConfiguration
            }
        },
        {
            name: "@electron-forge/maker-dmg",
            config: {
                // Volume icon of the MOUNTED image (Finder sidebar, desktop mount, DMG
                // title bar) — a drive body carrying the mark, NOT the app icon, so the
                // installer reads as media rather than a second copy of the app.
                // Generated from dmg-icon/volume-icon.html; see that folder's README.
                icon: path.join(ELECTRON_FORGE_DIR, "dmg-icon",
                    isNightly ? "volume-dev.icns" : "volume.icns"),
                // Branded Finder-window background (generated from dmg-background/background.html).
                // appdmg auto-uses the sibling [email protected] for Retina.
                background: path.join(ELECTRON_FORGE_DIR, "dmg-background", isNightly ? "background-dev.png" : "background.png"),
                iconSize: 128,
                additionalDMGOptions: {
                    window: { size: { width: 640, height: 400 } }
                },
                // Icon CENTERS in Finder's .DS_Store Iloc coordinate space: top-left origin,
                // y increasing downward. y=182 centers the icon + its caption pair vertically in
                // the window (there is no baked banner above them). Verify on a macOS build
                // (appdmg is darwin-only).
                contents: (opts: { appPath: string }) => [
                    { x: 180, y: 182, type: "file", path: opts.appPath },
                    { x: 460, y: 182, type: "link", path: "/Applications" }
                ]
            }
        },
        {
            name: "@electron-forge/maker-zip",
            config: {
                options: {
                    iconUrl: `https://raw.githubusercontent.com/TriliumNext/Trilium/refs/heads/main/apps/desktop/electron-forge/app-icon/${isNightly ? "icon-dev" : "icon"}.ico`,
                    icon: path.join(APP_ICON_PATH, isNightly ? "icon-dev.ico" : "icon.ico")
                }
            }
        }
    ],
    plugins: [
        {
            name: "@electron-forge/plugin-auto-unpack-natives",
            config: {}
        },
        {
            name: "@electron-forge/plugin-fuses",
            config: {
                ...FUSES,
                // The forge builds package the app into an asar archive; the Flathub build has none.
                [FuseV1Options.OnlyLoadAppFromAsar]: true,
                [FuseV1Options.EnableEmbeddedAsarIntegrityValidation]: true
            }
        }
    ],
    hooks: {
        // Remove unused locales from the packaged app to save some space.
        async postPackage(_, packageResult) {
            const isMac = (process.platform === "darwin");
            const localeDirs = packageResult.outputPaths.flatMap((outputPath) => isMac
                ? [
                    path.join(outputPath, `${PRODUCT_NAME}.app/Contents/Resources`),
                    path.join(outputPath, `${PRODUCT_NAME}.app/Contents/Frameworks/Electron Framework.framework/Resources`)
                ]
                : [ path.join(outputPath, 'locales') ]);

            const { removed } = trimElectronLocales(localeDirs, isMac);
            console.log(`Removed unused locale files: ${removed.join(", ")}`);

            // Check that the bettersqlite3 binary has the right architecture.
            // Since v13, better-sqlite3 ships N-API prebuilds and the Electron
            // native rebuild was dropped, so no build/Release/ addon is ever
            // produced. The loadable binary is the shipped prebuild, which
            // auto-unpack-natives extracts to app.asar.unpacked/.../prebuilds/.
            if (packageResult.platform === "linux" && packageResult.arch === "arm64") {
                for (const outputPath of packageResult.outputPaths) {
                    const binaryPath = join(outputPath, "resources/app.asar.unpacked/node_modules/better-sqlite3/prebuilds/linux-arm64.node");
                    if (!existsSync(binaryPath)) {
                        throw new Error(`[better-sqlite3] Unable to find .node file at ${binaryPath}`);
                    }

                    const actualArch = getELFArch(binaryPath);
                    if (actualArch !== "ARM64") {
                        throw new Error(`[better-sqlite3] Expected ARM64 architecture but got ${actualArch} at: ${binaryPath}`);
                    }
                }
            }
        },
        // Gather all the artifacts produced by the makers and copy them to a common upload directory.
        async postMake(_, makeResults) {
            const outputDir = path.join(__dirname, "..", "upload");
            mkdirSync(outputDir, { recursive: true });
            for (const makeResult of makeResults) {
                for (const artifactPath of makeResult.artifacts) {
                    // Ignore certain artifacts.
                    let fileName = path.basename(artifactPath);
                    const extension = path.extname(fileName);
                    if (fileName === "RELEASES" || extension === ".nupkg") {
                        continue;
                    }

                    // Override the extension for the CI.
                    const { TRILIUM_ARTIFACT_NAME_HINT } = process.env;
                    if (TRILIUM_ARTIFACT_NAME_HINT) {
                        fileName = TRILIUM_ARTIFACT_NAME_HINT.replaceAll("/", "-") + extension;
                    }

                    const outputPath = path.join(outputDir, fileName);
                    console.log(`[Artifact] ${artifactPath} -> ${outputPath}`);
                    copyFileSync(artifactPath, outputPath);
                }
            }
        }
    }
};

function getExtraResourcesForPlatform() {
    const resources: string[] = [];

    const getScriptResources = () => {
        const scripts = ["trilium-portable", "trilium-safe-mode", "trilium-no-cert-check"];
        const scriptExt = (process.platform === "win32") ? "bat" : "sh";
        return scripts.map(script => `electron-forge/${script}.${scriptExt}`);
    };

    switch (process.platform) {
        case "win32":
            resources.push(...getScriptResources());
            break;
        case "linux":
            resources.push(...getScriptResources(), path.join(APP_ICON_PATH, "png/256x256.png"));
            break;
        default:
            break;
    }

    return resources;
}

function getELFArch(file: string) {
    const buf = readFileSync(file);

    if (buf[0] !== 0x7f || buf[1] !== 0x45 || buf[2] !== 0x4c || buf[3] !== 0x46) {
        throw new Error("Not an ELF file");
    }

    const eiClass = buf[4];      // 1=32-bit, 2=64-bit
    const eiMachine = buf[18];   // architecture code

    if (eiMachine === 0x3E) return 'x86-64';
    if (eiMachine === 0xB7) return 'ARM64';
    return 'other';
}


export default config;