@stacksjs/desktop-build 0.75.556 → 0.75.557

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.
@@ -32,6 +32,14 @@ export declare function widenedPath(options?: { platform?: string, home?: string
32
32
  /** Set this process's PATH (and so its children's) to `widenedPath()`. */
33
33
  export declare function applyWidenedPath(): void;
34
34
  export declare function startWebviewAgent(options: WebviewAgentOptions): Promise<WebviewAgent>;
35
+ /**
36
+ * How stx is told where an app's components are: the first directory is the
37
+ * one it looks in first, the rest follow in order. `buddy dev:desktop`
38
+ * (stx's server) and `buddy build:desktop` (stx's static build) both read
39
+ * the list through here, so a component name defined twice resolves to the
40
+ * same file in the window you develop in and the app you ship.
41
+ */
42
+ export declare function webviewComponentDirs(components?: readonly string[]): { componentsDir?: string, additionalComponentsDirs?: string[] };
35
43
  export declare const INSTANCE_PATH: '/__desktop/instance';
36
44
  export declare const INSTANCE_HEADER: 'x-desktop-instance';
37
45
  /**
@@ -1 +1 @@
1
- import{timingSafeEqual}from"node:crypto";import{mkdirSync,writeFileSync}from"node:fs";import{homedir}from"node:os";import{dirname,posix,win32}from"node:path";import process from"node:process";import{isAgentHost,newAgentToken,rememberedPort,sessionCookie,staticContentType,staticFileResponse}from"./agent";export const INSTANCE_PATH="/__desktop/instance";export const INSTANCE_HEADER="x-desktop-instance";const ASSET_PREFIXES=["/_stx/","/assets/"];function sameSecret(given,expected){if(!given)return false;const left=Buffer.from(given);const right=Buffer.from(expected);return left.length===right.length&&timingSafeEqual(left,right)}function matchesPath(pathname,patterns){return patterns.some((pattern)=>pattern.endsWith("/")?pathname.startsWith(pattern):pathname===pattern)}const LAUNCH_TOKEN_TTL_MS=60000;export function createWebviewGate(options){const cookieName=options.cookieName??"stacks_desktop";const session=newAgentToken();const pending=new Map;const refusal=`Open ${options.appName??"the app"} to use this.`;return{cookieName,mint(){const token=newAgentToken();pending.set(token,Date.now()+LAUNCH_TOKEN_TTL_MS);return token},check(request){const url=new URL(request.url);if(!isAgentHost(request.headers.get("host"),options.port()))return{response:new Response("Forbidden",{status:403})};if(url.pathname===INSTANCE_PATH){if(request.method!=="POST"||!options.instanceSecret||!sameSecret(request.headers.get(INSTANCE_HEADER),options.instanceSecret))return{response:new Response("Forbidden",{status:403})};return{allow:"instance"}}const offered=url.searchParams.get("session");if(offered!==null){const expires=pending.get(offered);pending.delete(offered);if(request.method!=="GET"||expires===undefined||expires<Date.now())return{response:new Response(refusal,{status:401})};url.searchParams.delete("session");return{response:new Response(null,{status:302,headers:{location:`${url.pathname}${url.search}`,"set-cookie":sessionCookie(cookieName,session),"cache-control":"no-store"}})}}const cookies=request.headers.get("cookie");if(cookies&&cookies.split(/;\s*/).includes(`${cookieName}=${session}`))return{allow:"window"};if(options.publicPaths?.length&&matchesPath(url.pathname,options.publicPaths))return{allow:"public"};if(request.method==="GET"&&matchesPath(url.pathname,ASSET_PREFIXES))return{allow:"asset"};return{response:new Response(refusal,{status:401})}}}}export function portIsFree(port){try{Bun.listen({hostname:"127.0.0.1",port,socket:{data(){}}}).stop(true);return true}catch{return false}}export function pickAgentPort(options={}){const wanted=options.port??rememberedPort(options.portFile);let port=wanted&&portIsFree(wanted)?wanted:0;if(!port){const probe=Bun.listen({hostname:"127.0.0.1",port:0,socket:{data(){}}});port=probe.port;probe.stop(true)}rememberPort(options.portFile,port);return port}function rememberPort(portFile,port){if(!portFile)return;try{mkdirSync(dirname(portFile),{recursive:true});writeFileSync(portFile,String(port))}catch{}}export function desktopAppPaths(appName,options={}){const platform=options.platform??process.platform;const home=options.home??homedir();const env=options.env??process.env;const slug=appName.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")||"app";let dataDir;let logFile;const path=platform==="win32"?win32:posix;if(platform==="darwin"){dataDir=path.join(home,"Library","Application Support",appName);logFile=path.join(home,"Library","Logs",`${appName}.log`)}else if(platform==="win32"){dataDir=path.join(env.APPDATA||path.join(home,"AppData","Roaming"),appName);logFile=path.join(dataDir,"logs",`${appName}.log`)}else{dataDir=path.join(env.XDG_DATA_HOME||path.join(home,".local","share"),slug);logFile=path.join(env.XDG_STATE_HOME||path.join(home,".local","state"),slug,`${slug}.log`)}return{dataDir,portFile:path.join(dataDir,"agent.port"),lockFile:path.join(dataDir,"agent.lock"),logFile,updatesDir:path.join(dataDir,"updates")}}export function widenedPath(options={}){const platform=options.platform??process.platform;const home=options.home??homedir();const env=options.env??process.env;const current=env.PATH??env.Path??"";const path=platform==="win32"?win32:posix;const delimiter=platform==="win32"?";":":";const added=platform==="win32"?[path.join(home,".bun","bin"),path.join(env.LOCALAPPDATA||path.join(home,"AppData","Local"),"Microsoft","WinGet","Links"),path.join(home,"scoop","shims"),path.join(env.ProgramFiles||"C:\\Program Files","Git","cmd")]:[path.join(home,".local","bin"),path.join(home,".bun","bin"),path.join(home,".npm-global","bin"),path.join(home,".cargo","bin"),...platform==="darwin"?["/opt/homebrew/bin"]:["/home/linuxbrew/.linuxbrew/bin","/snap/bin"],"/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin"];const seen=new Set;return[...added,...current.split(delimiter)].filter((entry)=>{if(!entry||seen.has(entry))return false;seen.add(entry);return true}).join(delimiter)}export function applyWidenedPath(){const path=widenedPath();process.env.PATH=path;if(process.platform==="win32"&&process.env.Path!==undefined)process.env.Path=path}function embeddedFileResponse(files,pathname){let clean;try{clean=decodeURIComponent(pathname).replace(/\/+$/,"")||"/index"}catch{return null}for(const candidate of clean==="/index"?["/index.html"]:[`${clean}.html`,`${clean}/index.html`,clean]){const file=files[candidate];if(!file)continue;const headers={"content-type":staticContentType(candidate)};if(candidate.endsWith(".html"))headers["cache-control"]="no-store";return new Response(Bun.file(file),{headers})}return null}async function readSecondInstance(request){const body=await request.json().catch(()=>null);if(!body||!Array.isArray(body.args)||!body.args.every((arg)=>typeof arg==="string"))return null;return{args:body.args,cwd:typeof body.cwd==="string"?body.cwd:"",...typeof body.url==="string"?{url:body.url}:{}}}export async function startWebviewAgent(options){let port=0;const gate=createWebviewGate({port:()=>port,cookieName:options.cookieName,publicPaths:options.publicPaths,instanceSecret:options.instanceSecret,appName:options.appName});let markReady;const windowReady=new Promise((resolve)=>{markReady=resolve});const context=()=>({appName:options.appName,version:options.version??"0.0.0",origin:`http://127.0.0.1:${port}`,port,dataDir:options.dataDir??""});async function before(request){const decision=gate.check(request);if("response"in decision)return decision.response;if(decision.allow==="instance"){const launch=await readSecondInstance(request);if(!launch)return new Response("Bad request",{status:400});try{await options.onSecondInstance?.(launch)}catch(error){console.error(`[agent] second instance: ${error instanceof Error?error.message:String(error)}`)}return new Response(null,{status:204})}if(decision.allow==="asset")return;if(decision.allow==="window")markReady();if(!options.handler)return decision.allow==="public"?new Response("Not found",{status:404}):undefined;try{const answer=await options.handler(request,context());if(answer instanceof Response)return answer}catch(error){const message=error instanceof Error?error.message:String(error);console.error(`[agent] ${request.method} ${new URL(request.url).pathname}: ${message}`);return new Response(JSON.stringify({error:message}),{status:500,headers:{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}})}return decision.allow==="public"?new Response("Not found",{status:404}):undefined}const launchUrl=(path="/")=>{const url=new URL(path,`http://127.0.0.1:${port}`);url.searchParams.set("session",gate.mint());return url.toString()};const views=options.views;if(views.kind==="stx"){port=pickAgentPort({port:options.port,portFile:options.portFile});const serve=views.serve??(await import(Bun.resolveSync("bun-plugin-stx/serve",views.root))).serve;let stxServer;const[componentsDir,...additionalComponentsDirs]=views.components??[];serve({patterns:[views.dir],port,quiet:true,...componentsDir?{componentsDir}:{},...additionalComponentsDirs.length?{additionalComponentsDirs}:{},onRequest:(request,server)=>{stxServer=server;return before(request)}});for(let attempt=0;attempt<200;attempt++){try{await fetch(`http://127.0.0.1:${port}/`,{redirect:"manual"});break}catch{await Bun.sleep(25)}}return{port,origin:`http://127.0.0.1:${port}`,launchUrl,windowReady,stop:()=>{stxServer?.stop(true)}}}const fetchHandler=async(request)=>{const answered=await before(request);if(answered)return answered;const pathname=new URL(request.url).pathname;const page=request.method!=="GET"&&request.method!=="HEAD"?null:views.kind==="static"?staticFileResponse(views.dir,pathname):views.kind==="embedded"?embeddedFileResponse(views.files,pathname):null;return page??new Response("Not found",{status:404})};const listen=(wanted)=>Bun.serve({hostname:"127.0.0.1",port:wanted,idleTimeout:0,fetch:fetchHandler});const wanted=options.port??rememberedPort(options.portFile);let server;try{server=listen(wanted)}catch(error){if(wanted===0)throw error;server=listen(0)}port=server.port??0;rememberPort(options.portFile,port);return{port,origin:`http://127.0.0.1:${port}`,launchUrl,windowReady,stop:()=>{server.stop(true)}}}
1
+ import{timingSafeEqual}from"node:crypto";import{mkdirSync,writeFileSync}from"node:fs";import{homedir}from"node:os";import{dirname,posix,win32}from"node:path";import process from"node:process";import{isAgentHost,newAgentToken,rememberedPort,sessionCookie,staticContentType,staticFileResponse}from"./agent";export const INSTANCE_PATH="/__desktop/instance";export const INSTANCE_HEADER="x-desktop-instance";const ASSET_PREFIXES=["/_stx/","/assets/"];function sameSecret(given,expected){if(!given)return false;const left=Buffer.from(given);const right=Buffer.from(expected);return left.length===right.length&&timingSafeEqual(left,right)}function matchesPath(pathname,patterns){return patterns.some((pattern)=>pattern.endsWith("/")?pathname.startsWith(pattern):pathname===pattern)}const LAUNCH_TOKEN_TTL_MS=60000;export function createWebviewGate(options){const cookieName=options.cookieName??"stacks_desktop";const session=newAgentToken();const pending=new Map;const refusal=`Open ${options.appName??"the app"} to use this.`;return{cookieName,mint(){const token=newAgentToken();pending.set(token,Date.now()+LAUNCH_TOKEN_TTL_MS);return token},check(request){const url=new URL(request.url);if(!isAgentHost(request.headers.get("host"),options.port()))return{response:new Response("Forbidden",{status:403})};if(url.pathname===INSTANCE_PATH){if(request.method!=="POST"||!options.instanceSecret||!sameSecret(request.headers.get(INSTANCE_HEADER),options.instanceSecret))return{response:new Response("Forbidden",{status:403})};return{allow:"instance"}}const offered=url.searchParams.get("session");if(offered!==null){const expires=pending.get(offered);pending.delete(offered);if(request.method!=="GET"||expires===undefined||expires<Date.now())return{response:new Response(refusal,{status:401})};url.searchParams.delete("session");return{response:new Response(null,{status:302,headers:{location:`${url.pathname}${url.search}`,"set-cookie":sessionCookie(cookieName,session),"cache-control":"no-store"}})}}const cookies=request.headers.get("cookie");if(cookies&&cookies.split(/;\s*/).includes(`${cookieName}=${session}`))return{allow:"window"};if(options.publicPaths?.length&&matchesPath(url.pathname,options.publicPaths))return{allow:"public"};if(request.method==="GET"&&matchesPath(url.pathname,ASSET_PREFIXES))return{allow:"asset"};return{response:new Response(refusal,{status:401})}}}}export function portIsFree(port){try{Bun.listen({hostname:"127.0.0.1",port,socket:{data(){}}}).stop(true);return true}catch{return false}}export function pickAgentPort(options={}){const wanted=options.port??rememberedPort(options.portFile);let port=wanted&&portIsFree(wanted)?wanted:0;if(!port){const probe=Bun.listen({hostname:"127.0.0.1",port:0,socket:{data(){}}});port=probe.port;probe.stop(true)}rememberPort(options.portFile,port);return port}function rememberPort(portFile,port){if(!portFile)return;try{mkdirSync(dirname(portFile),{recursive:true});writeFileSync(portFile,String(port))}catch{}}export function desktopAppPaths(appName,options={}){const platform=options.platform??process.platform;const home=options.home??homedir();const env=options.env??process.env;const slug=appName.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")||"app";let dataDir;let logFile;const path=platform==="win32"?win32:posix;if(platform==="darwin"){dataDir=path.join(home,"Library","Application Support",appName);logFile=path.join(home,"Library","Logs",`${appName}.log`)}else if(platform==="win32"){dataDir=path.join(env.APPDATA||path.join(home,"AppData","Roaming"),appName);logFile=path.join(dataDir,"logs",`${appName}.log`)}else{dataDir=path.join(env.XDG_DATA_HOME||path.join(home,".local","share"),slug);logFile=path.join(env.XDG_STATE_HOME||path.join(home,".local","state"),slug,`${slug}.log`)}return{dataDir,portFile:path.join(dataDir,"agent.port"),lockFile:path.join(dataDir,"agent.lock"),logFile,updatesDir:path.join(dataDir,"updates")}}export function widenedPath(options={}){const platform=options.platform??process.platform;const home=options.home??homedir();const env=options.env??process.env;const current=env.PATH??env.Path??"";const path=platform==="win32"?win32:posix;const delimiter=platform==="win32"?";":":";const added=platform==="win32"?[path.join(home,".bun","bin"),path.join(env.LOCALAPPDATA||path.join(home,"AppData","Local"),"Microsoft","WinGet","Links"),path.join(home,"scoop","shims"),path.join(env.ProgramFiles||"C:\\Program Files","Git","cmd")]:[path.join(home,".local","bin"),path.join(home,".bun","bin"),path.join(home,".npm-global","bin"),path.join(home,".cargo","bin"),...platform==="darwin"?["/opt/homebrew/bin"]:["/home/linuxbrew/.linuxbrew/bin","/snap/bin"],"/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin"];const seen=new Set;return[...added,...current.split(delimiter)].filter((entry)=>{if(!entry||seen.has(entry))return false;seen.add(entry);return true}).join(delimiter)}export function applyWidenedPath(){const path=widenedPath();process.env.PATH=path;if(process.platform==="win32"&&process.env.Path!==undefined)process.env.Path=path}function embeddedFileResponse(files,pathname){let clean;try{clean=decodeURIComponent(pathname).replace(/\/+$/,"")||"/index"}catch{return null}for(const candidate of clean==="/index"?["/index.html"]:[`${clean}.html`,`${clean}/index.html`,clean]){const file=files[candidate];if(!file)continue;const headers={"content-type":staticContentType(candidate)};if(candidate.endsWith(".html"))headers["cache-control"]="no-store";return new Response(Bun.file(file),{headers})}return null}async function readSecondInstance(request){const body=await request.json().catch(()=>null);if(!body||!Array.isArray(body.args)||!body.args.every((arg)=>typeof arg==="string"))return null;return{args:body.args,cwd:typeof body.cwd==="string"?body.cwd:"",...typeof body.url==="string"?{url:body.url}:{}}}export async function startWebviewAgent(options){let port=0;const gate=createWebviewGate({port:()=>port,cookieName:options.cookieName,publicPaths:options.publicPaths,instanceSecret:options.instanceSecret,appName:options.appName});let markReady;const windowReady=new Promise((resolve)=>{markReady=resolve});const context=()=>({appName:options.appName,version:options.version??"0.0.0",origin:`http://127.0.0.1:${port}`,port,dataDir:options.dataDir??""});async function before(request){const decision=gate.check(request);if("response"in decision)return decision.response;if(decision.allow==="instance"){const launch=await readSecondInstance(request);if(!launch)return new Response("Bad request",{status:400});try{await options.onSecondInstance?.(launch)}catch(error){console.error(`[agent] second instance: ${error instanceof Error?error.message:String(error)}`)}return new Response(null,{status:204})}if(decision.allow==="asset")return;if(decision.allow==="window")markReady();if(!options.handler)return decision.allow==="public"?new Response("Not found",{status:404}):undefined;try{const answer=await options.handler(request,context());if(answer instanceof Response)return answer}catch(error){const message=error instanceof Error?error.message:String(error);console.error(`[agent] ${request.method} ${new URL(request.url).pathname}: ${message}`);return new Response(JSON.stringify({error:message}),{status:500,headers:{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}})}return decision.allow==="public"?new Response("Not found",{status:404}):undefined}const launchUrl=(path="/")=>{const url=new URL(path,`http://127.0.0.1:${port}`);url.searchParams.set("session",gate.mint());return url.toString()};const views=options.views;if(views.kind==="stx"){port=pickAgentPort({port:options.port,portFile:options.portFile});const serve=views.serve??(await import(Bun.resolveSync("bun-plugin-stx/serve",views.root))).serve;let stxServer;const{componentsDir,additionalComponentsDirs=[]}=webviewComponentDirs(views.components);serve({patterns:[views.dir],port,quiet:true,...componentsDir?{componentsDir}:{},...additionalComponentsDirs.length?{additionalComponentsDirs}:{},onRequest:(request,server)=>{stxServer=server;return before(request)}});for(let attempt=0;attempt<200;attempt++){try{await fetch(`http://127.0.0.1:${port}/`,{redirect:"manual"});break}catch{await Bun.sleep(25)}}return{port,origin:`http://127.0.0.1:${port}`,launchUrl,windowReady,stop:()=>{stxServer?.stop(true)}}}const fetchHandler=async(request)=>{const answered=await before(request);if(answered)return answered;const pathname=new URL(request.url).pathname;const page=request.method!=="GET"&&request.method!=="HEAD"?null:views.kind==="static"?staticFileResponse(views.dir,pathname):views.kind==="embedded"?embeddedFileResponse(views.files,pathname):null;return page??new Response("Not found",{status:404})};const listen=(wanted)=>Bun.serve({hostname:"127.0.0.1",port:wanted,idleTimeout:0,fetch:fetchHandler});const wanted=options.port??rememberedPort(options.portFile);let server;try{server=listen(wanted)}catch(error){if(wanted===0)throw error;server=listen(0)}port=server.port??0;rememberPort(options.portFile,port);return{port,origin:`http://127.0.0.1:${port}`,launchUrl,windowReady,stop:()=>{server.stop(true)}}}export function webviewComponentDirs(components=[]){const[componentsDir,...additionalComponentsDirs]=components;return{...componentsDir?{componentsDir}:{},...additionalComponentsDirs.length?{additionalComponentsDirs}:{}}}
@@ -71,6 +71,14 @@ export declare function releaseArtifactNames(config: Pick<ResolvedWebviewDesktop
71
71
  * they have.
72
72
  */
73
73
  export declare function releaseVersionProblem(version: string, published: string | null | undefined, compare: (left: string, right: string) => number): string | undefined;
74
+ /** `webview.agent.components`, as absolute directories, in the order the config lists them. */
75
+ export declare function resolveWebviewComponents(root: string, components: readonly string[] | undefined): string[];
76
+ /**
77
+ * The script `buddy build:desktop` runs to render an app's views to static
78
+ * files. It hands stx the same component directories, in the same order, as
79
+ * the server `buddy dev:desktop` starts.
80
+ */
81
+ export declare function renderViewsBuildScript(options: { appName: string, root: string, viewsDir: string, outDir: string, components?: readonly string[] }): string;
74
82
  /**
75
83
  * `desktop.webview` resolved, and the pieces `buddy build:desktop` puts
76
84
  * together for it: which targets, how each is compiled, and what each
@@ -1,6 +1,10 @@
1
- import{chmodSync,copyFileSync,existsSync,mkdirSync,readdirSync,readFileSync,rmSync,statSync,writeFileSync}from"node:fs";import{isAbsolute,join,relative,resolve,sep}from"node:path";import process from"node:process";import{codesignArgs,plistValue,renderInfoPlist}from"./index";import{loadDesktopConfig}from"./macos-app";import{makeIcns,runBundleCommand}from"./macos-bundle";import{OPTIONAL_CRAFT_FLAGS,WEBVIEW_RUNTIME_NAME}from"./webview-launcher";export const DESKTOP_TARGETS=["darwin-arm64","darwin-x64","linux-x64","linux-arm64","win32-x64","win32-arm64"];export const WEBVIEW_DEFAULTS={views:"resources/desktop",output:"storage/framework/desktop/webview",width:1280,height:800,minimumSystemVersion:"13.0",category:"public.app-category.developer-tools"};export async function hasWebviewDesktop(root){return Boolean((await loadDesktopConfig(root))?.webview)}export async function loadWebviewDesktop(root,packageVersion="0.0.0"){const config=await loadDesktopConfig(root);return config?.webview?resolveWebviewDesktop(config.webview,packageVersion):null}export function resolveWebviewDesktop(config,packageVersion="0.0.0"){return{...config,version:config.version??packageVersion,window:{...config.window,title:config.window?.title??config.appName,width:config.window?.width??WEBVIEW_DEFAULTS.width,height:config.window?.height??WEBVIEW_DEFAULTS.height},agent:{...config.agent,views:config.agent?.views??WEBVIEW_DEFAULTS.views},output:config.output??WEBVIEW_DEFAULTS.output,executable:config.appName.replace(/[^\w .-]+/g,"").trim()||"App",slug:config.appName.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")||"app"}}export function validateWebviewDesktop(config){const errors=[];if(!config.appName?.trim())errors.push("webview.appName is required");if(!/^[a-z0-9-]+(\.[a-z0-9-]+)+$/i.test(config.appId??""))errors.push(`webview.appId must be reverse-DNS, like org.example.app (got ${JSON.stringify(config.appId)})`);if(!/^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/.test(config.version))errors.push(`webview.version must be a semantic version (got ${JSON.stringify(config.version)})`);for(const scheme of config.urlSchemes??[]){if(!/^[a-z][a-z0-9+.-]*$/i.test(scheme))errors.push(`webview.urlSchemes: ${JSON.stringify(scheme)} is not a URL scheme`)}if(config.updates){try{const url=new URL(config.updates.feedUrl);if(url.protocol!=="https:"&&!["localhost","127.0.0.1"].includes(url.hostname))errors.push("webview.updates.feedUrl must be https")}catch{errors.push(`webview.updates.feedUrl is not a URL (got ${JSON.stringify(config.updates.feedUrl)})`)}const keys=Object.entries(config.updates.publicKeys??{});if(!keys.length)errors.push("webview.updates.publicKeys needs at least one key (run `buddy desktop:update:keypair`)");for(const[id,key]of keys){if(!key.startsWith("ed25519-public:"))errors.push(`webview.updates.publicKeys.${id} is not a public key (it starts with ed25519-public:)`)}}return errors}export function hostDesktopTarget(){return`${process.platform}-${process.arch}`}export function parseDesktopTargets(input,host=hostDesktopTarget()){if(!input?.trim())return[host];if(input.trim()==="all")return[...DESKTOP_TARGETS];const targets=input.split(",").map((part)=>part.trim()).filter(Boolean).map((part)=>{const name=part.replace(/^macos-/,"darwin-").replace(/^windows-/,"win32-");if(!DESKTOP_TARGETS.includes(name))throw new Error(`Unknown desktop target ${JSON.stringify(part)}. Targets: ${DESKTOP_TARGETS.join(", ")}, or all.`);return name});return[...new Set(targets)]}export function splitDesktopTarget(target){const[platform,architecture]=target.split("-");return{platform,architecture}}export function bunCompileTarget(target){const{platform,architecture}=splitDesktopTarget(target);return`bun-${platform==="win32"?"windows":platform}-${architecture}`}export function webviewCompileArgs(options){const cross=options.target!==(options.host??hostDesktopTarget());return["build","--compile",...options.minify===false?[]:["--minify"],...cross?[`--target=${bunCompileTarget(options.target)}`]:["--bytecode","--format=esm"],"--no-compile-autoload-bunfig","--no-compile-autoload-dotenv",...options.target.startsWith("win32-")?["--windows-hide-console"]:[],options.entry,"--outfile",options.outfile]}export function webviewRuntimeFor(config,target,options){const env=options.env??process.env;const variable=`CRAFT_BIN_${target.replace("-","_").toUpperCase()}`;const named=config.runtime?.[target]??env[variable];if(named){const file=isAbsolute(named)?named:resolve(options.root,named);if(!existsSync(file))throw new Error(`The Craft runtime for ${target} does not exist: ${file}`);return file}if(target===(options.host??hostDesktopTarget())&&options.hostRuntime)return options.hostRuntime();throw new Error(`No Craft runtime for ${target}. Unpack that platform's Craft release and name its binary in desktop.webview.runtime['${target}'] or ${variable}.`)}export function probeCraftFlags(runtime,flags=OPTIONAL_CRAFT_FLAGS){const binary=readFileSync(runtime);return flags.filter((flag)=>binary.includes(flag))}export function webviewManifest(config,options){return{appName:config.appName,appId:config.appId,version:config.version,runtime:options.runtime,window:{title:config.window.title,width:config.window.width,height:config.window.height,...config.window.darkMode!==undefined?{darkMode:config.window.darkMode}:{},...options.development||config.window.devtools?{devtools:true}:{},...config.window.titlebarHidden?{titlebarHidden:true}:{},...config.window.arguments?.length?{arguments:config.window.arguments}:{}},...config.agent.port?{port:config.agent.port}:{},...config.agent.startPath?{startPath:config.agent.startPath}:{},...config.agent.publicPaths?.length?{publicPaths:config.agent.publicPaths}:{},...config.urlSchemes?.length?{urlSchemes:config.urlSchemes}:{},...config.updates&&!options.development?{updates:{feedUrl:config.updates.feedUrl,publicKeys:config.updates.publicKeys,...config.updates.channel?{channel:config.updates.channel}:{},...config.updates.checkEveryHours!==undefined?{checkEveryHours:config.updates.checkEveryHours}:{}}}:{},...options.runtimeFlags?.length?{runtimeFlags:options.runtimeFlags}:{},...options.sourceRevision?{sourceRevision:options.sourceRevision}:{}}}export function collectViewFiles(directory){const files={};const walk=(current)=>{for(const entry of readdirSync(current).sort()){if(entry===".DS_Store")continue;const file=join(current,entry);if(statSync(file).isDirectory())walk(file);else files[`/${relative(directory,file).split(sep).join("/")}`]=file}};if(existsSync(directory))walk(directory);return files}export const BUN_HARDENED_ENTITLEMENTS={"com.apple.security.cs.allow-jit":true,"com.apple.security.cs.allow-unsigned-executable-memory":true,"com.apple.security.cs.disable-library-validation":true};export function renderWebviewEntitlements(config){return`<?xml version="1.0" encoding="UTF-8"?>
1
+ import{chmodSync,copyFileSync,existsSync,mkdirSync,readdirSync,readFileSync,rmSync,statSync,writeFileSync}from"node:fs";import{isAbsolute,join,relative,resolve,sep}from"node:path";import process from"node:process";import{codesignArgs,plistValue,renderInfoPlist}from"./index";import{loadDesktopConfig}from"./macos-app";import{makeIcns,runBundleCommand}from"./macos-bundle";import{webviewComponentDirs}from"./webview-agent";import{OPTIONAL_CRAFT_FLAGS,WEBVIEW_RUNTIME_NAME}from"./webview-launcher";export const DESKTOP_TARGETS=["darwin-arm64","darwin-x64","linux-x64","linux-arm64","win32-x64","win32-arm64"];export const WEBVIEW_DEFAULTS={views:"resources/desktop",output:"storage/framework/desktop/webview",width:1280,height:800,minimumSystemVersion:"13.0",category:"public.app-category.developer-tools"};export async function hasWebviewDesktop(root){return Boolean((await loadDesktopConfig(root))?.webview)}export async function loadWebviewDesktop(root,packageVersion="0.0.0"){const config=await loadDesktopConfig(root);return config?.webview?resolveWebviewDesktop(config.webview,packageVersion):null}export function resolveWebviewDesktop(config,packageVersion="0.0.0"){return{...config,version:config.version??packageVersion,window:{...config.window,title:config.window?.title??config.appName,width:config.window?.width??WEBVIEW_DEFAULTS.width,height:config.window?.height??WEBVIEW_DEFAULTS.height},agent:{...config.agent,views:config.agent?.views??WEBVIEW_DEFAULTS.views},output:config.output??WEBVIEW_DEFAULTS.output,executable:config.appName.replace(/[^\w .-]+/g,"").trim()||"App",slug:config.appName.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")||"app"}}export function validateWebviewDesktop(config){const errors=[];if(!config.appName?.trim())errors.push("webview.appName is required");if(!/^[a-z0-9-]+(\.[a-z0-9-]+)+$/i.test(config.appId??""))errors.push(`webview.appId must be reverse-DNS, like org.example.app (got ${JSON.stringify(config.appId)})`);if(!/^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/.test(config.version))errors.push(`webview.version must be a semantic version (got ${JSON.stringify(config.version)})`);for(const scheme of config.urlSchemes??[]){if(!/^[a-z][a-z0-9+.-]*$/i.test(scheme))errors.push(`webview.urlSchemes: ${JSON.stringify(scheme)} is not a URL scheme`)}if(config.updates){try{const url=new URL(config.updates.feedUrl);if(url.protocol!=="https:"&&!["localhost","127.0.0.1"].includes(url.hostname))errors.push("webview.updates.feedUrl must be https")}catch{errors.push(`webview.updates.feedUrl is not a URL (got ${JSON.stringify(config.updates.feedUrl)})`)}const keys=Object.entries(config.updates.publicKeys??{});if(!keys.length)errors.push("webview.updates.publicKeys needs at least one key (run `buddy desktop:update:keypair`)");for(const[id,key]of keys){if(!key.startsWith("ed25519-public:"))errors.push(`webview.updates.publicKeys.${id} is not a public key (it starts with ed25519-public:)`)}}return errors}export function hostDesktopTarget(){return`${process.platform}-${process.arch}`}export function parseDesktopTargets(input,host=hostDesktopTarget()){if(!input?.trim())return[host];if(input.trim()==="all")return[...DESKTOP_TARGETS];const targets=input.split(",").map((part)=>part.trim()).filter(Boolean).map((part)=>{const name=part.replace(/^macos-/,"darwin-").replace(/^windows-/,"win32-");if(!DESKTOP_TARGETS.includes(name))throw new Error(`Unknown desktop target ${JSON.stringify(part)}. Targets: ${DESKTOP_TARGETS.join(", ")}, or all.`);return name});return[...new Set(targets)]}export function splitDesktopTarget(target){const[platform,architecture]=target.split("-");return{platform,architecture}}export function bunCompileTarget(target){const{platform,architecture}=splitDesktopTarget(target);return`bun-${platform==="win32"?"windows":platform}-${architecture}`}export function webviewCompileArgs(options){const cross=options.target!==(options.host??hostDesktopTarget());return["build","--compile",...options.minify===false?[]:["--minify"],...cross?[`--target=${bunCompileTarget(options.target)}`]:["--bytecode","--format=esm"],"--no-compile-autoload-bunfig","--no-compile-autoload-dotenv",...options.target.startsWith("win32-")?["--windows-hide-console"]:[],options.entry,"--outfile",options.outfile]}export function webviewRuntimeFor(config,target,options){const env=options.env??process.env;const variable=`CRAFT_BIN_${target.replace("-","_").toUpperCase()}`;const named=config.runtime?.[target]??env[variable];if(named){const file=isAbsolute(named)?named:resolve(options.root,named);if(!existsSync(file))throw new Error(`The Craft runtime for ${target} does not exist: ${file}`);return file}if(target===(options.host??hostDesktopTarget())&&options.hostRuntime)return options.hostRuntime();throw new Error(`No Craft runtime for ${target}. Unpack that platform's Craft release and name its binary in desktop.webview.runtime['${target}'] or ${variable}.`)}export function probeCraftFlags(runtime,flags=OPTIONAL_CRAFT_FLAGS){const binary=readFileSync(runtime);return flags.filter((flag)=>binary.includes(flag))}export function webviewManifest(config,options){return{appName:config.appName,appId:config.appId,version:config.version,runtime:options.runtime,window:{title:config.window.title,width:config.window.width,height:config.window.height,...config.window.darkMode!==undefined?{darkMode:config.window.darkMode}:{},...options.development||config.window.devtools?{devtools:true}:{},...config.window.titlebarHidden?{titlebarHidden:true}:{},...config.window.arguments?.length?{arguments:config.window.arguments}:{}},...config.agent.port?{port:config.agent.port}:{},...config.agent.startPath?{startPath:config.agent.startPath}:{},...config.agent.publicPaths?.length?{publicPaths:config.agent.publicPaths}:{},...config.urlSchemes?.length?{urlSchemes:config.urlSchemes}:{},...config.updates&&!options.development?{updates:{feedUrl:config.updates.feedUrl,publicKeys:config.updates.publicKeys,...config.updates.channel?{channel:config.updates.channel}:{},...config.updates.checkEveryHours!==undefined?{checkEveryHours:config.updates.checkEveryHours}:{}}}:{},...options.runtimeFlags?.length?{runtimeFlags:options.runtimeFlags}:{},...options.sourceRevision?{sourceRevision:options.sourceRevision}:{}}}export function collectViewFiles(directory){const files={};const walk=(current)=>{for(const entry of readdirSync(current).sort()){if(entry===".DS_Store")continue;const file=join(current,entry);if(statSync(file).isDirectory())walk(file);else files[`/${relative(directory,file).split(sep).join("/")}`]=file}};if(existsSync(directory))walk(directory);return files}export const BUN_HARDENED_ENTITLEMENTS={"com.apple.security.cs.allow-jit":true,"com.apple.security.cs.allow-unsigned-executable-memory":true,"com.apple.security.cs.disable-library-validation":true};export function renderWebviewEntitlements(config){return`<?xml version="1.0" encoding="UTF-8"?>
2
2
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "https://www.apple.com/DTDs/PropertyList-1.0.dtd">
3
3
  <plist version="1.0">
4
4
  ${plistValue({...BUN_HARDENED_ENTITLEMENTS,...config.macos?.entitlements})}
5
5
  </plist>
6
- `}export function renderWebviewInfoPlist(config,options={}){const schemes=config.urlSchemes??[];return renderInfoPlist({appName:config.appName,bundleId:config.macos?.bundleId??config.appId,version:config.version,executable:config.executable,iconFile:options.iconFile,ownsLauncher:true,declared:{LSMinimumSystemVersion:config.macos?.minimumSystemVersion??WEBVIEW_DEFAULTS.minimumSystemVersion,LSApplicationCategoryType:config.macos?.category??WEBVIEW_DEFAULTS.category,...schemes.length?{CFBundleURLTypes:[{CFBundleURLName:config.appId,CFBundleURLSchemes:schemes}]}:{},...config.macos?.usageDescriptions,...config.macos?.infoPlist}})}export function assembleWebviewMacosApp(options){const{config}=options;const run=options.run??runBundleCommand;const identity=options.signingIdentity??"-";const appPath=join(options.output,`${config.appName}.app`);const macos=join(appPath,"Contents","MacOS");const resources=join(appPath,"Contents","Resources");rmSync(appPath,{recursive:true,force:true});mkdirSync(macos,{recursive:true});mkdirSync(resources,{recursive:true});const executable=join(macos,config.executable);const runtime=join(macos,WEBVIEW_RUNTIME_NAME);copyFileSync(options.agent,executable);copyFileSync(options.runtime,runtime);chmodSync(executable,493);chmodSync(runtime,493);let iconFile;if(config.icon){const icon=resolve(options.root,config.icon);if(!existsSync(icon))throw new Error(`webview.icon does not exist: ${icon}`);if(icon.endsWith(".icns"))copyFileSync(icon,join(resources,"AppIcon.icns"));else makeIcns(icon,join(resources,"AppIcon.icns"),options.output,run);iconFile="AppIcon"}const plist=renderWebviewInfoPlist(config,{iconFile});writeFileSync(join(appPath,"Contents","Info.plist"),plist.xml);const entitlementsPath=join(options.output,`${config.appName}.entitlements`);writeFileSync(entitlementsPath,renderWebviewEntitlements(config));run(codesignArgs({identity,target:runtime}));run(codesignArgs({identity,target:appPath,entitlements:entitlementsPath}));return{appPath,entitlementsPath,ignoredPlistKeys:plist.ignored}}export function webviewPackageConfig(config,target,staged){const{platform,architecture}=splitDesktopTarget(target);const base={name:config.appName,version:config.version,...config.description?{description:config.description}:{},...config.publisher?{author:config.publisher}:{},...config.homepage?{homepage:config.homepage}:{},bundleId:config.appId,binaryPath:staged.binary,...staged.icon?{iconPath:staged.icon}:{},outDir:staged.outDir};if(platform==="win32"){return{...base,platforms:["windows"],windows:{msi:true,zip:true,architecture,...staged.additionalFiles?.length?{additionalFiles:staged.additionalFiles}:{},...config.urlSchemes?.length?{urlSchemes:config.urlSchemes}:{},...config.windows?.certificatePath?{certificatePath:config.windows.certificatePath,...staged.certificatePassword?{certificatePassword:staged.certificatePassword}:{}}:{}}}}return{...base,platforms:["linux"],linux:{appImage:true,deb:true,rpm:true,categories:config.linux?.categories??["Development"],...config.urlSchemes?.length?{urlSchemes:config.urlSchemes}:{},...config.linux?.debDependencies?{debDependencies:config.linux.debDependencies}:{},...config.linux?.rpmDependencies?{rpmDependencies:config.linux.rpmDependencies}:{}}}}export function nativeBuildSteps(target){const{platform}=splitDesktopTarget(target);if(platform==="darwin")return"The .app is assembled and signed with codesign, notarized with notarytool and imaged with hdiutil: macOS only.";if(platform==="win32")return"The MSI is built with WiX (candle, light) and signed with signtool: Windows only.";return"The AppImage (appimagetool), deb (dpkg-deb) and rpm (rpmbuild) are built with Linux tools: Linux only."}export function signtoolArgs(options){return["signtool.exe","sign","/f",options.certificatePath,...options.certificatePassword?["/p",options.certificatePassword]:[],"/fd","SHA256","/tr",options.timestampUrl??"http://timestamp.digicert.com","/td","SHA256",options.file]}export function releaseArtifactNames(config,target){const{platform,architecture}=splitDesktopTarget(target);const base=`${config.appName.replace(/[^\w.-]+/g,"-")}-${config.version}-${architecture}`;if(platform==="darwin")return{update:`${base}.zip`,downloads:[`${base}.dmg`]};if(platform==="win32")return{update:`${base}.msi`,downloads:[]};return{update:`${base}.AppImage`,downloads:[`${base}.deb`,`${base}.rpm`]}}export function releaseVersionProblem(version,published,compare){if(!published)return;const order=compare(version,published);if(order===0)return`${version} is already published. Bump the version; a published build is never replaced under the same number.`;if(order<0)return`${published} is already published, which is newer than ${version}.`;return}
6
+ `}export function renderWebviewInfoPlist(config,options={}){const schemes=config.urlSchemes??[];return renderInfoPlist({appName:config.appName,bundleId:config.macos?.bundleId??config.appId,version:config.version,executable:config.executable,iconFile:options.iconFile,ownsLauncher:true,declared:{LSMinimumSystemVersion:config.macos?.minimumSystemVersion??WEBVIEW_DEFAULTS.minimumSystemVersion,LSApplicationCategoryType:config.macos?.category??WEBVIEW_DEFAULTS.category,...schemes.length?{CFBundleURLTypes:[{CFBundleURLName:config.appId,CFBundleURLSchemes:schemes}]}:{},...config.macos?.usageDescriptions,...config.macos?.infoPlist}})}export function assembleWebviewMacosApp(options){const{config}=options;const run=options.run??runBundleCommand;const identity=options.signingIdentity??"-";const appPath=join(options.output,`${config.appName}.app`);const macos=join(appPath,"Contents","MacOS");const resources=join(appPath,"Contents","Resources");rmSync(appPath,{recursive:true,force:true});mkdirSync(macos,{recursive:true});mkdirSync(resources,{recursive:true});const executable=join(macos,config.executable);const runtime=join(macos,WEBVIEW_RUNTIME_NAME);copyFileSync(options.agent,executable);copyFileSync(options.runtime,runtime);chmodSync(executable,493);chmodSync(runtime,493);let iconFile;if(config.icon){const icon=resolve(options.root,config.icon);if(!existsSync(icon))throw new Error(`webview.icon does not exist: ${icon}`);if(icon.endsWith(".icns"))copyFileSync(icon,join(resources,"AppIcon.icns"));else makeIcns(icon,join(resources,"AppIcon.icns"),options.output,run);iconFile="AppIcon"}const plist=renderWebviewInfoPlist(config,{iconFile});writeFileSync(join(appPath,"Contents","Info.plist"),plist.xml);const entitlementsPath=join(options.output,`${config.appName}.entitlements`);writeFileSync(entitlementsPath,renderWebviewEntitlements(config));run(codesignArgs({identity,target:runtime}));run(codesignArgs({identity,target:appPath,entitlements:entitlementsPath}));return{appPath,entitlementsPath,ignoredPlistKeys:plist.ignored}}export function webviewPackageConfig(config,target,staged){const{platform,architecture}=splitDesktopTarget(target);const base={name:config.appName,version:config.version,...config.description?{description:config.description}:{},...config.publisher?{author:config.publisher}:{},...config.homepage?{homepage:config.homepage}:{},bundleId:config.appId,binaryPath:staged.binary,...staged.icon?{iconPath:staged.icon}:{},outDir:staged.outDir};if(platform==="win32"){return{...base,platforms:["windows"],windows:{msi:true,zip:true,architecture,...staged.additionalFiles?.length?{additionalFiles:staged.additionalFiles}:{},...config.urlSchemes?.length?{urlSchemes:config.urlSchemes}:{},...config.windows?.certificatePath?{certificatePath:config.windows.certificatePath,...staged.certificatePassword?{certificatePassword:staged.certificatePassword}:{}}:{}}}}return{...base,platforms:["linux"],linux:{appImage:true,deb:true,rpm:true,categories:config.linux?.categories??["Development"],...config.urlSchemes?.length?{urlSchemes:config.urlSchemes}:{},...config.linux?.debDependencies?{debDependencies:config.linux.debDependencies}:{},...config.linux?.rpmDependencies?{rpmDependencies:config.linux.rpmDependencies}:{}}}}export function nativeBuildSteps(target){const{platform}=splitDesktopTarget(target);if(platform==="darwin")return"The .app is assembled and signed with codesign, notarized with notarytool and imaged with hdiutil: macOS only.";if(platform==="win32")return"The MSI is built with WiX (candle, light) and signed with signtool: Windows only.";return"The AppImage (appimagetool), deb (dpkg-deb) and rpm (rpmbuild) are built with Linux tools: Linux only."}export function signtoolArgs(options){return["signtool.exe","sign","/f",options.certificatePath,...options.certificatePassword?["/p",options.certificatePassword]:[],"/fd","SHA256","/tr",options.timestampUrl??"http://timestamp.digicert.com","/td","SHA256",options.file]}export function releaseArtifactNames(config,target){const{platform,architecture}=splitDesktopTarget(target);const base=`${config.appName.replace(/[^\w.-]+/g,"-")}-${config.version}-${architecture}`;if(platform==="darwin")return{update:`${base}.zip`,downloads:[`${base}.dmg`]};if(platform==="win32")return{update:`${base}.msi`,downloads:[]};return{update:`${base}.AppImage`,downloads:[`${base}.deb`,`${base}.rpm`]}}export function releaseVersionProblem(version,published,compare){if(!published)return;const order=compare(version,published);if(order===0)return`${version} is already published. Bump the version; a published build is never replaced under the same number.`;if(order<0)return`${published} is already published, which is newer than ${version}.`;return}export function resolveWebviewComponents(root,components){return(components??[]).map((directory)=>resolve(root,directory))}export function renderViewsBuildScript(options){const pages=relative(options.root,options.viewsDir);const site={name:options.appName,url:"http://127.0.0.1",pagesDir:pages,outDir:options.outDir,publicDir:join(pages,"public"),...webviewComponentDirs(resolveWebviewComponents(options.root,options.components)),sitemap:false,robots:false};return`// Written by buddy build:desktop. Do not edit.
7
+ import { buildStaticSite } from '@stacksjs/stx'
8
+
9
+ await buildStaticSite(${JSON.stringify(site,null,2)})
10
+ `}
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/desktop-build",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.75.556",
5
+ "version": "0.75.557",
6
6
  "description": "Build and launch Craft desktop applications for Stacks",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -73,17 +73,17 @@
73
73
  "prepublishOnly": "bun run build"
74
74
  },
75
75
  "dependencies": {
76
- "@stacksjs/config": "0.75.556",
77
- "@stacksjs/router": "0.75.556",
78
- "@stacksjs/server": "0.75.556",
79
- "@stacksjs/storage": "0.75.556",
76
+ "@stacksjs/config": "0.75.557",
77
+ "@stacksjs/router": "0.75.557",
78
+ "@stacksjs/server": "0.75.557",
79
+ "@stacksjs/storage": "0.75.557",
80
80
  "craft-native": ">=0.0.499"
81
81
  },
82
82
  "peerDependencies": {
83
- "@stacksjs/config": "0.75.556",
84
- "@stacksjs/router": "0.75.556",
85
- "@stacksjs/server": "0.75.556",
86
- "@stacksjs/storage": "0.75.556"
83
+ "@stacksjs/config": "0.75.557",
84
+ "@stacksjs/router": "0.75.557",
85
+ "@stacksjs/server": "0.75.557",
86
+ "@stacksjs/storage": "0.75.557"
87
87
  },
88
88
  "peerDependenciesMeta": {
89
89
  "@stacksjs/config": {
@@ -100,7 +100,7 @@
100
100
  }
101
101
  },
102
102
  "devDependencies": {
103
- "@stacksjs/build": "0.75.556",
103
+ "@stacksjs/build": "0.75.557",
104
104
  "better-dx": "^0.2.24"
105
105
  }
106
106
  }