Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
refactor(flatpak): share the Electron locale trim with the forge hook
Elian Doran0884f3d540d4
diff --git a/apps/desktop/electron-forge/forge.config.ts b/apps/desktop/electron-forge/forge.config.tsindex d1fd5a8421..94feb2044d 100644--- a/apps/desktop/electron-forge/forge.config.ts+++ b/apps/desktop/electron-forge/forge.config.ts@@ -1,7 +1,7 @@import type { ForgeConfig } from "@electron-forge/shared-types";import { FuseV1Options, FuseVersion } from "@electron/fuses";-import { LOCALES } from "@triliumnext/commons";-import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, unlinkSync } from "fs";+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" };@@ -204,70 +204,15 @@ const config: ForgeConfig = {// Remove unused locales from the packaged app to save some space.async postPackage(_, packageResult) {const isMac = (process.platform === "darwin");- let localesToKeep = LOCALES- .filter(locale => !locale.contentOnly)- .map(locale => locale.electronLocale) as string[];- if (!isMac) {- localesToKeep = localesToKeep.map(locale => locale.replace("_", "-"));- }-- const keptLocales = new Set();- const removedLocales: string[] = [];- const extension = (isMac ? ".lproj" : ".pak");-- for (const outputPath of packageResult.outputPaths) {- const localeDirs = 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') ];-- for (const localeDir of localeDirs) {- if (!existsSync(localeDir)) {- console.log(`No locales directory found in '${localeDir}'.`);- process.exit(2);- }-- const files = readdirSync(localeDir);-- for (const file of files) {- if (!file.endsWith(extension)) {- continue;- }-- let localeName = path.basename(file, extension);- if (localeName === "en-US" && !isMac) {- // If the locale is "en-US" on Windows, we treat it as "en".- // This is because the Windows version of Electron uses "en-US.pak" instead of "en.pak".- localeName = "en";- }-- if (localesToKeep.includes(localeName)) {- keptLocales.add(localeName);- continue;- }-- const filePath = path.join(localeDir, file);- if (isMac) {- rmSync(filePath, { recursive: true });- } else {- unlinkSync(filePath);- }-- removedLocales.push(file);- }- }- }-- console.log(`Removed unused locale files: ${removedLocales.join(", ")}`);+ 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') ]);- // Ensure all locales that should be kept are actually present.- for (const locale of localesToKeep) {- if (!keptLocales.has(locale)) {- throw new Error(`Locale ${locale} was not found in the packaged app.`);- }- }+ 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 Electrondiff --git a/apps/desktop/electron-forge/trim-locales.spec.ts b/apps/desktop/electron-forge/trim-locales.spec.tsnew file mode 100644index 0000000000..65c696f2f6--- /dev/null+++ b/apps/desktop/electron-forge/trim-locales.spec.ts@@ -0,0 +1,80 @@+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { afterEach, describe, expect, it } from "vitest";++import { trimElectronLocales } from "./trim-locales.js";++// The locale files Electron 44 ships on Linux and Windows.+const ELECTRON_PAKS = [+ "af", "am", "ar", "bg", "bn", "ca", "cs", "da", "de", "el", "en-GB", "en-US",+ "es", "es-419", "et", "fa", "fi", "fil", "fr", "gu", "he", "hi", "hr", "hu",+ "id", "it", "ja", "kn", "ko", "lt", "lv", "ml", "mr", "ms", "nb", "nl", "pl",+ "pt-BR", "pt-PT", "ro", "ru", "sk", "sl", "sr", "sv", "sw", "ta", "te", "th",+ "tr", "uk", "ur", "vi", "zh-CN", "zh-TW"+];++const tempDirs: string[] = [];++function makeLocaleDir(entries: string[], asDirectories = false): string {+ const dir = mkdtempSync(join(tmpdir(), "trim-locales-"));+ tempDirs.push(dir);+ for (const entry of entries) {+ if (asDirectories) {+ mkdirSync(join(dir, entry));+ writeFileSync(join(dir, entry, "locale.strings"), "");+ } else {+ writeFileSync(join(dir, entry), "");+ }+ }+ return dir;+}++afterEach(() => {+ for (const dir of tempDirs.splice(0)) {+ rmSync(dir, { recursive: true, force: true });+ }+});++describe("trimElectronLocales", () => {+ it("keeps exactly the exposed locales, resolving en-US.pak to the \"en\" entry", () => {+ const dir = makeLocaleDir(ELECTRON_PAKS.map((l) => `${l}.pak`));++ const { kept, removed } = trimElectronLocales([ dir ], false);++ expect(kept.size).toBe(21);+ expect(removed).toHaveLength(34);+ expect(existsSync(join(dir, "en-US.pak"))).toBe(true);+ expect(existsSync(join(dir, "zh-CN.pak"))).toBe(true);+ // Hebrew is content-only, so its Chromium locale goes.+ expect(existsSync(join(dir, "he.pak"))).toBe(false);+ });++ it("removes mac .lproj directories, keeping underscore names and ignoring other entries", () => {+ const resources = makeLocaleDir([ "zh_CN.lproj", "he.lproj" ], true);+ writeFileSync(join(resources, "icon.icns"), "");+ // Mac spreads locales over two directories; the keep check spans both.+ const frameworkResources = makeLocaleDir(+ [ "en.lproj", "de.lproj", "es.lproj", "fr.lproj", "zh_TW.lproj", "ro.lproj", "cs.lproj",+ "en_GB.lproj", "id.lproj", "it.lproj", "hi.lproj", "ja.lproj", "ko.lproj", "pt_BR.lproj",+ "pt_PT.lproj", "pl.lproj", "ru.lproj", "tr.lproj", "uk.lproj", "ar.lproj" ],+ true+ );++ const { kept, removed } = trimElectronLocales([ resources, frameworkResources ], true);++ expect(kept).toContain("zh_CN");+ expect(removed).toEqual([ "he.lproj" ]);+ expect(existsSync(join(resources, "he.lproj"))).toBe(false);+ expect(existsSync(join(resources, "icon.icns"))).toBe(true);+ });++ it("rejects a missing directory and a package missing a keep-list locale", () => {+ expect(() => trimElectronLocales([ "/nonexistent/locales" ], false))+ .toThrow(/No locales directory/);++ const incomplete = makeLocaleDir([ "en-US.pak", "de.pak" ]);+ expect(() => trimElectronLocales([ incomplete ], false)).toThrow(/was not found/);+ });+});diff --git a/apps/desktop/electron-forge/trim-locales.ts b/apps/desktop/electron-forge/trim-locales.tsnew file mode 100644index 0000000000..080c1bc2bf--- /dev/null+++ b/apps/desktop/electron-forge/trim-locales.ts@@ -0,0 +1,80 @@+/**+ * Trims the Chromium locale files a packaged Electron build carries (~38 MB)+ * down to the locales Trilium exposes. The electron-forge postPackage hook+ * calls it per package output; the Flathub build runs it as a script, with+ * tsx, on the locales directory of its unpacked Electron.+ */++import { existsSync, readdirSync, rmSync } from "node:fs";+import { basename, join } from "node:path";++import { LOCALES } from "@triliumnext/commons";++export function trimElectronLocales(localeDirs: string[], isMac: boolean) {+ const localesToKeep = getLocalesToKeep(isMac);+ // Mac locales are .lproj directories; the other platforms ship .pak files.+ const extension = isMac ? ".lproj" : ".pak";+ const kept = new Set<string>();+ const removed: string[] = [];++ for (const localeDir of localeDirs) {+ if (!existsSync(localeDir)) {+ throw new Error(`No locales directory found in '${localeDir}'.`);+ }++ for (const file of readdirSync(localeDir)) {+ if (!file.endsWith(extension)) {+ continue;+ }++ const localeName = normalizeLocaleName(basename(file, extension), isMac);+ if (localesToKeep.has(localeName)) {+ kept.add(localeName);+ } else {+ rmSync(join(localeDir, file), { recursive: true });+ removed.push(file);+ }+ }+ }++ // A keep-list locale absent from the package would ship a build silently+ // missing a UI language; fail the packaging instead.+ for (const locale of localesToKeep) {+ if (!kept.has(locale)) {+ throw new Error(`Locale ${locale} was not found in the packaged app.`);+ }+ }++ return { kept, removed };+}++/**+ * The locales to keep, as locale file base names — hyphenated (`zh-CN.pak`),+ * except on mac, which names its `.lproj` directories with underscores.+ */+function getLocalesToKeep(isMac: boolean): Set<string> {+ const names: string[] = [];+ for (const locale of LOCALES) {+ if (locale.contentOnly || !locale.electronLocale) {+ continue;+ }+ names.push(isMac ? locale.electronLocale : locale.electronLocale.replace("_", "-"));+ }+ return new Set(names);+}++/** Electron names the English locale file `en-US.pak` where {@link LOCALES} has "en"; mac names it `en.lproj` already. */+function normalizeLocaleName(name: string, isMac: boolean): string {+ return !isMac && name === "en-US" ? "en" : name;+}++// Only when run as a script — the Flathub build passes the locales directory+// of its unpacked, always-Linux Electron.+if (process.argv[1] === import.meta.filename) {+ const localesDir = process.argv[2];+ if (!localesDir) {+ throw new Error("Pass the locales directory to trim.");+ }+ const { kept, removed } = trimElectronLocales([ localesDir ], false);+ console.log(`Removed ${removed.length} locales, kept ${kept.size}.`);+}diff --git a/apps/desktop/vitest.config.mts b/apps/desktop/vitest.config.mtsindex 663b56bf8f..627b2b9fde 100644--- a/apps/desktop/vitest.config.mts+++ b/apps/desktop/vitest.config.mts@@ -26,7 +26,7 @@ export default defineConfig(() => ({// mock value is still what the code receives, so the value is never used.ELECTRON_OVERRIDE_DIST_PATH: "/nonexistent/electron-dist-test-override"},- include: ["src/**/*.spec.ts"],+ include: ["src/**/*.spec.ts", "electron-forge/**/*.spec.ts"],reporters: ["verbose",["junit", { outputFile: "./test-output/vitest/junit.xml", addFileAttribute: true }]