@stacksjs/buddy 0.75.648 → 0.75.652

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- import process from"node:process";import{intro,log,multiselect,onUnknownSubcommand,outro}from"@stacksjs/cli";import{Action}from"@stacksjs/enums";import{hasTTY,isCI}from"@stacksjs/env";import{projectPath}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";import{resultFailed}from"../result";let _runAction;async function runAction(...args){if(!_runAction)_runAction=(await import("@stacksjs/actions/run-action")).runAction;return _runAction(...args)}export function build(buddy){const descriptions={build:"Build any of your libraries (packages) for production use",components:"Build your component library",webComponents:"Build your framework agnostic web component library",elements:"An alias to the -w flag",buddy:"Build the Buddy binary",functions:"Build your function library",libs:"Build every package configured in config/library.ts",desktop:"Build the Desktop Application",mobile:"Build the native iOS and Android applications",android:"Build the native Android application",ios:"Build the native iOS application",dmg:"Package the desktop build as a macOS .app inside a .dmg",pages:"Build your frontend",docs:"Build your documentation",framework:"Build Stacks framework",cli:"Automagically build the CLI",server:"Build the Stacks cloud server (Docker image)",frontendStatic:"Build the prerendered marketing/public static site (storage/framework/frontend-dist)",select:"What are you trying to build?",project:"Target a specific project",verbose:"Enable verbose output"};buddy.command("build [type]",descriptions.build).option("-c, --components",descriptions.components).option("-w, --web-components",descriptions.webComponents).option("-e, --elements",descriptions.elements).option("-f, --functions",descriptions.functions).option("-l, --libs",descriptions.libs).option("-k, --desktop",descriptions.desktop).option("-m, --mobile",descriptions.mobile).option("--android",descriptions.android).option("--ios",descriptions.ios).option("-p, --views",descriptions.pages).option("--pages",descriptions.pages).option("-d, --docs",descriptions.docs).option("-b, --buddy",descriptions.buddy,{default:false}).option("-s, --stacks",descriptions.framework,{default:false}).option("--project [project]",descriptions.project,{default:false}).option("--server",descriptions.server,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(server,options)=>{log.debug("Running `buddy build` ...",options);applyBuildTarget(server,options);if(options.mobile){options.android=true;options.ios=true}if(hasNoOptions(options)){if(!isCI&&hasTTY&&process.stdin.isTTY){const answers=await multiselect({message:descriptions.select,choices:[{label:"Frontend (views)",value:"views"},{label:"Components",value:"components"},{label:"Web Components",value:"webComponents"},{label:"Functions",value:"functions"},{label:"All library packages",value:"libs"},{label:"Desktop application",value:"desktop"},{label:"Mobile applications (iOS + Android)",value:"mobile"},{label:"Android application",value:"android"},{label:"iOS application",value:"ios"},{label:"Documentation",value:"docs"},{label:"Stacks framework",value:"stacks"},{label:"Buddy CLI",value:"buddy"},{label:"Server (Docker image)",value:"server"}]});const selected=new Set(answers);if(selected.has("views"))options.views=true;if(selected.has("components"))options.components=true;if(selected.has("webComponents"))options.webComponents=true;if(selected.has("functions"))options.functions=true;if(selected.has("libs"))options.libs=true;if(selected.has("desktop"))options.desktop=true;if(selected.has("mobile")){options.mobile=true;options.android=true;options.ios=true}if(selected.has("android"))options.android=true;if(selected.has("ios"))options.ios=true;if(selected.has("docs"))options.docs=true;if(selected.has("stacks"))options.stacks=true;if(selected.has("buddy"))options.buddy=true;if(selected.has("server"))options.server=true}if(hasNoOptions(options)){options.views=true;log.info("No build target specified, defaulting to the frontend (views). See `buddy build --help` for all targets.")}}let succeeded=true;if(options.docs)succeeded=await runBuildAction(Action.BuildDocs,"documentation",options)&&succeeded;if(options.components)succeeded=await runBuildAction(Action.BuildComponentLibs,"component libraries",options)&&succeeded;if(options.webComponents)succeeded=await runBuildAction(Action.BuildWebComponentLib,"web component library",options)&&succeeded;if(options.functions)succeeded=await runBuildAction(Action.BuildFunctionLib,"function library",options)&&succeeded;if(options.libs)succeeded=await runBuildAction(Action.BuildLibs,"library packages",options)&&succeeded;if(options.desktop)succeeded=await runBuildAction(Action.BuildDesktop,"desktop application",options)&&succeeded;if(options.android)succeeded=await runBuildAction(Action.BuildAndroid,"Android application",options)&&succeeded;if(options.ios)succeeded=await runBuildAction(Action.BuildIos,"iOS application",options)&&succeeded;if(options.views)succeeded=await runBuildAction(Action.BuildViews,"frontend",options)&&succeeded;if(options.stacks)succeeded=await runBuildAction(Action.BuildStacks,"Stacks framework",options)&&succeeded;if(options.buddy)succeeded=await runBuildAction(Action.BuildCli,"Buddy CLI",options)&&succeeded;if(options.server)succeeded=await runBuildAction(Action.BuildServer,"server",options)&&succeeded;if(!succeeded)process.exit(ExitCode.FatalError);process.exit(ExitCode.Success)});buddy.command("build:components","Automagically build component libraries for production use & npm/CDN distribution").alias("prod:components").option("-c, --components",descriptions.components,{default:true}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:components` ...",options);if(!await runBuildAction(Action.BuildComponentLibs,"component libraries",options))process.exit(ExitCode.FatalError)});buddy.command("build:cli",descriptions.cli).alias("prod:cli").option("-b, --buddy",descriptions.buddy,{default:true}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:cli` ...",options);if(!await runBuildAction(Action.BuildCli,"Buddy CLI",options))process.exit(ExitCode.FatalError)});buddy.command("build:server",descriptions.server).alias("prod:server").alias("build:docker").option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:server` ...",options);if(!await runBuildAction(Action.BuildServer,"server",options))process.exit(ExitCode.FatalError)});buddy.command("build:functions","Automagically build function library for npm/CDN distribution").option("-f, --functions",descriptions.functions,{default:true}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:functions` ...",options);if(!await runBuildAction(Action.BuildFunctionLib,"function library",options))process.exit(ExitCode.FatalError)});buddy.command("build:libs",descriptions.libs).alias("build:libraries").alias("prod:libs").option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:libs` ...",options);if(!await runBuildAction(Action.BuildLibs,"library packages",options))process.exit(ExitCode.FatalError)});buddy.command("build:web-components","Automagically build Web Component library for npm/CDN distribution").alias("build:wc").alias("prod:web-components").alias("prod:wc").option("-w, --web-components",descriptions.webComponents,{default:true}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:web-components` ...",options);if(!await runBuildAction(Action.BuildWebComponentLib,"web component library",options))process.exit(ExitCode.FatalError)});buddy.command("build:frontend",descriptions.pages).alias("build:pages").alias("build:views").alias("prod:frontend").option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:frontend` ...",options);if(!await runBuildAction(Action.BuildViews,"frontend",options))process.exit(ExitCode.FatalError)});buddy.command("build:docs","Automagically build your documentation site.").alias("prod:docs").alias("build:documentation").alias("prod:documentation").option("-d, --docs",descriptions.docs,{default:true}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:docs` ...",options);if(!await runBuildAction(Action.BuildDocs,"documentation",options))process.exit(ExitCode.FatalError)});buddy.command("build:frontend-static",descriptions.frontendStatic).alias("build:public").alias("prod:frontend-static").option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:frontend-static` ...",options);if(!await runBuildAction(Action.BuildFrontendStatic,"static frontend",options))process.exit(ExitCode.FatalError)});buddy.command("build:core","Automagically build the Stacks core.").option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:core` ...",options);const startTime=await intro("buddy build:core");const result=await runAction(Action.BuildCore,options);if(resultFailed(result)){await log.error("Failed to build the Stacks core.",result.error);process.exit(ExitCode.FatalError)}await outro("Core packages built successfully",{startTime,useSeconds:true})});buddy.command("build:desktop",descriptions.desktop).alias("prod:desktop").option("--target <targets>","Web view app: comma-separated targets (darwin-arm64, linux-x64, win32-x64, ...) or all. Default: this machine").option("--package","Web view app: also make the installers this operating system can make (MSI on Windows; AppImage, deb, rpm on Linux)",{default:false}).option("--import <folder>","Web view app: add targets built on another machine (their output folder, with its build.json) to this build, checked against their recorded hashes").option("--identity <identity>","Web view app, macOS: the certificate to sign with (or DESKTOP_SIGNING_IDENTITY). A release needs a Developer ID Application certificate").option("--native","Build the AppKit app (`macos`) when the config also declares a web view app",{default:false}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:desktop` ...",options);const perf=await intro("buddy build:desktop");const{hasMacosDesktop,hasWebviewDesktop}=await import("@stacksjs/desktop-build");const webview=!options.native&&await hasWebviewDesktop(projectPath());if(webview){if(options.target)process.env.DESKTOP_TARGETS=options.target;if(options.package)process.env.DESKTOP_PACKAGE="1";if(options.import)process.env.DESKTOP_IMPORT=options.import;if(options.identity)process.env.DESKTOP_SIGNING_IDENTITY=options.identity}const result=await runAction(webview?Action.BuildDesktopWebview:await hasMacosDesktop(projectPath())?Action.BuildDesktopMacos:Action.BuildDesktop,options);if(resultFailed(result)){await outro("While running the build:desktop command, there was an issue",{startTime:perf,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}console.log("");await outro("Exited",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)});buddy.command("build:mobile",descriptions.mobile).alias("prod:mobile").option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:mobile` ...",options);const perf=await intro("buddy build:mobile");const androidSucceeded=await runBuildAction(Action.BuildAndroid,"Android application",options);const iosSucceeded=await runBuildAction(Action.BuildIos,"iOS application",options);if(!androidSucceeded||!iosSucceeded){await outro("One or more mobile application builds failed",{startTime:perf,useSeconds:true,type:"error"});process.exit(ExitCode.FatalError)}await outro("iOS and Android applications built",{startTime:perf,useSeconds:true})});buddy.command("build:android",descriptions.android).alias("prod:android").option("-p, --project [project]",descriptions.project,{default:false}).option("--bundle","Build a signed Android App Bundle (.aab) for Google Play (CRAFT_ANDROID_KEYSTORE and friends)",{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:android` ...",options);if(options.bundle)process.env.STACKS_ANDROID_BUNDLE="1";const perf=await intro("buddy build:android");const result=await runAction(Action.BuildAndroid,options);if(resultFailed(result)){await outro("While building the Android application, there was an issue",{startTime:perf,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}await outro("Android application built",{startTime:perf,useSeconds:true})});buddy.command("build:ios",descriptions.ios).alias("prod:ios").option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:ios` ...",options);const perf=await intro("buddy build:ios");const result=await runAction(Action.BuildIos,options);if(resultFailed(result)){await outro("While building the iOS application, there was an issue",{startTime:perf,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}await outro("iOS application built",{startTime:perf,useSeconds:true})});buddy.command("build:dmg",descriptions.dmg).option("--app-name <name>","Bundle display name (or DESKTOP_APP_NAME / APP_NAME)").option("--app-version <version>","Bundle version (or DESKTOP_APP_VERSION; defaults to the project's package.json)").option("--bundle-id <id>","Reverse-DNS bundle identifier (or DESKTOP_BUNDLE_ID)").option("--signing-identity <identity>","Developer ID identity to sign with (or DESKTOP_SIGNING_IDENTITY). An AppKit app (`macos`) is then built for direct distribution: not sandboxed, with its updater when it has `macos.updates`").option("--notary-profile <profile>","notarytool keychain profile to notarize and staple with (or DESKTOP_NOTARY_PROFILE)").option("--notarize","Notarize and staple with an App Store Connect API key (or DESKTOP_NOTARIZE)").option("--api-key-id <id>","App Store Connect API key ID (or APP_STORE_CONNECT_API_KEY_ID)").option("--api-issuer-id <id>","App Store Connect API issuer ID (or APP_STORE_CONNECT_API_ISSUER_ID)").option("--api-key-path <path>","The AuthKey_*.p8 file (or APP_STORE_CONNECT_API_KEY_PATH, or its PEM in APP_STORE_CONNECT_API_KEY)").option("--volume-name <name>","Name the mounted image shows (or DESKTOP_VOLUME_NAME)").option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:dmg` ...",options);const perf=await intro("buddy build:dmg");const{hasMacosDesktop}=await import("@stacksjs/desktop-build");const result=await runAction(await hasMacosDesktop(projectPath())?Action.BuildDmgMacos:Action.BuildDmg,options);if(resultFailed(result)){await outro("While running the build:dmg command, there was an issue",{startTime:perf,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}console.log("");await outro("Exited",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)});buddy.command("build:stacks","Build the Stacks framework.").option("-s, --stacks",descriptions.framework,{default:true}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:stacks` ...",options);const startTime=await intro("buddy build:stacks");const result=await runAction(Action.BuildStacks,options);if(resultFailed(result)){await log.error("Failed to build Stacks.",result.error);process.exit(ExitCode.FatalError)}await outro("Stacks built successfully",{startTime,useSeconds:true})});onUnknownSubcommand(buddy,"build")}function hasNoOptions(options){return!options.components&&!options.webComponents&&!options.elements&&!options.functions&&!options.libs&&!options.desktop&&!options.mobile&&!options.android&&!options.ios&&!options.views&&!options.docs&&!options.stacks&&!options.buddy&&!options.server}export function applyBuildTarget(target,options){switch(target){case"components":options.components=true;break;case"web-components":options.webComponents=true;break;case"functions":options.functions=true;break;case"libs":case"libraries":options.libs=true;break;case"desktop":options.desktop=true;break;case"mobile":options.mobile=true;options.android=true;options.ios=true;break;case"android":options.android=true;break;case"ios":options.ios=true;break;case"views":options.views=true;break;case"docs":options.docs=true;break;case"buddy":case"cli":options.buddy=true;break;case"stacks":options.stacks=true;break;case"server":options.server=true;break}}async function runBuildAction(action,target,options){const result=await runAction(action,options);if(resultFailed(result)){log.error(`Failed to build ${target}.`,result.error);return false}return true}
1
+ import{existsSync}from"node:fs";import process from"node:process";import{intro,log,multiselect,onUnknownSubcommand,outro}from"@stacksjs/cli";import{Action}from"@stacksjs/enums";import{hasTTY,isCI}from"@stacksjs/env";import{projectPath}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";import{resultFailed}from"../result";let _runAction;async function runAction(...args){if(!_runAction)_runAction=(await import("@stacksjs/actions/run-action")).runAction;return _runAction(...args)}async function configuredDesktopAction(native=false){if(!existsSync(projectPath("config/desktop.ts")))return;const{loadDesktopConfig}=await import("@stacksjs/desktop-build");const config=await loadDesktopConfig(projectPath());if(config?.webview&&!native)return{action:Action.BuildDesktopWebview};if(config?.macos)return{action:Action.BuildDesktopMacos};if(config?.launcher)return{action:Action.BuildDesktop,packageLauncher:process.platform==="darwin"}}async function runDesktopBuild(target,options){if(!await runBuildAction(target.action,"desktop application",options))return false;return!target.packageLauncher||await runBuildAction(Action.BuildDmg,"macOS installer",options)}export function build(buddy){const descriptions={build:"Build any of your libraries (packages) for production use",components:"Build your component library",webComponents:"Build your framework agnostic web component library",elements:"An alias to the -w flag",buddy:"Build the Buddy binary",functions:"Build your function library",libs:"Build every package configured in config/library.ts",desktop:"Build the Desktop Application",mobile:"Build the native iOS and Android applications",android:"Build the native Android application",ios:"Build the native iOS application",dmg:"Package the desktop build as a macOS .app inside a .dmg",pages:"Build your frontend",docs:"Build your documentation",framework:"Build Stacks framework",cli:"Automagically build the CLI",server:"Build the Stacks cloud server (Docker image)",frontendStatic:"Build the prerendered marketing/public static site (storage/framework/frontend-dist)",select:"What are you trying to build?",project:"Target a specific project",verbose:"Enable verbose output"};buddy.command("build [type]",descriptions.build).option("-c, --components",descriptions.components).option("-w, --web-components",descriptions.webComponents).option("-e, --elements",descriptions.elements).option("-f, --functions",descriptions.functions).option("-l, --libs",descriptions.libs).option("-k, --desktop",descriptions.desktop).option("-m, --mobile",descriptions.mobile).option("--android",descriptions.android).option("--ios",descriptions.ios).option("-p, --views",descriptions.pages).option("--pages",descriptions.pages).option("-d, --docs",descriptions.docs).option("-b, --buddy",descriptions.buddy,{default:false}).option("-s, --stacks",descriptions.framework,{default:false}).option("--project [project]",descriptions.project,{default:false}).option("--server",descriptions.server,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(server,options)=>{log.debug("Running `buddy build` ...",options);applyBuildTarget(server,options);if(options.mobile){options.android=true;options.ios=true}const defaultDesktop=hasNoOptions(options)?await configuredDesktopAction():undefined;if(defaultDesktop)options.desktop=true;if(hasNoOptions(options)){if(!isCI&&hasTTY&&process.stdin.isTTY){const answers=await multiselect({message:descriptions.select,choices:[{label:"Frontend (views)",value:"views"},{label:"Components",value:"components"},{label:"Web Components",value:"webComponents"},{label:"Functions",value:"functions"},{label:"All library packages",value:"libs"},{label:"Desktop application",value:"desktop"},{label:"Mobile applications (iOS + Android)",value:"mobile"},{label:"Android application",value:"android"},{label:"iOS application",value:"ios"},{label:"Documentation",value:"docs"},{label:"Stacks framework",value:"stacks"},{label:"Buddy CLI",value:"buddy"},{label:"Server (Docker image)",value:"server"}]});const selected=new Set(answers);if(selected.has("views"))options.views=true;if(selected.has("components"))options.components=true;if(selected.has("webComponents"))options.webComponents=true;if(selected.has("functions"))options.functions=true;if(selected.has("libs"))options.libs=true;if(selected.has("desktop"))options.desktop=true;if(selected.has("mobile")){options.mobile=true;options.android=true;options.ios=true}if(selected.has("android"))options.android=true;if(selected.has("ios"))options.ios=true;if(selected.has("docs"))options.docs=true;if(selected.has("stacks"))options.stacks=true;if(selected.has("buddy"))options.buddy=true;if(selected.has("server"))options.server=true}if(hasNoOptions(options)){options.views=true;log.info("No build target specified, defaulting to the frontend (views). See `buddy build --help` for all targets.")}}let succeeded=true;if(options.docs)succeeded=await runBuildAction(Action.BuildDocs,"documentation",options)&&succeeded;if(options.components)succeeded=await runBuildAction(Action.BuildComponentLibs,"component libraries",options)&&succeeded;if(options.webComponents)succeeded=await runBuildAction(Action.BuildWebComponentLib,"web component library",options)&&succeeded;if(options.functions)succeeded=await runBuildAction(Action.BuildFunctionLib,"function library",options)&&succeeded;if(options.libs)succeeded=await runBuildAction(Action.BuildLibs,"library packages",options)&&succeeded;if(options.desktop){const target=defaultDesktop??await configuredDesktopAction()??{action:Action.BuildDesktop};succeeded=await runDesktopBuild(target,options)&&succeeded}if(options.android)succeeded=await runBuildAction(Action.BuildAndroid,"Android application",options)&&succeeded;if(options.ios)succeeded=await runBuildAction(Action.BuildIos,"iOS application",options)&&succeeded;if(options.views)succeeded=await runBuildAction(Action.BuildViews,"frontend",options)&&succeeded;if(options.stacks)succeeded=await runBuildAction(Action.BuildStacks,"Stacks framework",options)&&succeeded;if(options.buddy)succeeded=await runBuildAction(Action.BuildCli,"Buddy CLI",options)&&succeeded;if(options.server)succeeded=await runBuildAction(Action.BuildServer,"server",options)&&succeeded;if(!succeeded)process.exit(ExitCode.FatalError);process.exit(ExitCode.Success)});buddy.command("build:components","Automagically build component libraries for production use & npm/CDN distribution").alias("prod:components").option("-c, --components",descriptions.components,{default:true}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:components` ...",options);if(!await runBuildAction(Action.BuildComponentLibs,"component libraries",options))process.exit(ExitCode.FatalError)});buddy.command("build:cli",descriptions.cli).alias("prod:cli").option("-b, --buddy",descriptions.buddy,{default:true}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:cli` ...",options);if(!await runBuildAction(Action.BuildCli,"Buddy CLI",options))process.exit(ExitCode.FatalError)});buddy.command("build:server",descriptions.server).alias("prod:server").alias("build:docker").option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:server` ...",options);if(!await runBuildAction(Action.BuildServer,"server",options))process.exit(ExitCode.FatalError)});buddy.command("build:functions","Automagically build function library for npm/CDN distribution").option("-f, --functions",descriptions.functions,{default:true}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:functions` ...",options);if(!await runBuildAction(Action.BuildFunctionLib,"function library",options))process.exit(ExitCode.FatalError)});buddy.command("build:libs",descriptions.libs).alias("build:libraries").alias("prod:libs").option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:libs` ...",options);if(!await runBuildAction(Action.BuildLibs,"library packages",options))process.exit(ExitCode.FatalError)});buddy.command("build:web-components","Automagically build Web Component library for npm/CDN distribution").alias("build:wc").alias("prod:web-components").alias("prod:wc").option("-w, --web-components",descriptions.webComponents,{default:true}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:web-components` ...",options);if(!await runBuildAction(Action.BuildWebComponentLib,"web component library",options))process.exit(ExitCode.FatalError)});buddy.command("build:frontend",descriptions.pages).alias("build:pages").alias("build:views").alias("prod:frontend").option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:frontend` ...",options);if(!await runBuildAction(Action.BuildViews,"frontend",options))process.exit(ExitCode.FatalError)});buddy.command("build:docs","Automagically build your documentation site.").alias("prod:docs").alias("build:documentation").alias("prod:documentation").option("-d, --docs",descriptions.docs,{default:true}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:docs` ...",options);if(!await runBuildAction(Action.BuildDocs,"documentation",options))process.exit(ExitCode.FatalError)});buddy.command("build:frontend-static",descriptions.frontendStatic).alias("build:public").alias("prod:frontend-static").option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:frontend-static` ...",options);if(!await runBuildAction(Action.BuildFrontendStatic,"static frontend",options))process.exit(ExitCode.FatalError)});buddy.command("build:core","Automagically build the Stacks core.").option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:core` ...",options);const startTime=await intro("buddy build:core");const result=await runAction(Action.BuildCore,options);if(resultFailed(result)){await log.error("Failed to build the Stacks core.",result.error);process.exit(ExitCode.FatalError)}await outro("Core packages built successfully",{startTime,useSeconds:true})});buddy.command("build:desktop",descriptions.desktop).alias("prod:desktop").option("--target <targets>","Web view app: comma-separated targets (darwin-arm64, linux-x64, win32-x64, ...) or all. Default: this machine").option("--package","Web view app: also make the installers this operating system can make (MSI on Windows; AppImage, deb, rpm on Linux)",{default:false}).option("--import <folder>","Web view app: add targets built on another machine (their output folder, with its build.json) to this build, checked against their recorded hashes").option("--identity <identity>","Web view app, macOS: the certificate to sign with (or DESKTOP_SIGNING_IDENTITY). A release needs a Developer ID Application certificate").option("--native","Build the AppKit app (`macos`) when the config also declares a web view app",{default:false}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:desktop` ...",options);const perf=await intro("buddy build:desktop");const target=await configuredDesktopAction(options.native)??{action:Action.BuildDesktop};if(target.action===Action.BuildDesktopWebview){if(options.target)process.env.DESKTOP_TARGETS=options.target;if(options.package)process.env.DESKTOP_PACKAGE="1";if(options.import)process.env.DESKTOP_IMPORT=options.import;if(options.identity)process.env.DESKTOP_SIGNING_IDENTITY=options.identity}const result=await runAction(target.action,options);if(resultFailed(result)){await outro("While running the build:desktop command, there was an issue",{startTime:perf,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}if(target.packageLauncher&&!await runBuildAction(Action.BuildDmg,"macOS installer",options))process.exit(ExitCode.FatalError);console.log("");await outro("Exited",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)});buddy.command("build:mobile",descriptions.mobile).alias("prod:mobile").option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:mobile` ...",options);const perf=await intro("buddy build:mobile");const androidSucceeded=await runBuildAction(Action.BuildAndroid,"Android application",options);const iosSucceeded=await runBuildAction(Action.BuildIos,"iOS application",options);if(!androidSucceeded||!iosSucceeded){await outro("One or more mobile application builds failed",{startTime:perf,useSeconds:true,type:"error"});process.exit(ExitCode.FatalError)}await outro("iOS and Android applications built",{startTime:perf,useSeconds:true})});buddy.command("build:android",descriptions.android).alias("prod:android").option("-p, --project [project]",descriptions.project,{default:false}).option("--bundle","Build a signed Android App Bundle (.aab) for Google Play (CRAFT_ANDROID_KEYSTORE and friends)",{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:android` ...",options);if(options.bundle)process.env.STACKS_ANDROID_BUNDLE="1";const perf=await intro("buddy build:android");const result=await runAction(Action.BuildAndroid,options);if(resultFailed(result)){await outro("While building the Android application, there was an issue",{startTime:perf,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}await outro("Android application built",{startTime:perf,useSeconds:true})});buddy.command("build:ios",descriptions.ios).alias("prod:ios").option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:ios` ...",options);const perf=await intro("buddy build:ios");const result=await runAction(Action.BuildIos,options);if(resultFailed(result)){await outro("While building the iOS application, there was an issue",{startTime:perf,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}await outro("iOS application built",{startTime:perf,useSeconds:true})});buddy.command("build:dmg",descriptions.dmg).option("--app-name <name>","Bundle display name (or DESKTOP_APP_NAME / APP_NAME)").option("--app-version <version>","Bundle version (or DESKTOP_APP_VERSION; defaults to the project's package.json)").option("--bundle-id <id>","Reverse-DNS bundle identifier (or DESKTOP_BUNDLE_ID)").option("--signing-identity <identity>","Developer ID identity to sign with (or DESKTOP_SIGNING_IDENTITY). An AppKit app (`macos`) is then built for direct distribution: not sandboxed, with its updater when it has `macos.updates`").option("--notary-profile <profile>","notarytool keychain profile to notarize and staple with (or DESKTOP_NOTARY_PROFILE)").option("--notarize","Notarize and staple with an App Store Connect API key (or DESKTOP_NOTARIZE)").option("--api-key-id <id>","App Store Connect API key ID (or APP_STORE_CONNECT_API_KEY_ID)").option("--api-issuer-id <id>","App Store Connect API issuer ID (or APP_STORE_CONNECT_API_ISSUER_ID)").option("--api-key-path <path>","The AuthKey_*.p8 file (or APP_STORE_CONNECT_API_KEY_PATH, or its PEM in APP_STORE_CONNECT_API_KEY)").option("--volume-name <name>","Name the mounted image shows (or DESKTOP_VOLUME_NAME)").option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:dmg` ...",options);const perf=await intro("buddy build:dmg");const{hasMacosDesktop}=await import("@stacksjs/desktop-build");const result=await runAction(await hasMacosDesktop(projectPath())?Action.BuildDmgMacos:Action.BuildDmg,options);if(resultFailed(result)){await outro("While running the build:dmg command, there was an issue",{startTime:perf,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}console.log("");await outro("Exited",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)});buddy.command("build:stacks","Build the Stacks framework.").option("-s, --stacks",descriptions.framework,{default:true}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:stacks` ...",options);const startTime=await intro("buddy build:stacks");const result=await runAction(Action.BuildStacks,options);if(resultFailed(result)){await log.error("Failed to build Stacks.",result.error);process.exit(ExitCode.FatalError)}await outro("Stacks built successfully",{startTime,useSeconds:true})});onUnknownSubcommand(buddy,"build")}function hasNoOptions(options){return!options.components&&!options.webComponents&&!options.elements&&!options.functions&&!options.libs&&!options.desktop&&!options.mobile&&!options.android&&!options.ios&&!options.views&&!options.docs&&!options.stacks&&!options.buddy&&!options.server}export function applyBuildTarget(target,options){switch(target){case"components":options.components=true;break;case"web-components":options.webComponents=true;break;case"functions":options.functions=true;break;case"libs":case"libraries":options.libs=true;break;case"desktop":options.desktop=true;break;case"mobile":options.mobile=true;options.android=true;options.ios=true;break;case"android":options.android=true;break;case"ios":options.ios=true;break;case"views":options.views=true;break;case"docs":options.docs=true;break;case"buddy":case"cli":options.buddy=true;break;case"stacks":options.stacks=true;break;case"server":options.server=true;break}}async function runBuildAction(action,target,options){const result=await runAction(action,options);if(resultFailed(result)){log.error(`Failed to build ${target}.`,result.error);return false}return true}
@@ -8,7 +8,7 @@ import type { SshTarget } from './deploy-ssh-target';
8
8
  export declare function installedTsCloudVersion(cliPath?: string): string | null;
9
9
  /** a >= b, for plain x.y.z versions. */
10
10
  export declare function versionAtLeast(a: string, b: string): boolean;
11
- export declare function resolveTsCloudCliPath(tsCloudEntry?: unknown): string;
11
+ export declare function resolveTsCloudCliPath(tsCloudEntry?: string, projectRoot?: ReturnType<typeof p.projectPath>): string;
12
12
  export declare function runDeployRollback(site: string | undefined, options: DeployRollbackOptions, execute?: (command: string[]) => Promise<number>, tsCloudVersion?: string | null): Promise<number>;
13
13
  /**
14
14
  * Load the `tsCloud` configuration object exported from `config/cloud.ts`.
@@ -1,4 +1,4 @@
1
- import{existsSync,mkdirSync,mkdtempSync,readFileSync,readdirSync,rmSync,statSync,writeFileSync}from"node:fs";import{homedir}from"node:os";import{dirname,isAbsolute,join,relative,resolve}from"node:path";import process from"node:process";import{missingQueueWorkerProblem}from"../deploy-queue-worker";import{pathToFileURL}from"node:url";import{runAction}from"@stacksjs/actions/run-action";import{assertPublicationAllowed}from"@stacksjs/actions/publication-preflight";import{runBeforeDeployHook}from"@stacksjs/actions/deploy/hooks";import{italic,onUnknownSubcommand,outro,prompts}from"@stacksjs/cli";import{app,dns as dnsConfig,email as emailConfig,security as securityConfig}from"@stacksjs/config";import{resolvePrivateTenants}from"../cloud-tenants";import{addDomain,hasUserDomainBeenAddedToCloud,syncDnsConfig}from"@stacksjs/dns";import{loadProjectDnsConfig}from"../config";import{env}from"@stacksjs/env";import{Action}from"@stacksjs/enums";import{path as p}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";import{getErrorMessage}from"@stacksjs/utils";import{withDeployNotification}from"../deploy-notify";import{deploymentIdentityConfig,withDeploymentIdentity}from"../deploy-identity";import{assertCurrentDeploymentRevision,assertNotBehindLiveRelease,automatedDeploymentRevision,liveReleasesCommand,SupersededDeploymentError}from"../deployment-revision";import{dnsCredentialFix,envFileForEnvironment,resolveZoneNameservers}from"../dns-credentials";import{assertComputeResidency}from"@stacksjs/ts-cloud";import{resultFailed}from"../result";import{deploymentRetirements,explicitDeploymentEnvFile,validateDeploymentProviderInputs}from"../deployment-inputs";import{findUnbackedManagedServices,hasOffsiteBackupDestination,unbackedDataMessage}from"../unbacked-data";import{applySecurityWaf}from"../waf-config";import{applyDeploymentDomainOverride,createDeploymentPreview,deploymentPreviewJsonPrefix,formatDeploymentPreview,resolveDeploymentEnvironment}from"./deploy-preview";import{buildPreviewTeardownScript,derivePreviewConfig,previewDomain,previewPort,previewTarget}from"./preview-deploy";import{deployTargetLabel,dnsHeld,dnsPublishingAllowed,hetznerTarget,isSshPipelineProvider,lanUrls,mergeSshStatePin,remoteExecOptions,resolveSshTarget,sshCliArgs,sshStatePin,toSshTarget}from"./deploy-ssh-target";const log={info:(...args)=>console.log("ℹ",...args),success:(...args)=>console.log("✓",...args),warn:(...args)=>console.log("⚠",...args),error:(...args)=>console.error("✗",...args),debug:(...args)=>{if(process.argv.includes("--verbose")||process.argv.includes("-v")){console.log("\uD83D\uDD0D",...args)}}};const MAIL_PACKAGE_DOMAIN="github.com/mail-os/mail";const MAIL_PACKAGE_SPEC=`${MAIL_PACKAGE_DOMAIN}@0.1.0`;const MAIL_TARGET_PLATFORM="linux-x86_64";const MAIL_BINARY_NAMES=["mail","mail-x86_64-linux","mail-x86_64-linux-gnu"];export const ROLLBACK_FLAGS_SINCE="0.16.34";export function installedTsCloudVersion(cliPath=resolveTsCloudCliPath()){try{const pkg=JSON.parse(readFileSync(resolve(dirname(cliPath),"..","..","package.json"),"utf8"));return typeof pkg.version==="string"?pkg.version:null}catch{return null}}export function versionAtLeast(a,b){const pa=a.split(".").map((n)=>Number.parseInt(n,10)||0);const pb=b.split(".").map((n)=>Number.parseInt(n,10)||0);for(let i=0;i<3;i++){if((pa[i]??0)!==(pb[i]??0))return(pa[i]??0)>(pb[i]??0)}return true}export function resolveTsCloudCliPath(tsCloudEntry=import.meta.resolve("@stacksjs/ts-cloud")){return resolve(dirname(new URL(tsCloudEntry).pathname),"bin/cli.js")}export async function runDeployRollback(site,options,execute=async(command)=>{const child=Bun.spawn(command,{cwd:p.projectPath(),env:process.env,stdin:"inherit",stdout:"inherit",stderr:"inherit"});return await child.exited},tsCloudVersion=installedTsCloudVersion()){const environment=resolveDeploymentEnvironment({option:options.env});const command=[process.execPath,resolveTsCloudCliPath(),"deploy:rollback"];const newFlags=[options.dryRun&&"--dry-run",options.all&&"--all",options.onlyIfLive&&"--only-if-live"].filter(Boolean);if(newFlags.length>0&&!(tsCloudVersion&&versionAtLeast(tsCloudVersion,ROLLBACK_FLAGS_SINCE))){log.error(`${newFlags.join(", ")} needs @stacksjs/ts-cloud ${ROLLBACK_FLAGS_SINCE} or newer (installed: ${tsCloudVersion??"unknown"}). An older one ignores it and rolls back for real.`);log.info(` ➡️ bun add @stacksjs/ts-cloud@^${ROLLBACK_FLAGS_SINCE}`);return ExitCode.InvalidArgument}if(site)command.push(site);command.push("--env",environment);if(options.to)command.push("--to",options.to);if(options.dryRun)command.push("--dry-run");if(options.all)command.push("--all");if(options.onlyIfLive)command.push("--only-if-live",options.onlyIfLive);if(options.verbose)command.push("--verbose");return await execute(command)}function collectMatchingFiles(root,names,maxDepth=8){const nameSet=new Set(names);const matches=[];if(!existsSync(root))return matches;function walk(dir,depth){if(depth>maxDepth)return;for(const entry of readdirSync(dir)){if(entry===".git"||entry==="node_modules")continue;const fullPath=join(dir,entry);const stat=statSync(fullPath);if(stat.isDirectory()){walk(fullPath,depth+1)}else if(stat.isFile()&&nameSet.has(entry)){matches.push(fullPath)}}}walk(root,0);return matches}function isElfBinary(filePath){const header=readFileSync(filePath).slice(0,4);return header[0]===127&&header[1]===69&&header[2]===76&&header[3]===70}function resolvePantryInstallCommand(){const localPantryCli=join(homedir(),"Code","Tools","pantry","packages","ts-pantry","bin","cli.ts");if(existsSync(localPantryCli)){return{command:"bun",args:[localPantryCli]}}const projectPantry=p.projectPath("pantry/.bin/pantry");if(existsSync(projectPantry)){return{command:projectPantry,args:[]}}const globalPantry=join(homedir(),".local","share","pantry","global","bin","pantry");if(existsSync(globalPantry)){return{command:globalPantry,args:[]}}return{command:"pantry",args:[]}}async function installMailBinaryWithPantry(){const{execFileSync}=await import("node:child_process");const pantry=resolvePantryInstallCommand();execFileSync(pantry.command,[...pantry.args,"install",MAIL_PACKAGE_SPEC,"--install-dir",p.projectPath("pantry"),"--platform",MAIL_TARGET_PLATFORM,"--quiet"],{cwd:p.projectPath(),stdio:process.argv.includes("--verbose")||process.argv.includes("-v")?"inherit":"pipe",env:process.env})}async function findPantryMailBinary(){const directCandidates=[...MAIL_BINARY_NAMES.map((name)=>p.projectPath(`pantry/.bin/${name}`)),...MAIL_BINARY_NAMES.map((name)=>join(homedir(),".local","share","pantry","global","bin",name))];for(const candidate of directCandidates){if(existsSync(candidate)&&isElfBinary(candidate))return candidate}for(const root of[p.projectPath("pantry"),join(homedir(),".local","share","pantry")]){for(const candidate of collectMatchingFiles(root,MAIL_BINARY_NAMES)){if(isElfBinary(candidate))return candidate}}return null}async function ensureDeployPrerequisites(verbose=false,environment="production",envFile){if(envFile){const values=await resolveDeployEnvValues(environment,undefined,envFile);if(!values.APP_KEY?.trim())throw new Error("The selected deployment environment requires APP_KEY");return}const{ensureAppKey,ensureDeployEnvIsSet,ensureEnvIsSet}=await import("./setup");const cwd=p.projectPath();await ensureEnvIsSet({cwd,verbose});await ensureDeployEnvIsSet(cwd,environment);await ensureAppKey(cwd)}function loadAwsCredentialsFromFile(){const credentialsPath=join(homedir(),".aws","credentials");const configPath=join(homedir(),".aws","config");if(!existsSync(credentialsPath)){return{}}try{const content=readFileSync(credentialsPath,"utf-8");const lines=content.split(`
1
+ import{existsSync,mkdirSync,mkdtempSync,readFileSync,readdirSync,rmSync,statSync,writeFileSync}from"node:fs";import{homedir}from"node:os";import{dirname,isAbsolute,join,relative,resolve}from"node:path";import process from"node:process";import{missingQueueWorkerProblem}from"../deploy-queue-worker";import{fileURLToPath,pathToFileURL}from"node:url";import{runAction}from"@stacksjs/actions/run-action";import{assertPublicationAllowed}from"@stacksjs/actions/publication-preflight";import{runBeforeDeployHook}from"@stacksjs/actions/deploy/hooks";import{italic,onUnknownSubcommand,outro,prompts}from"@stacksjs/cli";import{app,dns as dnsConfig,email as emailConfig,security as securityConfig}from"@stacksjs/config";import{resolvePrivateTenants}from"../cloud-tenants";import{addDomain,hasUserDomainBeenAddedToCloud,syncDnsConfig}from"@stacksjs/dns";import{loadProjectDnsConfig}from"../config";import{env}from"@stacksjs/env";import{Action}from"@stacksjs/enums";import{path as p}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";import{getErrorMessage}from"@stacksjs/utils";import{withDeployNotification}from"../deploy-notify";import{deploymentIdentityConfig,withDeploymentIdentity}from"../deploy-identity";import{assertCurrentDeploymentRevision,assertNotBehindLiveRelease,automatedDeploymentRevision,liveReleasesCommand,SupersededDeploymentError}from"../deployment-revision";import{dnsCredentialFix,envFileForEnvironment,resolveZoneNameservers}from"../dns-credentials";import{assertComputeResidency}from"@stacksjs/ts-cloud";import{resultFailed}from"../result";import{deploymentRetirements,explicitDeploymentEnvFile,validateDeploymentProviderInputs}from"../deployment-inputs";import{findUnbackedManagedServices,hasOffsiteBackupDestination,unbackedDataMessage}from"../unbacked-data";import{applySecurityWaf}from"../waf-config";import{applyDeploymentDomainOverride,createDeploymentPreview,deploymentPreviewJsonPrefix,formatDeploymentPreview,resolveDeploymentEnvironment}from"./deploy-preview";import{buildPreviewTeardownScript,derivePreviewConfig,previewDomain,previewPort,previewTarget}from"./preview-deploy";import{deployTargetLabel,dnsHeld,dnsPublishingAllowed,hetznerTarget,isSshPipelineProvider,lanUrls,mergeSshStatePin,remoteExecOptions,resolveSshTarget,sshCliArgs,sshStatePin,toSshTarget}from"./deploy-ssh-target";const log={info:(...args)=>console.log("ℹ",...args),success:(...args)=>console.log("✓",...args),warn:(...args)=>console.log("⚠",...args),error:(...args)=>console.error("✗",...args),debug:(...args)=>{if(process.argv.includes("--verbose")||process.argv.includes("-v")){console.log("\uD83D\uDD0D",...args)}}};const MAIL_PACKAGE_DOMAIN="github.com/mail-os/mail";const MAIL_PACKAGE_SPEC=`${MAIL_PACKAGE_DOMAIN}@0.1.0`;const MAIL_TARGET_PLATFORM="linux-x86_64";const MAIL_BINARY_NAMES=["mail","mail-x86_64-linux","mail-x86_64-linux-gnu"];export const ROLLBACK_FLAGS_SINCE="0.16.34";export function installedTsCloudVersion(cliPath=resolveTsCloudCliPath()){try{const pkg=JSON.parse(readFileSync(resolve(dirname(cliPath),"..","..","package.json"),"utf8"));return typeof pkg.version==="string"?pkg.version:null}catch{return null}}export function versionAtLeast(a,b){const pa=a.split(".").map((n)=>Number.parseInt(n,10)||0);const pb=b.split(".").map((n)=>Number.parseInt(n,10)||0);for(let i=0;i<3;i++){if((pa[i]??0)!==(pb[i]??0))return(pa[i]??0)>(pb[i]??0)}return true}export function resolveTsCloudCliPath(tsCloudEntry,projectRoot=p.projectPath()){const projectModule=tsCloudEntry?undefined:resolveProjectTsCloudModule(projectRoot);if(projectModule){const projectCli=resolve(dirname(projectModule),"bin/cli.js");if(existsSync(projectCli))return projectCli}const bundledModule=fileURLToPath(tsCloudEntry??import.meta.resolve("@stacksjs/ts-cloud"));return resolve(dirname(bundledModule),"bin/cli.js")}export async function runDeployRollback(site,options,execute=async(command)=>{const child=Bun.spawn(command,{cwd:p.projectPath(),env:process.env,stdin:"inherit",stdout:"inherit",stderr:"inherit"});return await child.exited},tsCloudVersion=installedTsCloudVersion()){const environment=resolveDeploymentEnvironment({option:options.env});const command=[process.execPath,resolveTsCloudCliPath(),"deploy:rollback"];const newFlags=[options.dryRun&&"--dry-run",options.all&&"--all",options.onlyIfLive&&"--only-if-live"].filter(Boolean);if(newFlags.length>0&&!(tsCloudVersion&&versionAtLeast(tsCloudVersion,ROLLBACK_FLAGS_SINCE))){log.error(`${newFlags.join(", ")} needs @stacksjs/ts-cloud ${ROLLBACK_FLAGS_SINCE} or newer (installed: ${tsCloudVersion??"unknown"}). An older one ignores it and rolls back for real.`);log.info(` ➡️ bun add @stacksjs/ts-cloud@^${ROLLBACK_FLAGS_SINCE}`);return ExitCode.InvalidArgument}if(site)command.push(site);command.push("--env",environment);if(options.to)command.push("--to",options.to);if(options.dryRun)command.push("--dry-run");if(options.all)command.push("--all");if(options.onlyIfLive)command.push("--only-if-live",options.onlyIfLive);if(options.verbose)command.push("--verbose");return await execute(command)}function collectMatchingFiles(root,names,maxDepth=8){const nameSet=new Set(names);const matches=[];if(!existsSync(root))return matches;function walk(dir,depth){if(depth>maxDepth)return;for(const entry of readdirSync(dir)){if(entry===".git"||entry==="node_modules")continue;const fullPath=join(dir,entry);const stat=statSync(fullPath);if(stat.isDirectory()){walk(fullPath,depth+1)}else if(stat.isFile()&&nameSet.has(entry)){matches.push(fullPath)}}}walk(root,0);return matches}function isElfBinary(filePath){const header=readFileSync(filePath).slice(0,4);return header[0]===127&&header[1]===69&&header[2]===76&&header[3]===70}function resolvePantryInstallCommand(){const localPantryCli=join(homedir(),"Code","Tools","pantry","packages","ts-pantry","bin","cli.ts");if(existsSync(localPantryCli)){return{command:"bun",args:[localPantryCli]}}const projectPantry=p.projectPath("pantry/.bin/pantry");if(existsSync(projectPantry)){return{command:projectPantry,args:[]}}const globalPantry=join(homedir(),".local","share","pantry","global","bin","pantry");if(existsSync(globalPantry)){return{command:globalPantry,args:[]}}return{command:"pantry",args:[]}}async function installMailBinaryWithPantry(){const{execFileSync}=await import("node:child_process");const pantry=resolvePantryInstallCommand();execFileSync(pantry.command,[...pantry.args,"install",MAIL_PACKAGE_SPEC,"--install-dir",p.projectPath("pantry"),"--platform",MAIL_TARGET_PLATFORM,"--quiet"],{cwd:p.projectPath(),stdio:process.argv.includes("--verbose")||process.argv.includes("-v")?"inherit":"pipe",env:process.env})}async function findPantryMailBinary(){const directCandidates=[...MAIL_BINARY_NAMES.map((name)=>p.projectPath(`pantry/.bin/${name}`)),...MAIL_BINARY_NAMES.map((name)=>join(homedir(),".local","share","pantry","global","bin",name))];for(const candidate of directCandidates){if(existsSync(candidate)&&isElfBinary(candidate))return candidate}for(const root of[p.projectPath("pantry"),join(homedir(),".local","share","pantry")]){for(const candidate of collectMatchingFiles(root,MAIL_BINARY_NAMES)){if(isElfBinary(candidate))return candidate}}return null}async function ensureDeployPrerequisites(verbose=false,environment="production",envFile){if(envFile){const values=await resolveDeployEnvValues(environment,undefined,envFile);if(!values.APP_KEY?.trim())throw new Error("The selected deployment environment requires APP_KEY");return}const{ensureAppKey,ensureDeployEnvIsSet,ensureEnvIsSet}=await import("./setup");const cwd=p.projectPath();await ensureEnvIsSet({cwd,verbose});await ensureDeployEnvIsSet(cwd,environment);await ensureAppKey(cwd)}function loadAwsCredentialsFromFile(){const credentialsPath=join(homedir(),".aws","credentials");const configPath=join(homedir(),".aws","config");if(!existsSync(credentialsPath)){return{}}try{const content=readFileSync(credentialsPath,"utf-8");const lines=content.split(`
2
2
  `);const profiles=["default","stacks"];let currentProfile="";let credentials={};const profileCredentials={};for(const line of lines){const trimmed=line.trim();const profileMatch=trimmed.match(/^\[(.+)\]$/);if(profileMatch?.[1]){currentProfile=profileMatch[1];profileCredentials[currentProfile]={};continue}const keyValue=trimmed.match(/^(\w+)\s*=\s*(.+)$/);if(keyValue&&currentProfile){const[,key,value]=keyValue;const target=profileCredentials[currentProfile];if(!target||value===undefined)continue;if(key==="aws_access_key_id"){target.accessKeyId=value}else if(key==="aws_secret_access_key"){target.secretAccessKey=value}}}for(const profile of profiles){if(profileCredentials[profile]?.accessKeyId&&profileCredentials[profile]?.secretAccessKey){credentials=profileCredentials[profile];log.debug(`Using AWS credentials from ~/.aws/credentials [${profile}] profile`);break}}if(!credentials.accessKeyId){for(const[profile,creds]of Object.entries(profileCredentials)){if(creds.accessKeyId&&creds.secretAccessKey){credentials=creds;log.debug(`Using AWS credentials from ~/.aws/credentials [${profile}] profile`);break}}}let region;if(existsSync(configPath)){const configContent=readFileSync(configPath,"utf-8");const regionMatch=configContent.match(/region\s*=\s*(.+)/);if(regionMatch?.[1]){region=regionMatch[1].trim()}}return{...credentials,region}}catch(error){log.debug("Failed to read AWS credentials file:",error);return{}}}async function setupEmailDnsRecords(emailDomain,region,logger,options){logger.info("Setting up email DNS records...");try{const{SESClient}=await import("@stacksjs/ts-cloud");const{Route53Client}=await import("@stacksjs/ts-cloud");const ses=new SESClient(region);const route53=new Route53Client(region);logger.info(`Getting DKIM tokens for ${emailDomain}...`);const identity=await ses.getEmailIdentity(emailDomain);const tokens=identity.DkimAttributes?.Tokens||[];if(tokens.length===0){logger.warn("No DKIM tokens found - domain may not be set up in SES yet");return}logger.info(`Found ${tokens.length} DKIM tokens`);const zones=await route53.listHostedZones();const zone=zones.HostedZones?.find((z)=>z.Name===`${emailDomain}.`);if(!zone){logger.warn(`Hosted zone not found for ${emailDomain} - DNS records must be added manually`);logger.info("DKIM records needed:");for(const token of tokens){logger.info(` CNAME: ${token}._domainkey.${emailDomain} -> ${token}.dkim.amazonses.com`)}logger.info(` MX: ${emailDomain} -> 10 inbound-smtp.${region}.amazonaws.com`);return}const hostedZoneId=zone.Id?.replace("/hostedzone/","");logger.info(`Found hosted zone: ${hostedZoneId}`);for(const token of tokens){const recordName=`${token}._domainkey.${emailDomain}`;const recordValue=`${token}.dkim.amazonses.com`;try{await route53.changeResourceRecordSets({HostedZoneId:hostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:recordName,Type:"CNAME",TTL:300,ResourceRecords:[{Value:recordValue}]}}]}});logger.success(`Added DKIM record: ${token}._domainkey`)}catch(e){logger.warn(`Failed to add DKIM record: ${getErrorMessage(e)}`)}}const mailSubdomain=options?.mailSubdomain||"mail";const mxTarget=options?.mode==="server"?`10 ${mailSubdomain}.${emailDomain}`:`10 inbound-smtp.${region}.amazonaws.com`;try{await route53.changeResourceRecordSets({HostedZoneId:hostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:emailDomain,Type:"MX",TTL:300,ResourceRecords:[{Value:mxTarget}]}}]}});logger.success(`Added MX record: ${mxTarget}`)}catch(e){logger.warn(`Failed to add MX record: ${getErrorMessage(e)}`)}try{await route53.changeResourceRecordSets({HostedZoneId:hostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:emailDomain,Type:"TXT",TTL:300,ResourceRecords:[{Value:'"v=spf1 include:amazonses.com ~all"'}]}}]}});logger.success("Added SPF record")}catch(e){logger.warn(`Failed to add SPF record: ${getErrorMessage(e)}`)}try{await route53.changeResourceRecordSets({HostedZoneId:hostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:`_dmarc.${emailDomain}`,Type:"TXT",TTL:300,ResourceRecords:[{Value:`"v=DMARC1;p=quarantine;pct=25;rua=mailto:dmarcreports@${emailDomain}"`}]}}]}});logger.success("Added DMARC record")}catch(e){logger.warn(`Failed to add DMARC record: ${getErrorMessage(e)}`)}try{const appName=process.env.APP_NAME?.toLowerCase().replace(/[^a-z0-9]/g,"-")||"stacks";const ruleSetName=`${appName}-email-rules`;await ses.setActiveReceiptRuleSet(ruleSetName);logger.success(`Activated email receipt rule set: ${ruleSetName}`)}catch(e){logger.warn(`Failed to activate receipt rule set: ${getErrorMessage(e)}`)}logger.success("Email DNS records configured!");logger.info("Note: DKIM verification may take 5-15 minutes to complete")}catch(error){logger.warn(`Failed to set up email DNS records: ${getErrorMessage(error)}`);logger.info("You can manually set up DNS records using: buddy email:verify")}}async function createDefaultMailUser(appName,emailDomain,region,logger){try{const{DynamoDBClient}=await import("@stacksjs/ts-cloud");const crypto=await import("crypto");const dynamodb=new DynamoDBClient(region);const tableName=`${appName}-mail-users`;const mailboxes=emailConfig?.mailboxes||[];if(mailboxes.length===0){const defaultEmail=`admin@${emailDomain}`;const defaultPassword=crypto.randomBytes(16).toString("hex");const passwordHash=crypto.createHash("sha256").update(defaultPassword).digest("hex");try{await dynamodb.putItem({TableName:tableName,Item:{email:{S:defaultEmail},passwordHash:{S:passwordHash},createdAt:{S:new Date().toISOString()},displayName:{S:"Admin"}}});logger.success(`Created default mail user: ${defaultEmail}`);logger.info(`Password: ${defaultPassword}`);logger.info("Save this password - it will not be shown again!")}catch(e){const msg=getErrorMessage(e);if(msg.includes("ConditionalCheckFailedException")||msg.includes("already exists")){logger.debug("Default mail user already exists")}else{throw e}}}else{for(const mailbox of mailboxes){const mb=typeof mailbox==="object"&&mailbox!==null?mailbox:null;const configured=mb?.email;const email=mb?configured?.includes("@")?configured:`${configured??""}@${emailDomain}`:`${mailbox}@${emailDomain}`;const password=mb?.password?mb.password:crypto.randomBytes(16).toString("hex");const passwordHash=crypto.createHash("sha256").update(password).digest("hex");try{await dynamodb.putItem({TableName:tableName,Item:{email:{S:email},passwordHash:{S:passwordHash},createdAt:{S:new Date().toISOString()},displayName:{S:mb?mb.displayName||email:String(mailbox)}}});logger.success(`Created mail user: ${email}`);if(!mb?.password){logger.info(` Password: ${password}`)}}catch(e){const msg=getErrorMessage(e);if(msg.includes("ConditionalCheckFailedException")){logger.debug(`Mail user ${email} already exists`)}else{logger.warn(`Failed to create mail user ${email}: ${msg}`)}}}}}catch(error){logger.warn(`Failed to create mail users: ${getErrorMessage(error)}`)}}async function uploadMailServerToS3(bucketName,region,mode){try{const{S3Client:S3}=await import("@stacksjs/ts-cloud");const s3Client=new S3(region);if(mode==="serverless"){const serverTsPath=p.frameworkPath("core/mail-server/server.ts");if(existsSync(serverTsPath)){const serverCode=readFileSync(serverTsPath,"utf-8");await s3Client.putObject({bucket:bucketName,key:"mail-server/server.ts",body:serverCode,contentType:"text/typescript"});log.success("Uploaded serverless mail server code to S3")}const pkgPath=p.frameworkPath("core/mail-server/package.json");if(existsSync(pkgPath)){const pkgJson=readFileSync(pkgPath,"utf-8");await s3Client.putObject({bucket:bucketName,key:"mail-server/package.json",body:pkgJson,contentType:"application/json"})}return}let binaryUploaded=false;try{await installMailBinaryWithPantry();const linuxBinaryPath=await findPantryMailBinary();if(linuxBinaryPath&&existsSync(linuxBinaryPath)&&isElfBinary(linuxBinaryPath)){log.info(`Uploading Pantry mail binary: ${linuxBinaryPath}`);const binaryContent=readFileSync(linuxBinaryPath);await s3Client.putObject({bucket:bucketName,key:"mail-server/smtp-server",body:binaryContent,contentType:"application/octet-stream"});log.success("Uploaded Linux x86_64 mail server binary to S3");binaryUploaded=true}}catch(error){log.debug(`Pantry mail install failed: ${getErrorMessage(error)}`)}if(!binaryUploaded){log.warn(`No Pantry-provided ${MAIL_TARGET_PLATFORM} mail binary found. Release ${MAIL_PACKAGE_DOMAIN}, then run the Pantry binary sync for that package.`)}}catch(uploadErr){log.debug(`Could not upload mail server to S3 (bucket may not exist yet): ${uploadErr.message}`)}}export async function loadTsCloudConfig(envName){try{const base=p.projectPath("config/cloud.ts");const spec=envName?`${base}?env=${envName}`:base;const mod=await import(spec);const applied=applySecurityWaf(mod.tsCloud,securityConfig?.waf,resolveProvider(mod.tsCloud));for(const warning of applied.warnings)log.warn(warning);return applied.config}catch(err){log.debug("Could not load config/cloud.ts tsCloud export:",err);return}}export function resolveProvider(tsCloudConfig){return tsCloudConfig?.cloud?.provider||process.env.CLOUD_PROVIDER||"aws"}function readWaitSecs(name,defaultSecs){const secs=process.env[name]?Number.parseInt(process.env[name],10):Number.NaN;return Number.isFinite(secs)&&secs>0?secs:defaultSecs}function fmtDuration(secs){const m=Math.floor(secs/60);const s=secs%60;return m?s?`${m}m${s}s`:`${m}m`:`${s}s`}export function pollFailureDetail(error){const raw=error instanceof Error?error.message:typeof error==="string"?error:"";const collapsed=raw.replace(/\s+/g," ").trim();if(!collapsed)return;return collapsed.length>300?`${collapsed.slice(0,297)}...`:collapsed}export function sshUnreachableMessage(opts){const detail=pollFailureDetail(opts.lastError);return`SSH did not become reachable on ${opts.ip} within ${fmtDuration(opts.waitSecs)} (waited ${opts.elapsedSecs}s).`+(detail?`
3
3
  Last attempt: ${detail}`:"")+`
4
4
  A connection timeout means the box is probably still booting, so raise TS_CLOUD_SSH_WAIT_SECS and retry. "Permission denied" means the key is not authorized, and a refused or reset connection (especially after earlier attempts got further) usually means fail2ban banned this IP. Waiting longer fixes neither.`}export function bunRuntimeMissingMessage(opts){const detail=pollFailureDetail(opts.lastError);return`bun runtime did not appear at /usr/local/bin/bun within ${fmtDuration(opts.waitSecs)} (waited ${opts.elapsedSecs}s).`+(detail?`
@@ -1,4 +1,4 @@
1
- import type { CLI } from '@stacksjs/types';
1
+ import type { CLI, DesktopLauncherConfig } from '@stacksjs/types';
2
2
  import type { ResolvedMacosDesktop } from '@stacksjs/desktop-build';
3
3
  /**
4
4
  * Flags, then the environment, then `config/desktop.ts` (`macos`), then the
@@ -6,7 +6,7 @@ import type { ResolvedMacosDesktop } from '@stacksjs/desktop-build';
6
6
  * needs the Apple variables for what is not secret: the name, bundle id, team,
7
7
  * version, category and icon.
8
8
  */
9
- export declare function resolveAppleDesktopConfig(options?: AppleDesktopOptions, native?: ResolvedMacosDesktop | null): AppleDesktopConfig;
9
+ export declare function resolveAppleDesktopConfig(options?: AppleDesktopOptions, native?: ResolvedMacosDesktop | null, launcher?: DesktopLauncherConfig): AppleDesktopConfig;
10
10
  /**
11
11
  * The App Store Connect key as a `.p8` file, from `APP_STORE_CONNECT_API_KEY`
12
12
  * when no path was given.
@@ -47,8 +47,8 @@ export declare function isAppleCategory(value: string): boolean;
47
47
  * `paths` are relative to the `.app` directory, POSIX-separated.
48
48
  */
49
49
  export declare function storeRejectionFindings(paths: readonly string[], executable?: string): string[];
50
- export declare function renderInfoPlist(config: AppleDesktopConfig, executable?: string): string;
51
- export declare function renderAppEntitlements(config: AppleDesktopConfig): string;
50
+ export declare function renderInfoPlist(config: AppleDesktopConfig, executable?: string, extra?: string): string;
51
+ export declare function renderAppEntitlements(config: AppleDesktopConfig, local?: DesktopLauncherConfig['appStore'], sandboxCheck?: boolean): string;
52
52
  export declare function renderHelperEntitlements(): string;
53
53
  export declare function renderAppleWorkflowCaller(): string;
54
54
  /**
@@ -114,6 +114,7 @@ export declare function parseDistributionIdentities(output: string, teamId: stri
114
114
  * needs no Apple variables beyond the App Store Connect key.
115
115
  */
116
116
  export declare function withKeychainIdentities(config: AppleDesktopConfig, read?: (keychain?: string) => string): AppleDesktopConfig;
117
+ export declare function unsupportedMacosTarget(loadCommands: string, minimumMacos: string): string | undefined;
117
118
  /**
118
119
  * What a failure prints, as a value.
119
120
  *
@@ -146,6 +147,7 @@ declare interface AppleDesktopOptions {
146
147
  apiKeyPath?: string
147
148
  icon?: string
148
149
  skipBuild?: boolean
150
+ sandboxCheck?: boolean
149
151
  validateOnly?: boolean
150
152
  packageOnly?: boolean
151
153
  plan?: boolean
@@ -1,6 +1,6 @@
1
- import{createHash}from"node:crypto";import{chmodSync,copyFileSync,existsSync,mkdirSync,mkdtempSync,readdirSync,readFileSync,rmSync,writeFileSync}from"node:fs";import{tmpdir}from"node:os";import{basename,join,resolve}from"node:path";import process from"node:process";import{log}from"@stacksjs/cli";import{projectPath,storagePath}from"@stacksjs/path";import{resultFailed}from"../result";const REQUIRED_TOOLS=["codesign","security","productbuild","pkgutil","xcrun"];function env(name){return process.env[name]?.trim()||""}function xml(value){return value.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&apos;")}async function nativeAppleConfig(){const{loadMacosDesktop}=await import("@stacksjs/desktop-build");return loadMacosDesktop(projectPath(),packageMetadata().version)}function packageMetadata(){const packageJson=JSON.parse(readFileSync(projectPath("package.json"),"utf8"));return{name:packageJson.name||"Stacks",version:packageJson.version||"0.1.0"}}export function resolveAppleDesktopConfig(options={},native){const metadata=packageMetadata();const provisioningProfile=options.provisioningProfile||env("APPLE_PROVISIONING_PROFILE");const apiKeyPath=options.apiKeyPath||env("APP_STORE_CONNECT_API_KEY_PATH");const craftArm64=options.craftArm64||env("CRAFT_BIN_ARM64");const craftX64=options.craftX64||env("CRAFT_BIN_X64");const keychain=options.keychain||env("APPLE_KEYCHAIN");return{appName:options.appName||env("APPLE_APP_NAME")||native?.appName||env("APP_NAME")||metadata.name,bundleId:options.bundleId||env("APPLE_BUNDLE_ID")||native?.bundleId||"",teamId:options.teamId||env("APPLE_TEAM_ID")||native?.teamId||"",version:options.appVersion||env("APPLE_APP_VERSION")||native?.version||metadata.version,buildNumber:options.buildNumber||env("APPLE_BUILD_NUMBER")||(native?native.buildNumber:"")||env("GITHUB_RUN_NUMBER")||String(Math.floor(Date.now()/1000)),minimumMacos:options.minimumMacos||env("APPLE_MINIMUM_MACOS")||native?.minimumSystemVersion||"13.0",category:options.category||env("APPLE_APP_CATEGORY")||native?.category||"public.app-category.productivity",appSigningIdentity:options.appSigningIdentity||env("APPLE_APP_SIGNING_IDENTITY"),installerSigningIdentity:options.installerSigningIdentity||env("APPLE_INSTALLER_SIGNING_IDENTITY"),provisioningProfile:provisioningProfile?resolve(provisioningProfile):"",apiKeyId:options.apiKeyId||env("APP_STORE_CONNECT_API_KEY_ID"),apiIssuerId:options.apiIssuerId||env("APP_STORE_CONNECT_API_ISSUER_ID"),apiKeyPath:apiKeyPath?resolve(apiKeyPath):"",icon:options.icon||env("APPLE_APP_ICON")||(native?.icon?resolve(projectPath(),native.icon):undefined),universal:Boolean(options.universal)||env("APPLE_UNIVERSAL")==="true",craftArm64:craftArm64?resolve(craftArm64):undefined,craftX64:craftX64?resolve(craftX64):undefined,keychain:keychain?resolve(keychain):undefined}}export function withApiKeyFile(config){const pem=env("APP_STORE_CONNECT_API_KEY").replaceAll("\\n",`
1
+ import{createHash}from"node:crypto";import{chmodSync,copyFileSync,cpSync,existsSync,mkdirSync,mkdtempSync,readdirSync,readFileSync,rmSync,writeFileSync}from"node:fs";import{tmpdir}from"node:os";import{basename,dirname,join,resolve}from"node:path";import process from"node:process";import{log}from"@stacksjs/cli";import{projectPath,storagePath}from"@stacksjs/path";import{resultFailed}from"../result";const REQUIRED_TOOLS=["codesign","security","productbuild","pkgutil","xcrun"];function env(name){return process.env[name]?.trim()||""}function xml(value){return value.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&apos;")}async function nativeAppleConfig(){const{loadMacosDesktop}=await import("@stacksjs/desktop-build");return loadMacosDesktop(projectPath(),packageMetadata().version)}function packageMetadata(){const packageJson=JSON.parse(readFileSync(projectPath("package.json"),"utf8"));return{name:packageJson.name||"Stacks",version:packageJson.version||"0.1.0"}}export function resolveAppleDesktopConfig(options={},native,launcher){const metadata=packageMetadata();const provisioningProfile=options.provisioningProfile||env("APPLE_PROVISIONING_PROFILE");const apiKeyPath=options.apiKeyPath||env("APP_STORE_CONNECT_API_KEY_PATH");const craftArm64=options.craftArm64||env("CRAFT_BIN_ARM64");const craftX64=options.craftX64||env("CRAFT_BIN_X64");const keychain=options.keychain||env("APPLE_KEYCHAIN");return{appName:options.appName||env("APPLE_APP_NAME")||native?.appName||launcher?.appName||env("APP_NAME")||metadata.name,bundleId:options.bundleId||env("APPLE_BUNDLE_ID")||native?.bundleId||launcher?.bundleId||"",teamId:options.teamId||env("APPLE_TEAM_ID")||native?.teamId||launcher?.appStore?.teamId||"",version:options.appVersion||env("APPLE_APP_VERSION")||native?.version||launcher?.appStore?.version||metadata.version,buildNumber:options.buildNumber||env("APPLE_BUILD_NUMBER")||(native?native.buildNumber:"")||env("GITHUB_RUN_NUMBER")||String(Math.floor(Date.now()/1000)),minimumMacos:options.minimumMacos||env("APPLE_MINIMUM_MACOS")||native?.minimumSystemVersion||launcher?.appStore?.minimumSystemVersion||"13.0",category:options.category||env("APPLE_APP_CATEGORY")||native?.category||launcher?.appStore?.category||"public.app-category.productivity",appSigningIdentity:options.appSigningIdentity||env("APPLE_APP_SIGNING_IDENTITY"),installerSigningIdentity:options.installerSigningIdentity||env("APPLE_INSTALLER_SIGNING_IDENTITY"),provisioningProfile:provisioningProfile?resolve(provisioningProfile):"",apiKeyId:options.apiKeyId||env("APP_STORE_CONNECT_API_KEY_ID"),apiIssuerId:options.apiIssuerId||env("APP_STORE_CONNECT_API_ISSUER_ID"),apiKeyPath:apiKeyPath?resolve(apiKeyPath):"",icon:options.icon||env("APPLE_APP_ICON")||(native?.icon?projectPath(native.icon):launcher?.appStore?.icon?projectPath(launcher.appStore.icon):undefined),universal:Boolean(options.universal)||env("APPLE_UNIVERSAL")==="true",craftArm64:craftArm64?resolve(craftArm64):undefined,craftX64:craftX64?resolve(craftX64):undefined,keychain:keychain?resolve(keychain):undefined}}export function withApiKeyFile(config){const pem=env("APP_STORE_CONNECT_API_KEY").replaceAll("\\n",`
2
2
  `);if(config.apiKeyPath||!pem||!config.apiKeyId)return config;if(!pem.includes("-----BEGIN PRIVATE KEY-----"))throw new Error("APP_STORE_CONNECT_API_KEY must hold the PEM text of the .p8 key");const directory=mkdtempSync(join(tmpdir(),"apple-api-key-"));const apiKeyPath=join(directory,`AuthKey_${config.apiKeyId}.p8`);writeFileSync(apiKeyPath,`${pem}
3
- `,{mode:384});process.on("exit",()=>rmSync(directory,{recursive:true,force:true}));return{...config,apiKeyPath}}export function validateAppleDesktopConfig(config,includeApi=true){const errors=[];if(process.platform!=="darwin")errors.push("Mac App Store packaging must run on macOS");if(!config.appName)errors.push("APPLE_APP_NAME or --app-name is required");if(!/^[A-Za-z0-9][A-Za-z0-9.-]+$/.test(config.bundleId))errors.push("APPLE_BUNDLE_ID must be a reverse-DNS bundle identifier");if(!/^[A-Z0-9]{10}$/.test(config.teamId))errors.push("APPLE_TEAM_ID must be the 10-character Apple Developer team ID");if(!/^\d+(?:\.\d+){0,2}$/.test(config.version))errors.push("The marketing version must contain one to three numeric components");if(!/^[A-Za-z0-9.-]+$/.test(config.buildNumber))errors.push("The build number must contain only letters, numbers, periods, and hyphens");if(config.buildNumber==="next")errors.push("--build-number next is resolved by desktop:apple:publish; give desktop:apple:package a number");if(!config.appSigningIdentity)errors.push("APPLE_APP_SIGNING_IDENTITY is required");if(!config.installerSigningIdentity)errors.push("APPLE_INSTALLER_SIGNING_IDENTITY is required");if(!config.provisioningProfile||!existsSync(config.provisioningProfile))errors.push("APPLE_PROVISIONING_PROFILE must point to an existing .provisionprofile file");if(config.icon&&!existsSync(resolve(config.icon)))errors.push(`Apple app icon does not exist: ${config.icon}`);if(!/^\d+(?:\.\d+){0,2}$/.test(config.minimumMacos))errors.push("APPLE_MINIMUM_MACOS must be a macOS version such as 13.0");if(!isAppleCategory(config.category))errors.push("APPLE_APP_CATEGORY must be an Apple LSApplicationCategoryType such as public.app-category.productivity");if(includeApi){if(!config.apiKeyId)errors.push("APP_STORE_CONNECT_API_KEY_ID is required");if(!config.apiIssuerId)errors.push("APP_STORE_CONNECT_API_ISSUER_ID is required");if(!config.apiKeyPath||!existsSync(config.apiKeyPath))errors.push("APP_STORE_CONNECT_API_KEY_PATH must point to an existing .p8 file, or APP_STORE_CONNECT_API_KEY hold its text")}if(config.universal){for(const[variable,path]of[["CRAFT_BIN_ARM64",config.craftArm64],["CRAFT_BIN_X64",config.craftX64]]){if(!path||!existsSync(path))errors.push(`${variable} must point to a native Craft runtime for a universal build`);else if(readFileSync(path).subarray(0,2).toString()==="#!")errors.push(`${variable} points at a script, not a native Craft runtime: ${path}`)}}for(const tool of config.universal?[...REQUIRED_TOOLS,"lipo"]:REQUIRED_TOOLS){if(!Bun.which(tool))errors.push(`Required Apple command is unavailable: ${tool}`)}return errors}function bundleFiles(appPath){const walk=(dir,prefix)=>readdirSync(dir,{withFileTypes:true}).flatMap((entry)=>{const relative=prefix?`${prefix}/${entry.name}`:entry.name;return entry.isDirectory()?walk(join(dir,entry.name),relative):[relative]});return walk(appPath,"")}export function isAppleCategory(value){return/^public\.app-category\.[a-z][a-z0-9-]*$/.test(value)}export function storeRejectionFindings(paths,executable="stacks-desktop"){const findings=[];const has=(path)=>paths.includes(path);for(const required of["Contents/Info.plist",`Contents/MacOS/${executable}`,"Contents/embedded.provisionprofile"]){if(!has(required))findings.push(`missing required bundle file: ${required}`)}for(const path of paths){const base=path.split("/").pop()??"";if(base===".DS_Store"||path.startsWith("__MACOSX/")||base.startsWith("._"))findings.push(`forbidden file in the bundle: ${path}`);if(/\.(?:dylib|so|framework|app|xpc)$/.test(path)){const allowed=path.startsWith("Contents/Frameworks/")||path.startsWith("Contents/MacOS/")||path.startsWith("Contents/XPCServices/")||path.startsWith("Contents/PlugIns/");if(!allowed)findings.push(`nested code outside a signed location: ${path}`)}if(path.startsWith("Contents/Resources/")&&/\.(?:sh|command|dylib|so)$/.test(path))findings.push(`executable content under Resources: ${path}`)}return findings}export function renderInfoPlist(config,executable="stacks-desktop"){const iconEntry=config.icon?`
3
+ `,{mode:384});process.on("exit",()=>rmSync(directory,{recursive:true,force:true}));return{...config,apiKeyPath}}export function validateAppleDesktopConfig(config,includeApi=true){const errors=[];if(process.platform!=="darwin")errors.push("Mac App Store packaging must run on macOS");if(!config.appName)errors.push("APPLE_APP_NAME or --app-name is required");if(!/^[A-Za-z0-9][A-Za-z0-9.-]+$/.test(config.bundleId))errors.push("APPLE_BUNDLE_ID must be a reverse-DNS bundle identifier");if(!/^[A-Z0-9]{10}$/.test(config.teamId))errors.push("APPLE_TEAM_ID must be the 10-character Apple Developer team ID");if(!/^\d+(?:\.\d+){0,2}$/.test(config.version))errors.push("The marketing version must contain one to three numeric components");if(!/^[A-Za-z0-9.-]+$/.test(config.buildNumber))errors.push("The build number must contain only letters, numbers, periods, and hyphens");if(config.buildNumber==="next")errors.push("--build-number next is resolved by desktop:apple:publish; give desktop:apple:package a number");if(!config.appSigningIdentity)errors.push("APPLE_APP_SIGNING_IDENTITY is required");if(!config.installerSigningIdentity)errors.push("APPLE_INSTALLER_SIGNING_IDENTITY is required");if(!config.provisioningProfile||!existsSync(config.provisioningProfile))errors.push("APPLE_PROVISIONING_PROFILE must point to an existing .provisionprofile file");if(config.icon&&!existsSync(resolve(config.icon)))errors.push(`Apple app icon does not exist: ${config.icon}`);if(!/^\d+(?:\.\d+){0,2}$/.test(config.minimumMacos))errors.push("APPLE_MINIMUM_MACOS must be a macOS version such as 13.0");if(!isAppleCategory(config.category))errors.push("APPLE_APP_CATEGORY must be an Apple LSApplicationCategoryType such as public.app-category.productivity");if(includeApi){if(!config.apiKeyId)errors.push("APP_STORE_CONNECT_API_KEY_ID is required");if(!config.apiIssuerId)errors.push("APP_STORE_CONNECT_API_ISSUER_ID is required");if(!config.apiKeyPath||!existsSync(config.apiKeyPath))errors.push("APP_STORE_CONNECT_API_KEY_PATH must point to an existing .p8 file, or APP_STORE_CONNECT_API_KEY hold its text")}if(config.universal){for(const[variable,path]of[["CRAFT_BIN_ARM64",config.craftArm64],["CRAFT_BIN_X64",config.craftX64]]){if(!path||!existsSync(path))errors.push(`${variable} must point to a native Craft runtime for a universal build`);else if(readFileSync(path).subarray(0,2).toString()==="#!")errors.push(`${variable} points at a script, not a native Craft runtime: ${path}`)}}for(const tool of config.universal?[...REQUIRED_TOOLS,"lipo"]:REQUIRED_TOOLS){if(!Bun.which(tool))errors.push(`Required Apple command is unavailable: ${tool}`)}return errors}function bundleFiles(appPath){const walk=(dir,prefix)=>readdirSync(dir,{withFileTypes:true}).flatMap((entry)=>{const relative=prefix?`${prefix}/${entry.name}`:entry.name;return entry.isDirectory()?walk(join(dir,entry.name),relative):[relative]});return walk(appPath,"")}export function isAppleCategory(value){return/^public\.app-category\.[a-z][a-z0-9-]*$/.test(value)}export function storeRejectionFindings(paths,executable="stacks-desktop"){const findings=[];const has=(path)=>paths.includes(path);for(const required of["Contents/Info.plist",`Contents/MacOS/${executable}`,"Contents/embedded.provisionprofile"]){if(!has(required))findings.push(`missing required bundle file: ${required}`)}for(const path of paths){const base=path.split("/").pop()??"";if(base===".DS_Store"||path.startsWith("__MACOSX/")||base.startsWith("._"))findings.push(`forbidden file in the bundle: ${path}`);if(/\.(?:dylib|so|framework|app|xpc)$/.test(path)){const allowed=path.startsWith("Contents/Frameworks/")||path.startsWith("Contents/MacOS/")||path.startsWith("Contents/XPCServices/")||path.startsWith("Contents/PlugIns/");if(!allowed)findings.push(`nested code outside a signed location: ${path}`)}if(path.startsWith("Contents/Resources/")&&/\.(?:sh|command|dylib|so)$/.test(path))findings.push(`executable content under Resources: ${path}`)}return findings}export function renderInfoPlist(config,executable="stacks-desktop",extra=""){const iconEntry=config.icon?`
4
4
  <key>CFBundleIconFile</key>
5
5
  <string>AppIcon</string>`:"";return`<?xml version="1.0" encoding="UTF-8"?>
6
6
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "https://www.apple.com/DTDs/PropertyList-1.0.dtd">
@@ -27,21 +27,25 @@ import{createHash}from"node:crypto";import{chmodSync,copyFileSync,existsSync,mkd
27
27
  <key>LSMinimumSystemVersion</key>
28
28
  <string>${xml(config.minimumMacos)}</string>${iconEntry}
29
29
  <key>NSHighResolutionCapable</key>
30
- <true/>
30
+ <true/>${extra}
31
31
  </dict>
32
32
  </plist>
33
- `}export function renderAppEntitlements(config){return`<?xml version="1.0" encoding="UTF-8"?>
34
- <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "https://www.apple.com/DTDs/PropertyList-1.0.dtd">
35
- <plist version="1.0">
36
- <dict>
33
+ `}export function renderAppEntitlements(config,local,sandboxCheck=false){const networkServer=local?.networkServer?`
34
+ <key>com.apple.security.network.server</key>
35
+ <true/>`:"";const fileAccess=local?.userSelectedFiles?`
36
+ <key>com.apple.security.files.user-selected.read-write</key>
37
+ <true/>`:"";const identity=sandboxCheck?"":`
37
38
  <key>com.apple.application-identifier</key>
38
39
  <string>${xml(config.teamId)}.${xml(config.bundleId)}</string>
39
40
  <key>com.apple.developer.team-identifier</key>
40
- <string>${xml(config.teamId)}</string>
41
+ <string>${xml(config.teamId)}</string>`;return`<?xml version="1.0" encoding="UTF-8"?>
42
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "https://www.apple.com/DTDs/PropertyList-1.0.dtd">
43
+ <plist version="1.0">
44
+ <dict>${identity}
41
45
  <key>com.apple.security.app-sandbox</key>
42
46
  <true/>
43
47
  <key>com.apple.security.network.client</key>
44
- <true/>
48
+ <true/>${networkServer}${fileAccess}
45
49
  </dict>
46
50
  </plist>
47
51
  `}export function renderHelperEntitlements(){return`<?xml version="1.0" encoding="UTF-8"?>
@@ -97,15 +101,13 @@ jobs:
97
101
  s3-public-url: \${{ vars.RELEASE_S3_PUBLIC_URL }}
98
102
  secrets: inherit
99
103
  `}function command(args,cwd=projectPath(),extraEnv={}){const result=Bun.spawnSync(args,{cwd,env:{...process.env,...extraEnv},stdin:"inherit",stdout:"inherit",stderr:"inherit"});if(result.exitCode!==0)throw new Error(`${args[0]} ${args.slice(1).join(" ")} exited with code ${result.exitCode}`)}export function signingPlan(input){const sign=(entitlements,target)=>["codesign","--force","--timestamp","--options","runtime","--entitlements",entitlements,...input.keychain?["--keychain",input.keychain]:[],"--sign",input.identity,target];return[sign(input.helperEntitlements,input.helperPath),sign(input.appEntitlements,input.appPath)]}export const captureCommand=(args)=>{const result=Bun.spawnSync(args,{cwd:projectPath(),stdin:"inherit",stdout:"pipe",stderr:"inherit"});if(result.exitCode!==0)throw new Error(`${args[0]} ${args.slice(1).join(" ")} exited with code ${result.exitCode}`);return result.stdout.toString()};export const MACH_O_ARCHITECTURE={arm64:"arm64",x64:"x86_64"};export function parseLipoArchs(output){return output.trim().split(/\s+/).filter(Boolean).sort()}export function mergeUniversalBinary(input,run=captureCommand){for(const architecture of["arm64","x64"]){const expected=MACH_O_ARCHITECTURE[architecture];const found=parseLipoArchs(run(["lipo","-archs",input[architecture]]));if(found.length!==1||found[0]!==expected){throw new Error(`${input.name}: the ${architecture} input ${input[architecture]} contains ${found.join(" + ")||"no architectures"}, expected only ${expected}`)}}run(["lipo","-create","-output",input.output,input.arm64,input.x64]);const merged=parseLipoArchs(run(["lipo","-archs",input.output]));const expected=Object.values(MACH_O_ARCHITECTURE).sort();if(merged.join(" ")!==expected.join(" "))throw new Error(`${input.name}: the universal binary ${input.output} contains ${merged.join(" + ")||"no architectures"}, expected ${expected.join(" + ")}`);return merged}export function buildUniversalPayload(input,run=captureCommand){const slice=(architecture)=>join(input.directory,architecture,"stacks-desktop");for(const architecture of["arm64","x64"]){mkdirSync(join(input.directory,architecture),{recursive:true});run(input.launcherCompileArgs(architecture,slice(architecture)))}const launcher=join(input.directory,"stacks-desktop");const runtime=join(input.directory,"craft-runtime");mergeUniversalBinary({name:"stacks-desktop",arm64:slice("arm64"),x64:slice("x64"),output:launcher},run);const architectures=mergeUniversalBinary({name:"craft-runtime",arm64:input.craft.arm64,x64:input.craft.x64,output:runtime},run);return{launcher,runtime,architectures}}export function launcherSliceCompileArgs(base,architecture){return["bun",...base,`--target=bun-darwin-${architecture}`]}export function parseDistributionIdentities(output,teamId){const named=(kinds)=>new RegExp(`"((?:${kinds}): [^"]+ \\(${teamId}\\))"`).exec(output)?.[1];return{app:named("Apple Distribution|3rd Party Mac Developer Application"),installer:named("3rd Party Mac Developer Installer|Mac Installer Distribution")}}export function withKeychainIdentities(config,read=readIdentities){if(config.appSigningIdentity&&config.installerSigningIdentity||!config.teamId)return config;const found=parseDistributionIdentities(read(config.keychain),config.teamId);return{...config,appSigningIdentity:config.appSigningIdentity||found.app||"",installerSigningIdentity:config.installerSigningIdentity||found.installer||""}}function readIdentities(keychain){const result=Bun.spawnSync(["security","find-identity","-v",...keychain?[keychain]:[]],{stdout:"pipe",stderr:"pipe"});return result.exitCode===0?result.stdout.toString():""}async function appStoreClient(config){if(!config.apiKeyId||!config.apiIssuerId||!config.apiKeyPath||!existsSync(config.apiKeyPath))throw new Error("App Store Connect API key ID, issuer ID, and .p8 key (APP_STORE_CONNECT_API_KEY or APP_STORE_CONNECT_API_KEY_PATH) are required");const{AppStoreConnectClient}=await import("ts-pantry");return new AppStoreConnectClient({keyId:config.apiKeyId,issuerId:config.apiIssuerId,keyPath:config.apiKeyPath})}async function appStoreAppId(client,bundleId){const app=await client.findApp(bundleId);if(!app)throw new Error(`App Store Connect has no app for ${bundleId}. Create it under Apps first.`);return app.id}async function withDownloadedProfile(config){if(config.provisioningProfile||!config.bundleId)return config;const client=await appStoreClient(config);const bundle=await client.findBundleId(config.bundleId);if(!bundle)throw new Error(`No Apple bundle id ${config.bundleId}. Run buddy desktop:apple:provision --apply first.`);const profile=(await client.listProfiles(bundle.id)).filter((item)=>item.attributes.profileState==="ACTIVE"&&item.attributes.profileContent).sort((a,b)=>String(b.attributes.expirationDate).localeCompare(String(a.attributes.expirationDate)))[0];if(!profile)throw new Error(`No active Mac App Store profile for ${config.bundleId}. Run buddy desktop:apple:provision --apply first.`);const directory=storagePath("framework/desktop-dist/apple");mkdirSync(directory,{recursive:true});const provisioningProfile=join(directory,`${config.bundleId}.provisionprofile`);writeFileSync(provisioningProfile,Buffer.from(String(profile.attributes.profileContent),"base64"),{mode:420});log.info(`Using the Mac App Store profile "${profile.attributes.name}" from App Store Connect`);return{...config,provisioningProfile}}async function withNextBuildNumber(config){if(config.buildNumber!=="next")return config;const client=await appStoreClient(config);const{nextBuildNumber}=await import("ts-pantry");const buildNumber=await nextBuildNumber(client,await appStoreAppId(client,config.bundleId));log.info(`Building ${config.version} (${buildNumber})`);return{...config,buildNumber}}async function releaseConfig(options,native){const config=withKeychainIdentities(withApiKeyFile(resolveAppleDesktopConfig(options,native)));return await withNextBuildNumber(await withDownloadedProfile(config))}async function distributeToTestFlight(config,groups,whatsNew){const client=await appStoreClient(config);const{distributeTestFlightBuild}=await import("ts-pantry");log.info(`Waiting for App Store Connect to process ${config.version} (${config.buildNumber})...`);const result=await distributeTestFlightBuild(client,{appId:await appStoreAppId(client,config.bundleId),version:config.version,buildNumber:config.buildNumber,groups,whatsNew});log.success(`${config.version} (${config.buildNumber}) is on TestFlight for ${result.groups.map((group)=>group.name).join(", ")}`)}function commitsSinceLastTag(){const run=(args)=>Bun.spawnSync(args,{cwd:projectPath(),stdout:"pipe",stderr:"pipe"});const tag=run(["git","describe","--tags","--abbrev=0"]);const range=tag.exitCode===0?[`${tag.stdout.toString().trim()}..HEAD`]:[];return run(["git","log","--no-merges","--format=- %s","-20",...range]).stdout.toString().trim().slice(0,4000)}function signingIdentityExists(identity,keychain){if(!identity)return false;const result=Bun.spawnSync(["security","find-identity","-v",...keychain?[keychain]:[]],{stdout:"pipe",stderr:"pipe"});return result.exitCode===0&&result.stdout.toString().includes(identity)}function provisioningProfileMatches(config){if(!config.provisioningProfile||!existsSync(config.provisioningProfile))return false;const result=Bun.spawnSync(["security","cms","-D","-i",config.provisioningProfile],{stdout:"pipe",stderr:"pipe"});if(result.exitCode!==0)return false;const profile=result.stdout.toString();return profile.includes(config.bundleId)&&profile.includes(config.teamId)}async function buildDesktop(){const{runAction}=await import("@stacksjs/actions");const{Action}=await import("@stacksjs/enums");const result=await runAction(Action.BuildDesktop);if(resultFailed(result))throw result.error}function sha256(path){return createHash("sha256").update(readFileSync(path)).digest("hex")}async function packageAppleDesktop(config,skipBuild=false,native=null){const errors=validateAppleDesktopConfig(config,false);if(config.keychain&&!existsSync(config.keychain))errors.push(`APPLE_KEYCHAIN does not exist: ${config.keychain}`);const where=config.keychain?` in ${config.keychain}`:"";if(!signingIdentityExists(config.appSigningIdentity,config.keychain))errors.push(`App signing identity is not installed${where}: ${config.appSigningIdentity}`);if(!signingIdentityExists(config.installerSigningIdentity,config.keychain))errors.push(`Installer signing identity is not installed${where}: ${config.installerSigningIdentity}`);if(!provisioningProfileMatches(config))errors.push(`Provisioning profile does not match ${config.teamId}.${config.bundleId}`);if(native&&config.universal)errors.push("--universal is not supported for a native macOS app yet: the AppKit host is built for this machine's architecture");if(errors.length)throw new Error(errors.join(`
100
- `));if(native)return packageNativeApple(config,native);if(!skipBuild)await buildDesktop();const desktopDist=storagePath("framework/desktop-dist");let launcher=join(desktopDist,"stacks-desktop");let runtime=join(desktopDist,"craft-runtime");const manifest=join(desktopDist,"desktop.json");for(const path of[launcher,runtime,manifest]){if(!existsSync(path))throw new Error(`Desktop build artifact is missing: ${path}`)}let architectures=[process.arch==="x64"?"x86_64":process.arch];let craftSlices;if(config.universal){const universalDir=join(desktopDist,"universal");if(existsSync(universalDir))rmSync(universalDir,{recursive:true});const{desktopLauncherCompileArgs,resolveDesktopLauncher}=await import("@stacksjs/desktop-build");const entry=resolveDesktopLauncher(projectPath());const minify=process.env.DESKTOP_MINIFY!=="false";const payload=buildUniversalPayload({directory:universalDir,launcherCompileArgs:(architecture,outfile)=>launcherSliceCompileArgs(desktopLauncherCompileArgs({entry,outfile,minify}),architecture),craft:{arm64:config.craftArm64,x64:config.craftX64}});launcher=payload.launcher;runtime=payload.runtime;architectures=payload.architectures;craftSlices={arm64:config.craftArm64,x64:config.craftX64}}const appleDir=join(desktopDist,"apple");const appPath=join(appleDir,`${config.appName}.app`);const contents=join(appPath,"Contents");const macosDir=join(contents,"MacOS");const resourcesDir=join(contents,"Resources");if(existsSync(appleDir))rmSync(appleDir,{recursive:true});mkdirSync(macosDir,{recursive:true});mkdirSync(resourcesDir,{recursive:true});copyFileSync(launcher,join(macosDir,"stacks-desktop"));copyFileSync(runtime,join(macosDir,"craft-runtime"));if(config.universal){const parsed=JSON.parse(readFileSync(manifest,"utf8"));writeFileSync(join(resourcesDir,"desktop.json"),`${JSON.stringify({...parsed,architecture:"universal"},null,2)}
101
- `)}else{copyFileSync(manifest,join(resourcesDir,"desktop.json"))}copyFileSync(config.provisioningProfile,join(contents,"embedded.provisionprofile"));chmodSync(join(contents,"embedded.provisionprofile"),420);chmodSync(join(macosDir,"stacks-desktop"),493);chmodSync(join(macosDir,"craft-runtime"),493);if(config.icon)copyFileSync(resolve(config.icon),join(resourcesDir,"AppIcon.icns"));const infoPlist=join(contents,"Info.plist");const appEntitlements=join(appleDir,"app.entitlements");const helperEntitlements=join(appleDir,"helper.entitlements");writeFileSync(infoPlist,renderInfoPlist(config));writeFileSync(appEntitlements,renderAppEntitlements(config));writeFileSync(helperEntitlements,renderHelperEntitlements());command(["plutil","-lint",infoPlist,appEntitlements,helperEntitlements]);for(const args of signingPlan({identity:config.appSigningIdentity,appPath,helperPath:join(macosDir,"craft-runtime"),appEntitlements,helperEntitlements,keychain:config.keychain}))command(args);command(["codesign","--verify","--deep","--strict","--verbose=2",appPath]);command(["codesign","-d","--entitlements","-","--xml",appPath]);const findings=storeRejectionFindings(bundleFiles(appPath));if(findings.length>0){throw new Error(`The app bundle would be rejected by App Review:
102
- ${findings.map((finding)=>` - ${finding}`).join(`
103
- `)}`)}return finishPackage(config,appPath,appleDir,{architectures,craft:{sha256:sha256(join(macosDir,"craft-runtime")),...craftSlices&&{slices:{arm64:sha256(craftSlices.arm64),x64:sha256(craftSlices.x64)}}}})}async function packageNativeApple(config,native){const{prepareMacosAgent,prepareMacosNative}=await import("@stacksjs/actions");const{assembleMacosApp}=await import("@stacksjs/desktop-build");const store={...native,appName:config.appName,executable:config.appName,bundleId:config.bundleId,teamId:config.teamId,version:config.version,buildNumber:config.buildNumber,minimumSystemVersion:config.minimumMacos,category:config.category,...config.icon?{icon:config.icon}:{},sandbox:true};const prepared=await prepareMacosNative(store,{distribution:"app-store"});const agent=store.agent?await prepareMacosAgent(store,prepared,"app-store"):undefined;const appleDir=join(storagePath("framework/desktop/macos"),"apple");if(existsSync(appleDir))rmSync(appleDir,{recursive:true});mkdirSync(appleDir,{recursive:true});const assembled=assembleMacosApp({config:store,root:projectPath(),host:prepared.host,nativeBundle:prepared.nativeBundle,output:appleDir,distribution:"app-store",provisioningProfile:config.provisioningProfile,signingIdentity:config.appSigningIdentity,keychain:config.keychain,agent});for(const note of assembled.notes)await log.warn(note);command(["codesign","-d","--entitlements","-","--xml",assembled.appPath]);const findings=storeRejectionFindings(bundleFiles(assembled.appPath),store.executable);if(findings.length>0)throw new Error(`The app bundle would be rejected by App Review:
104
+ `));if(native)return packageNativeApple(config,native);const{loadDesktopConfig}=await import("@stacksjs/desktop-build");const local=(await loadDesktopConfig(projectPath()))?.launcher?.appStore;if(local&&config.universal)throw new Error("The local App Store host supports one target architecture per build");if(!skipBuild)await buildDesktop();if(local)return packageLocalLauncher(config,local);const desktopDist=storagePath("framework/desktop-dist");let launcher=join(desktopDist,"stacks-desktop");let runtime=join(desktopDist,"craft-runtime");const manifest=join(desktopDist,"desktop.json");for(const path of[launcher,runtime,manifest]){if(!existsSync(path))throw new Error(`Desktop build artifact is missing: ${path}`)}let architectures=[process.arch==="x64"?"x86_64":process.arch];let craftSlices;if(config.universal){const universalDir=join(desktopDist,"universal");if(existsSync(universalDir))rmSync(universalDir,{recursive:true});const{desktopLauncherCompileArgs,resolveDesktopLauncher}=await import("@stacksjs/desktop-build");const entry=resolveDesktopLauncher(projectPath());const minify=process.env.DESKTOP_MINIFY!=="false";const payload=buildUniversalPayload({directory:universalDir,launcherCompileArgs:(architecture,outfile)=>launcherSliceCompileArgs(desktopLauncherCompileArgs({entry,outfile,minify}),architecture),craft:{arm64:config.craftArm64,x64:config.craftX64}});launcher=payload.launcher;runtime=payload.runtime;architectures=payload.architectures;craftSlices={arm64:config.craftArm64,x64:config.craftX64}}const appleDir=join(desktopDist,"apple");const appPath=join(appleDir,`${config.appName}.app`);const contents=join(appPath,"Contents");const macosDir=join(contents,"MacOS");const resourcesDir=join(contents,"Resources");if(existsSync(appleDir))rmSync(appleDir,{recursive:true});mkdirSync(macosDir,{recursive:true});mkdirSync(resourcesDir,{recursive:true});copyFileSync(launcher,join(macosDir,"stacks-desktop"));copyFileSync(runtime,join(macosDir,"craft-runtime"));if(config.universal){const parsed=JSON.parse(readFileSync(manifest,"utf8"));writeFileSync(join(resourcesDir,"desktop.json"),`${JSON.stringify({...parsed,architecture:"universal"},null,2)}
105
+ `)}else{copyFileSync(manifest,join(resourcesDir,"desktop.json"))}copyFileSync(config.provisioningProfile,join(contents,"embedded.provisionprofile"));chmodSync(join(contents,"embedded.provisionprofile"),420);chmodSync(join(macosDir,"stacks-desktop"),493);chmodSync(join(macosDir,"craft-runtime"),493);if(config.icon)copyFileSync(resolve(config.icon),join(resourcesDir,"AppIcon.icns"));const infoPlist=join(contents,"Info.plist");const appEntitlements=join(appleDir,"app.entitlements");const helperEntitlements=join(appleDir,"helper.entitlements");writeFileSync(infoPlist,renderInfoPlist(config));writeFileSync(appEntitlements,renderAppEntitlements(config));writeFileSync(helperEntitlements,renderHelperEntitlements());command(["plutil","-lint",infoPlist,appEntitlements,helperEntitlements]);for(const args of signingPlan({identity:config.appSigningIdentity,appPath,helperPath:join(macosDir,"craft-runtime"),appEntitlements,helperEntitlements,keychain:config.keychain}))command(args);command(["codesign","--verify","--deep","--strict","--verbose=2",appPath]);command(["codesign","-d","--entitlements","-","--xml",appPath]);await verifyStoreBundle(appPath,"stacks-desktop",config.minimumMacos);return finishPackage(config,appPath,appleDir,{architectures,craft:{sha256:sha256(join(macosDir,"craft-runtime")),...craftSlices&&{slices:{arm64:sha256(craftSlices.arm64),x64:sha256(craftSlices.x64)}}}})}async function packageLocalLauncher(config,local,sandboxCheck=false){const{renderUserlandPlistEntries,resolveCraftExecutable}=await import("@stacksjs/desktop-build");const desktopDist=storagePath("framework/desktop-dist");const executable=config.appName;const backend="craft-backend";const runtime=local.runtime?projectPath(local.runtime):join(dirname(resolveCraftExecutable()),"craft-app-store");const probe=Bun.spawnSync([runtime,"--distribution"],{stdout:"pipe",stderr:"pipe"});if(probe.exitCode!==0||probe.stdout.toString().trim()!=="app-store")throw new Error(`Expected Craft's App Store runtime at ${runtime}`);const appleDir=join(desktopDist,"apple");const app=join(appleDir,`${config.appName}.app`);const contents=join(app,"Contents");const macOS=join(contents,"MacOS");const resources=join(contents,"Resources");rmSync(appleDir,{recursive:true,force:true});mkdirSync(macOS,{recursive:true});mkdirSync(resources,{recursive:true});const launcher=join(desktopDist,"stacks-desktop");for(const[source,name]of[[runtime,executable],[launcher,backend]]){const target=join(macOS,name);copyFileSync(source,target);chmodSync(target,493)}for(const source of[projectPath("app/Desktop/Resources"),join(desktopDist,"resources")]){if(existsSync(source))cpSync(source,resources,{recursive:true})}if(config.icon)copyFileSync(resolve(config.icon),join(resources,"AppIcon.icns"));writeFileSync(join(resources,"craft.json"),JSON.stringify({title:executable,appName:executable,width:1400,height:900,titlebarHidden:true,backend:{executable:backend}}));if(!sandboxCheck){const profile=join(contents,"embedded.provisionprofile");copyFileSync(config.provisioningProfile,profile);chmodSync(profile,420)}const declared=projectPath("app/Desktop/Info.plist.json");const declaredInfo=existsSync(declared)?JSON.parse(readFileSync(declared,"utf8")):{};for(const key of["CFBundlePackageType","CFBundleInfoDictionaryVersion","CFBundleIconFile","LSApplicationCategoryType","LSMinimumSystemVersion","NSHighResolutionCapable"])delete declaredInfo[key];const extra=renderUserlandPlistEntries(declaredInfo).xml;const plist=join(contents,"Info.plist");const appEntitlements=join(appleDir,"app.entitlements");const helperEntitlements=join(appleDir,"helper.entitlements");writeFileSync(plist,renderInfoPlist(config,executable,extra));writeFileSync(appEntitlements,renderAppEntitlements(config,local,sandboxCheck));writeFileSync(helperEntitlements,renderHelperEntitlements());command(["plutil","-lint",plist,appEntitlements,helperEntitlements]);for(const args of signingPlan({identity:sandboxCheck?"-":config.appSigningIdentity,appPath:app,helperPath:join(macOS,backend),appEntitlements,helperEntitlements,keychain:config.keychain}))command(args);command(["codesign","--verify","--deep","--strict",app]);if(sandboxCheck)return app;await verifyStoreBundle(app,executable,config.minimumMacos);return finishPackage(config,app,appleDir,{architectures:[process.arch==="x64"?"x86_64":process.arch],craft:{kind:"app-store-host",sha256:sha256(runtime)}})}export function unsupportedMacosTarget(loadCommands,minimumMacos){const declared=minimumMacos.split(".").map(Number);const targets=loadCommands.matchAll(/^\s*(?:minos\s+|cmd LC_VERSION_MIN_MACOSX\s*\n\s*cmdsize \d+\s*\n\s*version\s+)(\d+(?:\.\d+){0,2})\s*$/gm);for(const[,target]of targets){if(!target)continue;const components=target.split(".").map(Number);for(let i=0;i<Math.max(components.length,declared.length);i++){const difference=(components[i]??0)-(declared[i]??0);if(difference>0)return target;if(difference<0)break}}}async function verifyStoreBundle(app,executable,minimumMacos){const{bundleDirectoryFor}=await import("@stacksjs/desktop-build");const files=bundleFiles(app);const findings=storeRejectionFindings(files,executable);for(const file of files){const path=join(app,file);if(bundleDirectoryFor(path)!=="MacOS")continue;const deps=Bun.spawnSync(["/usr/bin/otool","-L",path],{stdout:"pipe",stderr:"pipe"});if(deps.exitCode!==0)throw new Error(`Could not inspect the Mach-O dependencies of ${file}`);if(/^\s+\/usr\/lib\/libicucore(?:\.[^\s]+)?\.dylib\s/m.test(deps.stdout.toString()))findings.push(`${file} links Apple's system ICU library, which App Review flagged. Build with a Bun runtime linked to upstream ICU.`);const commands=Bun.spawnSync(["/usr/bin/otool","-l",path],{stdout:"pipe",stderr:"pipe"});if(commands.exitCode!==0)throw new Error(`Could not inspect the Mach-O deployment target of ${file}`);const target=unsupportedMacosTarget(commands.stdout.toString(),minimumMacos);if(target)findings.push(`${file} requires macOS ${target}, later than the app's declared minimum macOS ${minimumMacos}.`)}if(findings.length)throw new Error(`The app bundle failed Store preflight:
104
106
  ${findings.map((finding)=>` - ${finding}`).join(`
105
- `)}`);return finishPackage(config,assembled.appPath,appleDir,{architectures:[process.arch==="x64"?"x86_64":process.arch],craft:{kind:"native-appkit",hostKey:prepared.hostKey,sha256:sha256(prepared.host)}})}function finishPackage(config,appPath,appleDir,provenance){const packagePath=join(appleDir,`${config.appName}-${config.version}-${config.buildNumber}.pkg`);command(["productbuild","--component",appPath,"/Applications",...config.keychain?["--keychain",config.keychain]:[],"--sign",config.installerSigningIdentity,packagePath]);command(["pkgutil","--check-signature",packagePath]);const packageHash=sha256(packagePath);writeFileSync(join(appleDir,"checksums.sha256"),`${packageHash} ${basename(packagePath)}
107
+ `)}`)}async function packageNativeApple(config,native){const{prepareMacosAgent,prepareMacosNative}=await import("@stacksjs/actions");const{assembleMacosApp}=await import("@stacksjs/desktop-build");const store={...native,appName:config.appName,executable:config.appName,bundleId:config.bundleId,teamId:config.teamId,version:config.version,buildNumber:config.buildNumber,minimumSystemVersion:config.minimumMacos,category:config.category,...config.icon?{icon:config.icon}:{},sandbox:true};const prepared=await prepareMacosNative(store,{distribution:"app-store"});const agent=store.agent?await prepareMacosAgent(store,prepared,"app-store"):undefined;const appleDir=join(storagePath("framework/desktop/macos"),"apple");if(existsSync(appleDir))rmSync(appleDir,{recursive:true});mkdirSync(appleDir,{recursive:true});const assembled=assembleMacosApp({config:store,root:projectPath(),host:prepared.host,nativeBundle:prepared.nativeBundle,output:appleDir,distribution:"app-store",provisioningProfile:config.provisioningProfile,signingIdentity:config.appSigningIdentity,keychain:config.keychain,agent});for(const note of assembled.notes)await log.warn(note);command(["codesign","-d","--entitlements","-","--xml",assembled.appPath]);await verifyStoreBundle(assembled.appPath,store.executable,config.minimumMacos);return finishPackage(config,assembled.appPath,appleDir,{architectures:[process.arch==="x64"?"x86_64":process.arch],craft:{kind:"native-appkit",hostKey:prepared.hostKey,sha256:sha256(prepared.host)}})}function finishPackage(config,appPath,appleDir,provenance){const packagePath=join(appleDir,`${config.appName}-${config.version}-${config.buildNumber}.pkg`);command(["productbuild","--component",appPath,"/Applications",...config.keychain?["--keychain",config.keychain]:[],"--sign",config.installerSigningIdentity,packagePath]);command(["pkgutil","--check-signature",packagePath]);const packageHash=sha256(packagePath);writeFileSync(join(appleDir,"checksums.sha256"),`${packageHash} ${basename(packagePath)}
106
108
  `);writeFileSync(join(appleDir,"apple-provenance.json"),`${JSON.stringify({schemaVersion:"1.0.0",appName:config.appName,bundleId:config.bundleId,teamId:config.teamId,version:config.version,buildNumber:config.buildNumber,minimumMacos:config.minimumMacos,architectures:provenance.architectures,package:{name:basename(packagePath),sha256:packageHash},sourceRevision:Bun.spawnSync(["git","rev-parse","HEAD"],{cwd:projectPath()}).stdout.toString().trim(),craft:provenance.craft},null,2)}
107
109
  `);return packagePath}function validateOrUpload(packagePath,config,validateOnly){const errors=validateAppleDesktopConfig(config,true);if(errors.length)throw new Error(errors.join(`
108
110
  `));const common=["--type","macos","--file",packagePath,"--apiKey",config.apiKeyId,"--apiIssuer",config.apiIssuerId];const keysDirectory=resolve(config.apiKeyPath,"..");const env={API_PRIVATE_KEYS_DIR:keysDirectory};command(["xcrun","altool","--validate-app",...common],projectPath(),env);if(!validateOnly)command(["xcrun","altool","--upload-app",...common],projectPath(),env)}export function renderFailure(error){return`${error instanceof Error?error.message:String(error)}
109
111
  `}function fail(error){process.stderr.write(renderFailure(error));process.exit(1)}export function desktopApple(buddy){buddy.command("desktop:apple:csr","Generate local private keys and CSRs for Mac App Store distribution certificates").option("--common-name <name>","Certificate request common name").option("--output <path>","Directory for private keys and certificate requests").action(async(options)=>{try{const metadata=packageMetadata();const outputDirectory=resolve(options.output||storagePath("framework/desktop-dist/apple/provisioning"));const{generateMacCertificateRequests}=await import("ts-pantry");generateMacCertificateRequests({outputDirectory,commonName:options.commonName||metadata.name});log.success(`Generated Apple certificate requests and private keys in ${outputDirectory}`)}catch(error){fail(error)}});buddy.command("desktop:apple:provision","Plan or reconcile Apple Bundle ID, capabilities, certificates, and profile").option("--app-name <name>","Mac App Store display name").option("--bundle-id <id>","Reverse-DNS bundle identifier").option("--api-key-id <id>","App Store Connect API key ID").option("--api-issuer-id <id>","App Store Connect API issuer ID").option("--api-key-path <path>","App Store Connect AuthKey .p8 file").option("--capabilities <types>","Comma-separated Apple capability types").option("--app-certificate-csr <path>","CSR for a missing Mac App Distribution certificate").option("--installer-certificate-csr <path>","CSR for a missing Mac Installer Distribution certificate").option("--profile-name <name>","Provisioning profile name").option("--output <path>","Directory for the plan and downloaded Apple assets").option("--plan","Report the idempotent Apple resource diff without mutating it").option("--apply","Apply the Apple resource diff without revoking existing certificates").action(async(options)=>{try{if(options.plan&&options.apply)throw new Error("Choose either --plan or --apply");const config=withApiKeyFile(resolveAppleDesktopConfig(options,await nativeAppleConfig()));if(!config.bundleId)throw new Error("APPLE_BUNDLE_ID or --bundle-id is required");if(!config.apiKeyId||!config.apiIssuerId||!config.apiKeyPath||!existsSync(config.apiKeyPath))throw new Error("App Store Connect API key ID, issuer ID, and existing .p8 key path are required");const readCsr=(file)=>{if(!file)return;const resolved=resolve(file);if(!existsSync(resolved))throw new Error(`Apple certificate CSR does not exist: ${resolved}`);return readFileSync(resolved,"utf8")};const{exportAppleCertificateP12,provisionMacApp}=await import("ts-pantry");const result=await provisionMacApp({identifier:config.bundleId,name:config.appName,capabilities:options.capabilities?.split(",").map((value)=>value.trim()).filter(Boolean),appCertificateCsr:readCsr(options.appCertificateCsr),installerCertificateCsr:readCsr(options.installerCertificateCsr),profileName:options.profileName,keyId:config.apiKeyId,issuerId:config.apiIssuerId,keyPath:config.apiKeyPath,checkOnly:!options.apply});const outputDirectory=resolve(options.output||storagePath("framework/desktop-dist/apple/provisioning"));mkdirSync(outputDirectory,{recursive:true});for(const certificate of result.certificates){if(!certificate.certificateContent)continue;const fileName=certificate.type==="MAC_APP_DISTRIBUTION"?"mac-app-distribution.cer":"mac-installer-distribution.cer";writeFileSync(join(outputDirectory,fileName),Buffer.from(certificate.certificateContent,"base64"),{mode:384})}if(result.profile.profileContent){writeFileSync(join(outputDirectory,"mac-app-store.provisionprofile"),Buffer.from(result.profile.profileContent,"base64"),{mode:384})}const certificatePassword=env("APPLE_CERTIFICATE_PASSWORD");const certificateExports=[{type:"MAC_APP_DISTRIBUTION",csr:options.appCertificateCsr,certificate:"mac-app-distribution.cer",output:"mac-app-distribution.p12",name:`${config.appName} Mac App Distribution`},{type:"MAC_INSTALLER_DISTRIBUTION",csr:options.installerCertificateCsr,certificate:"mac-installer-distribution.cer",output:"mac-installer-distribution.p12",name:`${config.appName} Mac Installer Distribution`}];for(const certificateExport of certificateExports){const certificate=result.certificates.find((item)=>item.type===certificateExport.type);if(!certificate?.certificateContent||!certificateExport.csr||!certificatePassword)continue;exportAppleCertificateP12({certificatePath:join(outputDirectory,certificateExport.certificate),privateKeyPath:resolve(certificateExport.csr.replace(/\.csr$/i,".key")),outputPath:join(outputDirectory,certificateExport.output),password:certificatePassword,name:certificateExport.name})}const certificates=result.certificates.map((item)=>{const certificate={...item};delete certificate.certificateContent;return certificate});const profile={...result.profile};delete profile.profileContent;const report={...result,certificates,profile};const reportPath=join(outputDirectory,"provisioning-plan.json");writeFileSync(reportPath,`${JSON.stringify(report,null,2)}
110
112
  `,{mode:384});log.success(`${options.apply?"Applied":"Planned"} Apple provisioning: ${reportPath}`);if(!result.appRecord.exists&&result.appRecord.manualAction)log.warn(result.appRecord.manualAction)}catch(error){fail(error)}});buddy.command("desktop:apple:doctor","Validate Mac App Store tooling, credentials, certificates, and project metadata").option("--app-name <name>","Mac App Store display name").option("--bundle-id <id>","Reverse-DNS bundle identifier").option("--team-id <id>","Apple Developer team ID").option("--app-signing-identity <identity>","Mac App Distribution signing identity").option("--installer-signing-identity <identity>","Mac Installer Distribution signing identity").option("--provisioning-profile <path>","Mac App Store provisioning profile").option("--api-key-id <id>","App Store Connect API key ID").option("--api-issuer-id <id>","App Store Connect API issuer ID").option("--api-key-path <path>","App Store Connect AuthKey .p8 file").option("--keychain <path>","Look for the signing identities in this keychain file only (or APPLE_KEYCHAIN)").action(async(options)=>{try{const config=withApiKeyFile(resolveAppleDesktopConfig(options,await nativeAppleConfig()));const errors=validateAppleDesktopConfig(config,true);if(!signingIdentityExists(config.appSigningIdentity,config.keychain))errors.push(`App signing identity is not installed: ${config.appSigningIdentity}`);if(!signingIdentityExists(config.installerSigningIdentity,config.keychain))errors.push(`Installer signing identity is not installed: ${config.installerSigningIdentity}`);if(!provisioningProfileMatches(config))errors.push(`Provisioning profile does not match ${config.teamId}.${config.bundleId}`);if(errors.length)throw new Error(errors.join(`
111
- `));log.success(`Mac App Store prerequisites are ready for ${config.bundleId}`)}catch(error){fail(error)}});buddy.command("desktop:apple:init","Create a GitHub Actions caller for the reusable Stacks Mac App Store workflow").option("--force","Replace an existing workflow").action((options)=>{try{const workflowPath=projectPath(".github/workflows/apple-app-store.yml");if(existsSync(workflowPath)&&!options.force)throw new Error(`${workflowPath} already exists. Use --force to replace it.`);mkdirSync(resolve(workflowPath,".."),{recursive:true});writeFileSync(workflowPath,renderAppleWorkflowCaller());log.success(`Created ${workflowPath}`)}catch(error){fail(error)}});const addSharedOptions=(commandBuilder)=>commandBuilder.option("--app-name <name>","Mac App Store display name").option("--bundle-id <id>","Reverse-DNS bundle identifier").option("--team-id <id>","Apple Developer team ID").option("--app-version <version>","Marketing version").option("--build-number <number>",'Unique App Store build number, or "next" for one past the highest on App Store Connect (publish only)').option("--minimum-macos <version>","Minimum supported macOS version").option("--category <category>","LSApplicationCategoryType value").option("--app-signing-identity <identity>","Mac App Distribution signing identity").option("--installer-signing-identity <identity>","Mac Installer Distribution signing identity").option("--provisioning-profile <path>","Mac App Store provisioning profile").option("--icon <path>","Optional .icns app icon").option("--skip-build","Package existing storage/framework/desktop-dist artifacts").option("--universal","Ship one arm64 + x86_64 binary, merged with lipo").option("--craft-arm64 <path>","Thin arm64 Craft runtime for --universal (or CRAFT_BIN_ARM64)").option("--craft-x64 <path>","Thin x86_64 Craft runtime for --universal (or CRAFT_BIN_X64)").option("--keychain <path>","Sign with identities from this keychain file only (or APPLE_KEYCHAIN)");addSharedOptions(buddy.command("desktop:apple:package","Build, sandbox, sign, and package a Mac App Store desktop app")).action(async(options)=>{try{const native=await nativeAppleConfig();const packagePath=await packageAppleDesktop(withKeychainIdentities(resolveAppleDesktopConfig(options,native)),Boolean(options.skipBuild),native);log.success(`Created signed Mac App Store package ${packagePath}`)}catch(error){fail(error)}});addSharedOptions(buddy.command("desktop:apple:publish","Build and validate or upload a signed Mac App Store package")).option("--api-key-id <id>","App Store Connect API key ID").option("--api-issuer-id <id>","App Store Connect API issuer ID").option("--api-key-path <path>","App Store Connect AuthKey .p8 file").option("--validate-only","Validate with App Store Connect without uploading").option("--package-only","Create the signed package without contacting App Store Connect").option("--testflight <groups>","After the upload, wait for processing and give the build to these comma-separated TestFlight groups").option("--whats-new <text>",'TestFlight "What to Test" (default: the commit subjects since the last tag)').action(async(options)=>{try{const groups=options.testflight?.split(",").map((name)=>name.trim()).filter(Boolean)??[];if(groups.length&&(options.validateOnly||options.packageOnly))throw new Error("--testflight needs an upload, so it cannot be combined with --validate-only or --package-only");const native=await nativeAppleConfig();const config=await releaseConfig(options,native);const packagePath=await packageAppleDesktop(config,Boolean(options.skipBuild),native);if(!options.packageOnly)validateOrUpload(packagePath,config,Boolean(options.validateOnly));log.success(options.packageOnly?`Created signed Mac App Store package ${packagePath}`:options.validateOnly?`Validated ${packagePath} with App Store Connect`:`Uploaded ${packagePath} to App Store Connect`);if(groups.length)await distributeToTestFlight(config,groups,options.whatsNew??commitsSinceLastTag())}catch(error){fail(error)}})}
113
+ `));log.success(`Mac App Store prerequisites are ready for ${config.bundleId}`)}catch(error){fail(error)}});buddy.command("desktop:apple:init","Create a GitHub Actions caller for the reusable Stacks Mac App Store workflow").option("--force","Replace an existing workflow").action((options)=>{try{const workflowPath=projectPath(".github/workflows/apple-app-store.yml");if(existsSync(workflowPath)&&!options.force)throw new Error(`${workflowPath} already exists. Use --force to replace it.`);mkdirSync(resolve(workflowPath,".."),{recursive:true});writeFileSync(workflowPath,renderAppleWorkflowCaller());log.success(`Created ${workflowPath}`)}catch(error){fail(error)}});const addSharedOptions=(commandBuilder)=>commandBuilder.option("--app-name <name>","Mac App Store display name").option("--bundle-id <id>","Reverse-DNS bundle identifier").option("--team-id <id>","Apple Developer team ID").option("--app-version <version>","Marketing version").option("--build-number <number>",'Unique App Store build number, or "next" for one past the highest on App Store Connect (publish only)').option("--minimum-macos <version>","Minimum supported macOS version").option("--category <category>","LSApplicationCategoryType value").option("--app-signing-identity <identity>","Mac App Distribution signing identity").option("--installer-signing-identity <identity>","Mac Installer Distribution signing identity").option("--provisioning-profile <path>","Mac App Store provisioning profile").option("--icon <path>","Optional .icns app icon").option("--skip-build","Package existing storage/framework/desktop-dist artifacts").option("--universal","Ship one arm64 + x86_64 binary, merged with lipo").option("--craft-arm64 <path>","Thin arm64 Craft runtime for --universal (or CRAFT_BIN_ARM64)").option("--craft-x64 <path>","Thin x86_64 Craft runtime for --universal (or CRAFT_BIN_X64)").option("--keychain <path>","Sign with identities from this keychain file only (or APPLE_KEYCHAIN)");addSharedOptions(buddy.command("desktop:apple:package","Build, sandbox, sign, and package a Mac App Store desktop app")).option("--sandbox-check","Make a locally signed sandboxed app for testing a configured launcher").action(async(options)=>{try{const{loadDesktopConfig}=await import("@stacksjs/desktop-build");const launcher=(await loadDesktopConfig(projectPath()))?.launcher;const native=await nativeAppleConfig();const config=resolveAppleDesktopConfig(options,native,launcher);if(options.sandboxCheck){if(native||!launcher?.appStore)throw new Error("--sandbox-check requires desktop.launcher.appStore");if(!options.skipBuild)await buildDesktop();const app=await packageLocalLauncher(config,launcher.appStore,true);log.success(`Built sandboxed app ${app}`);return}const packagePath=await packageAppleDesktop(withKeychainIdentities(config),Boolean(options.skipBuild),native);log.success(`Created signed Mac App Store package ${packagePath}`)}catch(error){fail(error)}});addSharedOptions(buddy.command("desktop:apple:publish","Build and validate or upload a signed Mac App Store package")).option("--api-key-id <id>","App Store Connect API key ID").option("--api-issuer-id <id>","App Store Connect API issuer ID").option("--api-key-path <path>","App Store Connect AuthKey .p8 file").option("--validate-only","Validate with App Store Connect without uploading").option("--package-only","Create the signed package without contacting App Store Connect").option("--testflight <groups>","After the upload, wait for processing and give the build to these comma-separated TestFlight groups").option("--whats-new <text>",'TestFlight "What to Test" (default: the commit subjects since the last tag)').action(async(options)=>{try{const groups=options.testflight?.split(",").map((name)=>name.trim()).filter(Boolean)??[];if(groups.length&&(options.validateOnly||options.packageOnly))throw new Error("--testflight needs an upload, so it cannot be combined with --validate-only or --package-only");const native=await nativeAppleConfig();const config=await releaseConfig(options,native);const packagePath=await packageAppleDesktop(config,Boolean(options.skipBuild),native);if(!options.packageOnly)validateOrUpload(packagePath,config,Boolean(options.validateOnly));log.success(options.packageOnly?`Created signed Mac App Store package ${packagePath}`:options.validateOnly?`Validated ${packagePath} with App Store Connect`:`Uploaded ${packagePath} to App Store Connect`);if(groups.length)await distributeToTestFlight(config,groups,options.whatsNew??commitsSinceLastTag())}catch(error){fail(error)}})}
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/buddy",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.75.648",
5
+ "version": "0.75.652",
6
6
  "description": "Meet Buddy. The Stacks runtime.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -95,71 +95,71 @@
95
95
  "prepublishOnly": "bun run build"
96
96
  },
97
97
  "dependencies": {
98
- "@stacksjs/actions": "0.75.648",
99
- "@stacksjs/docs": "0.75.648",
100
- "@stacksjs/ai": "0.75.648",
101
- "@stacksjs/alias": "0.75.648",
102
- "@stacksjs/analytics": "0.75.648",
103
- "@stacksjs/api": "0.75.648",
104
- "@stacksjs/arrays": "0.75.648",
105
- "@stacksjs/auth": "0.75.648",
106
- "@stacksjs/browser-extension": "0.75.648",
107
- "@stacksjs/build": "0.75.648",
98
+ "@stacksjs/actions": "0.75.652",
99
+ "@stacksjs/docs": "0.75.652",
100
+ "@stacksjs/ai": "0.75.652",
101
+ "@stacksjs/alias": "0.75.652",
102
+ "@stacksjs/analytics": "0.75.652",
103
+ "@stacksjs/api": "0.75.652",
104
+ "@stacksjs/arrays": "0.75.652",
105
+ "@stacksjs/auth": "0.75.652",
106
+ "@stacksjs/browser-extension": "0.75.652",
107
+ "@stacksjs/build": "0.75.652",
108
108
  "@stacksjs/bumpx": "^0.2.32",
109
- "@stacksjs/cache": "0.75.648",
110
- "@stacksjs/chat": "0.75.648",
109
+ "@stacksjs/cache": "0.75.652",
110
+ "@stacksjs/chat": "0.75.652",
111
111
  "@stacksjs/clapp": "^0.2.17",
112
- "@stacksjs/cli": "0.75.648",
113
- "@stacksjs/cloud": "0.75.648",
114
- "@stacksjs/cms": "0.75.648",
115
- "@stacksjs/collections": "0.75.648",
116
- "@stacksjs/commerce": "0.75.648",
117
- "@stacksjs/config": "0.75.648",
118
- "@stacksjs/database": "0.75.648",
119
- "@stacksjs/desktop-build": "0.75.648",
120
- "@stacksjs/dns": "0.75.648",
112
+ "@stacksjs/cli": "0.75.652",
113
+ "@stacksjs/cloud": "0.75.652",
114
+ "@stacksjs/cms": "0.75.652",
115
+ "@stacksjs/collections": "0.75.652",
116
+ "@stacksjs/commerce": "0.75.652",
117
+ "@stacksjs/config": "0.75.652",
118
+ "@stacksjs/database": "0.75.652",
119
+ "@stacksjs/desktop-build": "0.75.652",
120
+ "@stacksjs/dns": "0.75.652",
121
121
  "@stacksjs/dnsx": "^0.2.3",
122
- "@stacksjs/email": "0.75.648",
123
- "@stacksjs/enums": "0.75.648",
124
- "@stacksjs/env": "0.75.648",
125
- "@stacksjs/error-handling": "0.75.648",
126
- "@stacksjs/events": "0.75.648",
127
- "@stacksjs/features": "0.75.648",
128
- "@stacksjs/git": "0.75.648",
122
+ "@stacksjs/email": "0.75.652",
123
+ "@stacksjs/enums": "0.75.652",
124
+ "@stacksjs/env": "0.75.652",
125
+ "@stacksjs/error-handling": "0.75.652",
126
+ "@stacksjs/events": "0.75.652",
127
+ "@stacksjs/features": "0.75.652",
128
+ "@stacksjs/git": "0.75.652",
129
129
  "@stacksjs/gitit": "^0.2.5",
130
- "@stacksjs/health": "0.75.648",
131
- "@stacksjs/hq": "0.75.648",
130
+ "@stacksjs/health": "0.75.652",
131
+ "@stacksjs/hq": "0.75.652",
132
132
  "@stacksjs/httx": "^0.1.10",
133
- "@stacksjs/image": "0.75.648",
134
- "@stacksjs/lint": "0.75.648",
135
- "@stacksjs/logging": "0.75.648",
136
- "@stacksjs/notifications": "0.75.648",
137
- "@stacksjs/objects": "0.75.648",
138
- "@stacksjs/orm": "0.75.648",
139
- "@stacksjs/path": "0.75.648",
140
- "@stacksjs/payments": "0.75.648",
141
- "@stacksjs/realtime": "0.75.648",
142
- "@stacksjs/router": "0.75.648",
133
+ "@stacksjs/image": "0.75.652",
134
+ "@stacksjs/lint": "0.75.652",
135
+ "@stacksjs/logging": "0.75.652",
136
+ "@stacksjs/notifications": "0.75.652",
137
+ "@stacksjs/objects": "0.75.652",
138
+ "@stacksjs/orm": "0.75.652",
139
+ "@stacksjs/path": "0.75.652",
140
+ "@stacksjs/payments": "0.75.652",
141
+ "@stacksjs/realtime": "0.75.652",
142
+ "@stacksjs/router": "0.75.652",
143
143
  "@stacksjs/rpx": "^0.11.54",
144
- "@stacksjs/scheduler": "0.75.648",
145
- "@stacksjs/search-engine": "0.75.648",
146
- "@stacksjs/security": "0.75.648",
147
- "@stacksjs/server": "0.75.648",
148
- "@stacksjs/sites": "0.75.648",
149
- "@stacksjs/skills": "0.75.648",
150
- "@stacksjs/socials": "0.75.648",
151
- "@stacksjs/storage": "0.75.648",
152
- "@stacksjs/strings": "0.75.648",
144
+ "@stacksjs/scheduler": "0.75.652",
145
+ "@stacksjs/search-engine": "0.75.652",
146
+ "@stacksjs/security": "0.75.652",
147
+ "@stacksjs/server": "0.75.652",
148
+ "@stacksjs/sites": "0.75.652",
149
+ "@stacksjs/skills": "0.75.652",
150
+ "@stacksjs/socials": "0.75.652",
151
+ "@stacksjs/storage": "0.75.652",
152
+ "@stacksjs/strings": "0.75.652",
153
153
  "@stacksjs/stx": "^0.2.908",
154
- "@stacksjs/testing": "0.75.648",
155
- "@stacksjs/tinker": "0.75.648",
154
+ "@stacksjs/testing": "0.75.652",
155
+ "@stacksjs/tinker": "0.75.652",
156
156
  "@stacksjs/tlsx": "^0.13.19",
157
157
  "@stacksjs/ts-cloud": "^0.16.144",
158
- "@stacksjs/tunnel": "0.75.648",
159
- "@stacksjs/types": "0.75.648",
160
- "@stacksjs/ui": "0.75.648",
161
- "@stacksjs/utils": "0.75.648",
162
- "@stacksjs/validation": "0.75.648",
158
+ "@stacksjs/tunnel": "0.75.652",
159
+ "@stacksjs/types": "0.75.652",
160
+ "@stacksjs/ui": "0.75.652",
161
+ "@stacksjs/utils": "0.75.652",
162
+ "@stacksjs/validation": "0.75.652",
163
163
  "ajv": "^8.20.0",
164
164
  "ajv-formats": "^3.0.1",
165
165
  "bun-plugin-stx": "^0.2.908",