@stacksjs/desktop-build 0.75.674 → 0.75.683
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.
- package/dist/agent-launcher.d.ts +17 -5
- package/dist/agent-launcher.js +5 -8
- package/dist/agent.js +1 -1
- package/dist/update-install.js +2 -2
- package/dist/webview-agent.js +1 -1
- package/dist/webview-launcher.d.ts +19 -1
- package/dist/webview-launcher.js +18 -3
- package/package.json +10 -10
package/dist/agent-launcher.d.ts
CHANGED
|
@@ -44,12 +44,12 @@ export declare function agentHostCommand(manifest: Pick<DesktopAgentManifest, 'h
|
|
|
44
44
|
*/
|
|
45
45
|
export declare function stacksAgentHandler(options: StacksAgentHandlerOptions): Promise<AgentHandler>;
|
|
46
46
|
/**
|
|
47
|
-
*
|
|
48
|
-
*
|
|
49
|
-
*
|
|
50
|
-
* module imports is inside the built app.
|
|
47
|
+
* Source for the loaders a compiled entry carries: each file named in a
|
|
48
|
+
* static `import()` the bundler follows, so it is inside the executable.
|
|
49
|
+
* Shared by the macOS agent entry and the webview one (stacksjs/stacks#3368).
|
|
51
50
|
*/
|
|
52
|
-
export declare function
|
|
51
|
+
export declare function agentBundleSource(files: AgentBundleFiles): { routes: string, actions: string, middleware: string };
|
|
52
|
+
export declare function renderAgentEntry(options?: { agentEntry?: string, launcherModule?: string } & AgentBundleFiles): string;
|
|
53
53
|
/**
|
|
54
54
|
* Lock, log, agent, host; resolves with the exit code once the window's
|
|
55
55
|
* process ends (or 0 at once when another copy is already running, which
|
|
@@ -108,6 +108,18 @@ export declare interface StacksAgentHandlerOptions {
|
|
|
108
108
|
actions?: Record<string, () => Promise<{ default?: unknown }>>
|
|
109
109
|
middleware?: Record<string, () => Promise<{ default?: unknown }>>
|
|
110
110
|
}
|
|
111
|
+
/**
|
|
112
|
+
* The launcher's entrypoint, written by the build next to the screens and
|
|
113
|
+
* compiled (or, in development, run) from there. It names the agent's own
|
|
114
|
+
* route module by absolute path so the bundler can follow it: whatever that
|
|
115
|
+
* module imports is inside the built app.
|
|
116
|
+
*/
|
|
117
|
+
/** The app's route files, the actions they name and its middleware, as files on the build machine. */
|
|
118
|
+
export declare interface AgentBundleFiles {
|
|
119
|
+
routes?: Array<{ file: string, prefix?: string, middleware?: string[] }>
|
|
120
|
+
actions?: Record<string, string>
|
|
121
|
+
middleware?: Record<string, string>
|
|
122
|
+
}
|
|
111
123
|
export declare interface RunDesktopAgentAppOptions {
|
|
112
124
|
manifest: DesktopAgentManifest
|
|
113
125
|
handler: () => Promise<AgentHandler>
|
package/dist/agent-launcher.js
CHANGED
|
@@ -1,14 +1,11 @@
|
|
|
1
1
|
import{appendFileSync,chmodSync,existsSync,mkdirSync,readFileSync,renameSync,rmSync,statSync,writeFileSync}from"node:fs";import{homedir}from"node:os";import{dirname,isAbsolute,join,resolve}from"node:path";import process from"node:process";import{fileURLToPath}from"node:url";import{format}from"node:util";import{startDesktopAgent}from"./agent";export const AGENT_MANIFEST="desktop-agent.json";export const AGENT_MANIFEST_ENV="STACKS_DESKTOP_AGENT_MANIFEST";export const AGENT_DATA_DIR_ENV="STACKS_DESKTOP_DATA_DIR";export const AGENT_RESOURCES_ENV="STACKS_DESKTOP_RESOURCES";export function desktopResource(name,env=process.env){try{const resources=JSON.parse(env[AGENT_RESOURCES_ENV]??"{}");return typeof resources[name]==="string"?resources[name]:undefined}catch{return}}export function desktopAgentPaths(appName,home=homedir()){const dataDir=join(home,"Library","Application Support",appName);return{dataDir,portFile:join(dataDir,"agent.port"),lockFile:join(dataDir,"agent.pid"),logFile:join(home,"Library","Logs",`${appName}.log`)}}export function acquireInstanceLock(lockFile,pid=process.pid){mkdirSync(dirname(lockFile),{recursive:true});if(existsSync(lockFile)){const holder=Number(readFileSync(lockFile,"utf8").trim());if(holder&&holder!==pid){try{process.kill(holder,0);return false}catch(error){if(error.code==="EPERM")return false}}}writeFileSync(lockFile,String(pid));return true}export function releaseInstanceLock(lockFile,pid=process.pid){try{if(readFileSync(lockFile,"utf8").trim()===String(pid))rmSync(lockFile)}catch{}}const DETACHED_LOG_MAX_BYTES=5*1024*1024;export function redactSessionTokens(text){return text.replace(/([?&]session=)[^&#\s"'`]+/g,"$1[redacted]")}export function logToFileWhenDetached(logFile,isTTY=Boolean(process.stdout.isTTY),options={}){if(isTTY)return false;const maxBytes=options.maxBytes??DETACHED_LOG_MAX_BYTES;mkdirSync(dirname(logFile),{recursive:true,mode:448});let size=0;try{size=statSync(logFile).size;chmodSync(logFile,384)}catch{}const rotate=()=>{try{renameSync(logFile,`${logFile}.1`)}catch{}size=0};if(size>maxBytes)rotate();for(const level of["log","info","warn","error","debug"]){console[level]=(...args)=>{try{const line=redactSessionTokens(`${new Date().toISOString()} ${level==="log"?"":`[${level}] `}${format(...args)}
|
|
2
|
-
`);const bytes=Buffer.byteLength(line);if(size>0&&size+bytes>maxBytes)rotate();appendFileSync(logFile,line,{mode:384});size+=bytes}catch{}}}return true}export function findAgentManifest(execPath=process.execPath,env=process.env){if(env[AGENT_MANIFEST_ENV])return resolve(env[AGENT_MANIFEST_ENV]);const bundled=join(dirname(execPath),"..","Resources",AGENT_MANIFEST);return existsSync(bundled)?bundled:null}export function readAgentManifest(file){const manifest=JSON.parse(readFileSync(file,"utf8"));const base=dirname(file);const at=(path)=>isAbsolute(path)?path:resolve(base,path);return{...manifest,host:at(manifest.host),nativeBundle:at(manifest.nativeBundle),...manifest.staticDir?{staticDir:at(manifest.staticDir)}:{},...manifest.resources?{resources:Object.fromEntries(Object.entries(manifest.resources).map(([name,path])=>[name,at(path)]))}:{}}}export function agentHostCommand(manifest,agentUrl){return[manifest.host,"--api-url",agentUrl,"--native-bundle",manifest.nativeBundle,...manifest.hostArguments]}export async function stacksAgentHandler(options){try{const{overridesReady}=await import("@stacksjs/config");await overridesReady}catch(error){console.warn(`[agent] config not loaded: ${error instanceof Error?error.message:String(error)}`)}if(options.appRoutes){try{const{injectGlobalAutoImports}=await import("@stacksjs/server");await injectGlobalAutoImports()}catch(error){console.warn(`[agent] models and framework globals not injected: ${error instanceof Error?error.message:String(error)}`)}}const{provideActions,provideMiddleware,route,serverResponse}=await import("@stacksjs/router");if(options.actions)provideActions(options.actions);if(options.middleware)provideMiddleware(options.middleware);const module=options.entry?await options.entry():undefined;if(typeof module?.default==="function")return module.default;if(options.appRoutes){const fromProject=(request)=>serverResponse(request);return fromProject}for(const file of options.routes??[]){if(file.prefix||file.middleware?.length)await route.group({prefix:file.prefix,middleware:file.middleware?.length?file.middleware:undefined},async()=>{await file.load()});else await file.load()}const bundled=(request)=>route.handleRequest(request);return bundled}export function
|
|
3
|
-
${
|
|
2
|
+
`);const bytes=Buffer.byteLength(line);if(size>0&&size+bytes>maxBytes)rotate();appendFileSync(logFile,line,{mode:384});size+=bytes}catch{}}}return true}export function findAgentManifest(execPath=process.execPath,env=process.env){if(env[AGENT_MANIFEST_ENV])return resolve(env[AGENT_MANIFEST_ENV]);const bundled=join(dirname(execPath),"..","Resources",AGENT_MANIFEST);return existsSync(bundled)?bundled:null}export function readAgentManifest(file){const manifest=JSON.parse(readFileSync(file,"utf8"));const base=dirname(file);const at=(path)=>isAbsolute(path)?path:resolve(base,path);return{...manifest,host:at(manifest.host),nativeBundle:at(manifest.nativeBundle),...manifest.staticDir?{staticDir:at(manifest.staticDir)}:{},...manifest.resources?{resources:Object.fromEntries(Object.entries(manifest.resources).map(([name,path])=>[name,at(path)]))}:{}}}export function agentHostCommand(manifest,agentUrl){return[manifest.host,"--api-url",agentUrl,"--native-bundle",manifest.nativeBundle,...manifest.hostArguments]}export async function stacksAgentHandler(options){try{const{overridesReady}=await import("@stacksjs/config");await overridesReady}catch(error){console.warn(`[agent] config not loaded: ${error instanceof Error?error.message:String(error)}`)}if(options.appRoutes){try{const{injectGlobalAutoImports}=await import("@stacksjs/server");await injectGlobalAutoImports()}catch(error){console.warn(`[agent] models and framework globals not injected: ${error instanceof Error?error.message:String(error)}`)}}const{provideActions,provideMiddleware,route,serverResponse}=await import("@stacksjs/router");if(options.actions)provideActions(options.actions);if(options.middleware)provideMiddleware(options.middleware);const module=options.entry?await options.entry():undefined;if(typeof module?.default==="function")return module.default;if(options.appRoutes){const fromProject=(request)=>serverResponse(request);return fromProject}for(const file of options.routes??[]){if(file.prefix||file.middleware?.length)await route.group({prefix:file.prefix,middleware:file.middleware?.length?file.middleware:undefined},async()=>{await file.load()});else await file.load()}const bundled=(request)=>route.handleRequest(request);return bundled}export function agentBundleSource(files){const routes=files.routes?.length?`[
|
|
3
|
+
${files.routes.map((file)=>` { load: () => import(${JSON.stringify(file.file)})${file.prefix?`, prefix: ${JSON.stringify(file.prefix)}`:""}${file.middleware?.length?`, middleware: ${JSON.stringify(file.middleware)}`:""} },`).join(`
|
|
4
4
|
`)}
|
|
5
|
-
]`:"[]";const
|
|
6
|
-
${
|
|
5
|
+
]`:"[]";const loaders=(entries)=>entries.length?`{
|
|
6
|
+
${entries.map(([name,file])=>` ${JSON.stringify(name)}: () => import(${JSON.stringify(file)}),`).join(`
|
|
7
7
|
`)}
|
|
8
|
-
}`:"{}";
|
|
9
|
-
${middlewareEntries.map(([name,file])=>` ${JSON.stringify(name)}: () => import(${JSON.stringify(file)}),`).join(`
|
|
10
|
-
`)}
|
|
11
|
-
}`:"{}";return`// Written by buddy build:desktop and buddy dev:desktop (macos.agent). Do not edit.
|
|
8
|
+
}`:"{}";return{routes,actions:loaders(Object.entries(files.actions??{})),middleware:loaders(Object.entries(files.middleware??{}))}}export function renderAgentEntry(options={}){const launcher=options.launcherModule??fileURLToPath(import.meta.url);const entry=options.agentEntry?`() => import(${JSON.stringify(options.agentEntry)})`:"undefined";const{routes,actions,middleware}=agentBundleSource(options);return`// Written by buddy build:desktop and buddy dev:desktop (macos.agent). Do not edit.
|
|
12
9
|
import process from 'node:process'
|
|
13
10
|
import { findAgentManifest, readAgentManifest, runDesktopAgentApp, stacksAgentHandler } from ${JSON.stringify(launcher)}
|
|
14
11
|
|
package/dist/agent.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{randomBytes}from"node:crypto";import{existsSync,mkdirSync,readFileSync,statSync,writeFileSync}from"node:fs";import{dirname,extname,join,normalize,sep}from"node:path";const MIME={".html":"text/html; charset=utf-8",".js":"text/javascript; charset=utf-8",".mjs":"text/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".json":"application/json; charset=utf-8",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".ico":"image/x-icon",".woff2":"font/woff2",".woff":"font/woff",".txt":"text/plain; charset=utf-8"};export function newAgentToken(){return randomBytes(24).toString("hex")}export function isAgentHost(host,port){return host===`127.0.0.1:${port}`||host===`localhost:${port}`}export function sessionCookie(name,token){return`${name}=${token}; Path=/; HttpOnly; SameSite=Strict`}export function hasSessionCookie(request,name,token){const cookies=request.headers.get("cookie");if(!cookies)return false;return cookies.split(/;\s*/).includes(`${name}=${token}`)}export function rememberedPort(portFile){if(!portFile)return 0;try{const port=Number(readFileSync(portFile,"utf8").trim());return Number.isInteger(port)&&port>1024&&port<65536?port:0}catch{return 0}}export function staticFileResponse(root,pathname){const base=normalize(root);let clean;try{clean=decodeURIComponent(pathname).replace(/\/+$/,"")||"/index"}catch{return null}const candidates=clean==="/index"?["index.html"]:[`${clean}.html`,`${clean}/index.html`,clean];for(const candidate of candidates){const file=normalize(join(base,candidate));if(file!==base&&!file.startsWith(`${base}${sep}`))continue;if(!existsSync(file)||!statSync(file).isFile())continue;const headers={"content-type":MIME[extname(file)]??"application/octet-stream"};if(extname(file)===".html")headers["cache-control"]="no-store";return new Response(Bun.file(file),{headers})}return null}export function staticContentType(file){return MIME[extname(file)]??"application/octet-stream"}function json(data,status=200){return new Response(JSON.stringify(data),{status,headers:{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}})}export async function startDesktopAgent(options){const cookieName=options.cookieName??"stacks_desktop";let token=newAgentToken();let port=0;function serveStatic(pathname){if(!options.staticDir)return null;const response=staticFileResponse(options.staticDir,pathname);if(response?.headers.get("content-type")?.startsWith("text/html"))response.headers.set("set-cookie",sessionCookie(cookieName,token));return response}async function fetch(request){const url=new URL(request.url);const host=request.headers.get("host");if(url.pathname==="/native/session"){if(request.method!=="GET")return json({error:"Method
|
|
1
|
+
import{randomBytes}from"node:crypto";import{existsSync,mkdirSync,readFileSync,statSync,writeFileSync}from"node:fs";import{dirname,extname,join,normalize,sep}from"node:path";import{errorBody,internalServerErrorBody}from"@stacksjs/router/error-body";const MIME={".html":"text/html; charset=utf-8",".js":"text/javascript; charset=utf-8",".mjs":"text/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".json":"application/json; charset=utf-8",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".ico":"image/x-icon",".woff2":"font/woff2",".woff":"font/woff",".txt":"text/plain; charset=utf-8"};export function newAgentToken(){return randomBytes(24).toString("hex")}export function isAgentHost(host,port){return host===`127.0.0.1:${port}`||host===`localhost:${port}`}export function sessionCookie(name,token){return`${name}=${token}; Path=/; HttpOnly; SameSite=Strict`}export function hasSessionCookie(request,name,token){const cookies=request.headers.get("cookie");if(!cookies)return false;return cookies.split(/;\s*/).includes(`${name}=${token}`)}export function rememberedPort(portFile){if(!portFile)return 0;try{const port=Number(readFileSync(portFile,"utf8").trim());return Number.isInteger(port)&&port>1024&&port<65536?port:0}catch{return 0}}export function staticFileResponse(root,pathname){const base=normalize(root);let clean;try{clean=decodeURIComponent(pathname).replace(/\/+$/,"")||"/index"}catch{return null}const candidates=clean==="/index"?["index.html"]:[`${clean}.html`,`${clean}/index.html`,clean];for(const candidate of candidates){const file=normalize(join(base,candidate));if(file!==base&&!file.startsWith(`${base}${sep}`))continue;if(!existsSync(file)||!statSync(file).isFile())continue;const headers={"content-type":MIME[extname(file)]??"application/octet-stream"};if(extname(file)===".html")headers["cache-control"]="no-store";return new Response(Bun.file(file),{headers})}return null}export function staticContentType(file){return MIME[extname(file)]??"application/octet-stream"}function json(data,status=200){return new Response(JSON.stringify(data),{status,headers:{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}})}const forbidden=()=>json(errorBody({error:"Forbidden",message:"This request is not from the app.",status:403}),403);export async function startDesktopAgent(options){const cookieName=options.cookieName??"stacks_desktop";let token=newAgentToken();let port=0;function serveStatic(pathname){if(!options.staticDir)return null;const response=staticFileResponse(options.staticDir,pathname);if(response?.headers.get("content-type")?.startsWith("text/html"))response.headers.set("set-cookie",sessionCookie(cookieName,token));return response}async function fetch(request){const url=new URL(request.url);const host=request.headers.get("host");if(url.pathname==="/native/session"){if(request.method!=="GET")return json(errorBody({error:"Method Not Allowed",message:"Fetch the session with GET.",status:405}),405);if(!isAgentHost(host,port))return forbidden();const response=json({name:options.name??null,version:options.version??null,renderer:"appkit"});response.headers.set("set-cookie",sessionCookie(cookieName,token));return response}if(!isAgentHost(host,port))return forbidden();if(request.method==="GET"&&!url.pathname.startsWith("/api/")){const file=serveStatic(url.pathname);if(file)return file}if(!hasSessionCookie(request,cookieName,token))return forbidden();try{return await options.handler(request)}catch(error){const message=error instanceof Error?error.message:String(error);console.error(`[agent] ${request.method} ${url.pathname}: ${message}`);return json(internalServerErrorBody(),500)}}const serve=(wanted)=>Bun.serve({hostname:"127.0.0.1",port:wanted,idleTimeout:0,fetch});const wanted=options.port??rememberedPort(options.portFile);let server;try{server=serve(wanted)}catch(error){if(wanted===0)throw error;server=serve(0)}port=server.port??0;if(options.portFile){try{mkdirSync(dirname(options.portFile),{recursive:true});writeFileSync(options.portFile,String(port))}catch{}}return{port,url:`http://127.0.0.1:${port}`,server,get token(){return token},rotateToken(){token=newAgentToken();return token},stop(){server.stop(true)}}}
|
package/dist/update-install.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{chmodSync,copyFileSync,existsSync,mkdirSync,mkdtempSync,readdirSync,renameSync,rmSync}from"node:fs";import{basename,dirname,join}from"node:path";import process from"node:process";import{updateFeedUrl}from"./update-feed";import{checkForDesktopUpdate,stageDesktopUpdate}from"./updater";export function detectInstallation(options={}){const platform=options.platform??process.platform;const execPath=options.execPath??process.execPath;const env=options.env??process.env;const name=basename(execPath).toLowerCase();if(name==="bun"||name==="bun.exe")return{kind:"unmanaged",executable:execPath};if(platform==="darwin"){const bundle=execPath.match(/^(.*\.app)\/Contents\/MacOS\/[^/]+$/);return bundle?{kind:"macos-bundle",path:bundle[1],executable:execPath}:{kind:"unmanaged",executable:execPath}}if(platform==="win32")return{kind:"windows-msi",executable:execPath};if(env.APPIMAGE)return{kind:"linux-appimage",path:env.APPIMAGE,executable:env.APPIMAGE};return execPath.startsWith("/usr/")||execPath.startsWith("/opt/")?{kind:"linux-package",executable:execPath}:{kind:"unmanaged",executable:execPath}}const runCommand=(command)=>{const result=Bun.spawnSync(command,{stdout:"pipe",stderr:"pipe"});return{exitCode:result.exitCode??1,stdout:result.stdout.toString(),stderr:result.stderr.toString()}};const spawnDetached=(command)=>{Bun.spawn(command,{stdio:["ignore","ignore","ignore"],detached:true}).unref()};export function macosSigner(bundle,run=runCommand){const described=run(["codesign","-dv","--verbose=4",bundle]);const text=`${described.stdout}
|
|
2
|
-
${described.stderr}`;const teamId=text.match(/^TeamIdentifier=(.+)$/m)?.[1]?.trim();const identifier=text.match(/^Identifier=(.+)$/m)?.[1]?.trim();return{...teamId&&teamId!=="not set"?{teamId}:{},...identifier?{identifier}:{}}}export function assertMacosBundleTrusted(current,next,options={}){const run=options.run??runCommand;const verified=run(["codesign","--verify","--deep","--strict",next]);const running=macosSigner(current,run);const incoming=macosSigner(next,run);if(!running.teamId){if(!options.allowUnsigned)throw new Error("The running app is not signed with a Developer ID, so an update cannot be checked against it.");return}if(verified.exitCode!==0)throw new Error(`The update's signature is not valid: ${(verified.stderr||verified.stdout).trim()}`);if(incoming.teamId!==running.teamId)throw new Error(`The update is signed by ${incoming.teamId??"no one"}, not by this app's team ${running.teamId}.`);if(incoming.identifier!==running.identifier)throw new Error(`The update is a different app (${incoming.identifier??"unknown"}), not ${running.identifier}.`)}const dittoExtract=(archive,into)=>{const result=runCommand(["ditto","-x","-k",archive,into]);if(result.exitCode!==0)throw new Error(`Unpacking the update failed: ${result.stderr.trim()}`)};export function swapMacosBundle(options){const{bundle}=options;const scratch=mkdtempSync(join(dirname(bundle),".update-"));const aside=`${bundle}.previous-${process.pid}`;try{(options.extract??dittoExtract)(options.archive,scratch);const unpacked=readdirSync(scratch).filter((entry)=>entry.endsWith(".app"));if(unpacked.length!==1)throw new Error(`The update archive holds ${unpacked.length} apps; it has to hold exactly one.`);const next=join(scratch,unpacked[0]);assertMacosBundleTrusted(bundle,next,{run:options.run,allowUnsigned:options.allowUnsigned});renameSync(bundle,aside);try{renameSync(next,bundle)}catch(error){renameSync(aside,bundle);throw error}rmSync(aside,{recursive:true,force:true})}finally{rmSync(scratch,{recursive:true,force:true})}}export function replaceAppImage(staged,appImage){const incoming=`${appImage}.update-${process.pid}`;try{copyFileSync(staged,incoming);chmodSync(incoming,493);renameSync(incoming,appImage)}catch(error){rmSync(incoming,{force:true});throw error}}export function windowsSigner(file,run=runCommand){const script=`$s = Get-AuthenticodeSignature -LiteralPath '${file.replace(/'/g,"''")}'; Write-Output $s.Status; if ($s.SignerCertificate) { Write-Output $s.SignerCertificate.Subject }`;const result=run(["powershell.exe","-NoProfile","-NonInteractive","-Command",script]);const[status,subject]=result.stdout.split(/\r?\n/).map((line)=>line.trim()).filter(Boolean);return{valid:result.exitCode===0&&status==="Valid",...subject?{subject}:{}}}export function assertWindowsInstallerTrusted(executable,installer,options={}){const running=windowsSigner(executable,options.run);if(!running.valid){if(options.allowUnsigned===false)throw new Error("The running app is not Authenticode-signed, so an update cannot be checked against it.");return}const incoming=windowsSigner(installer,options.run);if(!incoming.valid)throw new Error("The update installer is not validly signed.");if(incoming.subject!==running.subject)throw new Error(`The update is signed by ${incoming.subject??"no one"}, not by this app's publisher ${running.subject}.`)}export function installDesktopUpdate(options){const installation=options.installation??detectInstallation();const spawn=options.spawn??spawnDetached;const pid=options.pid??process.pid;const name=options.appName??"The app";switch(installation.kind){case"macos-bundle":{swapMacosBundle({archive:options.staged,bundle:installation.path,extract:options.extract,run:options.run,allowUnsigned:options.allowUnsigned});return{status:"installed",relaunch:()=>spawn(["open","-n",installation.path,"--args",`--wait-pid=${pid}`])}}case"linux-appimage":{replaceAppImage(options.staged,installation.path);return{status:"installed",relaunch:()=>spawn([installation.path,`--wait-pid=${pid}`])}}case"windows-msi":{assertWindowsInstallerTrusted(installation.executable,options.staged,{run:options.run,allowUnsigned:options.allowUnsigned});spawn(["cmd.exe","/d","/s","/c",`msiexec /i "${options.staged}" /passive /norestart && start "" "${installation.executable}" --wait-pid=${pid}`]);return{status:"installing"}}case"linux-package":return{status:"notice",message:`${name} ${options.manifest.version} is available. This copy was installed as a system package: update it with your package manager, or download the new package from ${new URL(options.manifest.url).origin}.`};default:return{status:"notice",message:`${name} ${options.manifest.version} is available, but this copy was not installed in a way that can update itself.`}}}const ARTIFACT_NAMES={darwin:"update.zip",win32:"update.msi",linux:"update.AppImage"};export function createDesktopUpdater(options){const installation=options.installation??detectInstallation();const target=options.target??{platform:process.platform,architecture:process.arch};const selfUpdating=["macos-bundle","windows-msi","linux-appimage"].includes(installation.kind);let state="idle";let manifest=null;let warning;let message;let error;let relaunch;let busy;const status=()=>({currentVersion:options.currentVersion,state,installKind:installation.kind,selfUpdating,...manifest?{version:manifest.version,...manifest.notes?{notes:manifest.notes}:{},...manifest.publishedAt?{publishedAt:manifest.publishedAt}:{}}:{},...warning?{warning}:{},...message?{message}:{},...error?{error}:{}});const once=(work)=>{busy??=work().catch((failure)=>{state="error";error=failure instanceof Error?failure.message:String(failure)}).then(()=>{busy=undefined;return status()});return busy};return{status,check:()=>once(async()=>{if(state==="installed"||state==="installing")return;state="checking";error=warning=message=undefined;manifest=await checkForDesktopUpdate({currentVersion:options.currentVersion,manifestUrl:updateFeedUrl(options.feedUrl,target,{channel:options.channel,currentVersion:options.currentVersion}),trustedKeys:options.trustedKeys,fetcher:options.fetcher,target});if(!manifest){state="current";return}const verdict=await options.beforeUpdate?.(manifest,{version:options.currentVersion});if(verdict&&"refuse"in verdict){state="refused";message=verdict.refuse;return}if(verdict&&"warn"in verdict)warning=verdict.warn;state="available"}),install:(install={})=>once(async()=>{if(state!=="available"||!manifest)throw new Error("There is no update to install. Check first.");if(warning&&!install.acknowledge)throw new Error(warning);if(!selfUpdating){const outcome=(options.install??installDesktopUpdate)({staged:"",manifest,appName:options.appName,installation});message=outcome.status==="notice"?outcome.message:undefined;return}const directory=join(options.updatesDir,manifest.version);mkdirSync(directory,{recursive:true});const staged=await stageDesktopUpdate(manifest,join(directory,ARTIFACT_NAMES[target.platform]??"update.bin"),options.fetcher,options.trustedKeys,target);const outcome=(options.install??installDesktopUpdate)({staged:staged.path,manifest,appName:options.appName,installation,allowUnsigned:options.allowUnsigned});if(outcome.status==="notice"){message=outcome.message;return}state=outcome.status;if(outcome.status==="installed"){relaunch=outcome.relaunch;rmSync(directory,{recursive:true,force:true})}}),async relaunchIfInstalled(){relaunch?.();relaunch=undefined}}}export const UPDATE_PATH="/__desktop/update";export function updateRequestHandler(updater){const json=(body,status=200)=>new Response(JSON.stringify(body),{status,headers:{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}});return async(request)=>{if(new URL(request.url).pathname!==UPDATE_PATH)return;if(request.method==="GET")return json(updater.status());if(request.method!=="POST")return json({error:"Method
|
|
1
|
+
import{chmodSync,copyFileSync,existsSync,mkdirSync,mkdtempSync,readdirSync,renameSync,rmSync}from"node:fs";import{basename,dirname,join}from"node:path";import process from"node:process";import{errorBody}from"@stacksjs/router/error-body";import{updateFeedUrl}from"./update-feed";import{checkForDesktopUpdate,stageDesktopUpdate}from"./updater";export function detectInstallation(options={}){const platform=options.platform??process.platform;const execPath=options.execPath??process.execPath;const env=options.env??process.env;const name=basename(execPath).toLowerCase();if(name==="bun"||name==="bun.exe")return{kind:"unmanaged",executable:execPath};if(platform==="darwin"){const bundle=execPath.match(/^(.*\.app)\/Contents\/MacOS\/[^/]+$/);return bundle?{kind:"macos-bundle",path:bundle[1],executable:execPath}:{kind:"unmanaged",executable:execPath}}if(platform==="win32")return{kind:"windows-msi",executable:execPath};if(env.APPIMAGE)return{kind:"linux-appimage",path:env.APPIMAGE,executable:env.APPIMAGE};return execPath.startsWith("/usr/")||execPath.startsWith("/opt/")?{kind:"linux-package",executable:execPath}:{kind:"unmanaged",executable:execPath}}const runCommand=(command)=>{const result=Bun.spawnSync(command,{stdout:"pipe",stderr:"pipe"});return{exitCode:result.exitCode??1,stdout:result.stdout.toString(),stderr:result.stderr.toString()}};const spawnDetached=(command)=>{Bun.spawn(command,{stdio:["ignore","ignore","ignore"],detached:true}).unref()};export function macosSigner(bundle,run=runCommand){const described=run(["codesign","-dv","--verbose=4",bundle]);const text=`${described.stdout}
|
|
2
|
+
${described.stderr}`;const teamId=text.match(/^TeamIdentifier=(.+)$/m)?.[1]?.trim();const identifier=text.match(/^Identifier=(.+)$/m)?.[1]?.trim();return{...teamId&&teamId!=="not set"?{teamId}:{},...identifier?{identifier}:{}}}export function assertMacosBundleTrusted(current,next,options={}){const run=options.run??runCommand;const verified=run(["codesign","--verify","--deep","--strict",next]);const running=macosSigner(current,run);const incoming=macosSigner(next,run);if(!running.teamId){if(!options.allowUnsigned)throw new Error("The running app is not signed with a Developer ID, so an update cannot be checked against it.");return}if(verified.exitCode!==0)throw new Error(`The update's signature is not valid: ${(verified.stderr||verified.stdout).trim()}`);if(incoming.teamId!==running.teamId)throw new Error(`The update is signed by ${incoming.teamId??"no one"}, not by this app's team ${running.teamId}.`);if(incoming.identifier!==running.identifier)throw new Error(`The update is a different app (${incoming.identifier??"unknown"}), not ${running.identifier}.`)}const dittoExtract=(archive,into)=>{const result=runCommand(["ditto","-x","-k",archive,into]);if(result.exitCode!==0)throw new Error(`Unpacking the update failed: ${result.stderr.trim()}`)};export function swapMacosBundle(options){const{bundle}=options;const scratch=mkdtempSync(join(dirname(bundle),".update-"));const aside=`${bundle}.previous-${process.pid}`;try{(options.extract??dittoExtract)(options.archive,scratch);const unpacked=readdirSync(scratch).filter((entry)=>entry.endsWith(".app"));if(unpacked.length!==1)throw new Error(`The update archive holds ${unpacked.length} apps; it has to hold exactly one.`);const next=join(scratch,unpacked[0]);assertMacosBundleTrusted(bundle,next,{run:options.run,allowUnsigned:options.allowUnsigned});renameSync(bundle,aside);try{renameSync(next,bundle)}catch(error){renameSync(aside,bundle);throw error}rmSync(aside,{recursive:true,force:true})}finally{rmSync(scratch,{recursive:true,force:true})}}export function replaceAppImage(staged,appImage){const incoming=`${appImage}.update-${process.pid}`;try{copyFileSync(staged,incoming);chmodSync(incoming,493);renameSync(incoming,appImage)}catch(error){rmSync(incoming,{force:true});throw error}}export function windowsSigner(file,run=runCommand){const script=`$s = Get-AuthenticodeSignature -LiteralPath '${file.replace(/'/g,"''")}'; Write-Output $s.Status; if ($s.SignerCertificate) { Write-Output $s.SignerCertificate.Subject }`;const result=run(["powershell.exe","-NoProfile","-NonInteractive","-Command",script]);const[status,subject]=result.stdout.split(/\r?\n/).map((line)=>line.trim()).filter(Boolean);return{valid:result.exitCode===0&&status==="Valid",...subject?{subject}:{}}}export function assertWindowsInstallerTrusted(executable,installer,options={}){const running=windowsSigner(executable,options.run);if(!running.valid){if(options.allowUnsigned===false)throw new Error("The running app is not Authenticode-signed, so an update cannot be checked against it.");return}const incoming=windowsSigner(installer,options.run);if(!incoming.valid)throw new Error("The update installer is not validly signed.");if(incoming.subject!==running.subject)throw new Error(`The update is signed by ${incoming.subject??"no one"}, not by this app's publisher ${running.subject}.`)}export function installDesktopUpdate(options){const installation=options.installation??detectInstallation();const spawn=options.spawn??spawnDetached;const pid=options.pid??process.pid;const name=options.appName??"The app";switch(installation.kind){case"macos-bundle":{swapMacosBundle({archive:options.staged,bundle:installation.path,extract:options.extract,run:options.run,allowUnsigned:options.allowUnsigned});return{status:"installed",relaunch:()=>spawn(["open","-n",installation.path,"--args",`--wait-pid=${pid}`])}}case"linux-appimage":{replaceAppImage(options.staged,installation.path);return{status:"installed",relaunch:()=>spawn([installation.path,`--wait-pid=${pid}`])}}case"windows-msi":{assertWindowsInstallerTrusted(installation.executable,options.staged,{run:options.run,allowUnsigned:options.allowUnsigned});spawn(["cmd.exe","/d","/s","/c",`msiexec /i "${options.staged}" /passive /norestart && start "" "${installation.executable}" --wait-pid=${pid}`]);return{status:"installing"}}case"linux-package":return{status:"notice",message:`${name} ${options.manifest.version} is available. This copy was installed as a system package: update it with your package manager, or download the new package from ${new URL(options.manifest.url).origin}.`};default:return{status:"notice",message:`${name} ${options.manifest.version} is available, but this copy was not installed in a way that can update itself.`}}}const ARTIFACT_NAMES={darwin:"update.zip",win32:"update.msi",linux:"update.AppImage"};export function createDesktopUpdater(options){const installation=options.installation??detectInstallation();const target=options.target??{platform:process.platform,architecture:process.arch};const selfUpdating=["macos-bundle","windows-msi","linux-appimage"].includes(installation.kind);let state="idle";let manifest=null;let warning;let message;let error;let relaunch;let busy;const status=()=>({currentVersion:options.currentVersion,state,installKind:installation.kind,selfUpdating,...manifest?{version:manifest.version,...manifest.notes?{notes:manifest.notes}:{},...manifest.publishedAt?{publishedAt:manifest.publishedAt}:{}}:{},...warning?{warning}:{},...message?{message}:{},...error?{error}:{}});const once=(work)=>{busy??=work().catch((failure)=>{state="error";error=failure instanceof Error?failure.message:String(failure)}).then(()=>{busy=undefined;return status()});return busy};return{status,check:()=>once(async()=>{if(state==="installed"||state==="installing")return;state="checking";error=warning=message=undefined;manifest=await checkForDesktopUpdate({currentVersion:options.currentVersion,manifestUrl:updateFeedUrl(options.feedUrl,target,{channel:options.channel,currentVersion:options.currentVersion}),trustedKeys:options.trustedKeys,fetcher:options.fetcher,target});if(!manifest){state="current";return}const verdict=await options.beforeUpdate?.(manifest,{version:options.currentVersion});if(verdict&&"refuse"in verdict){state="refused";message=verdict.refuse;return}if(verdict&&"warn"in verdict)warning=verdict.warn;state="available"}),install:(install={})=>once(async()=>{if(state!=="available"||!manifest)throw new Error("There is no update to install. Check first.");if(warning&&!install.acknowledge)throw new Error(warning);if(!selfUpdating){const outcome=(options.install??installDesktopUpdate)({staged:"",manifest,appName:options.appName,installation});message=outcome.status==="notice"?outcome.message:undefined;return}const directory=join(options.updatesDir,manifest.version);mkdirSync(directory,{recursive:true});const staged=await stageDesktopUpdate(manifest,join(directory,ARTIFACT_NAMES[target.platform]??"update.bin"),options.fetcher,options.trustedKeys,target);const outcome=(options.install??installDesktopUpdate)({staged:staged.path,manifest,appName:options.appName,installation,allowUnsigned:options.allowUnsigned});if(outcome.status==="notice"){message=outcome.message;return}state=outcome.status;if(outcome.status==="installed"){relaunch=outcome.relaunch;rmSync(directory,{recursive:true,force:true})}}),async relaunchIfInstalled(){relaunch?.();relaunch=undefined}}}export const UPDATE_PATH="/__desktop/update";export function updateRequestHandler(updater){const json=(body,status=200)=>new Response(JSON.stringify(body),{status,headers:{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}});return async(request)=>{if(new URL(request.url).pathname!==UPDATE_PATH)return;if(request.method==="GET")return json(updater.status());if(request.method!=="POST")return json(errorBody({error:"Method Not Allowed",message:"Read the status with GET, or POST an action.",status:405}),405);const body=await request.json().catch(()=>null);if(body?.action==="check")return json(await updater.check());if(body?.action==="install")return json(await updater.install({acknowledge:body.acknowledge===true}));return json(errorBody({error:"Bad Request",message:'Send { action: "check" } or { action: "install" }.',status:400}),400)}}export function isMacosBundle(path){return path.endsWith(".app")&&existsSync(join(path,"Contents","MacOS"))}
|
package/dist/webview-agent.js
CHANGED
|
@@ -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(
|
|
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{internalServerErrorBody}from"@stacksjs/router/error-body";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 ownType=staticContentType(file);const headers={"content-type":ownType==="application/octet-stream"?staticContentType(candidate):ownType};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(internalServerErrorBody()),{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}:{}}}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { desktopAppPaths } from './webview-agent';
|
|
2
|
+
import type { AgentBundleFiles, StacksAgentHandlerOptions } from './agent-launcher';
|
|
2
3
|
import type { BeforeDesktopUpdate, DesktopUpdater } from './update-install';
|
|
3
4
|
import type { SecondInstanceLaunch, WebviewAgent, WebviewAgentContext, WebviewHandler, WebviewViews } from './webview-agent';
|
|
4
5
|
/** A module's default export, as a `WebviewAgentModule`: a bare function is its `fetch`. */
|
|
@@ -41,6 +42,12 @@ export declare function resolveWebviewRuntime(manifest: Pick<WebviewAppManifest,
|
|
|
41
42
|
* resolves 0 without booting anything.
|
|
42
43
|
*/
|
|
43
44
|
export declare function runWebviewApp(options: RunWebviewAppOptions): Promise<number>;
|
|
45
|
+
/**
|
|
46
|
+
* The app's routes as a webview handler: their answer, or nothing when no
|
|
47
|
+
* route matches, so the views answer the window's pages. A route's own 404
|
|
48
|
+
* (a record that is not there) is still the app's answer.
|
|
49
|
+
*/
|
|
50
|
+
export declare function appRouteHandler(handler: (request: Request) => Response | Promise<Response>, unmatched: (response: Response, request: Request) => boolean | Promise<boolean>): (request: Request) => Promise<Response | undefined>;
|
|
44
51
|
/**
|
|
45
52
|
* The executable's entrypoint, written by the build and compiled (or, in
|
|
46
53
|
* development, run) from there. The agent module, the manifest and every
|
|
@@ -56,7 +63,11 @@ export declare function renderWebviewEntry(options: {
|
|
|
56
63
|
stxViews?: { dir: string, components?: string[], root: string }
|
|
57
64
|
embeddedRuntime?: string
|
|
58
65
|
launcherModule?: string
|
|
59
|
-
|
|
66
|
+
|
|
67
|
+
migrations?: Record<string, string>
|
|
68
|
+
|
|
69
|
+
migrationRunner?: string
|
|
70
|
+
} & AgentBundleFiles): string;
|
|
60
71
|
/** The agent module a project uses: `agent.entry`, else `app/Desktop/Agent.ts` when it exists. */
|
|
61
72
|
export declare function webviewAgentEntry(root: string, entry?: string): string | undefined;
|
|
62
73
|
/** Copy a file and keep it executable. */
|
|
@@ -132,4 +143,11 @@ export declare interface RunWebviewAppOptions {
|
|
|
132
143
|
spawn?: (command: string[], env: Record<string, string>) => SpawnedWindow
|
|
133
144
|
platform?: string
|
|
134
145
|
onAgent?: (agent: WebviewAgent) => void
|
|
146
|
+
app?: Pick<StacksAgentHandlerOptions, 'routes' | 'actions' | 'middleware'>
|
|
147
|
+
database?: WebviewDatabase
|
|
148
|
+
}
|
|
149
|
+
/** What `runWebviewApp` needs to bring the app's database up to date. */
|
|
150
|
+
export declare interface WebviewDatabase {
|
|
151
|
+
migrations: Record<string, string>
|
|
152
|
+
migrate: (options: { databasePath: string, migrations: Record<string, string> }) => { applied: string[] }
|
|
135
153
|
}
|
package/dist/webview-launcher.js
CHANGED
|
@@ -1,6 +1,13 @@
|
|
|
1
|
-
import{createHash}from"node:crypto";import{chmodSync,copyFileSync,existsSync,mkdirSync,readFileSync,renameSync,rmSync,writeFileSync}from"node:fs";import{dirname,isAbsolute,join,resolve}from"node:path";import process from"node:process";import{fileURLToPath}from"node:url";import{newAgentToken}from"./agent";import{logToFileWhenDetached}from"./agent-launcher";import{createDesktopUpdater,updateRequestHandler}from"./update-install";import{applyWidenedPath,desktopAppPaths,INSTANCE_HEADER,INSTANCE_PATH,startWebviewAgent}from"./webview-agent";export const OPTIONAL_CRAFT_FLAGS=["--single-instance","--deep-link","--app-name"];export const WEBVIEW_RUNTIME_NAME="craft-runtime";export const WAIT_PID_FLAG="--wait-pid=";export function agentModuleOf(loaded){const value=loaded&&typeof loaded==="object"&&"default"in loaded?loaded.default:loaded;if(typeof value==="function")return{fetch:value};return value&&typeof value==="object"?value:{}}function readInstance(lockFile){try{const record=JSON.parse(readFileSync(lockFile,"utf8"));return Number.isInteger(record.pid)&&typeof record.secret==="string"?{pid:record.pid,port:Number(record.port)||0,secret:record.secret}:null}catch{return null}}function isAlive(pid){try{process.kill(pid,0);return true}catch(error){return error.code==="EPERM"}}function writeInstance(lockFile,record){mkdirSync(dirname(lockFile),{recursive:true});const temporary=`${lockFile}.${record.pid}`;writeFileSync(temporary,JSON.stringify(record),{mode:384});renameSync(temporary,lockFile)}export function acquireWebviewInstance(lockFile,pid=process.pid){const holder=readInstance(lockFile);if(holder&&holder.pid!==pid&&isAlive(holder.pid))return{acquired:false,holder};const record={pid,port:0,secret:newAgentToken()};writeInstance(lockFile,record);return{acquired:true,record}}export function publishInstancePort(lockFile,record,port){record.port=port;writeInstance(lockFile,record)}export function releaseWebviewInstance(lockFile,pid=process.pid){if(readInstance(lockFile)?.pid===pid)rmSync(lockFile,{force:true})}export function parseLaunchArguments(argv,urlSchemes=[]){const args=[];let url;let waitPid;for(const arg of argv){if(arg.startsWith(WAIT_PID_FLAG)){const pid=Number(arg.slice(WAIT_PID_FLAG.length));if(Number.isInteger(pid)&&pid>0)waitPid=pid;continue}if(arg.startsWith("-psn_"))continue;if(!url&&urlSchemes.some((scheme)=>arg.toLowerCase().startsWith(`${scheme.toLowerCase()}:`))){url=arg;continue}args.push(arg)}return{args,...url?{url}:{},...waitPid?{waitPid}:{}}}export async function forwardToInstance(lockFile,launch,options={}){const fetcher=options.fetcher??fetch;for(let attempt=0;attempt<(options.attempts??40);attempt++){const holder=readInstance(lockFile);if(!holder||!isAlive(holder.pid))return false;if(holder.port){try{const response=await fetcher(`http://127.0.0.1:${holder.port}${INSTANCE_PATH}`,{method:"POST",headers:{"content-type":"application/json",[INSTANCE_HEADER]:holder.secret},body:JSON.stringify(launch)});if(response.status===204)return true}catch{}}await Bun.sleep(options.delayMs??125)}return false}export function craftWindowCommand(manifest,runtime,url,launch={}){const{window}=manifest;const has=(flag)=>manifest.runtimeFlags?.includes(flag)===true;return[runtime,"--url",url,"--title",window.title,"--width",String(window.width),"--height",String(window.height),...has("--app-name")?["--app-name",manifest.appName]:[],...has("--single-instance")?["--single-instance",manifest.appId,...(launch.args??[]).flatMap((arg)=>["--instance-arg",arg])]:[],...launch.url&&has("--deep-link")?["--deep-link",launch.url]:[],...window.devtools?[]:["--no-devtools"],...window.darkMode===true?["--dark"]:window.darkMode===false?["--light"]:[],...window.titlebarHidden?["--titlebar-hidden"]:[],...window.arguments??[]]}export function resolveWebviewRuntime(manifest,options){const platform=options.platform??process.platform;const name=platform==="win32"?`${WEBVIEW_RUNTIME_NAME}.exe`:WEBVIEW_RUNTIME_NAME;if(manifest.runtime==="beside")return join(dirname(options.execPath??process.execPath),name);if(manifest.runtime!=="embedded")return manifest.runtime;if(!options.embedded)throw new Error("This app was built with an embedded Craft runtime, but none was compiled in.");const bytes=readFileSync(options.embedded);const digest=createHash("sha256").update(bytes).digest("hex");const target=join(options.dataDir,"runtime",digest.slice(0,16),name);const current=existsSync(target)?createHash("sha256").update(readFileSync(target)).digest("hex"):"";if(current!==digest){mkdirSync(dirname(target),{recursive:true});const temporary=`${target}.${process.pid}`;writeFileSync(temporary,bytes,{mode:493});renameSync(temporary,target)}if(platform!=="win32")chmodSync(target,493);return target}async function waitForExit(pid,timeoutMs=15000){const until=Date.now()+timeoutMs;while(isAlive(pid)&&Date.now()<until)await Bun.sleep(100)}function defaultArgv(){return process.argv.slice(2)}function spawnCraft(command,env){const child=Bun.spawn(command,{env:{...process.env,...env},stdio:["ignore","inherit","pipe"]});new Response(child.stderr).text().then((stderr)=>{const lines=stderr.split(`
|
|
1
|
+
import{createHash}from"node:crypto";import{chmodSync,copyFileSync,existsSync,mkdirSync,readFileSync,renameSync,rmSync,writeFileSync}from"node:fs";import{dirname,isAbsolute,join,resolve}from"node:path";import process from"node:process";import{fileURLToPath}from"node:url";import{newAgentToken}from"./agent";import{agentBundleSource,logToFileWhenDetached,stacksAgentHandler}from"./agent-launcher";import{createDesktopUpdater,updateRequestHandler}from"./update-install";import{applyWidenedPath,desktopAppPaths,INSTANCE_HEADER,INSTANCE_PATH,startWebviewAgent}from"./webview-agent";export const OPTIONAL_CRAFT_FLAGS=["--single-instance","--deep-link","--app-name"];export const WEBVIEW_RUNTIME_NAME="craft-runtime";export const WAIT_PID_FLAG="--wait-pid=";export function agentModuleOf(loaded){const value=loaded&&typeof loaded==="object"&&"default"in loaded?loaded.default:loaded;if(typeof value==="function")return{fetch:value};return value&&typeof value==="object"?value:{}}function readInstance(lockFile){try{const record=JSON.parse(readFileSync(lockFile,"utf8"));return Number.isInteger(record.pid)&&typeof record.secret==="string"?{pid:record.pid,port:Number(record.port)||0,secret:record.secret}:null}catch{return null}}function isAlive(pid){try{process.kill(pid,0);return true}catch(error){return error.code==="EPERM"}}function writeInstance(lockFile,record){mkdirSync(dirname(lockFile),{recursive:true});const temporary=`${lockFile}.${record.pid}`;writeFileSync(temporary,JSON.stringify(record),{mode:384});renameSync(temporary,lockFile)}export function acquireWebviewInstance(lockFile,pid=process.pid){const holder=readInstance(lockFile);if(holder&&holder.pid!==pid&&isAlive(holder.pid))return{acquired:false,holder};const record={pid,port:0,secret:newAgentToken()};writeInstance(lockFile,record);return{acquired:true,record}}export function publishInstancePort(lockFile,record,port){record.port=port;writeInstance(lockFile,record)}export function releaseWebviewInstance(lockFile,pid=process.pid){if(readInstance(lockFile)?.pid===pid)rmSync(lockFile,{force:true})}export function parseLaunchArguments(argv,urlSchemes=[]){const args=[];let url;let waitPid;for(const arg of argv){if(arg.startsWith(WAIT_PID_FLAG)){const pid=Number(arg.slice(WAIT_PID_FLAG.length));if(Number.isInteger(pid)&&pid>0)waitPid=pid;continue}if(arg.startsWith("-psn_"))continue;if(!url&&urlSchemes.some((scheme)=>arg.toLowerCase().startsWith(`${scheme.toLowerCase()}:`))){url=arg;continue}args.push(arg)}return{args,...url?{url}:{},...waitPid?{waitPid}:{}}}export async function forwardToInstance(lockFile,launch,options={}){const fetcher=options.fetcher??fetch;for(let attempt=0;attempt<(options.attempts??40);attempt++){const holder=readInstance(lockFile);if(!holder||!isAlive(holder.pid))return false;if(holder.port){try{const response=await fetcher(`http://127.0.0.1:${holder.port}${INSTANCE_PATH}`,{method:"POST",headers:{"content-type":"application/json",[INSTANCE_HEADER]:holder.secret},body:JSON.stringify(launch)});if(response.status===204)return true}catch{}}await Bun.sleep(options.delayMs??125)}return false}export function craftWindowCommand(manifest,runtime,url,launch={}){const{window}=manifest;const has=(flag)=>manifest.runtimeFlags?.includes(flag)===true;return[runtime,"--url",url,"--title",window.title,"--width",String(window.width),"--height",String(window.height),...has("--app-name")?["--app-name",manifest.appName]:[],...has("--single-instance")?["--single-instance",manifest.appId,...(launch.args??[]).flatMap((arg)=>["--instance-arg",arg])]:[],...launch.url&&has("--deep-link")?["--deep-link",launch.url]:[],...window.devtools?[]:["--no-devtools"],...window.darkMode===true?["--dark"]:window.darkMode===false?["--light"]:[],...window.titlebarHidden?["--titlebar-hidden"]:[],...window.arguments??[]]}export function resolveWebviewRuntime(manifest,options){const platform=options.platform??process.platform;const name=platform==="win32"?`${WEBVIEW_RUNTIME_NAME}.exe`:WEBVIEW_RUNTIME_NAME;if(manifest.runtime==="beside")return join(dirname(options.execPath??process.execPath),name);if(manifest.runtime!=="embedded")return manifest.runtime;if(!options.embedded)throw new Error("This app was built with an embedded Craft runtime, but none was compiled in.");const bytes=readFileSync(options.embedded);const digest=createHash("sha256").update(bytes).digest("hex");const target=join(options.dataDir,"runtime",digest.slice(0,16),name);const current=existsSync(target)?createHash("sha256").update(readFileSync(target)).digest("hex"):"";if(current!==digest){mkdirSync(dirname(target),{recursive:true});const temporary=`${target}.${process.pid}`;writeFileSync(temporary,bytes,{mode:493});renameSync(temporary,target)}if(platform!=="win32")chmodSync(target,493);return target}async function waitForExit(pid,timeoutMs=15000){const until=Date.now()+timeoutMs;while(isAlive(pid)&&Date.now()<until)await Bun.sleep(100)}function defaultArgv(){return process.argv.slice(2)}function spawnCraft(command,env){const child=Bun.spawn(command,{env:{...process.env,...env},stdio:["ignore","inherit","pipe"]});new Response(child.stderr).text().then((stderr)=>{const lines=stderr.split(`
|
|
2
2
|
`).filter((line)=>line.trim());if(lines.length)console.error(`[craft] ${lines.join(`
|
|
3
|
-
`)}`)});return{exited:child.exited,kill:()=>child.kill()}}export async function runWebviewApp(options){const{manifest}=options;const paths=options.paths??desktopAppPaths(manifest.appName);const tag=`[${manifest.appName}]`;if(options.logWhenDetached!==false)logToFileWhenDetached(paths.logFile);const launch=parseLaunchArguments(options.argv??defaultArgv(),manifest.urlSchemes);const incoming={args:launch.args,cwd:process.cwd(),...launch.url?{url:launch.url}:{}};const spawn=options.spawn??spawnCraft;if(launch.waitPid)await waitForExit(launch.waitPid);let runtime;try{runtime=resolveWebviewRuntime(manifest,{embedded:options.embeddedRuntime,dataDir:paths.dataDir});if(!existsSync(runtime))throw new Error(`the Craft runtime is missing: ${runtime}`)}catch(error){console.error(`${tag} could not start: ${error instanceof Error?error.message:String(error)}`);return 1}const lock=acquireWebviewInstance(paths.lockFile);if(!lock.acquired){const reached=await forwardToInstance(paths.lockFile,incoming);if((options.platform??process.platform)!=="darwin"&&manifest.runtimeFlags?.includes("--single-instance"))await spawn(craftWindowCommand(manifest,runtime,"about:blank",incoming),{}).exited.catch(()=>0);console.log(reached?`${tag} already running; handed over`:`${tag} already running`);return 0}applyWidenedPath();let module={};let agent;let updater;try{module=options.module?agentModuleOf(await options.module()):{};if(manifest.updates){updater=createDesktopUpdater({appName:manifest.appName,currentVersion:manifest.version,feedUrl:manifest.updates.feedUrl,trustedKeys:manifest.updates.publicKeys,channel:manifest.updates.channel,updatesDir:paths.updatesDir,beforeUpdate:module.beforeUpdate})}const answerUpdate=updater?updateRequestHandler(updater):undefined;agent=await startWebviewAgent({appName:manifest.appName,version:manifest.version,views:options.views,port:manifest.port,portFile:paths.portFile,dataDir:paths.dataDir,publicPaths:manifest.publicPaths,instanceSecret:lock.record.secret,handler:async(request,context)=>await answerUpdate?.(request)??module.fetch?.(request,context),onSecondInstance:(next)=>module.secondInstance?.(next)});publishInstancePort(paths.lockFile,lock.record,agent.port);await module.start?.({appName:manifest.appName,version:manifest.version,origin:agent.origin,port:agent.port,dataDir:paths.dataDir,launch:incoming,...updater?{updater}:{}})}catch(error){console.error(`${tag} could not start: ${error instanceof Error?error.stack??error.message:String(error)}`);releaseWebviewInstance(paths.lockFile);return 1}options.onAgent?.(agent);console.log(`${tag} ${manifest.version} serving on ${agent.origin}`);const window=spawn(craftWindowCommand(manifest,runtime,agent.launchUrl(manifest.startPath),incoming),{CRAFT_RELAUNCH_EXECUTABLE:process.execPath,CRAFT_RELAUNCH_ARGS:JSON.stringify([...process.execPath.endsWith("bun")||process.execPath.endsWith("bun.exe")?[process.argv[1]??""]:[],`${WAIT_PID_FLAG}${process.pid}`])});const hours=manifest.updates?.checkEveryHours??24;let timer;if(updater&&hours>0){const check=()=>{updater.check().catch(()=>{})};agent.windowReady.then(check);timer=setInterval(check,hours*3600000);timer.unref?.()}let stopped=false;const stop=async()=>{if(stopped)return;stopped=true;if(timer)clearInterval(timer);window.kill();try{await module.stop?.()}catch(error){console.error(`${tag} stop: ${error instanceof Error?error.message:String(error)}`)}agent.stop();releaseWebviewInstance(paths.lockFile)};const signals=process.platform==="win32"?["SIGINT","SIGTERM"]:["SIGTERM","SIGINT","SIGHUP"];const onSignal=()=>{stop().then(()=>process.exit(0))};for(const signal of signals)process.on(signal,onSignal);const code=await window.exited;console.log(`${tag} window closed (${code})`);for(const signal of signals)process.off(signal,onSignal);await stop();await updater?.relaunchIfInstalled();return 0}export function renderWebviewEntry(options){const launcher=options.launcherModule??fileURLToPath(import.meta.url);const files=Object.entries(options.viewFiles??{});const imports=files.map(([,file],index)=>`import view${index} from ${JSON.stringify(file)} with { type: 'file' }`);
|
|
3
|
+
`)}`)});return{exited:child.exited,kill:()=>child.kill()}}export async function runWebviewApp(options){const{manifest}=options;const paths=options.paths??desktopAppPaths(manifest.appName);const tag=`[${manifest.appName}]`;if(options.logWhenDetached!==false)logToFileWhenDetached(paths.logFile);const launch=parseLaunchArguments(options.argv??defaultArgv(),manifest.urlSchemes);const incoming={args:launch.args,cwd:process.cwd(),...launch.url?{url:launch.url}:{}};const spawn=options.spawn??spawnCraft;if(launch.waitPid)await waitForExit(launch.waitPid);let runtime;try{runtime=resolveWebviewRuntime(manifest,{embedded:options.embeddedRuntime,dataDir:paths.dataDir});if(!existsSync(runtime))throw new Error(`the Craft runtime is missing: ${runtime}`)}catch(error){console.error(`${tag} could not start: ${error instanceof Error?error.message:String(error)}`);return 1}const lock=acquireWebviewInstance(paths.lockFile);if(!lock.acquired){const reached=await forwardToInstance(paths.lockFile,incoming);if((options.platform??process.platform)!=="darwin"&&manifest.runtimeFlags?.includes("--single-instance"))await spawn(craftWindowCommand(manifest,runtime,"about:blank",incoming),{}).exited.catch(()=>0);console.log(reached?`${tag} already running; handed over`:`${tag} already running`);return 0}applyWidenedPath();let module={};let agent;let updater;try{if(options.database){const databasePath=join(paths.dataDir,"database.sqlite");const{applied}=options.database.migrate({databasePath,migrations:options.database.migrations});if(applied.length)console.log(`${tag} applied ${applied.length} migration(s) to ${databasePath}`);process.env.DB_CONNECTION="sqlite";process.env.DB_DATABASE_PATH=databasePath}module=options.module?agentModuleOf(await options.module()):{};if(manifest.updates){updater=createDesktopUpdater({appName:manifest.appName,currentVersion:manifest.version,feedUrl:manifest.updates.feedUrl,trustedKeys:manifest.updates.publicKeys,channel:manifest.updates.channel,updatesDir:paths.updatesDir,beforeUpdate:module.beforeUpdate})}const answerUpdate=updater?updateRequestHandler(updater):undefined;const answerApp=options.app?appRouteHandler(await stacksAgentHandler({appRoutes:false,...options.app}),(await import("@stacksjs/router")).isUnmatchedRouteResponse):undefined;agent=await startWebviewAgent({appName:manifest.appName,version:manifest.version,views:options.views,port:manifest.port,portFile:paths.portFile,dataDir:paths.dataDir,publicPaths:manifest.publicPaths,instanceSecret:lock.record.secret,handler:async(request,context)=>await answerUpdate?.(request)??await module.fetch?.(request,context)??answerApp?.(request),onSecondInstance:(next)=>module.secondInstance?.(next)});publishInstancePort(paths.lockFile,lock.record,agent.port);await module.start?.({appName:manifest.appName,version:manifest.version,origin:agent.origin,port:agent.port,dataDir:paths.dataDir,launch:incoming,...updater?{updater}:{}})}catch(error){console.error(`${tag} could not start: ${error instanceof Error?error.stack??error.message:String(error)}`);releaseWebviewInstance(paths.lockFile);return 1}options.onAgent?.(agent);console.log(`${tag} ${manifest.version} serving on ${agent.origin}`);const window=spawn(craftWindowCommand(manifest,runtime,agent.launchUrl(manifest.startPath),incoming),{CRAFT_RELAUNCH_EXECUTABLE:process.execPath,CRAFT_RELAUNCH_ARGS:JSON.stringify([...process.execPath.endsWith("bun")||process.execPath.endsWith("bun.exe")?[process.argv[1]??""]:[],`${WAIT_PID_FLAG}${process.pid}`])});const hours=manifest.updates?.checkEveryHours??24;let timer;if(updater&&hours>0){const check=()=>{updater.check().catch(()=>{})};agent.windowReady.then(check);timer=setInterval(check,hours*3600000);timer.unref?.()}let stopped=false;const stop=async()=>{if(stopped)return;stopped=true;if(timer)clearInterval(timer);window.kill();try{await module.stop?.()}catch(error){console.error(`${tag} stop: ${error instanceof Error?error.message:String(error)}`)}agent.stop();releaseWebviewInstance(paths.lockFile)};const signals=process.platform==="win32"?["SIGINT","SIGTERM"]:["SIGTERM","SIGINT","SIGHUP"];const onSignal=()=>{stop().then(()=>process.exit(0))};for(const signal of signals)process.on(signal,onSignal);const code=await window.exited;console.log(`${tag} window closed (${code})`);for(const signal of signals)process.off(signal,onSignal);await stop();await updater?.relaunchIfInstalled();return 0}export function appRouteHandler(handler,unmatched){return async(request)=>{const response=await handler(request);return await unmatched(response,request)?undefined:response}}export function renderWebviewEntry(options){const launcher=options.launcherModule??fileURLToPath(import.meta.url);const bundled=options.routes?.length?agentBundleSource(options):undefined;const files=Object.entries(options.viewFiles??{});const imports=files.map(([,file],index)=>`import view${index} from ${JSON.stringify(file)} with { type: 'file' }`);const migrations=options.migrations?Object.entries(options.migrations):undefined;if(migrations){imports.push(`import { migrateCompiledDatabase } from ${JSON.stringify(options.migrationRunner??"@stacksjs/database/compiled-migrations")}`);migrations.forEach(([,file],index)=>imports.push(`import migration${index} from ${JSON.stringify(file)} with { type: 'text' }`))}const database=migrations?`
|
|
4
|
+
database: {
|
|
5
|
+
migrations: {
|
|
6
|
+
${migrations.map(([name],index)=>` ${JSON.stringify(name)}: migration${index},`).join(`
|
|
7
|
+
`)}
|
|
8
|
+
},
|
|
9
|
+
migrate: migrateCompiledDatabase,
|
|
10
|
+
},`:"";if(options.embeddedRuntime)imports.push(`import embeddedRuntime from ${JSON.stringify(options.embeddedRuntime)} with { type: 'file' }`);const views=options.stxViews?`{ kind: 'stx', ...${JSON.stringify(options.stxViews)} }`:files.length?`{ kind: 'embedded', files: {
|
|
4
11
|
${files.map(([path],index)=>` ${JSON.stringify(path)}: view${index},`).join(`
|
|
5
12
|
`)}
|
|
6
13
|
} }`:`{ kind: 'none' }`;return`// Written by buddy build:desktop and buddy dev:desktop (desktop.webview). Do not edit.
|
|
@@ -14,6 +21,14 @@ process.exit(await runWebviewApp({
|
|
|
14
21
|
`)},
|
|
15
22
|
views: ${views},
|
|
16
23
|
module: ${options.agentEntry?`() => import(${JSON.stringify(options.agentEntry)})`:"undefined"},${options.embeddedRuntime?`
|
|
17
|
-
embeddedRuntime,`:""}
|
|
24
|
+
embeddedRuntime,`:""}${bundled?`
|
|
25
|
+
app: {
|
|
26
|
+
routes: ${bundled.routes.replace(/\n/g,`
|
|
27
|
+
`)},
|
|
28
|
+
actions: ${bundled.actions.replace(/\n/g,`
|
|
29
|
+
`)},
|
|
30
|
+
middleware: ${bundled.middleware.replace(/\n/g,`
|
|
31
|
+
`)},
|
|
32
|
+
},`:""}${database}
|
|
18
33
|
}))
|
|
19
34
|
`}export function webviewAgentEntry(root,entry){if(entry){const file=isAbsolute(entry)?entry:resolve(root,entry);if(!existsSync(file))throw new Error(`desktop.webview.agent.entry does not exist: ${file}`);return file}const conventional=join(root,"app/Desktop/Agent.ts");return existsSync(conventional)?conventional:undefined}export function copyExecutable(from,to){mkdirSync(dirname(to),{recursive:true});copyFileSync(from,to);if(process.platform!=="win32")chmodSync(to,493)}
|
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.
|
|
5
|
+
"version": "0.75.683",
|
|
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.
|
|
77
|
-
"@stacksjs/router": "0.75.
|
|
78
|
-
"@stacksjs/server": "0.75.
|
|
79
|
-
"@stacksjs/storage": "0.75.
|
|
76
|
+
"@stacksjs/config": "0.75.683",
|
|
77
|
+
"@stacksjs/router": "0.75.683",
|
|
78
|
+
"@stacksjs/server": "0.75.683",
|
|
79
|
+
"@stacksjs/storage": "0.75.683",
|
|
80
80
|
"craft-native": ">=0.0.505"
|
|
81
81
|
},
|
|
82
82
|
"peerDependencies": {
|
|
83
|
-
"@stacksjs/config": "0.75.
|
|
84
|
-
"@stacksjs/router": "0.75.
|
|
85
|
-
"@stacksjs/server": "0.75.
|
|
86
|
-
"@stacksjs/storage": "0.75.
|
|
83
|
+
"@stacksjs/config": "0.75.683",
|
|
84
|
+
"@stacksjs/router": "0.75.683",
|
|
85
|
+
"@stacksjs/server": "0.75.683",
|
|
86
|
+
"@stacksjs/storage": "0.75.683"
|
|
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.
|
|
103
|
+
"@stacksjs/build": "0.75.683",
|
|
104
104
|
"better-dx": "^0.2.39"
|
|
105
105
|
}
|
|
106
106
|
}
|