import { promises as fs } from 'node:fs'; import { isAbsolute, join, relative, sep } from 'node:path'; import { throwIfCancelled } from '../cancellation.ts'; import { phaseLine } from '../command-output.ts'; import { runCaptured } from '../engine/deps.ts'; import { runCancellationSignal } from '../engine/native-run.ts'; import { withWorkspaceProcessLock } from '../engine/workspace-process-lock.ts'; import { HEARTBEAT_INTERVAL_MS } from '../engine/xcode.ts'; import { getExecutor } from '../exec.ts'; import { reidentifyBundle } from '../macos/stage.ts'; import type { ProjectPluginMacosTarget } from '../project-plugin.ts'; import { getConfigDir } from '../workspace/config.ts'; import { workspaceDir } from '../workspace/paths.ts'; import { settingValueAt } from '../workspace/settings.ts'; import type { MacosArtifactRecipe, MacosProject } from './macos-project.ts'; const FILE_NAME = /^(?!\.\.?$)[^/\0]+$/; function failure(message: string, remedy: string): Error { return Object.assign(new Error(message), { code: 'STIM_BUILD_FAILED', remedy }); } async function isFile(path: string): Promise { return (await fs.stat(path).catch(() => null))?.isFile() ?? false; } async function linkOutside(dir: string, root: string): Promise { for (const entry of await fs.readdir(dir, { withFileTypes: true })) { const path = join(dir, entry.name); if (entry.isSymbolicLink()) { const target = await fs.realpath(path).catch(() => null); if (target === null || (target !== root && !target.startsWith(`${root}${sep}`))) return path; } else if (entry.isDirectory()) { const found = await linkOutside(path, root); if (found !== null) return found; } } return null; } // @ref LLP 0014#use-fixed-invocations -- the manifest's program and argument list run as written, with no shell export function pluginMacosProject( root: string, plugin: { id: string; name: string; package: string; dir: string }, { build, resources = {} }: ProjectPluginMacosTarget, ): MacosProject { const local = `the plugin ${plugin.package} builds this ${plugin.name} project with its own command, on this machine and with no cache`; return { async prepare(context, settings) { const configured = settingValueAt(settings, 'macos.arguments'); const manifest = `the macOS build command in the package.json of the plugin ${plugin.package}`; const wrote = `Check that ${manifest} writes one .app bundle to the {output} argument.`; const recipe: MacosArtifactRecipe = { product: plugin.id, arguments: Array.isArray(configured) ? configured.filter((arg) => typeof arg === 'string') : [], bundleId: '', offload: { unsupported: local }, async compile({ writer, note }) { const signal = runCancellationSignal(context) ?? context.signal; const [executable, ...declared] = build.debug; const install = `Install ${executable}${isAbsolute(executable) ? '' : ' and put it on PATH'}, or correct ${manifest}.`; // @ref LLP 0014#use-fixed-invocations -- a bare name resolves on PATH from the plugin's directory, never from the project root const program = getExecutor().findExecutable(executable, { cwd: plugin.dir, env: context.env }); if (!program) throw failure( `The plugin ${plugin.package} could not start ${executable}: it is not ${isAbsolute(executable) ? 'an executable file' : 'on PATH'}.`, install, ); const folder = join(workspaceDir(root), 'plugin-build', 'macos-debug'); await fs.rm(folder, { recursive: true, force: true }); await fs.mkdir(folder, { recursive: true }); const output = join(folder, `${plugin.id}.app`); let waiting = false; // Godot's macOS export writes and deletes `.entitlements` in NSTemporaryDirectory(), which TMPDIR does not move, so two exports of one game collide. const run = await withWorkspaceProcessLock( getConfigDir(), 'plugin-macos-export', () => runCaptured({ cmd: program, args: declared.map((arg) => (arg === '{root}' ? root : arg === '{output}' ? output : arg)), cwd: root, env: context.env, spawn: (file, args, options) => getExecutor().spawn(file, args, options), managedContext: context, now: Date.now, heartbeatMs: HEARTBEAT_INTERVAL_MS, onHeartbeat: note, logWriter: writer, event: 'plugin_build', label: 'build', }), { external: true, signal, waitMs: Number.POSITIVE_INFINITY, onHeld: () => { if (!waiting) note(phaseLine('build:', 'waiting for another plugin macOS export on this Mac to end')); waiting = true; }, }, ); throwIfCancelled(signal, 'macOS build'); if (run.error) throw failure( `The plugin ${plugin.package} could not start ${executable}: ${run.error instanceof Error ? run.error.message : String(run.error)}`, install, ); if (run.code !== 0) throw failure( `The macOS build command of the plugin ${plugin.package} (${executable}) ${run.code === null ? `was stopped by ${run.signal ?? 'a signal'}` : `exited with code ${run.code}`}.`, `Read the build output with stim logs --source build, fix the ${plugin.name} project or ${manifest}, then retry.`, ); const written = await fs.lstat(output).catch(() => null); if (!written?.isDirectory()) throw failure( `The macOS build command of the plugin ${plugin.package} (${executable}) exited with code 0 and wrote ${written?.isSymbolicLink() ? 'a symbolic link' : 'no app bundle'} at ${output}.`, wrote, ); const plist = join(output, 'Contents', 'Info.plist'); let unreadable = ''; const key = (name: string): Promise => getExecutor() .runFileAsync('plutil', ['-extract', name, 'raw', '-expect', 'string', '-o', '-', plist], { timeoutMs: 10_000, declareFor: context, }) .then( (value) => (value.endsWith('\n') ? value.slice(0, -1) : value), (error: unknown) => { throwIfCancelled(signal, 'macOS build'); unreadable ||= `: ${error instanceof Error ? error.message : String(error)}`; return null; }, ); const product = await key('CFBundleExecutable'); const bundleId = await key('CFBundleIdentifier'); if ( product === null || !FILE_NAME.test(product) || !bundleId || !(await isFile(join(output, 'Contents', 'MacOS', product))) ) throw failure( `The Contents/Info.plist of the app the plugin ${plugin.package} built must name a CFBundleIdentifier and a CFBundleExecutable that is a file in Contents/MacOS${unreadable}.`, wrote, ); recipe.product = product; recipe.bundleId = bundleId; return output; }, async stage(bin, bundle, bundleId, displayName) { await fs.rm(bundle, { recursive: true, force: true }); await fs.rename(bin, bundle); const real = await fs.realpath(bundle); const escape = await linkOutside(bundle, real); if (escape !== null) throw failure( `The app the plugin ${plugin.package} built holds ${relative(bundle, escape)}, a symbolic link that resolves outside the bundle or nowhere.`, `Make ${manifest} write an app bundle whose links stay inside it.`, ); for (const file of [join('Contents', 'Info.plist'), join('Contents', 'MacOS', recipe.product)]) if (!(await isFile(join(bundle, file)))) throw failure(`The app the plugin ${plugin.package} built has no file at ${file}.`, wrote); const folder = join(bundle, 'Contents', 'Resources'); if (Object.keys(resources).length) await fs.mkdir(folder, { recursive: true }); for (const [name, text] of Object.entries(resources)) { const file = join(folder, name); if (await fs.lstat(file).catch(() => null)) throw failure( `The app the plugin ${plugin.package} built already holds Contents/Resources/${name}, which the plugin writes there itself.`, `Remove ${name} from the ${plugin.name} export, or update the plugin ${plugin.package}.`, ); await fs.writeFile(file, text.replaceAll('{bundleId}', bundleId), { flag: 'wx' }); } const entitlements = () => getExecutor() .runFileAsync('codesign', ['-d', '--entitlements', '-', '--xml', bundle], { timeoutMs: 30_000, declareFor: context, }) .catch(() => ''); const signed = await entitlements(); await reidentifyBundle(context, bundle, bundleId, displayName); if ((await entitlements()) !== signed) throw failure( `The app the plugin ${plugin.package} built is signed with entitlements, and re-signing it under the workspace's bundle id did not keep them.`, `Remove the entitlements from the ${plugin.name} project's macOS export preset to run it with stim macos.`, ); }, validateFetched: async () => { throw new Error(local); }, }; return recipe; }, }; }