import { spawn } from 'node:child_process'; import { existsSync, readFileSync, readdirSync } from 'node:fs'; import fs from 'node:fs/promises'; import path from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; import { parseArgs } from 'node:util'; import { packager } from '@electron/packager'; import { reportTemplateMagicString, validateCoreReportTemplateModules, } from '../../../scripts/report-template-utils.mjs'; import { writeAppUpdateYmlIntoResources, writeUpdateMetadataForArtifact, } from './build-update-metadata.mjs'; import { notarizeMacArtifact } from './mac-notarization.mjs'; import { assertPackagedExternalResourcesUnpacked, packagedAsarOptions, } from './packaged-asar-resources.mjs'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); const studioRootDir = path.resolve(__dirname, '..'); const workspaceRootDir = path.resolve(studioRootDir, '..', '..'); const studioBuildDir = path.join(studioRootDir, 'build'); const studioFontLicensePath = path.join( studioRootDir, 'src', 'renderer', 'assets', 'fonts', 'OFL.txt', ); const reportRootDir = path.join(workspaceRootDir, 'apps', 'report'); const coreDistDir = path.join(workspaceRootDir, 'packages', 'core', 'dist'); const reportTemplatePath = path.join(reportRootDir, 'dist', 'index.html'); const unresolvedReportTemplatePattern = new RegExp( String.raw`(?:=|return)\s*(['"])${reportTemplateMagicString}\1`, ); // Keep release packaging state outside `apps/studio` so local build outputs do // not recurse back into the generated Electron payload. export const releaseWorkspaceDir = path.join( workspaceRootDir, '.release', 'studio', ); export const artifactDir = path.join(releaseWorkspaceDir, 'artifacts'); const packagingWorkspaceDir = path.join(releaseWorkspaceDir, 'workspace'); const packagedDir = path.join(releaseWorkspaceDir, 'packaged'); const packagedAppId = 'midscene-studio-beta'; const packagedWindowsAppId = 'ai.midscene.studio.beta'; const packagedProductName = 'Midscene Studio Beta'; const packagedIgnorePatterns = [ /^\/pnpm-lock\.yaml$/, /^\/vendor($|\/)/, // Documentation / changelog noise from third-party packages. /\/(README|CHANGELOG|HISTORY|CONTRIBUTING|AUTHORS)(\.[a-zA-Z]+)?$/i, // Editor / repo metadata that shipped from upstream `files` globs. /\/\.(github|vscode|idea|circleci|husky)(\/|$)/, /\/(\.npmignore|\.editorconfig|\.gitignore|\.gitattributes|\.prettierrc[^/]*|\.eslintrc[^/]*|\.eslintignore|\.babelrc[^/]*)$/, // TypeScript type definitions are not loaded by the packaged runtime. /\.d\.ts(\.map)?$/, // Source maps duplicate what `pruneSourceMapFiles` already removed. /\.js\.map$/, ]; const defaultMacEntitlementsPath = path.join( studioBuildDir, 'entitlements.mac.plist', ); const gpuMacEntitlementsPath = path.join( studioBuildDir, 'entitlements.mac.gpu.plist', ); const pluginMacEntitlementsPath = path.join( studioBuildDir, 'entitlements.mac.plugin.plist', ); const rendererMacEntitlementsPath = path.join( studioBuildDir, 'entitlements.mac.renderer.plist', ); const packageBuildSourceTargets = [ 'src', 'html', 'bin', 'package.json', 'project.json', 'tsconfig.json', 'tsup.config.ts', 'rslib.config.ts', 'rslib.config.mjs', 'rslib.inspect.config.ts', ]; const studioBuildSourceTargets = [ 'src', 'package.json', 'project.json', 'tsconfig.json', 'postcss.config.mjs', 'rsbuild.config.ts', ]; const reportBuildSourceTargets = [ 'src', 'e2e', 'template', 'package.json', 'tsconfig.json', 'tsconfig.build.json', 'rsbuild.config.ts', ]; const playgroundAppBuildSourceTargets = [ 'src', 'package.json', 'project.json', 'tsconfig.json', 'postcss.config.mjs', 'rsbuild.config.ts', ]; const staticWorkspacePackageSourceConfigs = [ { appRelativeDir: 'apps/playground', packageNames: [ '@midscene/playground', '@midscene/ios', '@midscene/harmony', ], }, { appRelativeDir: 'apps/android-playground', packageNames: ['@midscene/android-playground'], }, { appRelativeDir: 'apps/computer-playground', packageNames: ['@midscene/computer-playground'], }, ].map((config) => ({ ...config, appDir: path.join(workspaceRootDir, config.appRelativeDir), distDir: path.join(workspaceRootDir, config.appRelativeDir, 'dist'), faviconPath: path.join( workspaceRootDir, config.appRelativeDir, 'src', 'favicon.ico', ), })); const supportedPlatforms = new Set(['darwin', 'linux', 'win32']); const truthyBooleanTokens = new Set(['1', 'true', 'yes', 'on']); const falsyBooleanTokens = new Set(['0', 'false', 'no', 'off']); const macNestedCodeBundleExtensions = new Set([ '.app', '.appex', '.framework', '.xpc', ]); const macStandaloneCodeFileExtensions = new Set([ '.bare', '.dylib', '.node', '.so', ]); const macMachOMagicHeaders = new Set([ 'cafebabe', 'cafebabf', 'bebafeca', 'bfbafeca', 'cefaedfe', 'cffaedfe', 'feedface', 'feedfacf', ]); const macThinMachOMagic = new Map([ [0xfeedface, 'be'], [0xfeedfacf, 'be'], [0xcefaedfe, 'le'], [0xcffaedfe, 'le'], ]); const macFatMachOMagic = new Map([ [0xcafebabe, { endian: 'be', archEntrySize: 20 }], [0xcafebabf, { endian: 'be', archEntrySize: 32 }], [0xbebafeca, { endian: 'le', archEntrySize: 20 }], [0xbfbafeca, { endian: 'le', archEntrySize: 32 }], ]); const macCpuTypeNames = new Map([ [0x00000007, 'x86'], [0x01000007, 'x86_64'], [0x0000000c, 'arm'], [0x0100000c, 'arm64'], ]); const macTargetArchNames = new Map([ ['x64', 'x86_64'], ['arm64', 'arm64'], ]); export const shouldUseShellForCommand = ( command, platform = process.platform, ) => platform === 'win32' && /\.(cmd|bat)$/i.test(command); export const quoteWindowsShellArg = (arg) => { if (arg === '') { return '""'; } if (!/[\s"&|<>()^]/.test(arg)) { return arg; } return `"${arg.replace(/(["&|<>()^])/g, '^$1')}"`; }; const run = (command, args, { cwd = workspaceRootDir, env } = {}) => new Promise((resolve, reject) => { const shell = shouldUseShellForCommand(command); const spawnArgs = shell ? args.map(quoteWindowsShellArg) : args; const child = spawn(command, spawnArgs, { cwd, env: env ? { ...process.env, ...env } : process.env, shell, stdio: 'inherit', }); child.on('error', reject); child.on('exit', (code) => { if (code === 0) { resolve(); return; } reject( new Error( `Command failed with exit code ${code}: ${command} ${args.join(' ')}`, ), ); }); }); const resolveTrimmedEnv = (value) => { if (typeof value !== 'string') { return undefined; } const trimmed = value.trim(); return trimmed || undefined; }; export const parseBooleanLike = (value, defaultValue = false) => { if (typeof value === 'boolean') { return value; } if (typeof value !== 'string') { return defaultValue; } const normalized = value.trim().toLowerCase(); if (!normalized) { return defaultValue; } if (truthyBooleanTokens.has(normalized)) { return true; } if (falsyBooleanTokens.has(normalized)) { return false; } throw new Error(`Expected a boolean-like value, but received "${value}".`); }; export const resolveMacPackagedAppSecurity = ({ env = process.env, platform = process.platform, } = {}) => { const requireCodesign = parseBooleanLike( env.MIDSCENE_REQUIRE_MAC_CODESIGN, false, ); const requireNotarization = parseBooleanLike( env.MIDSCENE_REQUIRE_MAC_NOTARIZATION, false, ); if (platform !== 'darwin') { return { notarizeOptions: undefined, requireCodesign, requireNotarization, shouldDeveloperIdSign: false, shouldNotarize: false, signIdentity: undefined, signKeychain: undefined, teamId: undefined, }; } const signIdentity = resolveTrimmedEnv(env.APPLE_CODESIGN_IDENTITY); const signKeychain = resolveTrimmedEnv(env.APPLE_CODESIGN_KEYCHAIN); const teamId = resolveTrimmedEnv(env.APPLE_TEAM_ID); const appleApiKey = resolveTrimmedEnv(env.APPLE_API_KEY_PATH); const appleApiKeyId = resolveTrimmedEnv(env.APPLE_API_KEY_ID); const appleApiIssuer = resolveTrimmedEnv(env.APPLE_API_ISSUER_ID); const shouldDeveloperIdSign = Boolean(signIdentity); const notarizeOptions = appleApiKey && appleApiKeyId ? { appleApiKey, appleApiKeyId, ...(appleApiIssuer ? { appleApiIssuer } : {}), } : undefined; // Always notarize when both Developer ID signing and notarization // credentials are available, regardless of the require flag. Otherwise // a prerelease ends up Developer-ID signed but unnotarized, which // Gatekeeper rejects on download with "Apple cannot verify..." even // though the signature itself is valid. The require flag only governs // whether missing credentials should fail the build (handled below). const shouldNotarize = shouldDeveloperIdSign && Boolean(notarizeOptions); if (requireCodesign && !shouldDeveloperIdSign) { throw new Error( 'macOS release packaging requires a Developer ID signing identity. Set APPLE_CODESIGN_IDENTITY.', ); } if (teamId && signIdentity && !signIdentity.includes(`(${teamId})`)) { throw new Error( `Developer ID identity "${signIdentity}" does not match APPLE_TEAM_ID "${teamId}".`, ); } if (requireNotarization && !shouldDeveloperIdSign) { throw new Error( 'macOS notarization requires a Developer ID signing identity. Set APPLE_CODESIGN_IDENTITY.', ); } if (requireNotarization && !notarizeOptions) { throw new Error( [ 'macOS notarization is required, but notarization credentials are missing.', 'Set APPLE_API_KEY_PATH and APPLE_API_KEY_ID', '(plus APPLE_API_ISSUER_ID for App Store Connect team keys).', ].join(' '), ); } return { notarizeOptions, requireCodesign, requireNotarization, shouldDeveloperIdSign, shouldNotarize, signIdentity, signKeychain, teamId, }; }; export const normalizeReleaseVersion = (version) => { const trimmed = version?.trim(); if (!trimmed) { throw new Error( 'A release version is required. Pass --version= when packaging Midscene Studio.', ); } return trimmed.startsWith('v') ? trimmed.slice(1) : trimmed; }; export const buildArtifactBaseName = ({ version, platform, arch }) => { if (!supportedPlatforms.has(platform)) { throw new Error( `Unsupported Electron platform "${platform}". Expected one of: ${Array.from(supportedPlatforms).join(', ')}`, ); } if (!arch) { throw new Error('An Electron arch is required.'); } return `${packagedAppId}-v${normalizeReleaseVersion(version)}-${platform}-${arch}`; }; export const resolveDefaultPackageArch = ( platform = process.platform, hostArch = process.arch, ) => { if (platform === 'win32') { return 'x64'; } return hostArch; }; export const buildPackagedAppManifest = ( packageJson, version, dependencies = packageJson.dependencies ?? {}, ) => ({ name: packagedAppId, productName: packagedProductName, private: true, version: normalizeReleaseVersion(version), description: packageJson.description ?? 'Midscene Studio packaged Electron application', license: packageJson.license, author: packageJson.author, type: packageJson.type, main: 'dist/main/main.cjs', dependencies, }); export const resolvePackagerIconPath = (platform) => { const assetsDir = path.join(studioRootDir, 'assets'); const macIcon = path.join(assetsDir, 'midscene-icon.icns'); const winIcon = path.join(assetsDir, 'midscene-icon.ico'); if (platform === 'darwin' && existsSync(macIcon)) { return macIcon; } if (platform === 'win32' && existsSync(winIcon)) { return winIcon; } // Packager accepts undefined and falls back to the default Electron icon. // On Linux, packager ignores icon entirely for plain folder output. return undefined; }; export const buildPackagerOptions = ({ arch, outDir, platform, stageDir }) => ({ arch, // Store the JS payload in app.asar so release artifacts do not have to // compress/extract tens of thousands of tiny node_modules files. Native // modules and helper binaries stay unpacked because the OS dynamic loader and // spawned processes need real filesystem paths. asar: packagedAsarOptions, derefSymlinks: false, dir: stageDir, electronVersion: getStudioElectronVersion(), icon: resolvePackagerIconPath(platform), ignore: packagedIgnorePatterns, name: packagedProductName, out: outDir, overwrite: true, platform, prune: false, }); const packageManagerCommand = process.platform === 'win32' ? 'pnpm.cmd' : 'pnpm'; export const buildWindowsNsisArtifactName = (baseName) => `${baseName}-setup.exe`; export const buildWindowsNsisConfig = ({ artifactName, iconPath }) => ({ appId: packagedWindowsAppId, productName: packagedProductName, directories: { output: artifactDir, }, win: { // `@electron/packager` names the prepackaged executable from its `name` // option. electron-builder does not rename that executable when using // `--prepackaged`, so NSIS must target the exact same product filename for // shortcuts, process shutdown, and updater relaunch. executableName: packagedProductName, target: [ { target: 'nsis', arch: ['x64'], }, ], ...(iconPath ? { icon: iconPath } : {}), }, nsis: { oneClick: true, perMachine: false, allowElevation: false, artifactName, shortcutName: packagedProductName, uninstallDisplayName: packagedProductName, createDesktopShortcut: 'always', }, npmRebuild: false, publish: null, }); export const buildWindowsNsisInstallerArgs = ({ arch, configPath, packagedAppPath, }) => [ 'exec', 'electron-builder', '--win', 'nsis', `--${arch}`, `--prepackaged=${packagedAppPath}`, `--config=${configPath}`, '--publish=never', ]; let cachedStudioElectronVersion; let cachedStudioPackageJson; let cachedWorkspacePackageCatalog; export const getStudioElectronVersion = () => { if (cachedStudioElectronVersion) { return cachedStudioElectronVersion; } const studioPackageJson = JSON.parse( readFileSync(path.join(studioRootDir, 'package.json'), 'utf8'), ); const electronVersion = studioPackageJson.dependencies?.electron ?? studioPackageJson.devDependencies?.electron ?? studioPackageJson.dependencies?.['electron-nightly'] ?? studioPackageJson.devDependencies?.['electron-nightly']; if (!electronVersion) { throw new Error( 'Midscene Studio package.json must declare electron or electron-nightly.', ); } cachedStudioElectronVersion = electronVersion; return electronVersion; }; const readPackageJsonSync = (targetPath) => JSON.parse(readFileSync(targetPath, 'utf8')); const getStudioPackageJson = () => { if (!cachedStudioPackageJson) { cachedStudioPackageJson = readPackageJsonSync( path.join(studioRootDir, 'package.json'), ); } return cachedStudioPackageJson; }; const getWorkspacePackageCatalog = () => { if (cachedWorkspacePackageCatalog) { return cachedWorkspacePackageCatalog; } const packageCatalog = new Map(); for (const scopeDir of ['apps', 'packages']) { const baseDir = path.join(workspaceRootDir, scopeDir); for (const entry of readdirSync(baseDir, { withFileTypes: true, })) { if (!entry.isDirectory()) { continue; } const packageDir = path.join(baseDir, entry.name); const packageJsonPath = path.join(packageDir, 'package.json'); try { const packageJson = readPackageJsonSync(packageJsonPath); packageCatalog.set(packageJson.name, { name: packageJson.name, packageDir, packageJson, relativeDir: path.relative(workspaceRootDir, packageDir), }); } catch (error) { if (error?.code !== 'ENOENT') { throw error; } } } } cachedWorkspacePackageCatalog = packageCatalog; return packageCatalog; }; const getStudioRuntimeWorkspaceDependencyNames = ( packageJson = getStudioPackageJson(), ) => Object.entries(packageJson.dependencies ?? {}) .filter( ([, version]) => typeof version === 'string' && version.startsWith('workspace:'), ) .map(([dependencyName]) => dependencyName); export const collectWorkspaceDependencyClosure = ( rootDependencyNames, packageCatalog = getWorkspacePackageCatalog(), ) => { const visitedPackageNames = new Set(); const orderedPackages = []; const visitPackage = (packageName) => { if (visitedPackageNames.has(packageName)) { return; } visitedPackageNames.add(packageName); const packageEntry = packageCatalog.get(packageName); if (!packageEntry) { throw new Error( `Unable to resolve workspace package "${packageName}" from the Midscene workspace.`, ); } const workspaceDependencies = { ...(packageEntry.packageJson.dependencies ?? {}), ...(packageEntry.packageJson.optionalDependencies ?? {}), }; for (const [dependencyName, dependencyVersion] of Object.entries( workspaceDependencies, )) { if ( typeof dependencyVersion === 'string' && dependencyVersion.startsWith('workspace:') ) { visitPackage(dependencyName); } } orderedPackages.push(packageEntry); }; for (const dependencyName of rootDependencyNames) { visitPackage(dependencyName); } return orderedPackages; }; const collectLatestMtime = async (targetPath) => { let stats; try { stats = await fs.stat(targetPath); } catch (error) { if (error?.code === 'ENOENT') { return 0; } throw error; } if (!stats.isDirectory()) { return stats.mtimeMs; } let latestMtime = stats.mtimeMs; const entries = await fs.readdir(targetPath, { withFileTypes: true }); for (const entry of entries) { if (entry.name === 'node_modules' || entry.name === '.git') { continue; } latestMtime = Math.max( latestMtime, await collectLatestMtime(path.join(targetPath, entry.name)), ); } return latestMtime; }; const reportRuntimeOutputExtensions = new Set(['.cjs', '.html', '.js', '.mjs']); export const pathContainsReportTemplatePlaceholder = async (rootDir) => { let entries; try { entries = await fs.readdir(rootDir, { withFileTypes: true }); } catch (error) { if (error?.code === 'ENOENT') { return false; } throw error; } for (const entry of entries) { const entryPath = path.join(rootDir, entry.name); if (entry.isDirectory()) { if (await pathContainsReportTemplatePlaceholder(entryPath)) { return true; } continue; } if ( !entry.isFile() || !reportRuntimeOutputExtensions.has(path.extname(entry.name)) ) { continue; } const content = await fs.readFile(entryPath, 'utf8'); if (unresolvedReportTemplatePattern.test(content)) { return true; } } return false; }; const BUILD_META_FILENAME = '.release-build-meta.json'; const BUILD_META_SCHEMA_VERSION = 1; const readBuildMeta = async (distDir) => { try { const raw = await fs.readFile( path.join(distDir, BUILD_META_FILENAME), 'utf8', ); const parsed = JSON.parse(raw); if ( typeof parsed === 'object' && parsed !== null && parsed.schemaVersion === BUILD_META_SCHEMA_VERSION && typeof parsed.nodeEnv === 'string' ) { return parsed; } return null; } catch { return null; } }; export const writeBuildMeta = async (packageDir, { nodeEnv }) => { const distDir = path.join(packageDir, 'dist'); try { await fs.mkdir(distDir, { recursive: true }); } catch { // dist may not exist for packages that still bundle only into a sibling // directory (e.g. preload/main split); skip marker in that case. return; } await fs.writeFile( path.join(distDir, BUILD_META_FILENAME), `${JSON.stringify( { schemaVersion: BUILD_META_SCHEMA_VERSION, nodeEnv }, null, 2, )}\n`, ); }; export const getBuildStatus = async ({ packageDir, sourceTargets, additionalSourceTargets = [], }) => { const distDir = path.join(packageDir, 'dist'); try { const distStats = await fs.stat(distDir); if (!distStats.isDirectory()) { return { needsBuild: true, reason: 'dist output is missing', }; } } catch (error) { if (error?.code === 'ENOENT') { return { needsBuild: true, reason: 'dist output is missing', }; } throw error; } // Reject caches from `pnpm dev` runs: they bake `NODE_ENV=development` // into rsbuild's `assetPrefix`, which produces absolute `/static/...` // paths that 404 under `file://` inside the packaged app and leave the // user with a white screen. Only a dist explicitly built in // production mode is safe to reuse for `package:release`. const meta = await readBuildMeta(distDir); if (!meta || meta.nodeEnv !== 'production') { return { needsBuild: true, reason: meta ? `previous build used NODE_ENV=${meta.nodeEnv}` : 'no production build marker', }; } const sourcePaths = [ ...sourceTargets.map((target) => path.join(packageDir, target)), ...additionalSourceTargets, ]; const latestSourceMtime = await Promise.all( sourcePaths.map((targetPath) => collectLatestMtime(targetPath)), ).then((mtimes) => Math.max(0, ...mtimes)); const latestDistMtime = await collectLatestMtime(distDir); if (latestSourceMtime > latestDistMtime) { return { needsBuild: true, reason: 'source files are newer than build output', }; } return { needsBuild: false, reason: 'up to date', }; }; const buildPackageDir = async (packageDir) => { await run(packageManagerCommand, ['--dir', packageDir, 'build'], { env: { ...process.env, NODE_ENV: 'production' }, }); await writeBuildMeta( path.isAbsolute(packageDir) ? packageDir : path.join(workspaceRootDir, packageDir), { nodeEnv: 'production' }, ); }; const ensureReportTemplateReady = async () => { let content; try { content = await fs.readFile(reportTemplatePath, 'utf8'); } catch (error) { if (error?.code === 'ENOENT') { throw new Error( `Expected report template to exist after build: ${reportTemplatePath}`, ); } throw error; } if (!content.trim()) { throw new Error(`Report template is empty: ${reportTemplatePath}`); } }; const prepareReportBuildOutput = async () => { let status = await getBuildStatus({ packageDir: reportRootDir, sourceTargets: reportBuildSourceTargets, }); if (!status.needsBuild) { try { const templateStats = await fs.stat(reportTemplatePath); if (!templateStats.isFile()) { status = { needsBuild: true, reason: 'report template output is missing', }; } } catch (error) { if (error?.code !== 'ENOENT') { throw error; } status = { needsBuild: true, reason: 'report template output is missing', }; } } if (status.needsBuild) { console.log(`Building apps/report (${status.reason}).`); // Report's type check includes tests, so prepare its development workspace // dependencies (including @midscene/test) through Nx before building it. await run( packageManagerCommand, ['exec', 'nx', 'build', '@midscene/report'], { env: { ...process.env, NODE_ENV: 'production' }, }, ); await writeBuildMeta(reportRootDir, { nodeEnv: 'production' }); } else { console.log(`Skipping apps/report build (${status.reason}).`); } await ensureReportTemplateReady(); }; const prepareStudioWorkspacePackages = async (workspacePackages) => { for (const workspacePackage of workspacePackages) { const status = await getBuildStatus({ packageDir: workspacePackage.packageDir, sourceTargets: packageBuildSourceTargets, }); if (!status.needsBuild) { console.log( `Skipping ${workspacePackage.relativeDir} (${status.reason}).`, ); continue; } console.log(`Building ${workspacePackage.relativeDir} (${status.reason}).`); await buildPackageDir(workspacePackage.relativeDir); } }; const prepareStudioBuildOutput = async ({ additionalSourceTargets = [], } = {}) => { let status = await getBuildStatus({ packageDir: studioRootDir, sourceTargets: studioBuildSourceTargets, additionalSourceTargets, }); const studioDistDir = path.join(studioRootDir, 'dist'); if ( !status.needsBuild && (await pathContainsReportTemplatePlaceholder(studioDistDir)) ) { status = { needsBuild: true, reason: 'report template placeholder remains in build output', }; } if (status.needsBuild) { console.log(`Building apps/studio (${status.reason}).`); await buildPackageDir(path.relative(workspaceRootDir, studioRootDir)); } else { console.log(`Skipping apps/studio build (${status.reason}).`); } if (await pathContainsReportTemplatePlaceholder(studioDistDir)) { throw new Error( `apps/studio build still contains ${reportTemplateMagicString}; rebuild apps/report before packaging.`, ); } }; const getStaticWorkspacePackageSourceConfig = (packageName) => staticWorkspacePackageSourceConfigs.find((config) => config.packageNames.includes(packageName), ) ?? null; const prepareStaticWorkspacePackageSources = async (workspacePackages) => { const requiredStaticConfigs = new Map(); for (const workspacePackage of workspacePackages) { const staticSourceConfig = getStaticWorkspacePackageSourceConfig( workspacePackage.name, ); if (!staticSourceConfig) { continue; } requiredStaticConfigs.set( staticSourceConfig.appRelativeDir, staticSourceConfig, ); } for (const staticSourceConfig of requiredStaticConfigs.values()) { const status = await getBuildStatus({ packageDir: staticSourceConfig.appDir, sourceTargets: playgroundAppBuildSourceTargets, }); if (!status.needsBuild) { console.log( `Skipping ${staticSourceConfig.appRelativeDir} (${status.reason}).`, ); continue; } console.log( `Building ${staticSourceConfig.appRelativeDir} (${status.reason}).`, ); await buildPackageDir(staticSourceConfig.appRelativeDir); } }; export const buildVendoredWorkspaceDirName = (packageName) => packageName.replace(/^@/, '').replace(/\//g, '-'); const buildResolvedWorkspaceDependencyVersions = ({ dependencies, workspacePackages, }) => { const resolvedDependencies = {}; const workspaceVersions = new Map( workspacePackages.map((workspacePackage) => [ workspacePackage.name, workspacePackage.packageJson.version, ]), ); for (const [dependencyName, dependencyVersion] of Object.entries( dependencies ?? {}, )) { if ( typeof dependencyVersion === 'string' && dependencyVersion.startsWith('workspace:') ) { const resolvedVersion = workspaceVersions.get(dependencyName); if (!resolvedVersion) { throw new Error( `Missing packaged workspace version for dependency "${dependencyName}".`, ); } resolvedDependencies[dependencyName] = resolvedVersion; continue; } resolvedDependencies[dependencyName] = dependencyVersion; } return resolvedDependencies; }; export const buildVendoredWorkspaceManifest = ({ packageJson, workspacePackages, }) => { const { devDependencies: _devDependencies, scripts: _scripts, ...vendoredManifest } = packageJson; for (const dependencyField of [ 'dependencies', 'optionalDependencies', 'peerDependencies', ]) { const resolvedDependencies = buildResolvedWorkspaceDependencyVersions({ dependencies: vendoredManifest[dependencyField], workspacePackages, }); if (Object.keys(resolvedDependencies).length === 0) { delete vendoredManifest[dependencyField]; continue; } vendoredManifest[dependencyField] = resolvedDependencies; } return vendoredManifest; }; const ensurePathExists = async (targetPath, { ignoreMissing = false } = {}) => { try { return await fs.stat(targetPath); } catch (error) { if (error?.code === 'ENOENT') { if (ignoreMissing) { return null; } throw new Error( `Expected packaging input to exist, but it is missing: ${targetPath}`, ); } throw error; } }; const copyRelativePath = async ({ sourcePath, destinationPath, ignoreMissing = false, }) => { const sourceStats = await ensurePathExists(sourcePath, { ignoreMissing }); if (!sourceStats) { return false; } await fs.mkdir(path.dirname(destinationPath), { recursive: true }); await fs.cp(sourcePath, destinationPath, { recursive: sourceStats.isDirectory(), }); return true; }; const copyStaticWorkspacePackageFiles = async ({ staticSourceConfig, destinationPath, }) => { await copyRelativePath({ sourcePath: staticSourceConfig.distDir, destinationPath, }); try { await fs.copyFile( staticSourceConfig.faviconPath, path.join(destinationPath, 'favicon.ico'), ); } catch (error) { if (error?.code !== 'ENOENT') { throw error; } } }; const collectPublishEntries = (packageJson) => { const publishEntries = new Set(packageJson.files ?? []); for (const binPath of Object.values(packageJson.bin ?? {})) { publishEntries.add(binPath); } publishEntries.delete('package.json'); return [...publishEntries]; }; export const pruneSourceMapFiles = async (rootDir) => { let entries; try { entries = await fs.readdir(rootDir, { withFileTypes: true }); } catch (error) { if (error?.code === 'ENOENT') { return; } throw error; } for (const entry of entries) { const entryPath = path.join(rootDir, entry.name); if (entry.isDirectory()) { await pruneSourceMapFiles(entryPath); continue; } if (entry.name.endsWith('.map')) { await fs.rm(entryPath, { force: true }); } } }; // Drops the antd UMD dist (antd*.js + maps + LICENSE.txt + reset.css). // Studio's renderer imports from `antd/es|lib`, so nothing references // `antd/dist/*` at packaged runtime. ~45 MB saved. export const pruneAntdUmdBundles = async (nodeModulesDir) => { const distDir = path.join(nodeModulesDir, 'antd', 'dist'); await removeIfExists(distDir); }; // The packaged Studio main process is CJS and resolves @midscene/* via // each package's `"main"` (./dist/lib/*). The ESM build at ./dist/es // is never loaded at runtime, so drop it. Renderer code is bundled by // rsbuild during the earlier build step, so it doesn't look at these // files either. ~65 MB saved across ~6 @midscene packages. export const dropMidsceneEsmBuilds = async (nodeModulesDir) => { const midsceneDir = path.join(nodeModulesDir, '@midscene'); let entries; try { entries = await fs.readdir(midsceneDir, { withFileTypes: true }); } catch (error) { if (error?.code === 'ENOENT') { return; } throw error; } for (const entry of entries) { if (!entry.isDirectory()) continue; const esDir = path.join(midsceneDir, entry.name, 'dist', 'es'); await removeIfExists(esDir); } }; // The packaged app never loads antd at runtime (renderer is bundled, // main.cjs never requires it). Dropping the ESM tree keeps the CJS // `lib/` available as a safety net for any transitive `require('antd')` // while reclaiming the second copy. ~8 MB saved. export const dropAntdEsmBuild = async (nodeModulesDir) => { const esDir = path.join(nodeModulesDir, 'antd', 'es'); await removeIfExists(esDir); }; // gifwrap ships PNG fixtures under test/ that are never used at runtime. // Leaving them in the app bundle makes Developer ID signing attempt to // timestamp-sign those images as nested resources, which fails. export const pruneGifwrapTestFixtures = async (nodeModulesDir) => { await removeIfExists(path.join(nodeModulesDir, 'gifwrap', 'test')); }; // Hardlink every file from `sourceDir` into `destDir`, recreating // subdirectories. Same filesystem required — safe inside a single // node_modules tree. const hardlinkTreeInto = async (sourceDir, destDir) => { await fs.mkdir(destDir, { recursive: true }); const entries = await fs.readdir(sourceDir, { withFileTypes: true }); for (const entry of entries) { const src = path.join(sourceDir, entry.name); const dest = path.join(destDir, entry.name); if (entry.isDirectory()) { await hardlinkTreeInto(src, dest); continue; } await fs.link(src, dest); } }; // `@midscene/{playground,ios,harmony}` all ship the same bundled web // playground as their `static/` directory (verified byte-identical tree // hash). Keep playground's copy as canonical and hardlink the ios/harmony // trees into it. ~36 MB of on-disk duplication reclaimed in the final // .app. (ditto's pkzip output still serializes each hardlinked file // independently, so the .zip size is mostly unaffected.) export const PLAYGROUND_STATIC_DEDUPE_GROUPS = [ { canonical: '@midscene/playground', aliases: ['@midscene/ios', '@midscene/harmony'], }, ]; export const dedupePlaygroundStatic = async (nodeModulesDir) => { for (const group of PLAYGROUND_STATIC_DEDUPE_GROUPS) { const canonicalStatic = path.join( nodeModulesDir, group.canonical, 'static', ); try { await fs.access(canonicalStatic); } catch { continue; } for (const alias of group.aliases) { const aliasStatic = path.join(nodeModulesDir, alias, 'static'); try { await fs.access(aliasStatic); } catch { continue; } await fs.rm(aliasStatic, { recursive: true, force: true }); await hardlinkTreeInto(canonicalStatic, aliasStatic); } } }; // Runs after `pnpm install --prod` populates the stage node_modules but // before `@electron/packager` copies it into the .app. Deletions here // propagate through the copy; hardlinks would be flattened into real // files, so the playground-static dedup has to wait until the .app exists. export const slimStageNodeModules = async (nodeModulesDir) => { await pruneSourceMapFiles(nodeModulesDir); await pruneAntdUmdBundles(nodeModulesDir); await dropMidsceneEsmBuilds(nodeModulesDir); await dropAntdEsmBuild(nodeModulesDir); await pruneGifwrapTestFixtures(nodeModulesDir); }; const vendorWorkspacePackages = async ({ workspacePackages, vendorDir }) => { await removeIfExists(vendorDir); await fs.mkdir(vendorDir, { recursive: true }); const vendoredWorkspacePackages = []; for (const workspacePackage of workspacePackages) { const vendorDirName = buildVendoredWorkspaceDirName(workspacePackage.name); const vendorPackageDir = path.join(vendorDir, vendorDirName); const staticSourceConfig = getStaticWorkspacePackageSourceConfig( workspacePackage.name, ); await removeIfExists(vendorPackageDir); await fs.mkdir(vendorPackageDir, { recursive: true }); for (const publishEntry of collectPublishEntries( workspacePackage.packageJson, )) { const destinationPath = path.join(vendorPackageDir, publishEntry); if (publishEntry === 'static' && staticSourceConfig) { await copyStaticWorkspacePackageFiles({ staticSourceConfig, destinationPath, }); continue; } await copyRelativePath({ sourcePath: path.join(workspacePackage.packageDir, publishEntry), destinationPath, ignoreMissing: true, }); } await pruneSourceMapFiles(vendorPackageDir); await fs.writeFile( path.join(vendorPackageDir, 'package.json'), `${JSON.stringify( buildVendoredWorkspaceManifest({ packageJson: workspacePackage.packageJson, workspacePackages, }), null, 2, )}\n`, ); vendoredWorkspacePackages.push({ ...workspacePackage, vendorDirName, }); } return vendoredWorkspacePackages; }; // `pnpm.supportedArchitectures` tells pnpm which platform/arch slices of // optional dependencies to materialize. Without it, cross-platform packaging // (e.g. building the Windows artifact on a macOS host) silently drops the // target's native binaries — most importantly `@img/sharp-win32-x64`, which // makes `import('sharp')` throw inside the packaged Windows Studio and forces // every image transform onto the WASM fallback. export const buildPnpmSupportedArchitectures = (platform, arch) => { if (!platform || !arch) { return undefined; } return { os: [platform], cpu: [arch], }; }; export const buildInstallWorkspaceManifest = ({ packageJson, version, vendoredWorkspacePackages, targetPlatform, targetArch, }) => { const dependencies = buildResolvedWorkspaceDependencyVersions({ dependencies: packageJson.dependencies, workspacePackages: vendoredWorkspacePackages, }); const optionalDependencies = buildResolvedWorkspaceDependencyVersions({ dependencies: packageJson.optionalDependencies, workspacePackages: vendoredWorkspacePackages, }); const overrides = Object.fromEntries( vendoredWorkspacePackages.map((workspacePackage) => [ workspacePackage.name, `file:vendor/${workspacePackage.vendorDirName}`, ]), ); const supportedArchitectures = buildPnpmSupportedArchitectures( targetPlatform, targetArch, ); return { ...buildPackagedAppManifest(packageJson, version, dependencies), ...(Object.keys(optionalDependencies).length > 0 ? { optionalDependencies } : {}), pnpm: { overrides, ...(supportedArchitectures ? { supportedArchitectures } : {}), }, }; }; const removeIfExists = async (targetPath) => { await fs.rm(targetPath, { force: true, recursive: true }); }; const resolveSymlinkTarget = (entryPath, targetPath) => path.isAbsolute(targetPath) ? targetPath : path.resolve(path.dirname(entryPath), targetPath); export const collectPackagedNodeModuleSymlinkIssues = async ( rootDir, issues = [], ) => { let entries; try { entries = await fs.readdir(rootDir, { withFileTypes: true }); } catch (error) { if (error?.code === 'ENOENT') { return issues; } throw error; } for (const entry of entries) { const entryPath = path.join(rootDir, entry.name); const stats = await fs.lstat(entryPath); if (stats.isSymbolicLink()) { const targetPath = await fs.readlink(entryPath); const resolvedTargetPath = resolveSymlinkTarget(entryPath, targetPath); const issue = { path: entryPath, target: targetPath, }; if (path.isAbsolute(targetPath)) { issues.push({ ...issue, reason: 'absolute', }); continue; } try { await fs.access(resolvedTargetPath); } catch (error) { if (error?.code === 'ENOENT') { issues.push({ ...issue, reason: 'broken', }); continue; } throw error; } continue; } if (stats.isDirectory()) { await collectPackagedNodeModuleSymlinkIssues(entryPath, issues); } } return issues; }; const buildPackagedAppPayloadCandidates = async (packagedAppPath) => { const candidates = [ path.join(packagedAppPath, 'Contents', 'Resources', 'app'), path.join(packagedAppPath, 'resources', 'app'), ]; let packagedOutputStats; try { packagedOutputStats = await fs.stat(packagedAppPath); } catch (error) { if (error?.code === 'ENOENT') { return candidates; } throw error; } if (!packagedOutputStats.isDirectory()) { return candidates; } const packagedOutputEntries = await fs.readdir(packagedAppPath, { withFileTypes: true, }); for (const entry of packagedOutputEntries) { if (!entry.isDirectory() || !entry.name.endsWith('.app')) { continue; } const nestedBundleRoot = path.join(packagedAppPath, entry.name); candidates.push( path.join(nestedBundleRoot, 'Contents', 'Resources', 'app'), path.join(nestedBundleRoot, 'resources', 'app'), ); } return [...new Set(candidates)]; }; export const buildPackagedResourcesCandidates = async (packagedAppPath) => { const candidates = [ path.join(packagedAppPath, 'Contents', 'Resources'), path.join(packagedAppPath, 'resources'), ]; let packagedOutputStats; try { packagedOutputStats = await fs.stat(packagedAppPath); } catch (error) { if (error?.code === 'ENOENT') { return candidates; } throw error; } if (!packagedOutputStats.isDirectory()) { return candidates; } const packagedOutputEntries = await fs.readdir(packagedAppPath, { withFileTypes: true, }); for (const entry of packagedOutputEntries) { if (!entry.isDirectory() || !entry.name.endsWith('.app')) { continue; } const nestedBundleRoot = path.join(packagedAppPath, entry.name); candidates.push( path.join(nestedBundleRoot, 'Contents', 'Resources'), path.join(nestedBundleRoot, 'resources'), ); } return [...new Set(candidates)]; }; export const resolveMacPackagedAppBundlePath = async (packagedAppPath) => { if (packagedAppPath.endsWith('.app')) { return packagedAppPath; } let packagedOutputStats; try { packagedOutputStats = await fs.stat(packagedAppPath); } catch (error) { if (error?.code === 'ENOENT') { throw new Error( `Packaged macOS output does not exist: ${packagedAppPath}`, ); } throw error; } if (!packagedOutputStats.isDirectory()) { throw new Error( `Expected a packaged macOS output directory, received ${packagedAppPath}.`, ); } const packagedOutputEntries = await fs.readdir(packagedAppPath, { withFileTypes: true, }); const appBundleEntries = packagedOutputEntries.filter( (entry) => entry.isDirectory() && entry.name.endsWith('.app'), ); if (appBundleEntries.length !== 1) { throw new Error( [ `Expected exactly one .app bundle inside ${packagedAppPath},`, `received ${appBundleEntries.length}.`, ].join(' '), ); } return path.join(packagedAppPath, appBundleEntries[0].name); }; const findPackagedAppPayloadDir = async (packagedAppPath) => { const candidates = await buildPackagedAppPayloadCandidates(packagedAppPath); for (const candidatePath of candidates) { try { const stats = await fs.stat(candidatePath); if (stats.isDirectory()) { return candidatePath; } } catch (error) { if (error?.code !== 'ENOENT') { throw error; } } } return null; }; const resolvePackagedResourcesDir = async (packagedAppPath) => { const candidates = await buildPackagedResourcesCandidates(packagedAppPath); for (const candidatePath of candidates) { try { const stats = await fs.stat(candidatePath); if (stats.isDirectory()) { return candidatePath; } } catch (error) { if (error?.code !== 'ENOENT') { throw error; } } } throw new Error( `Unable to locate the resources directory in packaged Midscene Studio app: ${packagedAppPath}`, ); }; const findPackagedNodeModulesDir = async (packagedAppPath) => { const packagedAppPayloadDir = await findPackagedAppPayloadDir(packagedAppPath); if (!packagedAppPayloadDir) { return null; } const packagedNodeModulesDir = path.join( packagedAppPayloadDir, 'node_modules', ); try { const stats = await fs.stat(packagedNodeModulesDir); if (stats.isDirectory()) { return packagedNodeModulesDir; } } catch (error) { if (error?.code !== 'ENOENT') { throw error; } } return null; }; export const assertPortablePackagedNodeModules = async (packagedAppPath) => { const packagedNodeModulesDir = await findPackagedNodeModulesDir(packagedAppPath); if (!packagedNodeModulesDir) { return; } const issues = await collectPackagedNodeModuleSymlinkIssues( packagedNodeModulesDir, ); if (issues.length === 0) { return; } const formattedIssues = issues .slice(0, 5) .map(({ path: issuePath, target, reason }) => { const relativeIssuePath = path.relative(packagedAppPath, issuePath); return `${relativeIssuePath} -> ${target} (${reason})`; }) .join('; '); throw new Error( `Packaged Midscene Studio app contains non-portable node_modules symlinks: ${formattedIssues}`, ); }; export const copyStudioFontLicenseToStageDir = async (stageDir) => { const destinationPath = path.join(stageDir, 'licenses', 'Inter-OFL.txt'); await fs.mkdir(path.dirname(destinationPath), { recursive: true }); await fs.copyFile(studioFontLicensePath, destinationPath); return destinationPath; }; const copyStudioBuildOutputToStageDir = async (stageDir) => { await fs.mkdir(stageDir, { recursive: true }); await fs.cp(path.join(studioRootDir, 'dist'), path.join(stageDir, 'dist'), { recursive: true, }); await copyStudioFontLicenseToStageDir(stageDir); }; const installStageDependencies = async (stageDir) => { await run( packageManagerCommand, [ 'install', '--prod', '--ignore-workspace', '--config.node-linker=hoisted', '--config.package-import-method=clone-or-copy', '--no-frozen-lockfile', ], { cwd: stageDir, }, ); }; const createPackagingWorkspace = async ({ stageDir, version, targetPlatform, targetArch, }) => { const studioPackageJson = getStudioPackageJson(); const workspacePackages = collectWorkspaceDependencyClosure( getStudioRuntimeWorkspaceDependencyNames(studioPackageJson), ); const vendorDir = path.join(stageDir, 'vendor'); await prepareStaticWorkspacePackageSources(workspacePackages); await prepareStudioWorkspacePackages(workspacePackages); await prepareReportBuildOutput(); validateCoreReportTemplateModules(coreDistDir); await prepareStudioBuildOutput({ additionalSourceTargets: [coreDistDir], }); await removeIfExists(stageDir); await fs.mkdir(path.dirname(stageDir), { recursive: true }); await copyStudioBuildOutputToStageDir(stageDir); const vendoredWorkspacePackages = await vendorWorkspacePackages({ workspacePackages, vendorDir, }); const installManifest = buildInstallWorkspaceManifest({ packageJson: studioPackageJson, version, vendoredWorkspacePackages, targetPlatform, targetArch, }); await fs.writeFile( path.join(stageDir, 'package.json'), `${JSON.stringify(installManifest, null, 2)}\n`, ); await installStageDependencies(stageDir); await slimStageNodeModules(path.join(stageDir, 'node_modules')); await removeIfExists(vendorDir); await removeIfExists(path.join(stageDir, 'pnpm-lock.yaml')); const packagedManifest = buildPackagedAppManifest( studioPackageJson, version, buildResolvedWorkspaceDependencyVersions({ dependencies: studioPackageJson.dependencies, workspacePackages, }), ); await fs.writeFile( path.join(stageDir, 'package.json'), `${JSON.stringify(packagedManifest, null, 2)}\n`, ); }; // `--sequesterRsrc` and `--keepParent` are load-bearing for macOS: they keep // extended attributes (where the notarization stapler ticket lives) and the // Electron `.app` framework symlinks intact through the zip round-trip. // Without them, Gatekeeper rejects the unzipped bundle with // "Apple cannot verify Midscene Studio.app". export const buildMacDittoArchiveArgs = ({ sourcePath, artifactPath }) => [ '-c', '-k', '--sequesterRsrc', '--keepParent', sourcePath, artifactPath, ]; const archiveWithDitto = async ({ sourcePath, artifactPath }) => { await run('ditto', buildMacDittoArchiveArgs({ sourcePath, artifactPath })); }; const archiveWithZip = async ({ sourcePath, artifactPath }) => { await run('zip', ['-qry', artifactPath, path.basename(sourcePath)], { cwd: path.dirname(sourcePath), }); }; const archiveWithPowerShell = async ({ sourcePath, artifactPath }) => { await run('powershell', [ '-NoProfile', '-Command', `Compress-Archive -Path '${sourcePath}' -DestinationPath '${artifactPath}' -Force`, ]); }; // Returns the archiver name selected for a given host platform. Exported so // regression tests can assert macOS always routes through `ditto` — anything // else (the generic zip used by `actions/upload-artifact`, `zip`, etc.) drops // xattrs and breaks the signed/notarized bundle. export const resolvePackagedAppArchiver = (hostPlatform) => { if (hostPlatform === 'darwin') { return 'ditto'; } if (hostPlatform === 'win32') { return 'powershell'; } return 'zip'; }; const archivePackagedApp = async ({ hostPlatform, sourcePath, artifactPath, }) => { await removeIfExists(artifactPath); await fs.mkdir(path.dirname(artifactPath), { recursive: true }); // macOS MUST go through ditto. Skipping archive (or substituting a generic // zip step like `actions/upload-artifact`'s internal compressor) strips the // stapled notarization ticket and breaks `_CodeSignature/CodeResources`, // causing Gatekeeper to refuse to launch the bundle after download. if (hostPlatform === 'darwin') { await archiveWithDitto({ sourcePath, artifactPath }); return artifactPath; } if (hostPlatform === 'win32') { await archiveWithPowerShell({ sourcePath, artifactPath }); return artifactPath; } await archiveWithZip({ sourcePath, artifactPath }); return artifactPath; }; export const signPackagedMacApp = async ({ appPath, security = resolveMacPackagedAppSecurity({ platform: 'darwin' }), } = {}) => { if (process.platform !== 'darwin') { throw new Error('macOS app signing requires a macOS host runner.'); } if (security.shouldDeveloperIdSign) { console.log( `Signing ${path.basename(appPath)} with ${security.signIdentity}.`, ); for (const target of await collectNestedMacCodeSignTargets(appPath)) { await run( 'codesign', buildDeveloperIdCodesignArgs({ entitlementsPath: resolveMacCodeSignEntitlementsPath(target), security, targetPath: target, }), ); } await run( 'codesign', buildDeveloperIdCodesignArgs({ entitlementsPath: resolveMacCodeSignEntitlementsPath(appPath), security, targetPath: appPath, }), ); await run('codesign', [ '--verify', '--deep', '--strict', '--verbose=2', appPath, ]); return 'developer-id'; } console.log( [ `No Developer ID identity configured for ${path.basename(appPath)}.`, 'Applying ad-hoc codesign so the Electron bundle remains runnable after packaging-time mutations.', ].join(' '), ); await run('codesign', [ '--force', '--deep', '--sign', '-', '--timestamp=none', appPath, ]); await run('codesign', [ '--verify', '--deep', '--strict', '--verbose=2', appPath, ]); return 'adhoc'; }; export const buildDeveloperIdCodesignArgs = ({ entitlementsPath, security, targetPath, useRuntime = true, }) => { const codesignArgs = ['--force', '--sign', security.signIdentity]; if (useRuntime) { codesignArgs.push('--options', 'runtime'); } codesignArgs.push('--timestamp'); if (security.signKeychain) { codesignArgs.push('--keychain', security.signKeychain); } if (entitlementsPath) { codesignArgs.push('--entitlements', entitlementsPath); } codesignArgs.push(targetPath); return codesignArgs; }; export const resolveMacCodeSignEntitlementsPath = (targetPath) => { if (targetPath.includes('(Plugin).app')) { return pluginMacEntitlementsPath; } if (targetPath.includes('(GPU).app')) { return gpuMacEntitlementsPath; } if (targetPath.includes('(Renderer).app')) { return rendererMacEntitlementsPath; } return defaultMacEntitlementsPath; }; const isMacMachOFile = async (filePath) => { const fileHandle = await fs.open(filePath, 'r'); try { const buffer = Buffer.alloc(4); const { bytesRead } = await fileHandle.read(buffer, 0, buffer.length, 0); return ( bytesRead === buffer.length && macMachOMagicHeaders.has(buffer.toString('hex')) ); } finally { await fileHandle.close(); } }; const isMacStandaloneCodeFile = async (filePath) => { const entryExt = path.extname(filePath).toLowerCase(); if (macStandaloneCodeFileExtensions.has(entryExt)) { return true; } return isMacMachOFile(filePath); }; const readUInt32ByEndian = (buffer, offset, endian) => endian === 'le' ? buffer.readUInt32LE(offset) : buffer.readUInt32BE(offset); const readMacCpuTypeName = (buffer, offset, endian) => { const cpuType = readUInt32ByEndian(buffer, offset, endian); return macCpuTypeNames.get(cpuType) ?? `unknown(${cpuType})`; }; export const readMacMachOArchitectures = async (filePath) => { const fileHandle = await fs.open(filePath, 'r'); try { const header = Buffer.alloc(8); const { bytesRead } = await fileHandle.read(header, 0, header.length, 0); if (bytesRead < header.length) { return []; } const magic = header.readUInt32BE(0); const thinEndian = macThinMachOMagic.get(magic); if (thinEndian) { return [readMacCpuTypeName(header, 4, thinEndian)]; } const fatHeader = macFatMachOMagic.get(magic); if (!fatHeader) { return []; } const archCount = readUInt32ByEndian(header, 4, fatHeader.endian); if (archCount < 1 || archCount > 512) { throw new Error( `Unexpected Mach-O architecture count ${archCount} in ${filePath}`, ); } const archBuffer = Buffer.alloc(archCount * fatHeader.archEntrySize); const archBytes = await fileHandle.read( archBuffer, 0, archBuffer.length, header.length, ); if (archBytes.bytesRead < archBuffer.length) { throw new Error(`Unable to read complete Mach-O fat header: ${filePath}`); } const archNames = []; for (let index = 0; index < archCount; index += 1) { archNames.push( readMacCpuTypeName( archBuffer, index * fatHeader.archEntrySize, fatHeader.endian, ), ); } return [...new Set(archNames)]; } finally { await fileHandle.close(); } }; export const collectMacNativeArchitectureIssues = async ({ appPath, arch }) => { const expectedArch = macTargetArchNames.get(arch); if (!expectedArch) { throw new Error(`Unsupported macOS package architecture "${arch}".`); } const issues = []; const visitDirectory = async (dirPath) => { const entries = await fs.readdir(dirPath, { withFileTypes: true }); for (const entry of entries) { if (entry.isSymbolicLink()) { continue; } const entryPath = path.join(dirPath, entry.name); if (entry.isDirectory()) { await visitDirectory(entryPath); continue; } if (!entry.isFile()) { continue; } const actualArchs = await readMacMachOArchitectures(entryPath); if (actualArchs.length > 0 && !actualArchs.includes(expectedArch)) { issues.push({ path: entryPath, expectedArch, actualArchs, }); } } }; await visitDirectory(appPath); return issues; }; export const assertMacNativeCodeArchitectures = async ({ appPath, arch }) => { const issues = await collectMacNativeArchitectureIssues({ appPath, arch }); if (issues.length === 0) { return; } const relativeIssues = issues .slice(0, 20) .map( (issue) => `- ${path.relative(appPath, issue.path)}: expected ${issue.expectedArch}, found ${issue.actualArchs.join(', ')}`, ); const remainingCount = issues.length - relativeIssues.length; if (remainingCount > 0) { relativeIssues.push(`- ...and ${remainingCount} more file(s)`); } throw new Error( [ `Packaged macOS app contains native code for the wrong architecture (${arch}).`, ...relativeIssues, ].join('\n'), ); }; export const collectNestedMacCodeSignTargets = async (appPath) => { const nestedBundles = []; const standaloneFiles = []; const visitDirectory = async (dirPath, isRoot = false) => { const entries = await fs.readdir(dirPath, { withFileTypes: true }); for (const entry of entries) { if (entry.isSymbolicLink()) { continue; } const entryPath = path.join(dirPath, entry.name); const entryExt = path.extname(entry.name); if (entry.isDirectory()) { const isNestedBundle = macNestedCodeBundleExtensions.has(entryExt); if (isNestedBundle && !isRoot) { nestedBundles.push(entryPath); } await visitDirectory(entryPath, false); continue; } if (entry.isFile() && (await isMacStandaloneCodeFile(entryPath))) { standaloneFiles.push(entryPath); } } }; await visitDirectory(appPath, true); const byDescendingDepth = (leftPath, rightPath) => rightPath.split(path.sep).length - leftPath.split(path.sep).length || leftPath.localeCompare(rightPath); standaloneFiles.sort(byDescendingDepth); nestedBundles.sort(byDescendingDepth); return [...standaloneFiles, ...nestedBundles]; }; /** * Build the appdmg specification for the Mac DMG. The layout drops the * signed `.app` on the left and a symlink to `/Applications` on the * right inside a 540×380 window — the standard "drag to install" * affordance that .zip downloads don't offer. */ export const dmgBackgroundPath = path.join( studioBuildDir, 'dmg-background.png', ); export const buildStudioDmgSpecification = ({ appBundlePath, iconPath, backgroundPath = dmgBackgroundPath, productName = packagedProductName, }) => ({ title: productName, ...(iconPath ? { icon: iconPath } : {}), ...(backgroundPath ? { background: backgroundPath } : {}), 'icon-size': 96, window: { size: { width: 540, height: 380 } }, contents: [ { x: 410, y: 160, type: 'link', path: '/Applications' }, { x: 130, y: 160, type: 'file', path: appBundlePath, name: path.basename(appBundlePath), }, ], format: 'ULFO', }); const resolvePackageEntry = (packageDir) => { const packageJsonPath = path.join(packageDir, 'package.json'); if (!existsSync(packageJsonPath)) { return undefined; } const packageManifest = JSON.parse(readFileSync(packageJsonPath, 'utf8')); return path.join(packageDir, packageManifest.main ?? 'index.js'); }; export const resolveNodeModulesPackageEntry = ({ packageName, workspaceRoot = workspaceRootDir, }) => { const packageDir = path.join( workspaceRoot, 'node_modules', ...packageName.split('/'), ); return resolvePackageEntry(packageDir); }; export const resolvePnpmPackageEntry = ({ packageName, version, workspaceRoot = workspaceRootDir, }) => { const pnpmStoreDir = path.join(workspaceRoot, 'node_modules', '.pnpm'); if (!existsSync(pnpmStoreDir)) { return undefined; } const storePackageName = packageName.replace('/', '+'); const storeEntryPrefix = `${storePackageName}@${version}`; const packagePathSegments = packageName.split('/'); for (const storeEntry of readdirSync(pnpmStoreDir).sort()) { if ( storeEntry !== storeEntryPrefix && !storeEntry.startsWith(`${storeEntryPrefix}_`) ) { continue; } const packageDir = path.join( pnpmStoreDir, storeEntry, 'node_modules', ...packagePathSegments, ); const packageEntry = resolvePackageEntry(packageDir); if (packageEntry) { return packageEntry; } } return undefined; }; export const loadAppDmg = async ({ directImport = () => import('appdmg'), workspaceRoot = workspaceRootDir, extraWorkspaceRoots = [], } = {}) => { try { const appdmgModule = await directImport(); return appdmgModule.default ?? appdmgModule; } catch (error) { if (error?.code !== 'ERR_MODULE_NOT_FOUND') { throw error; } const appdmgEntry = [workspaceRoot, ...extraWorkspaceRoots] .flatMap((root) => [ resolveNodeModulesPackageEntry({ packageName: 'appdmg', workspaceRoot: root, }), resolvePnpmPackageEntry({ packageName: 'appdmg', version: '0.6.6', workspaceRoot: root, }), ]) .find(Boolean); if (!appdmgEntry) { throw error; } const appdmgModule = await import(pathToFileURL(appdmgEntry).href); return appdmgModule.default ?? appdmgModule; } }; const runAppDmg = async ({ source, target, extraWorkspaceRoots = [] }) => { // `appdmg` (via `macos-alias`) loads a darwin-only native binding at // require time, so keep the import dynamic and gated to the darwin // packaging path. CI can have the package in pnpm's store without a // direct workspace symlink, so `loadAppDmg` falls back to that store path. const appdmg = await loadAppDmg({ extraWorkspaceRoots }); return new Promise((resolve, reject) => { const ee = appdmg({ source, target }); ee.on('progress', (info) => { if (info?.type === 'step-begin') { console.log(`dmg: ${info.title}`); } }); ee.on('error', reject); ee.on('finish', resolve); }); }; export const buildStudioDmgArtifact = async ({ appBundlePath, baseName, iconPath, security = resolveMacPackagedAppSecurity({ platform: 'darwin' }), stageDir, }) => { const dmgArtifactPath = path.join(artifactDir, `${baseName}.dmg`); await removeIfExists(dmgArtifactPath); await fs.mkdir(path.dirname(dmgArtifactPath), { recursive: true }); // appdmg 0.6.x only consumes a spec JSON from disk (it uses // `path.dirname(source)` to resolve any relative paths within the // spec). Drop the runtime-built specification into a sibling file — // we already use absolute paths so basepath resolution doesn't kick // in, but appdmg still requires `source` to exist. const specPath = path.join(artifactDir, `${baseName}.dmg.spec.json`); await fs.writeFile( specPath, `${JSON.stringify( buildStudioDmgSpecification({ appBundlePath, iconPath }), null, 2, )}\n`, ); try { await runAppDmg({ source: specPath, target: dmgArtifactPath, extraWorkspaceRoots: stageDir ? [stageDir] : [], }); } finally { await removeIfExists(specPath); } // Sign + (optionally) staple the DMG so Gatekeeper can verify the // notarization ticket offline. The wrapped .app inside is already // signed/notarized; signing the wrapper DMG just gives the disk // image its own Developer ID identity. Skip signing in ad-hoc mode. if (security.shouldDeveloperIdSign) { await run( 'codesign', buildDeveloperIdCodesignArgs({ entitlementsPath: undefined, security, targetPath: dmgArtifactPath, useRuntime: false, }), ); } if (security.shouldNotarize) { console.log( `Submitting ${path.basename(dmgArtifactPath)} for notarization.`, ); await notarizeMacArtifact({ appPath: dmgArtifactPath, ...security.notarizeOptions, }); } return dmgArtifactPath; }; export const notarizePackagedMacApp = async ({ appPath, security = resolveMacPackagedAppSecurity({ platform: 'darwin' }), } = {}) => { if (!security.shouldNotarize) { return false; } console.log(`Submitting ${path.basename(appPath)} for notarization.`); await notarizeMacArtifact({ appPath, ...security.notarizeOptions, }); return true; }; export const buildWindowsNsisInstaller = async ({ arch, baseName, packagedAppPath, }) => { // electron-builder's NSIS target only ships x64-compatible installers on // Windows; arm64 NSIS support is not yet stable upstream. The Studio // package-validation and release workflows also only exercise x64 for the // Windows matrix, so we guard here rather than let electron-builder fail // with a less clear error downstream. if (arch !== 'x64') { throw new Error( `Windows NSIS packaging only supports x64 for now, received "${arch}".`, ); } const artifactName = buildWindowsNsisArtifactName(baseName); const installerPath = path.join(artifactDir, artifactName); const configPath = path.join(artifactDir, `${baseName}.nsis.config.json`); await removeIfExists(installerPath); await removeIfExists(`${installerPath}.blockmap`); await fs.mkdir(artifactDir, { recursive: true }); await fs.writeFile( configPath, `${JSON.stringify( buildWindowsNsisConfig({ artifactName, iconPath: resolvePackagerIconPath('win32'), }), null, 2, )}\n`, ); try { await run( packageManagerCommand, buildWindowsNsisInstallerArgs({ arch, configPath, packagedAppPath, }), { cwd: studioRootDir }, ); } finally { await removeIfExists(configPath); } return installerPath; }; export const packageStudioElectronApp = async ({ version, platform = process.platform, arch = resolveDefaultPackageArch(platform, process.arch), } = {}) => { const normalizedVersion = normalizeReleaseVersion(version); const baseName = buildArtifactBaseName({ version: normalizedVersion, platform, arch, }); const stageDir = path.join(packagingWorkspaceDir, baseName); const macSecurity = resolveMacPackagedAppSecurity({ platform }); await createPackagingWorkspace({ stageDir, version: normalizedVersion, targetPlatform: platform, targetArch: arch, }); await removeIfExists(packagedDir); await fs.mkdir(packagedDir, { recursive: true }); const packagedAppPaths = await packager( buildPackagerOptions({ arch, outDir: packagedDir, platform, stageDir, }), ); if (packagedAppPaths.length !== 1) { throw new Error( `Expected one packaged app output, received ${packagedAppPaths.length}.`, ); } const packagedAppPath = packagedAppPaths[0]; const artifactPath = path.join(artifactDir, `${baseName}.zip`); const resourcesDir = await resolvePackagedResourcesDir(packagedAppPath); await Promise.all([ assertPortablePackagedNodeModules(packagedAppPath), assertPackagedExternalResourcesUnpacked(resourcesDir), ]); const packagedPayloadDir = await findPackagedAppPayloadDir(packagedAppPath); if (packagedPayloadDir) { await dedupePlaygroundStatic(path.join(packagedPayloadDir, 'node_modules')); } // app-update.yml lives next to the `app` payload (NOT inside it). // electron-updater reads it from `process.resourcesPath/app-update.yml` // at runtime to learn which provider / repo / cache dir to use. Must be // written before signing on macOS so it ends up inside the signed // bundle. await writeAppUpdateYmlIntoResources(resourcesDir); let dmgArtifactPath; if (platform === 'darwin') { const macAppBundlePath = await resolveMacPackagedAppBundlePath(packagedAppPath); await assertMacNativeCodeArchitectures({ appPath: macAppBundlePath, arch, }); await signPackagedMacApp({ appPath: macAppBundlePath, security: macSecurity, }); await notarizePackagedMacApp({ appPath: macAppBundlePath, security: macSecurity, }); // Wrap the signed/notarized .app in a DMG that ships a // drag-to-Applications layout. The .zip artifact below stays so // electron-updater can keep streaming the unwrapped bundle. dmgArtifactPath = await buildStudioDmgArtifact({ appBundlePath: macAppBundlePath, baseName, iconPath: resolvePackagerIconPath(platform), security: macSecurity, stageDir, }); } await archivePackagedApp({ hostPlatform: process.platform, sourcePath: packagedAppPath, artifactPath, }); let updaterArtifactPath = artifactPath; let windowsInstallerArtifactPath; if (platform === 'win32') { windowsInstallerArtifactPath = await buildWindowsNsisInstaller({ arch, baseName, packagedAppPath, }); updaterArtifactPath = windowsInstallerArtifactPath; } // Emit the electron-updater channel manifest (latest-*.yml + beta-*.yml // when the version is prerelease) so the GitHub Release surfaces the // sha512/size the autoUpdater needs to verify the matching update artifact. const updateMetadata = await writeUpdateMetadataForArtifact({ artifactPath: updaterArtifactPath, artifactDir, platform, version: normalizedVersion, }); console.log(`Packaged Midscene Studio archive: ${artifactPath}`); if (dmgArtifactPath) { console.log(`Packaged Midscene Studio dmg: ${dmgArtifactPath}`); } if (windowsInstallerArtifactPath) { console.log( `Packaged Midscene Studio Windows installer: ${windowsInstallerArtifactPath}`, ); } for (const ymlPath of updateMetadata.writtenPaths) { console.log(`Wrote updater manifest: ${ymlPath}`); } return artifactPath; }; const isDirectInvocation = process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href; if (isDirectInvocation) { const cliArgs = process.argv.slice(2).filter((arg) => arg !== '--'); const { values } = parseArgs({ args: cliArgs, allowPositionals: false, options: { arch: { type: 'string' }, platform: { type: 'string' }, version: { type: 'string' }, }, }); const version = values.version ?? JSON.parse( await fs.readFile(path.join(studioRootDir, 'package.json'), 'utf8'), ).version; await packageStudioElectronApp({ arch: values.arch, platform: values.platform, version, }); }