#!/usr/bin/env node
/**
* Build the optional self-contained macOS app for Luminary.
*
* Like windows/build.mjs this is deliberately additive: it only reads the
* repository (`dist/`, `server/`, `package.json`) and writes everything into a
* directory outside the checkout. Nothing in `src/`, `server/`, `package.json`,
* the Dockerfile or the deploy script is modified, and no npm script is added.
* Run it directly, on macOS:
*
* node macos/build.mjs # host arch, Node 24, ad-hoc signed
* node macos/build.mjs --arch universal --dmg
* node macos/build.mjs --node v22.23.5 # minimum macOS 11.0
* node macos/build.mjs --skip-build --sign none
*
* The bundle keeps the layout the server expects (it derives `DIST_DIR` from
* the parent of `server/`), with a native shim as the app's main executable:
*
* Luminary.app/Contents/
* Info.plist, PkgInfo
* MacOS/Luminary native shim that execs the launcher script
* Resources/
* launcher.sh start/stop/status/verify logic (bash)
* Luminary.icns
* version.txt, README-macos.txt
* runtime/node official Node for this architecture
* app/ unchanged server/, dist/, production deps
*/
import { createHash } from 'node:crypto';
import { spawnSync } from 'node:child_process';
import {
chmodSync,
cpSync,
existsSync,
mkdirSync,
readFileSync,
readdirSync,
renameSync,
rmSync,
statSync,
symlinkSync,
writeFileSync,
} from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(HERE, '..');
const LAUNCHER_DIR = path.join(HERE, 'launcher');
const RELEASES_DIR = path.join(HERE, 'releases');
const DEFAULT_NODE = 'v24.22.2';
const DEFAULT_BUNDLE_ID = 'net.maple-street.luminary';
const INFO_PLIST = path.join(HERE, 'Info.plist');
const ENTITLEMENTS = path.join(HERE, 'entitlements.plist');
const HELP = `Luminary macOS app
Usage: node macos/build.mjs [options]
--out
output directory (default: ~/Library/Caches/luminary-macos).
Must be outside this repository; the app is staged in
/stage/Luminary.app and archived next to it.
--skip-build reuse the existing dist/ instead of running npm run build
--node bundled Node version (default ${DEFAULT_NODE}).
v22.18+ gives a macOS 11.0 bundle; v24+ needs macOS 13.5.
--node-bin bundle this node binary instead of downloading one
--arch host (default), arm64, x64 or universal
--target minimum macOS version (default: derived from Node;
e.g. 11.0 for Node 22, 13.5 for Node 24)
--sign adhoc (default), developer-id or none
--identity Developer ID Application identity for --sign developer-id
--notarize notarytool keychain profile; implies --sign developer-id
--dmg also write a disk image (default)
--no-dmg skip the disk image
--icon icon source (default: macos/icon-1024.png)
--bundle-id CFBundleIdentifier (default ${DEFAULT_BUNDLE_ID})
--allow-dirty skip the check that the checkout is clean outside macos/
--publish copy the finished zip and dmg to macos/releases
--help print this text
Requires macOS with the Xcode command line tools (clang, codesign, ditto,
hdiutil, sips, iconutil). Nothing is written into the repository except with
--publish.
`;
function fail(message) {
process.stderr.write(`macos: FAILED: ${message}\n`);
process.exit(1);
}
function log(step, message) {
process.stdout.write(`macos: ${step.padEnd(9)} ${message}\n`);
}
function warn(message) {
process.stderr.write(`macos: warning: ${message}\n`);
}
function capture(command, args, cwd) {
return spawnSync(command, args, { cwd, encoding: 'utf8' });
}
function run(command, args, cwd, extraEnv) {
log('run', [command, ...args].join(' '));
const result = spawnSync(command, args, {
cwd,
stdio: 'inherit',
env: extraEnv ? { ...process.env, ...extraEnv } : process.env,
});
if (result.error) fail(`${command} could not start: ${result.error.message}`);
if (result.status !== 0) fail(`${command} ${args.join(' ')} exited with ${result.status}`);
return result;
}
function defaultOutDir() {
return path.join(os.homedir(), 'Library', 'Caches', 'luminary-macos');
}
function parseArgs(argv) {
const options = {
out: defaultOutDir(),
node: DEFAULT_NODE,
nodeBin: '',
arch: 'host',
target: '',
sign: 'adhoc',
identity: '',
notarize: '',
dmg: true,
build: true,
icon: path.join(HERE, 'icon-1024.png'),
bundleId: DEFAULT_BUNDLE_ID,
allowDirty: false,
publish: false,
help: false,
};
const value = (index, flag) => {
const next = argv[index + 1];
if (!next || next.startsWith('--')) fail(`${flag} needs a value`);
return next;
};
for (let i = 0; i < argv.length; i++) {
const arg = argv[i];
if (arg === '--out') {
options.out = path.resolve(value(i, arg));
i += 1;
} else if (arg === '--node') {
const version = value(i, arg);
options.node = version.startsWith('v') ? version : `v${version}`;
i += 1;
} else if (arg === '--node-bin') {
options.nodeBin = path.resolve(value(i, arg));
i += 1;
} else if (arg === '--arch') {
options.arch = value(i, arg);
i += 1;
} else if (arg === '--target') {
options.target = value(i, arg);
i += 1;
} else if (arg === '--sign') {
options.sign = value(i, arg);
i += 1;
} else if (arg === '--identity') {
options.identity = value(i, arg);
i += 1;
} else if (arg === '--notarize') {
options.notarize = value(i, arg);
i += 1;
} else if (arg === '--icon') {
options.icon = path.resolve(value(i, arg));
i += 1;
} else if (arg === '--bundle-id') {
options.bundleId = value(i, arg);
i += 1;
} else if (arg === '--skip-build') {
options.build = false;
} else if (arg === '--dmg') {
options.dmg = true;
} else if (arg === '--no-dmg') {
options.dmg = false;
} else if (arg === '--allow-dirty') {
options.allowDirty = true;
} else if (arg === '--publish') {
options.publish = true;
} else if (arg === '--help' || arg === '-h') {
options.help = true;
} else {
fail(`unknown option ${arg} (see --help)`);
}
}
if (!['host', 'arm64', 'x64', 'universal'].includes(options.arch)) {
fail(`--arch must be host, arm64, x64 or universal (got ${options.arch})`);
}
if (!['adhoc', 'developer-id', 'none'].includes(options.sign)) {
fail(`--sign must be adhoc, developer-id or none (got ${options.sign})`);
}
if (!/^v\d+\.\d+\.\d+$/.test(options.node)) {
fail(`--node must look like v24.22.2 (got ${options.node})`);
}
if (options.notarize) options.sign = 'developer-id';
if (options.sign === 'developer-id' && !options.identity) {
fail('--sign developer-id needs --identity "Developer ID Application: ..."');
}
if (options.nodeBin && !existsSync(options.nodeBin)) {
fail(`--node-bin not found: ${options.nodeBin}`);
}
return options;
}
/**
* The staged app and its runtime must not land in the checkout: scripts/deploy
* rsyncs the worktree to production and docker build would pull it into the
* context.
*/
function assertOutsideRepo(outDir) {
const relative = path.relative(ROOT, outDir);
const inside = !relative.startsWith('..') && !path.isAbsolute(relative);
if (inside) {
fail(
`--out resolves inside the repository (${outDir}).\n` +
'Pick a directory outside the checkout, or omit --out to use the cache.',
);
}
}
function git(args, { trim = true } = {}) {
const result = capture('git', args, ROOT);
if (result.error || result.status !== 0) return null;
return trim ? result.stdout.trim() : result.stdout;
}
/** Only this folder and the long-standing untracked logo may be dirty. */
function checkRepoClean(options) {
const status = git(['status', '--porcelain'], { trim: false });
if (status === null) {
warn('git is unavailable here; skipping the worktree check');
return;
}
const unexpected = status
.split('\n')
.filter((line) => line.length > 3)
.map((line) => line.slice(3).replace(/^"|"$/g, '').replace(/^.* -> /, '').trim())
.filter((file) => file && !file.startsWith('macos/') && file !== 'logo.png');
if (!unexpected.length) return;
if (options.allowDirty) {
warn(`building from a modified checkout: ${unexpected.join(', ')}`);
return;
}
fail(
`the checkout has changes outside macos/:\n ${unexpected.join('\n ')}\n` +
'Commit or stash them, or pass --allow-dirty to build anyway.',
);
}
function readPackage() {
const file = path.join(ROOT, 'package.json');
if (!existsSync(file)) fail('run this from a Luminary checkout (package.json missing)');
return JSON.parse(readFileSync(file, 'utf8'));
}
function sha256File(file) {
return createHash('sha256').update(readFileSync(file)).digest('hex');
}
async function download(url) {
const response = await fetch(url);
if (!response.ok) throw new Error(`${response.status} ${response.statusText} from ${url}`);
return Buffer.from(await response.arrayBuffer());
}
function fileType(file) {
const result = capture('file', ['-b', file]);
return result.status === 0 ? result.stdout.trim() : '';
}
function nodeMajor(version) {
return Number(version.slice(1).split('.')[0]);
}
function minimumOS(version) {
const major = nodeMajor(version);
if (major === 22) return '11.0';
if (major >= 24) return '13.5';
return '11.0';
}
function resolveArchs(requested) {
if (requested === 'universal') return ['arm64', 'x64'];
if (requested === 'host') return [process.arch === 'arm64' ? 'arm64' : 'x64'];
return [requested];
}
function clangArch(arch) {
return arch === 'x64' ? 'x86_64' : 'arm64';
}
function ensureUi(options) {
const dist = path.join(ROOT, 'dist', 'index.html');
if (options.build) {
log('ui', 'npm run build (typecheck + vite build + compressed variants)');
run('npm', ['run', 'build'], ROOT);
} else {
log('ui', 'reusing the existing dist/ (--skip-build)');
}
if (!existsSync(dist)) fail('dist/index.html is missing; drop --skip-build or run "npm run build"');
}
function copyServer(appDir) {
cpSync(path.join(ROOT, 'server'), path.join(appDir, 'server'), {
recursive: true,
filter: (source) => {
const relative = path.relative(path.join(ROOT, 'server'), source).split(path.sep).join('/');
if (relative === 'data' || relative.startsWith('data/')) return false;
if (/\.test\.(mjs|ts)$/.test(relative)) return false;
return true;
},
});
}
function copyLegal(appDir) {
for (const name of ['LICENSE', 'THIRD_PARTY_NOTICES.md']) {
const source = path.join(ROOT, name);
if (existsSync(source)) cpSync(source, path.join(appDir, name));
}
const licenses = path.join(ROOT, 'licenses');
if (existsSync(licenses)) cpSync(licenses, path.join(appDir, 'licenses'), { recursive: true });
}
function installDeps(appDir, archs, outDir) {
cpSync(path.join(ROOT, 'package.json'), path.join(appDir, 'package.json'));
cpSync(path.join(ROOT, 'package-lock.json'), path.join(appDir, 'package-lock.json'));
log('deps', `npm ci --omit=dev --os=darwin --cpu=${archs[0]} (sharp darwin-${archs[0]})`);
// sharp resolves its prebuilt binary through optionalDependencies, so npm can
// fetch the target architecture's package from any host. The ONNX skip keeps
// the postinstall from downloading the CUDA build; CPU binaries ship in the
// package.
run(
'npm',
['ci', '--omit=dev', '--os=darwin', `--cpu=${archs[0]}`, '--ignore-scripts', '--no-audit', '--no-fund'],
appDir,
{ ONNXRUNTIME_NODE_INSTALL: 'skip' },
);
rmSync(path.join(appDir, 'node_modules', '.bin'), { recursive: true, force: true });
// A universal app needs both sharp slices; npm's --cpu selects one at a time,
// so install the second architecture separately and copy its packages across.
for (const arch of archs.slice(1)) {
const side = path.join(outDir, `deps-${arch}`);
rmSync(side, { recursive: true, force: true });
mkdirSync(side, { recursive: true });
cpSync(path.join(ROOT, 'package.json'), path.join(side, 'package.json'));
cpSync(path.join(ROOT, 'package-lock.json'), path.join(side, 'package-lock.json'));
run(
'npm',
['ci', '--omit=dev', '--os=darwin', `--cpu=${arch}`, '--ignore-scripts', '--no-audit', '--no-fund'],
side,
{ ONNXRUNTIME_NODE_INSTALL: 'skip' },
);
for (const pkg of [`@img/sharp-darwin-${arch}`, `@img/sharp-libvips-darwin-${arch}`]) {
const from = path.join(side, 'node_modules', pkg);
if (!existsSync(from)) fail(`${pkg} was not installed for the ${arch} slice`);
rmSync(path.join(appDir, 'node_modules', pkg), { recursive: true, force: true });
cpSync(from, path.join(appDir, 'node_modules', pkg), { recursive: true });
log('deps', `added ${pkg}`);
}
rmSync(side, { recursive: true, force: true });
}
verifySharp(appDir, archs);
}
function verifySharp(appDir, archs) {
for (const arch of archs) {
const dir = path.join(appDir, 'node_modules', '@img', `sharp-darwin-${arch}`);
if (!existsSync(dir)) {
warn(`@img/sharp-darwin-${arch} is missing; the server will fall back to JPEG proxies`);
continue;
}
const binaries = [];
const walk = (current) => {
for (const entry of readdirSync(current, { withFileTypes: true })) {
const absolute = path.join(current, entry.name);
if (entry.isDirectory()) walk(absolute);
else if (/\.(node|dylib)$/i.test(entry.name)) binaries.push(path.relative(dir, absolute));
}
};
walk(dir);
const libvips = path.join(appDir, 'node_modules', '@img', `sharp-libvips-darwin-${arch}`);
log(
'deps',
binaries.some((file) => file.endsWith('.node'))
? `sharp darwin-${arch} ready (${binaries.length} native file(s)${existsSync(libvips) ? ', libvips included' : ''})`
: `sharp darwin-${arch} has no .node binary`,
);
}
}
async function ensureNode(options, outDir, archs) {
if (options.nodeBin) {
const kind = fileType(options.nodeBin);
if (!/Mach-O/.test(kind)) fail(`--node-bin is not a Mach-O binary (${kind || 'unknown'})`);
const binaryArch = /universal/.test(kind) ? 'universal' : /arm64/.test(kind) ? 'arm64' : 'x64';
if (binaryArch !== 'universal' && (archs.length > 1 || binaryArch !== archs[0])) {
fail(
`--node-bin is ${binaryArch} but --arch needs ${archs.join(' + ')}.\n` +
'Use the official nodejs.org tarball, or omit --node-bin to download both slices.',
);
}
log('node', `using ${options.nodeBin} (${binaryArch})`);
return { path: options.nodeBin, arch: binaryArch, version: options.node, hash: sha256File(options.nodeBin) };
}
const version = options.node;
const major = nodeMajor(version);
if (major === 23) fail('Node 23 is not an LTS line; use v22 (macOS 11) or v24 (macOS 13.5)');
if (major < 22) fail(`Node ${version} is too old: node:sqlite needs 22.13+ (type stripping 22.18+)`);
if (major === 22 && Number(version.split('.')[1]) < 18) {
fail(`${version} cannot strip types by default; server/denoise-worker.mjs needs v22.18+`);
}
const cache = path.join(outDir, 'cache', `node-${version}`);
mkdirSync(cache, { recursive: true });
const sumsFile = path.join(cache, 'SHASUMS256.txt');
if (!existsSync(sumsFile)) {
log('node', `downloading SHASUMS256.txt for ${version}`);
writeFileSync(sumsFile, await download(`https://nodejs.org/dist/${version}/SHASUMS256.txt`));
}
const sums = new Map(
readFileSync(sumsFile, 'utf8')
.split('\n')
.filter(Boolean)
.map((line) => {
const [hash, name] = line.trim().split(/\s+/);
return [name, hash];
}),
);
const binaries = [];
for (const arch of archs) {
const name = `node-${version}-darwin-${arch}.tar.gz`;
const tarball = path.join(cache, name);
if (!existsSync(tarball)) {
log('node', `downloading ${name}`);
try {
writeFileSync(tarball, await download(`https://nodejs.org/dist/${version}/${name}`));
} catch (error) {
fail(`could not download ${name}: ${error.message}`);
}
}
const hash = sha256File(tarball);
const expected = sums.get(name);
if (expected && expected !== hash) {
rmSync(tarball, { force: true });
fail(`${name} failed its SHA-256 check (${hash} != ${expected}); re-run to download again`);
}
if (!expected) warn(`${name} has no published checksum; using it unverified`);
const dir = path.join(cache, `node-${version}-darwin-${arch}`);
const binary = path.join(dir, 'bin', 'node');
if (!existsSync(binary)) {
mkdirSync(dir, { recursive: true });
run('tar', ['-xzf', tarball, '-C', dir, '--strip-components=1']);
}
const kind = fileType(binary);
if (!/Mach-O/.test(kind)) fail(`extracted ${arch} node is not a Mach-O binary (${kind})`);
binaries.push(binary);
log('node', `${version} darwin-${arch} verified (sha256 ${hash.slice(0, 12)}…)`);
}
if (binaries.length === 1) {
return { path: binaries[0], arch: archs[0], version, hash: sha256File(binaries[0]) };
}
const universal = path.join(cache, `node-${version}-universal`);
rmSync(universal, { force: true });
run('lipo', ['-create', ...binaries, '-output', universal]);
const kind = fileType(universal);
if (!/universal binary/.test(kind)) fail(`lipo did not produce a universal binary (${kind})`);
chmodSync(universal, 0o755);
log('node', `${version} universal (arm64 + x86_64)`);
return { path: universal, arch: 'universal', version, hash: sha256File(universal) };
}
function checkNodePortability(binary) {
const result = capture('otool', ['-L', binary]);
if (result.status !== 0) return;
const foreign = result.stdout
.split('\n')
.slice(1)
.map((line) => line.trim().split(' ')[0])
.filter((lib) => lib && !lib.startsWith('/usr/lib/') && !lib.startsWith('/System/'));
if (foreign.length) {
warn(
`the bundled node links to libraries outside macOS: ${foreign.join(', ')}.\n` +
'Use the official nodejs.org tarball so the app runs on a Mac without Homebrew.',
);
}
}
function compileShim(app, archs, target) {
const found = capture('xcrun', ['--find', 'clang']);
const clang = found.status === 0 ? found.stdout.trim() : '';
if (!clang) {
fail(
'clang is missing. Install the Xcode command line tools:\n' +
' xcode-select --install\n' +
'and run the build again.',
);
}
const output = path.join(app, 'Contents', 'MacOS', 'Luminary');
const args = ['-O2', '-Wall', '-Wextra', `-mmacosx-version-min=${target}`];
for (const arch of archs) args.push('-arch', clangArch(arch));
args.push('-o', output, path.join(LAUNCHER_DIR, 'main.c'));
run(clang, args);
chmodSync(output, 0o755);
log('launcher', `native shim (${archs.join(' + ')}, macOS ${target}+)`);
}
function renderInfoPlist(app, { version, target, bundleId }) {
const text = readFileSync(INFO_PLIST, 'utf8')
.replaceAll('__VERSION__', version)
.replaceAll('__MIN_OS__', target)
.replaceAll('__BUNDLE_ID__', bundleId);
writeFileSync(path.join(app, 'Contents', 'Info.plist'), text);
writeFileSync(path.join(app, 'Contents', 'PkgInfo'), 'APPL????');
}
function buildIcon(app, source, outDir) {
if (!existsSync(source)) {
warn(`icon source not found: ${source}; the app will use the generic icon`);
return;
}
const sips = '/usr/bin/sips';
const iconutil = '/usr/bin/iconutil';
if (!existsSync(sips) || !existsSync(iconutil)) {
warn('sips/iconutil are missing; skipping the icon');
return;
}
const probe = capture(sips, ['-g', 'pixelWidth', '-g', 'pixelHeight', source]);
const width = Number((probe.stdout.match(/pixelWidth:\s*(\d+)/) ?? [])[1] ?? 0);
const height = Number((probe.stdout.match(/pixelHeight:\s*(\d+)/) ?? [])[1] ?? 0);
if (!width || !height) {
warn(`could not read the icon size of ${source}; skipping the icon`);
return;
}
const square = Math.max(width, height);
if (square < 512) {
warn(
`the icon source is ${width}x${height}; the .icns will look soft.\n` +
'Pass --icon with a 1024x1024 PNG for a crisp Dock icon.',
);
}
const work = path.join(outDir, 'cache', 'icon');
rmSync(work, { recursive: true, force: true });
mkdirSync(path.join(work, 'Luminary.iconset'), { recursive: true });
const padded = path.join(work, 'square.png');
if (width === height) {
cpSync(source, padded);
} else {
run(sips, ['-p', String(square), String(square), '--padColor', '0B0D10', source, '--out', padded]);
}
const iconset = path.join(work, 'Luminary.iconset');
for (const size of [16, 32, 128, 256, 512]) {
for (const scale of [1, 2]) {
const pixels = size * scale;
const name = scale === 1 ? `icon_${size}x${size}.png` : `icon_${size}x${size}@2x.png`;
run(sips, ['-z', String(pixels), String(pixels), padded, '--out', path.join(iconset, name)]);
}
}
run(iconutil, ['-c', 'icns', iconset, '-o', path.join(app, 'Contents', 'Resources', 'Luminary.icns')]);
log('icon', `Luminary.icns from ${path.relative(ROOT, source)} (${width}x${height})`);
}
function writeVersion(resources, info) {
const commit = git(['rev-parse', '--short', 'HEAD']) ?? 'unknown';
const lines = [
`Luminary ${info.version}`,
`commit ${commit}`,
`built ${new Date().toISOString()}`,
`node ${info.nodeVersion} darwin-${info.nodeArch} sha256 ${info.nodeHash} size ${info.nodeSize}`,
`arch ${info.archs.join(' + ')}`,
`minimum macOS ${info.target}`,
'launcher native shim -> launcher.sh',
];
writeFileSync(path.join(resources, 'version.txt'), `${lines.join('\n')}\n`);
return commit;
}
function machOFiles(root) {
const found = [];
const walk = (current) => {
for (const entry of readdirSync(current, { withFileTypes: true })) {
const absolute = path.join(current, entry.name);
if (entry.isDirectory()) {
walk(absolute);
continue;
}
if (!entry.isFile()) continue;
// `file` per file would be hundreds of subprocesses across node_modules;
// only native modules, dylibs and executables can be Mach-O here.
const stat = statSync(absolute);
const candidate =
/\.(node|dylib|so)$/i.test(entry.name) || (stat.mode & 0o111) !== 0;
if (candidate && /Mach-O/.test(fileType(absolute))) found.push(absolute);
}
};
walk(root);
return found;
}
function signApp(app, options) {
if (options.sign === 'none') {
warn(
'the app is unsigned: arm64 Macs refuse to launch it at all, and Intel\n' +
'Macs show the Gatekeeper warning. Ship adhoc or developer-id instead.',
);
return;
}
const nested = machOFiles(app).filter((file) => !file.endsWith('/Contents/MacOS/Luminary'));
for (const file of nested) {
if (options.sign === 'adhoc') {
run('codesign', ['--force', '--sign', '-', file]);
continue;
}
const kind = fileType(file);
const executable = /executable/.test(kind) && !/dylib|bundle/.test(kind);
const args = ['--force', '--timestamp', '--sign', options.identity];
if (executable) args.push('--options', 'runtime', '--entitlements', ENTITLEMENTS);
args.push(file);
run('codesign', args);
}
const finalArgs =
options.sign === 'adhoc'
? ['--force', '--sign', '-', app]
: [
'--force',
'--timestamp',
'--options',
'runtime',
'--entitlements',
ENTITLEMENTS,
'--sign',
options.identity,
app,
];
run('codesign', finalArgs);
const verify = capture('codesign', ['--verify', '--deep', '--strict', '--verbose=2', app]);
if (verify.status !== 0) fail(`codesign verification failed:\n${verify.stderr.trim()}`);
log('sign', options.sign === 'adhoc' ? 'ad-hoc signature verified' : `signed with ${options.identity}`);
}
function zipApp(app, zipPath) {
rmSync(zipPath, { force: true });
// ditto keeps symlinks, extended attributes and the code signature intact;
// `zip -r` corrupts bundles often enough to produce "app is damaged".
run('ditto', ['-c', '-k', '--keepParent', '--sequesterRsrc', app, zipPath]);
return statSync(zipPath).size;
}
function makeDmg(app, dmgPath, outDir) {
const root = path.join(outDir, 'dmg');
rmSync(root, { recursive: true, force: true });
mkdirSync(root, { recursive: true });
cpSync(app, path.join(root, 'Luminary.app'), { recursive: true, verbatimSymlinks: true });
symlinkSync('Applications', path.join(root, 'Applications'));
cpSync(path.join(HERE, 'README-macos.txt'), path.join(root, 'README-macos.txt'));
const stop = path.join(LAUNCHER_DIR, 'Stop Luminary.command');
if (existsSync(stop)) {
cpSync(stop, path.join(root, 'Stop Luminary.command'));
chmodSync(path.join(root, 'Stop Luminary.command'), 0o755);
}
rmSync(dmgPath, { force: true });
run('hdiutil', [
'create',
'-volname',
'Luminary',
'-srcfolder',
root,
'-ov',
'-format',
'UDZO',
dmgPath,
]);
rmSync(root, { recursive: true, force: true });
return statSync(dmgPath).size;
}
function notarize(artifact, profile) {
log('notarize', `submitting ${path.basename(artifact)}`);
run('xcrun', ['notarytool', 'submit', artifact, '--keychain-profile', profile, '--wait']);
}
function staple(artifact) {
run('xcrun', ['stapler', 'staple', artifact]);
run('xcrun', ['stapler', 'validate', artifact]);
}
async function main() {
const options = parseArgs(process.argv.slice(2));
if (options.help) {
process.stdout.write(HELP);
return 0;
}
if (process.platform !== 'darwin') {
fail(
'the macOS app must be built on macOS: it needs clang, codesign, ditto and hdiutil.\n' +
'The Windows bundle is the one that cross-builds from Linux.',
);
}
assertOutsideRepo(options.out);
const pkg = readPackage();
const archs = resolveArchs(options.arch);
const target = options.target || minimumOS(options.node);
const [targetMajor, targetMinor = 0] = target.split('.').map(Number);
if (nodeMajor(options.node) >= 24 && (targetMajor < 13 || (targetMajor === 13 && targetMinor < 5))) {
fail(
`Node ${options.node} needs macOS 13.5 or newer, but --target is ${target}.\n` +
'Build with --node v22.23.5 for a macOS 11.0 bundle.',
);
}
log('repo', `${pkg.name} ${pkg.version} at ${ROOT}`);
log('out', options.out);
checkRepoClean(options);
ensureUi(options);
const stageRoot = path.join(options.out, 'stage');
const workRoot = path.join(options.out, 'stage.next');
const app = path.join(workRoot, 'Luminary.app');
const contents = path.join(app, 'Contents');
const resources = path.join(contents, 'Resources');
const appDir = path.join(resources, 'app');
rmSync(workRoot, { recursive: true, force: true });
for (const dir of [path.join(contents, 'MacOS'), resources, appDir, path.join(resources, 'runtime')]) {
mkdirSync(dir, { recursive: true });
}
log('stage', 'copying dist/ and server/ (the layout the server expects)');
cpSync(path.join(ROOT, 'dist'), path.join(appDir, 'dist'), { recursive: true });
copyServer(appDir);
copyLegal(appDir);
installDeps(appDir, archs, options.out);
const node = await ensureNode(options, options.out, archs);
checkNodePortability(node.path);
cpSync(node.path, path.join(resources, 'runtime', 'node'));
chmodSync(path.join(resources, 'runtime', 'node'), 0o755);
log('node', `bundled ${path.basename(node.path)} (${(statSync(node.path).size / 1024 / 1024).toFixed(1)} MB)`);
cpSync(path.join(LAUNCHER_DIR, 'launcher.sh'), path.join(resources, 'launcher.sh'));
chmodSync(path.join(resources, 'launcher.sh'), 0o755);
cpSync(path.join(HERE, 'README-macos.txt'), path.join(resources, 'README-macos.txt'));
renderInfoPlist(app, { version: pkg.version, target, bundleId: options.bundleId });
compileShim(app, archs, target);
buildIcon(app, options.icon, options.out);
const commit = writeVersion(resources, {
version: pkg.version,
nodeVersion: options.node,
nodeArch: node.arch,
nodeHash: node.hash,
nodeSize: statSync(node.path).size,
archs,
target,
});
signApp(app, options);
const label = archs.length > 1 ? 'universal' : archs[0];
const zipPath = path.join(options.out, `Luminary-${pkg.version}-mac-${label}.zip`);
let zipBytes = zipApp(app, zipPath);
if (options.notarize) {
notarize(zipPath, options.notarize);
staple(app);
zipBytes = zipApp(app, zipPath);
} else {
const assessment = capture('spctl', ['-a', '-vv', '-t', 'exec', app]);
if (assessment.status !== 0) {
log('gatekeeper', 'not notarized: users must use Privacy & Security > Open Anyway');
}
}
let dmgPath = '';
let dmgBytes = 0;
if (options.dmg) {
dmgPath = path.join(options.out, `Luminary-${pkg.version}-mac-${label}.dmg`);
dmgBytes = makeDmg(app, dmgPath, options.out);
if (options.notarize) {
notarize(dmgPath, options.notarize);
staple(dmgPath);
}
log('dmg', `${path.basename(dmgPath)} (${(dmgBytes / 1024 / 1024).toFixed(1)} MB)`);
}
// The isolation contract: nothing outside macos/ may have changed. Checked
// before --publish writes anything into the checkout.
if (!options.allowDirty) checkRepoClean(options);
rmSync(stageRoot, { recursive: true, force: true });
renameSync(workRoot, stageRoot);
let published = [];
if (options.publish) {
mkdirSync(RELEASES_DIR, { recursive: true });
const sums = [];
for (const artifact of [zipPath, ...(dmgPath ? [dmgPath] : [])]) {
const targetPath = path.join(RELEASES_DIR, path.basename(artifact));
cpSync(artifact, targetPath);
sums.push(`${sha256File(targetPath)} ${path.basename(targetPath)}`);
log('publish', path.relative(ROOT, targetPath));
}
writeFileSync(path.join(RELEASES_DIR, 'SHA256SUMS.txt'), `${sums.join('\n')}\n`);
published = sums;
}
process.stdout.write(
[
'',
'macos build PASSED',
` app ${path.join(stageRoot, 'Luminary.app')}`,
` zip ${zipPath}`,
` zip size ${(zipBytes / 1024 / 1024).toFixed(1)} MB`,
` zip sha256 ${sha256File(zipPath)}`,
...(dmgPath
? [
` dmg ${dmgPath}`,
` dmg size ${(dmgBytes / 1024 / 1024).toFixed(1)} MB`,
` dmg sha256 ${sha256File(dmgPath)}`,
]
: []),
` arch ${label}`,
` node ${options.node} darwin-${node.arch}`,
` target macOS ${target}+`,
` signature ${options.sign}${options.identity ? ` (${options.identity})` : ''}`,
` commit ${commit}`,
...(published.length ? ['', ...published.map((line) => ` publish ${line}`)] : []),
'',
options.notarize
? 'Notarized and stapled: users can open it with a normal double-click.'
: 'Not notarized: first launch needs Privacy & Security > Open Anyway (see README-macos.txt).',
'',
].join('\n'),
);
return 0;
}
main().then(
(code) => {
process.exitCode = code;
},
(error) => {
fail(error instanceof Error ? error.message : String(error));
},
);