// `mollusc build`: stage what the installer needs, then let electron-builder // pack it. The asar holds only the shell; the app's own files and production // dependencies ship unpacked under Resources/mollusc-app, where the sidecar // runs them as plain files. Output goes to /dist (or `build.output`), and // the stage lives in /.mollusc/stage. import { execFile, spawn } from 'node:child_process'; import { cp, mkdir, readFile, realpath, rm, writeFile } from 'node:fs/promises'; import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import { promisify } from 'node:util'; import { loadConfig } from '../shell/config.js'; import { expand, toPosix } from '../shell/glob.js'; export const root = resolve(dirname(fileURLToPath(import.meta.url)), '..'); export const shellDir = join(root, 'shell'); export const electronDir = join(root, 'node_modules', 'electron'); export const electronDist = join(electronDir, 'dist'); const PLATFORM_NAMES = { mac: 'darwin', win: 'win32', linux: 'linux' }; // Where the app's files sit in the stage and, unpacked, in the bundle's // Resources. Not `app/`: electron-builder takes an `app/package.json` for a // legacy two-package layout and packs it as the Electron app. export const APP_DIR = 'mollusc-app'; export const hostPlatform = () => ({ darwin: 'mac', win32: 'win', linux: 'linux' })[process.platform]; const readJson = async (file) => JSON.parse(await readFile(file, 'utf8')); export async function electronVersion () { return (await readJson(join(electronDir, 'package.json'))).version; } export async function buildApp (appDir, { mac = false, win = false, linux = false, sign = false, log = console.log } = {}) { appDir = resolve(appDir); const { config, warnings } = await loadConfig(appDir); for (const w of warnings) log(`warning: ${w}`); const outDir = join(appDir, config.build.output); const stage = join(outDir, '.mollusc', 'stage'); for (const command of config.build.before) await runBefore(command, appDir, log); await stageApp({ appDir, config, stage, log }); const platforms = { mac, win, linux }; if (!mac && !win && !linux) platforms[hostPlatform()] = true; const cfg = builderConfig({ config, stage, outDir, sign, electronVersion: await electronVersion(), hostPlatform: hostPlatform() }); const { build, Platform } = await import('electron-builder'); const targets = new Map(); for (const [key, on] of Object.entries(platforms)) { if (!on) continue; // electron-builder's names: MAC, WINDOWS, LINUX. const name = key === 'win' ? 'WINDOWS' : key.toUpperCase(); for (const [platform, archs] of Platform[name].createTarget()) targets.set(platform, archs); } // Without --sign, no identity is looked up and nothing is signed. if (!sign) process.env.CSC_IDENTITY_AUTO_DISCOVERY = 'false'; log(`building ${Object.keys(platforms).filter((k) => platforms[k]).join(', ')} with Electron ${cfg.electronVersion}${sign ? ' (signed)' : ''}`); const artifacts = await build({ targets, config: cfg, projectDir: stage, publish: 'never' }); return { artifacts, outDir, stage }; } // A `build.before` step: a string goes through the shell, an array is run as is. export function runBefore (command, cwd, log = () => {}) { const shown = Array.isArray(command) ? command.join(' ') : command; log(`running ${shown}`); const child = Array.isArray(command) ? spawn(command[0], command.slice(1), { cwd, stdio: 'inherit' }) : spawn(command, { cwd, stdio: 'inherit', shell: true }); return new Promise((res, rej) => { child.on('error', (err) => rej(new Error(`${shown}: ${err.message}`))); child.on('exit', (code, signal) => (code === 0 ? res() : rej(new Error(`${shown} failed (${signal || code})`)))); }); } // The electron-builder configuration for an app. Pure, so it can be tested. export function builderConfig ({ config, stage, outDir, sign, electronVersion, hostPlatform, dist = electronDist, env = process.env }) { const b = config.build || {}; const productName = b.productName || config.name; const icon = config.icon ? `${APP_DIR}/${toPosix(config.icon)}` : undefined; // Any of the three ways electron-builder notarises: an Apple ID, an App Store // Connect API key, or a notarytool keychain profile. const hasAppleCredentials = !!((env.APPLE_ID && env.APPLE_APP_SPECIFIC_PASSWORD && env.APPLE_TEAM_ID) || (env.APPLE_API_KEY && env.APPLE_API_KEY_ID && env.APPLE_API_ISSUER) || env.APPLE_KEYCHAIN_PROFILE); const { category: macCategory, ...mac } = b.mac || {}; const { category: linuxCategory, ...linux } = b.linux || {}; return compact({ appId: config.id, productName, electronVersion, // The host platform and architecture pack this install's own Electron; // every other platform, and the host's other architecture (an Intel build // made on Apple Silicon, say), comes from the shared download cache. electronDist: ({ platformName, arch = process.arch }) => (platformName === PLATFORM_NAMES[hostPlatform] && arch === process.arch ? dist : null), directories: { output: outDir, buildResources: join(stage, 'build') }, files: ['package.json', 'shell/**/*'], // The app goes into Resources by hand: electron-builder's own copy of // extra resources leaves node_modules out. afterPack runs before signing. afterPack: async ({ appOutDir, packager }) => { await cp(join(stage, APP_DIR), join(packager.getResourcesDir(appOutDir), APP_DIR), { recursive: true }); }, asar: true, npmRebuild: false, nodeGypRebuild: false, fileAssociations: (config.fileTypes || []).map((ft) => ({ ext: ft.ext, name: ft.name, description: ft.description, role: ft.role, rank: ft.rank, mimeType: ft.mimeType, icon: ft.icon ? `${APP_DIR}/${toPosix(ft.icon)}` : undefined, })), protocols: config.urlSchemes?.length ? [{ name: productName, schemes: config.urlSchemes }] : undefined, mac: { icon, category: macCategory, hardenedRuntime: true, gatekeeperAssess: false, ...(sign ? { notarize: hasAppleCredentials } : { identity: null }), ...mac, }, win: { icon, ...b.win }, linux: { icon, category: linuxCategory, ...linux }, dmg: b.dmg, nsis: b.nsis, }); } // Copies the shell, writes the package.json electron-builder reads, and lays // the app out under `app/`: its listed files, mollusc.json, its icons, and // its production dependencies. export async function stageApp ({ appDir, config, stage, log = () => {} }) { await rm(stage, { recursive: true, force: true }); await mkdir(stage, { recursive: true }); await cp(shellDir, join(stage, 'shell'), { recursive: true }); const pkg = await readJson(join(appDir, 'package.json')).catch(() => ({})); await writeFile(join(stage, 'package.json'), `${JSON.stringify(compact({ name: config.name, productName: config.build?.productName || config.name, version: config.version, description: config.description || pkg.description, author: config.author || pkg.author || 'mollusc', license: pkg.license, homepage: pkg.homepage, main: 'shell/main.js', type: 'module', }), null, 2)}\n`); const patterns = config.build?.files || ['**/*', '!node_modules/**', '!test/**']; const files = new Set(await expand(appDir, [...patterns, `!${toPosix(config.build.output).replace(/\/+$/, '')}/**`])); files.add('mollusc.json'); for (const icon of [config.icon, config.tray?.icon, ...(config.fileTypes || []).map((ft) => ft.icon)]) if (icon) files.add(toPosix(icon)); for (const rel of files) { const dest = join(stage, APP_DIR, rel); await mkdir(dirname(dest), { recursive: true }); await cp(join(appDir, rel), dest, { dereference: true }); } log(`staged ${files.size} files`); // Production dependencies, for a sidecar on Electron's Node, unless the app // chose to list node_modules itself. A page that a bundler built, or a // compiled sidecar, needs none. let modules = []; const listsModules = patterns.some((p) => !p.startsWith('!') && p.includes('node_modules')); if (config.sidecar?.node && config.build?.modules !== false && !listsModules && Object.keys(pkg.dependencies || {}).length) { modules = await productionModules(appDir); for (const { from, to } of modules) { await cp(from, join(stage, APP_DIR, to), { recursive: true, dereference: true, // Nested node_modules are listed on their own; the copy of a package stops at them. filter: (src) => src === from || basename(src) !== 'node_modules', }); } log(`staged ${modules.length} production dependencies`); } return { files: [...files], modules }; } // Every package in the app's production dependency tree, as npm installed it: // where it is, and where it goes relative to the app (linked packages that // live elsewhere are placed under node_modules by name). export async function productionModules (appDir) { let stdout; try { ({ stdout } = await promisify(execFile)('npm', ['ls', '--omit=dev', '--all', '--parseable'], { cwd: appDir, maxBuffer: 64 * 1024 * 1024 })); } catch (err) { // npm ls exits non-zero for extraneous or invalid packages but still lists the tree. if (!err.stdout) throw new Error(`npm ls failed in ${appDir}: ${err.message}`); stdout = err.stdout; } // npm prints real paths; compare against the real app directory so a // symlinked one (macOS's /var/… → /private/var/…) is not taken for elsewhere. const base = await realpath(appDir); const seen = new Set(); const out = []; for (const line of stdout.split('\n').map((l) => l.trim()).filter(Boolean)) { const from = resolve(line); if (from === base || seen.has(from)) continue; seen.add(from); let rel = relative(base, from); if (rel.startsWith('..') || isAbsolute(rel)) rel = join('node_modules', (await readJson(join(from, 'package.json'))).name); out.push({ from, to: toPosix(rel) }); } return out; } // Drops undefined values so the configuration validates; keeps functions. export function compact (value) { if (Array.isArray(value)) return value.map(compact); if (value && typeof value === 'object') { return Object.fromEntries(Object.entries(value).filter(([, v]) => v !== undefined).map(([k, v]) => [k, compact(v)])); } return value; }