@stacksjs/desktop-build 0.75.709 → 0.75.711
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/webview-app.js +1 -1
- package/dist/webview-launcher.d.ts +3 -0
- package/dist/webview-launcher.js +11 -3
- package/package.json +10 -10
package/dist/webview-app.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{chmodSync,copyFileSync,existsSync,mkdirSync,readdirSync,readFileSync,rmSync,statSync,writeFileSync}from"node:fs";import{basename,dirname,isAbsolute,join,relative,resolve,sep}from"node:path";import process from"node:process";import{codesignArgs,desktopLauncherCompileArgs,plistValue,renderInfoPlist}from"./index";import{loadDesktopConfig}from"./macos-app";import{makeIcns,runBundleCommand}from"./macos-bundle";import{desktopUpdatesProblems}from"./update-signing";import{validWebviewDatabaseFilename,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",env=process.env){const version=config.version??packageVersion;return{...config,version,buildNumber:String(config.buildNumber??env.DESKTOP_BUILD_NUMBER??"").trim()||version.replace(/-.*$/,""),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)})`);const versionValid=/^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/.test(config.version);if(!versionValid)errors.push(`webview.version must be a semantic version (got ${JSON.stringify(config.version)})`);if((versionValid||config.buildNumber!==config.version)&&!/^\d+(\.\d+){0,2}$/.test(config.buildNumber))errors.push(`webview.buildNumber must be one to three dot-separated integers, as CFBundleVersion is (got ${JSON.stringify(config.buildNumber)})`);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)errors.push(...desktopUpdatesProblems(config.updates,"webview.updates"));const database=config.agent.database;if(database&&typeof database==="object"
|
|
1
|
+
import{chmodSync,copyFileSync,existsSync,mkdirSync,readdirSync,readFileSync,rmSync,statSync,writeFileSync}from"node:fs";import{basename,dirname,isAbsolute,join,relative,resolve,sep}from"node:path";import process from"node:process";import{codesignArgs,desktopLauncherCompileArgs,plistValue,renderInfoPlist}from"./index";import{loadDesktopConfig}from"./macos-app";import{makeIcns,runBundleCommand}from"./macos-bundle";import{desktopUpdatesProblems}from"./update-signing";import{validWebviewDatabaseFilename,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",env=process.env){const version=config.version??packageVersion;return{...config,version,buildNumber:String(config.buildNumber??env.DESKTOP_BUILD_NUMBER??"").trim()||version.replace(/-.*$/,""),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)})`);const versionValid=/^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/.test(config.version);if(!versionValid)errors.push(`webview.version must be a semantic version (got ${JSON.stringify(config.version)})`);if((versionValid||config.buildNumber!==config.version)&&!/^\d+(\.\d+){0,2}$/.test(config.buildNumber))errors.push(`webview.buildNumber must be one to three dot-separated integers, as CFBundleVersion is (got ${JSON.stringify(config.buildNumber)})`);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)errors.push(...desktopUpdatesProblems(config.updates,"webview.updates"));const database=config.agent.database;if(database&&typeof database==="object"){if(database.filename!==undefined&&!validWebviewDatabaseFilename(database.filename))errors.push("webview.agent.database.filename must be a filename within the app data directory");if(database.auth!==undefined&&typeof database.auth!=="boolean")errors.push("webview.agent.database.auth must be a boolean")}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());const[command,...args]=desktopLauncherCompileArgs(options);return[command,...cross?[`--target=${bunCompileTarget(options.target)}`]:[],...options.target.startsWith("win32-")?["--windows-hide-console"]:[],...args]}export function webviewRuntimeFor(config,target,options){const configured=configuredWebviewRuntime(config,target,options);if(configured)return configured;throw new Error(`No Craft runtime for ${target}. Unpack that platform's Craft release and name its binary in desktop.webview.runtime['${target}'] or CRAFT_BIN_${target.replace("-","_").toUpperCase()}.`)}export function isWrapperScript(file){return readFileSync(file).subarray(0,2).toString()==="#!"}export function nativeHostRuntime(hostRuntime){const found=hostRuntime();if(isWrapperScript(found))throw new Error(`The Craft on this machine is a wrapper script, not a native binary: ${found}. Name the native binary in CRAFT_BIN, or let the build fetch the published runtime.`);return found}export function configuredWebviewRuntime(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();return null}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})}
|
|
@@ -93,6 +93,8 @@ export declare function renderWebviewEntry(options: {
|
|
|
93
93
|
migrations?: Record<string, string>
|
|
94
94
|
databaseFilename?: string
|
|
95
95
|
|
|
96
|
+
databaseAuth?: boolean
|
|
97
|
+
|
|
96
98
|
migrationRunner?: string
|
|
97
99
|
|
|
98
100
|
configFiles?: Record<string, string>
|
|
@@ -183,5 +185,6 @@ export declare interface WebviewDatabase {
|
|
|
183
185
|
filename?: string
|
|
184
186
|
migrations: Record<string, string>
|
|
185
187
|
migrate: (options: { databasePath: string, migrations: Record<string, string> }) => { applied: string[] }
|
|
188
|
+
migrateAuth?: (databasePath: string) => Promise<{ success: boolean, error?: string }>
|
|
186
189
|
}
|
|
187
190
|
export type WebviewAgentPreparation = (context: WebviewAgentContext & { databasePath?: string }) => void | Promise<void>;
|
package/dist/webview-launcher.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
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,validWebviewDatabaseFilename}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}]`;const loggingToFile=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 serving;let updater;let answerUpdate;let answerApp;try{const filename=options.database?.filename??"database.sqlite";if(!validWebviewDatabaseFilename(filename))throw new Error("The desktop database must use a filename within the app data directory.");const databasePath=options.database?join(paths.dataDir,filename):undefined;const initialize=async(context)=>{if(context)await options.prepare?.({...context,databasePath});if(options.database&&databasePath){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}if(options.config)await loadBundledConfig(options.config);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,beforeInstall:module.beforeInstall})}answerUpdate=updater?updateRequestHandler(updater):undefined;answerApp=options.app?appRouteHandler(await stacksAgentHandler({appRoutes:false,...options.app}),(await import("@stacksjs/router")).isUnmatchedRouteResponse):undefined;const{describeConfigSource,settledConfigSource}=await import("@stacksjs/config/sources");const source=await settledConfigSource();if(source)console.log(`${tag} ${describeConfigSource(source)}`)};if(!options.prepare)await initialize();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,initialize:options.prepare?initialize:undefined,handler:async(request,context)=>await answerUpdate?.(request)??await module.fetch?.(request,context)??answerApp?.(request),onSecondInstance:(next)=>module.secondInstance?.(next)});serving=agent;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)}`);serving?.stop();await showFailureWindow({manifest,runtime,reason:error instanceof Error?error.message:String(error),...loggingToFile?{logFile:paths.logFile}:{},spawn,launch:incoming}).catch((shown)=>console.error(`${tag} could not show why: ${shown instanceof Error?shown.message:String(shown)}`));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 renderFailurePage(options){const escape=(text)=>text.replace(/[&<>"']/g,(char)=>`&#${char.charCodeAt(0)};`);const name=escape(options.appName);return`<!doctype html>
|
|
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}]`;const loggingToFile=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 serving;let updater;let answerUpdate;let answerApp;try{const filename=options.database?.filename??"database.sqlite";if(!validWebviewDatabaseFilename(filename))throw new Error("The desktop database must use a filename within the app data directory.");const databasePath=options.database?join(paths.dataDir,filename):undefined;const initialize=async(context)=>{if(context)await options.prepare?.({...context,databasePath});if(options.database&&databasePath){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}if(options.config)await loadBundledConfig(options.config);if(databasePath&&options.database?.migrateAuth){const result=await options.database.migrateAuth(databasePath);if(!result.success)throw new Error(result.error??"Failed to initialize the managed auth schema.")}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,beforeInstall:module.beforeInstall})}answerUpdate=updater?updateRequestHandler(updater):undefined;answerApp=options.app?appRouteHandler(await stacksAgentHandler({appRoutes:false,...options.app}),(await import("@stacksjs/router")).isUnmatchedRouteResponse):undefined;const{describeConfigSource,settledConfigSource}=await import("@stacksjs/config/sources");const source=await settledConfigSource();if(source)console.log(`${tag} ${describeConfigSource(source)}`)};if(!options.prepare)await initialize();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,initialize:options.prepare?initialize:undefined,handler:async(request,context)=>await answerUpdate?.(request)??await module.fetch?.(request,context)??answerApp?.(request),onSecondInstance:(next)=>module.secondInstance?.(next)});serving=agent;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)}`);serving?.stop();await showFailureWindow({manifest,runtime,reason:error instanceof Error?error.message:String(error),...loggingToFile?{logFile:paths.logFile}:{},spawn,launch:incoming}).catch((shown)=>console.error(`${tag} could not show why: ${shown instanceof Error?shown.message:String(shown)}`));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 renderFailurePage(options){const escape=(text)=>text.replace(/[&<>"']/g,(char)=>`&#${char.charCodeAt(0)};`);const name=escape(options.appName);return`<!doctype html>
|
|
4
4
|
<html lang="en">
|
|
5
5
|
<head>
|
|
6
6
|
<meta charset="utf-8">
|
|
@@ -21,14 +21,22 @@ import{createHash}from"node:crypto";import{chmodSync,copyFileSync,existsSync,mkd
|
|
|
21
21
|
<p>${options.logFile?`Closing this window quits the app. The details are also in <code>${escape(options.logFile)}</code>.`:"Closing this window quits the app."}</p>
|
|
22
22
|
</body>
|
|
23
23
|
</html>
|
|
24
|
-
`}export async function showFailureWindow(options){const page=renderFailurePage({appName:options.manifest.appName,reason:options.reason,...options.logFile?{logFile:options.logFile}:{}});const server=Bun.serve({hostname:"127.0.0.1",port:0,fetch:()=>new Response(page,{headers:{"content-type":"text/html; charset=utf-8","content-security-policy":"default-src 'none'; style-src 'unsafe-inline'","cache-control":"no-store"}})});try{const{window}=options.manifest;const manifest={...options.manifest,window:{title:`${options.manifest.appName} could not start`,width:560,height:340,...window.darkMode!==undefined?{darkMode:window.darkMode}:{}}};await options.spawn(craftWindowCommand(manifest,options.runtime,`http://127.0.0.1:${server.port}/`,{args:options.launch?.args??[]}),{}).exited}finally{server.stop(true)}}export async function loadBundledConfig(config){const{configSource,registerBundledConfig}=await import("@stacksjs/config/sources");registerBundledConfig(config);await(await import("@stacksjs/config")).overridesReady;const failed=configSource()?.failed??[];if(failed.length)throw new Error(`config failed to load: ${failed.map((file)=>`config/${file.name}.ts: ${file.error}`).join("; ")}`)}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
|
|
24
|
+
`}export async function showFailureWindow(options){const page=renderFailurePage({appName:options.manifest.appName,reason:options.reason,...options.logFile?{logFile:options.logFile}:{}});const server=Bun.serve({hostname:"127.0.0.1",port:0,fetch:()=>new Response(page,{headers:{"content-type":"text/html; charset=utf-8","content-security-policy":"default-src 'none'; style-src 'unsafe-inline'","cache-control":"no-store"}})});try{const{window}=options.manifest;const manifest={...options.manifest,window:{title:`${options.manifest.appName} could not start`,width:560,height:340,...window.darkMode!==undefined?{darkMode:window.darkMode}:{}}};await options.spawn(craftWindowCommand(manifest,options.runtime,`http://127.0.0.1:${server.port}/`,{args:options.launch?.args??[]}),{}).exited}finally{server.stop(true)}}export async function loadBundledConfig(config){const{configSource,registerBundledConfig}=await import("@stacksjs/config/sources");registerBundledConfig(config);await(await import("@stacksjs/config")).overridesReady;const failed=configSource()?.failed??[];if(failed.length)throw new Error(`config failed to load: ${failed.map((file)=>`config/${file.name}.ts: ${file.error}`).join("; ")}`)}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 migrateAuth=options.databaseAuth===true?`
|
|
25
|
+
migrateAuth: async (databasePath) => {
|
|
26
|
+
const { ensureDatabaseConfigLoaded, migrateAuthTables, resolvedDatabaseConfig } = await import('@stacksjs/database')
|
|
27
|
+
await ensureDatabaseConfigLoaded()
|
|
28
|
+
const { driver, connections } = resolvedDatabaseConfig()
|
|
29
|
+
if (driver !== 'sqlite' || connections.sqlite.database !== databasePath)
|
|
30
|
+
throw new Error('The managed auth schema requires the webview SQLite database.')
|
|
31
|
+
return migrateAuthTables()
|
|
32
|
+
},`:"";const database=migrations?`
|
|
25
33
|
database: {${options.databaseFilename?`
|
|
26
34
|
filename: ${JSON.stringify(options.databaseFilename)},`:""}
|
|
27
35
|
migrations: {
|
|
28
36
|
${migrations.map(([name],index)=>` ${JSON.stringify(name)}: migration${index},`).join(`
|
|
29
37
|
`)}
|
|
30
38
|
},
|
|
31
|
-
migrate: migrateCompiledDatabase
|
|
39
|
+
migrate: migrateCompiledDatabase,${migrateAuth}
|
|
32
40
|
},`:"";const prepare=options.prepareEntry?`
|
|
33
41
|
prepare: async context => (await import(${JSON.stringify(options.prepareEntry)})).default(context),`:"";const configFiles=Object.entries(options.configFiles??{});const config=configFiles.length?`
|
|
34
42
|
config: {
|
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.711",
|
|
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.711",
|
|
77
|
+
"@stacksjs/router": "0.75.711",
|
|
78
|
+
"@stacksjs/server": "0.75.711",
|
|
79
|
+
"@stacksjs/storage": "0.75.711",
|
|
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.711",
|
|
84
|
+
"@stacksjs/router": "0.75.711",
|
|
85
|
+
"@stacksjs/server": "0.75.711",
|
|
86
|
+
"@stacksjs/storage": "0.75.711"
|
|
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.711",
|
|
104
104
|
"better-dx": "^0.2.39"
|
|
105
105
|
}
|
|
106
106
|
}
|