@stacksjs/desktop-build 0.75.515 → 0.75.518
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.js +5 -5
- package/dist/agent.js +1 -1
- package/dist/index.js +15 -15
- package/dist/invites.js +1 -1
- package/dist/launcher.js +1 -1
- package/dist/macos-app.js +7 -7
- package/dist/macos-bundle.js +2 -2
- package/dist/probe/page.js +3 -3
- package/dist/probe/payload.js +1 -1
- package/dist/probe/record.js +1 -1
- package/dist/probe/records.js +1 -1
- package/dist/probe/render.js +2 -2
- package/dist/probe/runner.js +5 -5
- package/dist/probe/schema.js +1 -1
- package/dist/probe/stats.js +1 -1
- package/dist/support.js +1 -1
- package/dist/updater.js +1 -1
- package/package.json +8 -8
package/dist/agent-launcher.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{appendFileSync,existsSync,mkdirSync,readFileSync,rmSync,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"
|
|
2
|
-
`)}catch{}}
|
|
1
|
+
import{appendFileSync,existsSync,mkdirSync,readFileSync,rmSync,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{}}export function logToFileWhenDetached(logFile,isTTY=Boolean(process.stdout.isTTY)){if(isTTY)return false;mkdirSync(dirname(logFile),{recursive:true});for(const level of["log","info","warn","error","debug"]){console[level]=(...args)=>{try{appendFileSync(logFile,`${new Date().toISOString()} ${level==="log"?"":`[${level}] `}${format(...args)}
|
|
2
|
+
`)}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,route,serverResponse}=await import("@stacksjs/router");if(options.actions)provideActions(options.actions);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 renderAgentEntry(options={}){const launcher=options.launcherModule??fileURLToPath(import.meta.url);const entry=options.agentEntry?`() => import(${JSON.stringify(options.agentEntry)})`:"undefined";const routes=options.routes?.length?`[
|
|
3
3
|
${options.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
|
-
]`:"[]"
|
|
5
|
+
]`:"[]";const actionEntries=Object.entries(options.actions??{});const actions=actionEntries.length?`{
|
|
6
6
|
${actionEntries.map(([name,file])=>` ${JSON.stringify(name)}: () => import(${JSON.stringify(file)}),`).join(`
|
|
7
7
|
`)}
|
|
8
8
|
}`:"{}";return`// Written by buddy build:desktop and buddy dev:desktop (macos.agent). Do not edit.
|
|
@@ -19,6 +19,6 @@ process.exit(await runDesktopAgentApp({
|
|
|
19
19
|
manifest,
|
|
20
20
|
handler: () => stacksAgentHandler({ entry: ${entry}, appRoutes: manifest.appRoutes, routes: ${routes}, actions: ${actions} }),
|
|
21
21
|
}))
|
|
22
|
-
`}export async function runDesktopAgentApp(options){const{manifest}=options
|
|
22
|
+
`}export async function runDesktopAgentApp(options){const{manifest}=options;const paths=options.paths??desktopAgentPaths(manifest.appName);const tag=`[${manifest.appName}]`;if(options.logWhenDetached!==false)logToFileWhenDetached(paths.logFile);if(!acquireInstanceLock(paths.lockFile)){console.log(`${tag} already running`);return 0}if(!existsSync(manifest.host)){console.error(`${tag} the AppKit host is missing: ${manifest.host}`);releaseInstanceLock(paths.lockFile);return 1}if(!existsSync(manifest.nativeBundle)){console.error(`${tag} the native screens are missing: ${manifest.nativeBundle}`);releaseInstanceLock(paths.lockFile);return 1}let agent;let handlerReady;try{if(manifest.projectRoot&&manifest.appRoutes)process.chdir(manifest.projectRoot);process.env[AGENT_DATA_DIR_ENV]=paths.dataDir;process.env[AGENT_RESOURCES_ENV]=JSON.stringify(manifest.resources??{});const ready=options.handler();handlerReady=ready;ready.catch(()=>{});agent=await startDesktopAgent({handler:async(request)=>(await ready)(request),name:manifest.appName,version:manifest.version,port:manifest.port,portFile:paths.portFile,staticDir:manifest.staticDir})}catch(error){console.error(`${tag} could not start: ${error instanceof Error?error.stack??error.message:String(error)}`);releaseInstanceLock(paths.lockFile);return 1}console.log(`${tag} ${manifest.version} serving on ${agent.url}`);const command=agentHostCommand(manifest,agent.url);const host=options.spawn?options.spawn(command):(()=>{const child=Bun.spawn(command,{stdio:["ignore","inherit","pipe"]});new Response(child.stderr).text().then((stderr)=>{const lines=stderr.split(`
|
|
23
23
|
`).filter((line)=>line.trim());if(lines.length)console.error(`[craft] ${lines.join(`
|
|
24
|
-
`)}`)});return{exited:child.exited,kill:()=>child.kill()}})();let stopped
|
|
24
|
+
`)}`)});return{exited:child.exited,kill:()=>child.kill()}})();let stopped=false;const stop=()=>{if(stopped)return;stopped=true;host.kill();agent.stop();releaseInstanceLock(paths.lockFile)};const onSignal=()=>{stop();process.exit(0)};for(const signal of["SIGTERM","SIGINT","SIGHUP"])process.on(signal,onSignal);try{await handlerReady}catch(error){console.error(`${tag} could not start: ${error instanceof Error?error.stack??error.message:String(error)}`);for(const signal of["SIGTERM","SIGINT","SIGHUP"])process.off(signal,onSignal);stop();return 1}const code=await host.exited;console.log(`${tag} window closed (${code})`);for(const signal of["SIGTERM","SIGINT","SIGHUP"])process.off(signal,onSignal);stop();return 0}
|
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
|
|
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}}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 root=normalize(options.staticDir);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(root,candidate));if(file!==root&&!file.startsWith(`${root}${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";headers["set-cookie"]=sessionCookie(cookieName,token)}return new Response(Bun.file(file),{headers})}return null}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 not allowed"},405);if(!isAgentHost(host,port))return json({error:"Forbidden"},403);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 json({error:"Forbidden"},403);if(request.method==="GET"&&!url.pathname.startsWith("/api/")){const file=serveStatic(url.pathname);if(file)return file}if(!hasSessionCookie(request,cookieName,token))return json({error:"Forbidden"},403);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({error:message},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/index.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import{closeSync,existsSync,openSync,readSync,statSync}from"node:fs";import{dirname,join}from"node:path";import process from"node:process";import{fileURLToPath}from"node:url";import{craftBinaryNotFoundMessage,resolveCraftBinary as resolveCraftNativeBinary}from"craft-native";export*from"./agent";export*from"./agent-launcher";export*from"./invites";export*from"./updater";export*from"./support";export*from"./macos-app";export*from"./macos-bundle";export function resolveCraftBinary(explicit=process.env.CRAFT_BIN){return resolveCraftNativeBinary(explicit)}export function resolveCraftExecutable(explicit=process.env.CRAFT_BIN,findOnPath=(binary)=>Bun.which(binary)){const resolved=resolveCraftBinary(explicit);if(resolved!=="craft")return resolved;const executable=findOnPath(resolved);if(!executable)throw Error(craftBinaryNotFoundMessage(resolved));return executable}export const USERLAND_LAUNCHER="app/Desktop/launcher.ts";export function hasUserlandDesktopLauncher(projectRoot=process.cwd()){return existsSync(join(projectRoot,USERLAND_LAUNCHER))}export function desktopLauncherCompileArgs(options){return["build","--compile",...options.minify
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
${indent}</array>`}if(value&&typeof value==="object"){const entries=Object.entries(value);if(entries.length===0)return"<dict/>";
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
${indent}</dict>`}throw Error(`Unsupported Info.plist value: ${JSON.stringify(value)??String(value)}`)}export function renderUserlandPlistEntries(declared){const ignored=Object.keys(declared).filter((key)=>RESERVED_PLIST_KEYS.has(key))
|
|
1
|
+
import{closeSync,existsSync,openSync,readSync,statSync}from"node:fs";import{dirname,join}from"node:path";import process from"node:process";import{fileURLToPath}from"node:url";import{craftBinaryNotFoundMessage,resolveCraftBinary as resolveCraftNativeBinary}from"craft-native";export*from"./agent";export*from"./agent-launcher";export*from"./invites";export*from"./updater";export*from"./support";export*from"./macos-app";export*from"./macos-bundle";export function resolveCraftBinary(explicit=process.env.CRAFT_BIN){return resolveCraftNativeBinary(explicit)}export function resolveCraftExecutable(explicit=process.env.CRAFT_BIN,findOnPath=(binary)=>Bun.which(binary)){const resolved=resolveCraftBinary(explicit);if(resolved!=="craft")return resolved;const executable=findOnPath(resolved);if(!executable)throw new Error(craftBinaryNotFoundMessage(resolved));return executable}export const USERLAND_LAUNCHER="app/Desktop/launcher.ts";export function hasUserlandDesktopLauncher(projectRoot=process.cwd()){return existsSync(join(projectRoot,USERLAND_LAUNCHER))}export function desktopLauncherCompileArgs(options){return["build","--compile",...options.minify===false?[]:["--minify"],...options.bytecode===false?[]:["--bytecode","--format=esm"],"--no-compile-autoload-bunfig","--no-compile-autoload-dotenv",options.entry,"--outfile",options.outfile]}export function resolveDesktopLauncher(projectRoot=process.cwd()){const userland=join(projectRoot,USERLAND_LAUNCHER);if(existsSync(userland))return userland;const here=dirname(fileURLToPath(import.meta.url));const candidates=[join(here,"launcher.ts"),join(here,"launcher.js")];const launcher=candidates.find((candidate)=>existsSync(candidate));if(!launcher){throw new Error("Desktop launcher entrypoint not found. Reinstall @stacksjs/desktop - the package must ship dist/launcher.js.")}return launcher}export const RESERVED_PLIST_KEYS=new Set(["CFBundleName","CFBundleDisplayName","CFBundleIdentifier","CFBundleVersion","CFBundleShortVersionString","CFBundleExecutable","CFBundlePackageType","CFBundleInfoDictionaryVersion","CFBundleIconFile"]);export function xmlEscape(value){return value.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}export function plistValue(value,indent=""){if(typeof value==="string")return`<string>${xmlEscape(value)}</string>`;if(typeof value==="boolean")return value?"<true/>":"<false/>";if(typeof value==="number"){if(!Number.isFinite(value))throw new Error(`Unsupported Info.plist number: ${value}`);return Number.isInteger(value)?`<integer>${value}</integer>`:`<real>${value}</real>`}if(Array.isArray(value)){if(value.length===0)return"<array/>";const items=value.map((item)=>`${indent} ${plistValue(item,`${indent} `)}`).join(`
|
|
2
|
+
`);return`<array>
|
|
3
|
+
${items}
|
|
4
|
+
${indent}</array>`}if(value&&typeof value==="object"){const entries=Object.entries(value);if(entries.length===0)return"<dict/>";const body=entries.map(([key,val])=>`${indent} <key>${xmlEscape(key)}</key>${plistValue(val,`${indent} `)}`).join(`
|
|
5
|
+
`);return`<dict>
|
|
6
|
+
${body}
|
|
7
|
+
${indent}</dict>`}throw new Error(`Unsupported Info.plist value: ${JSON.stringify(value)??String(value)}`)}export function renderUserlandPlistEntries(declared){const ignored=Object.keys(declared).filter((key)=>RESERVED_PLIST_KEYS.has(key));const kept=Object.entries(declared).filter(([key])=>!RESERVED_PLIST_KEYS.has(key));if(kept.length===0)return{xml:"",ignored};const xml=`
|
|
8
8
|
${kept.map(([key,value])=>` <key>${xmlEscape(key)}</key>${plistValue(value," ")}`).join(`
|
|
9
|
-
`)}
|
|
9
|
+
`)}`;return{xml,ignored}}export function renderInfoPlist(options){const declared=options.declared??{};const{xml:extra,ignored}=renderUserlandPlistEntries(declared);const overridden=(key)=>Object.hasOwn(declared,key);const loopbackTransportSecurity=` <!-- The window talks to something this app started on loopback, so an
|
|
10
10
|
exception for 127.0.0.1 is all it needs. NSAllowsArbitraryLoads would
|
|
11
11
|
additionally permit every unencrypted host on the internet. -->
|
|
12
12
|
<key>NSAppTransportSecurity</key>
|
|
@@ -17,11 +17,11 @@ ${kept.map(([key,value])=>` <key>${xmlEscape(key)}</key>${plistValue(value," "
|
|
|
17
17
|
<key>127.0.0.1</key>
|
|
18
18
|
<dict><key>NSExceptionAllowsInsecureHTTPLoads</key><true/></dict>
|
|
19
19
|
</dict>
|
|
20
|
-
</dict
|
|
21
|
-
<key>NSAppTransportSecurity</key><dict><key>NSAllowsArbitraryLoads</key><true/></dict
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
<key>CFBundleIconFile</key><string>${xmlEscape(options.iconFile)}</string>`:""
|
|
20
|
+
</dict>`;const remoteTransportSecurity=` <!-- The window loads a remote URL, so the app has to be allowed to reach it. -->
|
|
21
|
+
<key>NSAppTransportSecurity</key><dict><key>NSAllowsArbitraryLoads</key><true/></dict>`;const minimumSystem=overridden("LSMinimumSystemVersion")?"":` <key>LSMinimumSystemVersion</key><string>11.0</string>
|
|
22
|
+
`;const highResolution=overridden("NSHighResolutionCapable")?"":` <key>NSHighResolutionCapable</key><true/>
|
|
23
|
+
`;const transportSecurity=overridden("NSAppTransportSecurity")?"":options.ownsLauncher?loopbackTransportSecurity:remoteTransportSecurity;const icon=options.iconFile?`
|
|
24
|
+
<key>CFBundleIconFile</key><string>${xmlEscape(options.iconFile)}</string>`:"";const name=xmlEscape(options.appName);const version=xmlEscape(options.version);const xml=`<?xml version="1.0" encoding="UTF-8"?>
|
|
25
25
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
26
26
|
<plist version="1.0">
|
|
27
27
|
<dict>
|
|
@@ -36,5 +36,5 @@ ${kept.map(([key,value])=>` <key>${xmlEscape(key)}</key>${plistValue(value," "
|
|
|
36
36
|
${minimumSystem}${highResolution}${transportSecurity}${icon}${extra}
|
|
37
37
|
</dict>
|
|
38
38
|
</plist>
|
|
39
|
-
|
|
40
|
-
`)
|
|
39
|
+
`;return{xml,ignored}}export function resolveDevWindowUrl(port,options={}){if(!Number.isInteger(port)||port<1||port>65535)throw new RangeError(`Invalid desktop development port: ${port}`);const configured=options.url||process.env.APP_URL;if(!configured)return`https://stacks.test`;const withProtocol=/^https?:\/\//.test(configured)?configured:`https://${configured}`;return new URL(withProtocol).toString().replace(/\/$/,"")}export function craftDevCommand(port,options={}){const command=[resolveCraftBinary(options.craftBin),resolveDevWindowUrl(port,options),"--title",options.title||"Stacks","--width",String(options.width||1400),"--height",String(options.height||900)];if(options.hotReload!==false)command.push("--hot-reload");if(options.devTools===false)command.push("--no-devtools");if(options.darkMode)command.push("--dark");if(options.systemTray)command.push("--system-tray");if(options.hideDockIcon)command.push("--hide-dock-icon");if(options.menubarOnly)command.push("--menubar-only");return command}export function createUpdateManifestUrl(baseUrl,channel="stable"){if(!/^[a-z0-9-]+$/i.test(channel))throw new Error("Update channel may only contain letters, numbers, and hyphens");return new URL(`/desktop/updates/${channel}.json`,/^https?:\/\//.test(baseUrl)?baseUrl:`https://${baseUrl}`).toString()}async function launchCraft(command){const process=Bun.spawn(command,{stdin:"inherit",stdout:"inherit",stderr:"inherit"});process.unref()}export async function openDevWindow(port,options={},launcher=launchCraft){await launcher(craftDevCommand(port,options));return true}export const BUN_EXECUTABLE_MARKER="---- Bun!";const MARKER_SEARCH_BYTES=8*1024*1024;const RUNTIME_SIZE_FLOOR=40*1024*1024;const MACH_O_MAGIC=new Set([4277009102,3472551422,4277009103,3489328638,3405691582,3199925962]);export function isMachO(path){try{const fd=openSync(path,"r");try{const head=Buffer.alloc(4);if(readSync(fd,head,0,4,0)<4)return false;return MACH_O_MAGIC.has(head.readUInt32BE(0))}finally{closeSync(fd)}}catch{return false}}export function bundleDirectoryFor(path){return isMachO(path)?"MacOS":"Resources"}export function desktopAppVersion(options={}){const override=options.override?.trim();if(override)return override;const declared=typeof options.declared==="string"?options.declared.trim():"";return declared||"0.0.0"}export function dmgVolumeName(options){const override=options.override?.trim();if(override)return override;const appName=options.appName.trim();const version=options.version?.trim();return version?`${appName} ${version}`:`${appName} Installer`}export function notarytoolAuthArgs(credentials){return"profile"in credentials?["--keychain-profile",credentials.profile]:["--key",credentials.keyPath,"--key-id",credentials.keyId,"--issuer",credentials.issuerId]}export function notarizationOutcome(report,exitCode){const status=report.match(/status: (\w[\w ]*)/g)?.pop()?.replace("status: ","").trim();const id=report.match(/id: ([0-9a-f-]{36})/)?.[1];return{accepted:exitCode===0&&status==="Accepted",status,id}}export function developerIdProblem(codesignReport){if(/code object is not signed/.test(codesignReport)||/Signature=adhoc/.test(codesignReport))return"it is not signed with a certificate. Pass a Developer ID Application identity with --signing-identity.";const authority=/^Authority=(.+)$/m.exec(codesignReport)?.[1];if(!authority?.startsWith("Developer ID Application:"))return`it is signed by ${authority?`"${authority}"`:"an unknown identity"}, not a Developer ID Application certificate.`;if(!/flags=0x[0-9a-f]+\([^)]*runtime[^)]*\)/.test(codesignReport))return"it is not signed with the hardened runtime.";if(!/^Timestamp=/m.test(codesignReport))return"its signature has no secure timestamp.";return}function resolveNotary(flags,env){const profile=supplied(flags.notaryProfile)??supplied(env.DESKTOP_NOTARY_PROFILE);if(profile)return{profile};const requested=flags.notarize===true||["1","true","yes"].includes(supplied(env.DESKTOP_NOTARIZE)?.toLowerCase()??"");if(!requested)return;const keyId=supplied(flags.apiKeyId)??supplied(env.APP_STORE_CONNECT_API_KEY_ID);const issuerId=supplied(flags.apiIssuerId)??supplied(env.APP_STORE_CONNECT_API_ISSUER_ID);const keyPath=supplied(flags.apiKeyPath)??supplied(env.APP_STORE_CONNECT_API_KEY_PATH);const keyPem=supplied(env.APP_STORE_CONNECT_API_KEY)?.replaceAll("\\n",`
|
|
40
|
+
`);const missing=[!keyId&&"APP_STORE_CONNECT_API_KEY_ID (--api-key-id)",!issuerId&&"APP_STORE_CONNECT_API_ISSUER_ID (--api-issuer-id)",!keyPath&&!keyPem&&"APP_STORE_CONNECT_API_KEY_PATH (--api-key-path) or APP_STORE_CONNECT_API_KEY"].filter(Boolean);if(missing.length||!keyId||!issuerId)throw new Error(`Notarizing needs a keychain profile (--notary-profile or DESKTOP_NOTARY_PROFILE) or an App Store Connect API key. Missing: ${missing.join(", ")}.`);if(keyPath)return{keyId,issuerId,keyPath};if(!keyPem.includes("-----BEGIN PRIVATE KEY-----"))throw new Error("APP_STORE_CONNECT_API_KEY must hold the PEM text of the .p8 key.");return{keyId,issuerId,keyPem}}function supplied(value){if(typeof value!=="string")return;const trimmed=value.trim();return trimmed||undefined}export function resolveDmgPackaging(inputs={}){const flags=inputs.flags??{};const env=inputs.env??{};const appName=supplied(flags.appName)??supplied(env.DESKTOP_APP_NAME)??supplied(inputs.manifestTitle)??supplied(env.APP_NAME)??"Stacks";const version=desktopAppVersion({override:supplied(flags.appVersion)??supplied(env.DESKTOP_APP_VERSION),declared:inputs.declaredVersion});const bundleId=supplied(flags.bundleId)??supplied(env.DESKTOP_BUNDLE_ID)??`sh.stacks.${appName.toLowerCase().replace(/[^a-z0-9]+/g,"-")}`;return{appName,bundleId,version,volumeName:dmgVolumeName({appName,version,override:supplied(flags.volumeName)??supplied(env.DESKTOP_VOLUME_NAME)}),signingIdentity:supplied(flags.signingIdentity)??supplied(env.DESKTOP_SIGNING_IDENTITY),notaryProfile:supplied(flags.notaryProfile)??supplied(env.DESKTOP_NOTARY_PROFILE),notary:resolveNotary(flags,env)}}export function codesignArgs(options){return["codesign","--force",options.identity==="-"?"--timestamp=none":"--timestamp","--options","runtime",...options.entitlements?["--entitlements",options.entitlements]:[],"--sign",options.identity,options.target]}export function looksLikeBunExecutable(path,read=readTail){const file=read(path);if(!file||file.size<RUNTIME_SIZE_FLOOR)return false;return file.tail.includes(BUN_EXECUTABLE_MARKER)}function readTail(path){try{const{size}=statSync(path);if(size<RUNTIME_SIZE_FLOOR)return{size,tail:""};const fd=openSync(path,"r");try{const length=Math.min(MARKER_SEARCH_BYTES,size);const buffer=Buffer.alloc(length);readSync(fd,buffer,0,length,size-length);return{size,tail:buffer.toString("latin1")}}finally{closeSync(fd)}}catch{return null}}export function describeRuntimeDuplication(runtimes){if(runtimes.length<2)return null;const sorted=[...runtimes].sort((a,b)=>b.bytes-a.bytes);const duplicated=sorted.slice(1);const wasted=duplicated.length*RUNTIME_SIZE_FLOOR;const names=sorted.map((r)=>`${r.name} (${(r.bytes/1024/1024).toFixed(1)} MB)`).join(", ");return`This bundle ships ${runtimes.length} Bun-compiled executables: ${names}. `+`Each embeds a full copy of the Bun runtime, so at least ${(wasted/1024/1024).toFixed(0)} MB of the bundle is the same runtime repeated. `+`Compiling one binary that dispatches on a subcommand — \`MyApp agent\`, \`MyApp worker\` — keeps the helpers as separate processes and pays for the runtime once.`}
|
package/dist/invites.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export function createInviteLink(baseUrl,token,options={}){if(!token.trim())throw Error("Invite token is required");const url=new URL("/invite",/^https?:\/\//.test(baseUrl)?baseUrl:`https://${baseUrl}`);url.searchParams.set("token",token);if(options.email)url.searchParams.set("email",options.email);if(options.team)url.searchParams.set("team",options.team);if(options.role)url.searchParams.set("role",options.role);if(options.expiresAt){const date=options.expiresAt instanceof Date?options.expiresAt:new Date(options.expiresAt);if(Number.isNaN(date.valueOf()))throw Error("Invite expiration must be a valid date");url.searchParams.set("expires",date.toISOString())}return url.toString()}export async function sendDesktopInvites(recipients,options){return Promise.all(recipients.map(async(input)=>{const recipient=typeof input==="string"?{email:input}:input;try{assertEmail(recipient.email);const token=await options.createToken(recipient)
|
|
1
|
+
export function createInviteLink(baseUrl,token,options={}){if(!token.trim())throw new Error("Invite token is required");const url=new URL("/invite",/^https?:\/\//.test(baseUrl)?baseUrl:`https://${baseUrl}`);url.searchParams.set("token",token);if(options.email)url.searchParams.set("email",options.email);if(options.team)url.searchParams.set("team",options.team);if(options.role)url.searchParams.set("role",options.role);if(options.expiresAt){const date=options.expiresAt instanceof Date?options.expiresAt:new Date(options.expiresAt);if(Number.isNaN(date.valueOf()))throw new Error("Invite expiration must be a valid date");url.searchParams.set("expires",date.toISOString())}return url.toString()}export async function sendDesktopInvites(recipients,options){return Promise.all(recipients.map(async(input)=>{const recipient=typeof input==="string"?{email:input}:input;try{assertEmail(recipient.email);const token=await options.createToken(recipient);const url=createInviteLink(options.baseUrl,token,{email:recipient.email,team:recipient.team,role:recipient.role,expiresAt:options.expiresAt});await options.send({recipient,url});return{recipient,url,delivered:true}}catch(error){return{recipient,url:"",delivered:false,error:error instanceof Error?error.message:String(error)}}}))}function assertEmail(email){if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email))throw new Error(`Invalid invite email: ${email}`)}
|
package/dist/launcher.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync,readFileSync}from"node:fs";import{dirname,join}from"node:path";const bundleDir=dirname(process.execPath)
|
|
1
|
+
import{existsSync,readFileSync}from"node:fs";import{dirname,join}from"node:path";const bundleDir=dirname(process.execPath);const manifestPath=[join(bundleDir,"..","Resources","desktop.json"),join(bundleDir,"desktop.json")].find((candidate)=>existsSync(candidate))??join(bundleDir,"desktop.json");const craftPath=join(bundleDir,process.platform==="win32"?"craft-runtime.exe":"craft-runtime");if(!existsSync(manifestPath))throw new Error(`Desktop manifest not found: ${manifestPath}`);if(!existsSync(craftPath))throw new Error(`Craft runtime not found: ${craftPath}`);const manifest=JSON.parse(readFileSync(manifestPath,"utf8"));const command=[craftPath,manifest.url,"--title",manifest.title,"--width",String(manifest.width),"--height",String(manifest.height),"--no-devtools"];if(manifest.darkMode)command.push("--dark");if(manifest.systemTray)command.push("--system-tray");if(manifest.hideDockIcon)command.push("--hide-dock-icon");const child=Bun.spawn(command,{stdin:"inherit",stdout:"inherit",stderr:"inherit"});process.exit(await child.exited);
|
package/dist/macos-app.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{existsSync}from"node:fs";import{join,resolve}from"node:path";import{pathToFileURL}from"node:url";import{plistValue,renderUserlandPlistEntries,xmlEscape}from"./index";export const MACOS_DEFAULTS={minimumSystemVersion:"13.0",category:"public.app-category.productivity",nativeScreensDir:"resources/native",initialScreen:"Main",window:{width:1180,height:760,minWidth:820,minHeight:520}}
|
|
2
|
-
`}export function hostArguments(config,nativeBundle){return["--api-url",config.url.replace(/\/+$/,""),"--native-bundle",nativeBundle,...windowArguments(config),"--no-session"]}export function agentHostArguments(config){return windowArguments(config)}function windowArguments(config){const window={...MACOS_DEFAULTS.window,...config.window};return["--title",config.appName,"--route",config.initialScreen,"--titlebar-style",window.titlebarStyle??"standard","--width",String(window.width),"--height",String(window.height),"--min-width",String(window.minWidth),"--min-height",String(window.minHeight),...window.trafficLights?["--traffic-lights",window.trafficLights.join(",")]:[]]}const OWNED_KEYS=["CFBundleIdentifier","CFBundleExecutable","CFBundleName","CFBundleDisplayName","CFBundleShortVersionString","CFBundleVersion","CFBundlePackageType","LSApplicationCategoryType","LSMinimumSystemVersion","CFBundleIconFile","CFBundleURLTypes"];export const BROWSER_DOCUMENT_TYPES=[{name:"HTML document",types:["public.html"]},{name:"XHTML document",types:["public.xhtml"]},{name:"Web archive",types:["com.apple.webarchive"]},{name:"PDF document",types:["com.adobe.pdf"]}];export function defaultUsageDescriptions(appName){return{camera:`${appName} uses the camera when you allow a page or feature to.`,microphone:`${appName} uses the microphone when you allow a page or feature to.`,location:`${appName} uses your location when you allow a page or feature to.`}}export function permissionUsageDescriptions(config){const permissions=config.permissions??{}
|
|
3
|
-
`:""
|
|
4
|
-
`:""
|
|
5
|
-
`:"";
|
|
1
|
+
import{existsSync}from"node:fs";import{join,resolve}from"node:path";import{pathToFileURL}from"node:url";import{plistValue,renderUserlandPlistEntries,xmlEscape}from"./index";export const MACOS_DEFAULTS={minimumSystemVersion:"13.0",category:"public.app-category.productivity",nativeScreensDir:"resources/native",initialScreen:"Main",window:{width:1180,height:760,minWidth:820,minHeight:520}};export const RESERVED_RESOURCES=new Set(["web","native-screen.js","craft-app.json","desktop-agent.json","PrivacyInfo.xcprivacy","AppIcon.icns"]);export async function loadDesktopConfig(root){const file=join(root,"config/desktop.ts");if(!existsSync(file))return null;const module=await import(`${pathToFileURL(file).href}?t=${Date.now()}`);return module.default??null}export async function hasMacosDesktop(root){return Boolean((await loadDesktopConfig(root))?.macos)}export async function loadMacosDesktop(root,packageVersion="0.0.0"){const config=await loadDesktopConfig(root);return config?.macos?resolveMacosDesktop(config.macos,packageVersion):null}export function resolveMacosDesktop(config,packageVersion="0.0.0"){const version=config.version??packageVersion;const agent=config.agent?config.agent===true?{}:{...config.agent}:null;return{...config,agent,url:agent?"http://127.0.0.1":config.url??"",version,buildNumber:config.buildNumber??version.split(/[-+]/)[0],minimumSystemVersion:config.minimumSystemVersion??MACOS_DEFAULTS.minimumSystemVersion,category:config.category??MACOS_DEFAULTS.category,nativeScreensDir:config.nativeScreensDir??MACOS_DEFAULTS.nativeScreensDir,initialScreen:config.initialScreen??(Array.isArray(config.nativeScreens)?config.nativeScreens.includes("Main")?"Main":config.nativeScreens[0]:Object.keys(config.nativeScreens).includes("Main")?"Main":Object.keys(config.nativeScreens)[0])??MACOS_DEFAULTS.initialScreen,sandbox:config.sandbox!==false,executable:config.appName}}export function validateMacosDesktop(config){const errors=[];if(!config.appName?.trim())errors.push("macos.appName is required");if(!/^[A-Za-z0-9][A-Za-z0-9.-]*\.[A-Za-z0-9.-]+$/.test(config.bundleId??""))errors.push("macos.bundleId must be a reverse-DNS identifier such as com.example.app");if(config.teamId!==undefined&&!/^[A-Z0-9]{10}$/.test(config.teamId))errors.push("macos.teamId must be the 10-character Apple Developer team ID");if(!/^\d+(?:\.\d+){0,2}$/.test(config.version))errors.push(`macos.version must be one to three numeric components, not "${config.version}"`);if(!/^[A-Za-z0-9.-]+$/.test(config.buildNumber))errors.push("macos.buildNumber must contain only letters, numbers, periods and hyphens");if(!/^\d+(?:\.\d+){0,2}$/.test(config.minimumSystemVersion))errors.push("macos.minimumSystemVersion must be a macOS version such as 13.0");if(!/^public\.app-category\.[a-z][a-z0-9-]*$/.test(config.category))errors.push("macos.category must be an LSApplicationCategoryType such as public.app-category.productivity");if(!config.agent){try{const url=new URL(config.url);if(!["http:","https:"].includes(url.protocol))errors.push("macos.url must be an http(s) origin")}catch{errors.push("macos.url must be the server origin the app talks to, e.g. https://example.com, or turn on macos.agent to run the API inside the app")}}else{if(config.agent.port!==undefined&&!(Number.isInteger(config.agent.port)&&config.agent.port>1024&&config.agent.port<65536))errors.push("macos.agent.port must be a port above 1024");for(const[name,path]of Object.entries(config.agent.resources??{})){if(!/^[\w-][\w.-]*$/.test(name)||RESERVED_RESOURCES.has(name))errors.push(`macos.agent.resources: "${name}" must be a plain file name (letters, digits, . _ -) other than ${[...RESERVED_RESOURCES].join(", ")}`);if(typeof path!=="string"||!path.trim())errors.push(`macos.agent.resources.${name} must be a path in the project`)}}const lights=config.window?.trafficLights;if(lights!==undefined&&!(Array.isArray(lights)&&lights.length===2&&lights.every((value)=>Number.isFinite(value)&&value>=0)))errors.push("macos.window.trafficLights must be [x, y], two points from the window's top-left");for(const[index,item]of(config.dockMenu??[]).entries()){if(!item?.title?.trim())errors.push(`macos.dockMenu[${index}] needs a title`);if(!item?.action?.trim())errors.push(`macos.dockMenu[${index}] needs an action`)}const names=Object.keys(macosScreens(config));if(!names.length)errors.push("macos.nativeScreens must name at least one screen");if(names.length&&!names.includes(config.initialScreen))errors.push(`macos.initialScreen "${config.initialScreen}" is not one of the native screens (${names.join(", ")})`);for(const scheme of config.urlSchemes??[])if(!/^[a-z][a-z0-9+.-]*$/.test(scheme))errors.push(`macos.urlSchemes: "${scheme}" is not a valid URL scheme`);return errors}export function macosScreens(config){const dir=config.nativeScreensDir??MACOS_DEFAULTS.nativeScreensDir;if(Array.isArray(config.nativeScreens))return Object.fromEntries(config.nativeScreens.map((name)=>[name,`${dir}/${name}.stx`]));return{...config.nativeScreens}}export function renderHostConfig(config){const window={...MACOS_DEFAULTS.window,...config.window};return`${JSON.stringify({...config.agent?{}:{apiUrl:config.url.replace(/\/+$/,"")},title:config.appName,route:config.initialScreen,session:Boolean(config.agent),titlebarStyle:window.titlebarStyle??"standard",width:window.width,height:window.height,minWidth:window.minWidth,minHeight:window.minHeight,...window.trafficLights?{trafficLights:window.trafficLights}:{},...config.webkit?{webkit:true}:{},...config.dockMenu?.length?{dockMenu:config.dockMenu.map((item)=>({title:item.title,action:item.action}))}:{}},null,2)}
|
|
2
|
+
`}export function hostArguments(config,nativeBundle){return["--api-url",config.url.replace(/\/+$/,""),"--native-bundle",nativeBundle,...windowArguments(config),"--no-session"]}export function agentHostArguments(config){return windowArguments(config)}function windowArguments(config){const window={...MACOS_DEFAULTS.window,...config.window};return["--title",config.appName,"--route",config.initialScreen,"--titlebar-style",window.titlebarStyle??"standard","--width",String(window.width),"--height",String(window.height),"--min-width",String(window.minWidth),"--min-height",String(window.minHeight),...window.trafficLights?["--traffic-lights",window.trafficLights.join(",")]:[]]}const OWNED_KEYS=["CFBundleIdentifier","CFBundleExecutable","CFBundleName","CFBundleDisplayName","CFBundleShortVersionString","CFBundleVersion","CFBundlePackageType","LSApplicationCategoryType","LSMinimumSystemVersion","CFBundleIconFile","CFBundleURLTypes"];export const BROWSER_DOCUMENT_TYPES=[{name:"HTML document",types:["public.html"]},{name:"XHTML document",types:["public.xhtml"]},{name:"Web archive",types:["com.apple.webarchive"]},{name:"PDF document",types:["com.adobe.pdf"]}];export function defaultUsageDescriptions(appName){return{camera:`${appName} uses the camera when you allow a page or feature to.`,microphone:`${appName} uses the microphone when you allow a page or feature to.`,location:`${appName} uses your location when you allow a page or feature to.`}}export function permissionUsageDescriptions(config){const permissions=config.permissions??{};const defaults=defaultUsageDescriptions(config.appName);const sentence=(value,fallback)=>typeof value==="string"&&value.trim()?value:value?fallback:undefined;const usage={};const camera=sentence(permissions.camera,defaults.camera);if(camera)usage.NSCameraUsageDescription=camera;const microphone=sentence(permissions.microphone,defaults.microphone);if(microphone)usage.NSMicrophoneUsageDescription=microphone;const location=sentence(permissions.location,defaults.location);if(location){usage.NSLocationUsageDescription=location;usage.NSLocationWhenInUseUsageDescription=location}return usage}export function renderMacosInfoPlist(config,options={}){const owns=config.defaultBrowser?[...OWNED_KEYS,"CFBundleDocumentTypes"]:OWNED_KEYS;const declared={...permissionUsageDescriptions(config),...config.usageDescriptions,...config.infoPlist};if(config.defaultBrowser&&declared.NSAppTransportSecurity===undefined)declared.NSAppTransportSecurity={NSAllowsArbitraryLoadsInWebContent:true};const{xml:extra,ignored}=renderUserlandPlistEntries(Object.fromEntries(Object.entries(declared).filter(([key])=>!owns.includes(key))));const owned=Object.keys(declared).filter((key)=>owns.includes(key));const urlTypes=[];if(config.urlSchemes?.length)urlTypes.push({CFBundleURLName:config.bundleId,CFBundleURLSchemes:config.urlSchemes});if(config.defaultBrowser)urlTypes.push({CFBundleURLName:"Web site URL",CFBundleTypeRole:"Viewer",CFBundleURLSchemes:["http","https"]});const schemes=urlTypes.length?` <key>CFBundleURLTypes</key>${plistValue(urlTypes," ")}
|
|
3
|
+
`:"";const documents=config.defaultBrowser?` <key>CFBundleDocumentTypes</key>${plistValue(BROWSER_DOCUMENT_TYPES.map((type)=>({CFBundleTypeName:type.name,CFBundleTypeRole:"Viewer",LSHandlerRank:"Default",LSItemContentTypes:type.types}))," ")}
|
|
4
|
+
`:"";const icon=options.iconFile?` <key>CFBundleIconFile</key><string>${xmlEscape(options.iconFile)}</string>
|
|
5
|
+
`:"";const xml=`<?xml version="1.0" encoding="UTF-8"?>
|
|
6
6
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "https://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
7
7
|
<plist version="1.0">
|
|
8
8
|
<dict>
|
|
@@ -22,12 +22,12 @@ import{existsSync}from"node:fs";import{join,resolve}from"node:path";import{pathT
|
|
|
22
22
|
<key>ITSAppUsesNonExemptEncryption</key><false/>
|
|
23
23
|
${icon}${schemes}${documents}${extra}</dict>
|
|
24
24
|
</plist>
|
|
25
|
-
|
|
25
|
+
`;return{xml,ignored:[...ignored,...owned]}}export function renderMacosEntitlements(config,distribution){const entitlements={};const permissions=config.permissions??{};if(config.sandbox){entitlements["com.apple.security.app-sandbox"]=true;if(permissions.network!==false)entitlements["com.apple.security.network.client"]=true;if(config.agent)entitlements["com.apple.security.network.server"]=true;if(permissions.downloads)entitlements[permissions.downloads==="read-only"?"com.apple.security.files.downloads.read-only":"com.apple.security.files.downloads.read-write"]=true;if(permissions.printing)entitlements["com.apple.security.print"]=true}if(permissions.camera)entitlements["com.apple.security.device.camera"]=true;if(permissions.microphone)entitlements["com.apple.security.device.audio-input"]=true;if(permissions.location)entitlements["com.apple.security.personal-information.location"]=true;if(config.agent){entitlements["com.apple.security.cs.allow-jit"]=true;entitlements["com.apple.security.cs.allow-unsigned-executable-memory"]=true;entitlements["com.apple.security.cs.disable-library-validation"]=true}if(distribution==="app-store"){if(!config.teamId)throw new Error("macos.teamId is required to sign for the Mac App Store");entitlements["com.apple.application-identifier"]=`${config.teamId}.${config.bundleId}`;entitlements["com.apple.developer.team-identifier"]=config.teamId;entitlements["keychain-access-groups"]=[`${config.teamId}.${config.bundleId}`]}Object.assign(entitlements,config.entitlements);return renderEntitlementsPlist(entitlements)}export function renderMacosHostEntitlements(config){if(config.sandbox)return renderEntitlementsPlist({"com.apple.security.app-sandbox":true,"com.apple.security.inherit":true});const permissions=config.permissions??{};const entitlements={};if(permissions.camera)entitlements["com.apple.security.device.camera"]=true;if(permissions.microphone)entitlements["com.apple.security.device.audio-input"]=true;if(permissions.location)entitlements["com.apple.security.personal-information.location"]=true;return renderEntitlementsPlist(entitlements)}function renderEntitlementsPlist(entitlements){return`<?xml version="1.0" encoding="UTF-8"?>
|
|
26
26
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "https://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
27
27
|
<plist version="1.0">
|
|
28
28
|
${plistValue(entitlements)}
|
|
29
29
|
</plist>
|
|
30
|
-
`}export function renderPrivacyManifest(config){const privacy=config.privacy??{}
|
|
30
|
+
`}export function renderPrivacyManifest(config){const privacy=config.privacy??{};const manifest={NSPrivacyTracking:privacy.tracking===true,NSPrivacyTrackingDomains:privacy.trackingDomains??[],NSPrivacyCollectedDataTypes:(privacy.collectedDataTypes??[]).map((item)=>({NSPrivacyCollectedDataType:item.type,NSPrivacyCollectedDataTypeLinked:item.linked===true,NSPrivacyCollectedDataTypeTracking:item.tracking===true,NSPrivacyCollectedDataTypePurposes:item.purposes})),NSPrivacyAccessedAPITypes:(privacy.accessedApiTypes??[]).map((item)=>({NSPrivacyAccessedAPIType:item.type,NSPrivacyAccessedAPITypeReasons:item.reasons}))};return`<?xml version="1.0" encoding="UTF-8"?>
|
|
31
31
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "https://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
32
32
|
<plist version="1.0">
|
|
33
33
|
${plistValue(manifest)}
|
package/dist/macos-bundle.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{chmodSync,copyFileSync,cpSync,existsSync,mkdirSync,rmSync,writeFileSync}from"node:fs";import{join,resolve}from"node:path";import{AGENT_MANIFEST}from"./agent-launcher";import{ICONSET_SIZES,renderHostConfig,renderMacosEntitlements,renderMacosHostEntitlements,renderMacosInfoPlist,renderPrivacyManifest}from"./macos-app";export const AGENT_HOST_EXECUTABLE="craft-runtime"
|
|
2
|
-
`)}else
|
|
1
|
+
import{chmodSync,copyFileSync,cpSync,existsSync,mkdirSync,rmSync,writeFileSync}from"node:fs";import{join,resolve}from"node:path";import{AGENT_MANIFEST}from"./agent-launcher";import{ICONSET_SIZES,renderHostConfig,renderMacosEntitlements,renderMacosHostEntitlements,renderMacosInfoPlist,renderPrivacyManifest}from"./macos-app";export const AGENT_HOST_EXECUTABLE="craft-runtime";export const runBundleCommand=(args)=>{const result=Bun.spawnSync(args,{stdout:"pipe",stderr:"pipe"});if(result.exitCode!==0)throw new Error(`${args[0]} ${args.slice(1).join(" ")} exited with ${result.exitCode}: ${result.stderr.toString().trim()||result.stdout.toString().trim()}`)};export function makeIcns(png,output,scratch,run=runBundleCommand){const iconset=join(scratch,"AppIcon.iconset");rmSync(iconset,{recursive:true,force:true});mkdirSync(iconset,{recursive:true});for(const{file,pixels}of ICONSET_SIZES)run(["sips","-z",String(pixels),String(pixels),png,"--out",join(iconset,file)]);run(["iconutil","-c","icns",iconset,"-o",output]);rmSync(iconset,{recursive:true,force:true})}export function assembleMacosApp(options){const run=options.run??runBundleCommand;const{config}=options;const notes=[];const appPath=join(options.output,`${config.appName}.app`);const contents=join(appPath,"Contents");const macos=join(contents,"MacOS");const resources=join(contents,"Resources");rmSync(appPath,{recursive:true,force:true});mkdirSync(macos,{recursive:true});mkdirSync(resources,{recursive:true});if(options.agent){if(!config.agent)throw new Error("An agent launcher was given for an app whose config has no macos.agent");copyFileSync(options.agent.launcher,join(macos,config.executable));copyFileSync(options.host,join(macos,AGENT_HOST_EXECUTABLE));chmodSync(join(macos,AGENT_HOST_EXECUTABLE),493);const manifest={...options.agent.manifest,host:`../MacOS/${AGENT_HOST_EXECUTABLE}`,nativeBundle:"native-screen.js"};if(options.agent.manifest.staticDir){cpSync(options.agent.manifest.staticDir,join(resources,"web"),{recursive:true});manifest.staticDir="web"}if(options.agent.manifest.resources){for(const[name,source]of Object.entries(options.agent.manifest.resources)){if(!existsSync(source))throw new Error(`macos.agent.resources.${name} does not exist: ${source}`);cpSync(source,join(resources,name),{recursive:true,dereference:true})}manifest.resources=Object.fromEntries(Object.keys(options.agent.manifest.resources).map((name)=>[name,name]))}writeFileSync(join(resources,AGENT_MANIFEST),`${JSON.stringify(manifest,null,2)}
|
|
2
|
+
`)}else{copyFileSync(options.host,join(macos,config.executable))}chmodSync(join(macos,config.executable),493);copyFileSync(options.nativeBundle,join(resources,"native-screen.js"));writeFileSync(join(resources,"craft-app.json"),renderHostConfig(config));writeFileSync(join(resources,"PrivacyInfo.xcprivacy"),renderPrivacyManifest(config));let iconFile;if(config.icon){const icon=resolve(options.root,config.icon);if(!existsSync(icon))throw new Error(`macos.icon does not exist: ${icon}`);if(icon.endsWith(".icns"))copyFileSync(icon,join(resources,"AppIcon.icns"));else makeIcns(icon,join(resources,"AppIcon.icns"),options.output,run);iconFile="AppIcon"}else notes.push("No macos.icon: the app has the generic icon, which the Mac App Store rejects.");const plist=renderMacosInfoPlist(config,{iconFile});writeFileSync(join(contents,"Info.plist"),plist.xml);if(options.distribution==="app-store"){if(!options.provisioningProfile)throw new Error("A Mac App Store build needs a provisioning profile");const embedded=join(contents,"embedded.provisionprofile");copyFileSync(options.provisioningProfile,embedded);chmodSync(embedded,420)}const signed=options.unsandboxed?{...config,sandbox:false}:config;const entitlementsPath=join(options.output,`${config.appName}.entitlements`);writeFileSync(entitlementsPath,renderMacosEntitlements(signed,options.distribution));const hostEntitlements=join(options.output,`${config.appName}.host.entitlements`);if(options.agent)writeFileSync(hostEntitlements,renderMacosHostEntitlements(signed));run(["plutil","-lint",join(contents,"Info.plist"),join(resources,"PrivacyInfo.xcprivacy"),entitlementsPath,...options.agent?[hostEntitlements]:[]]);const identity=options.signingIdentity||"-";if(options.agent){run(["codesign","--force","--options","runtime",...identity==="-"?[]:["--timestamp"],"--entitlements",hostEntitlements,...options.keychain?["--keychain",options.keychain]:[],"--sign",identity,join(macos,AGENT_HOST_EXECUTABLE)])}run(["codesign","--force","--options","runtime",...identity==="-"?[]:["--timestamp"],"--entitlements",entitlementsPath,...options.keychain?["--keychain",options.keychain]:[],"--sign",identity,appPath]);run(["codesign","--verify","--deep","--strict",appPath]);return{appPath,entitlementsPath,ignoredPlistKeys:plist.ignored,notes}}export function parseDevelopmentIdentity(output){for(const line of output.split(`
|
|
3
3
|
`)){const match=/^\s*\d+\)\s+([0-9A-F]{40})\s+"Apple Development:/.exec(line);if(match)return match[1]}return}export function findDevelopmentIdentity(read=()=>Bun.spawnSync(["security","find-identity","-v","-p","codesigning"],{stdout:"pipe",stderr:"ignore"}).stdout.toString()){try{return parseDevelopmentIdentity(read())}catch{return}}
|
package/dist/probe/page.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const configElement=document.getElementById("probe-config")
|
|
1
|
+
const configElement=document.getElementById("probe-config");const config=JSON.parse(configElement?.textContent||"{}");const statusElement=document.getElementById("status");const panel=document.getElementById("interactive");const canvas=document.getElementById("scene");const errors=[];function say(message){statusElement.textContent=message;fetch("/progress",{method:"POST",body:message}).catch(()=>{})}function errorText(error){if(error instanceof Error)return`${error.name}: ${error.message}`;return String(error)}function sleep(ms){return new Promise((resolve)=>setTimeout(resolve,ms))}function nextFrame(){return new Promise((resolve)=>requestAnimationFrame(resolve))}function withTimeout(work,ms,fallback){return Promise.race([work,sleep(ms).then(()=>fallback)])}function timerResolution(){let smallest=Number.POSITIVE_INFINITY;let last=performance.now();const deadline=last+50;while(last<deadline){const now=performance.now();const step=now-last;if(step>0&&step<smallest)smallest=step;last=now}return Math.round(smallest*1000)/1000}function eventTimeStampComparable(){const event=new Event("probe");return Math.abs(event.timeStamp-performance.now())<1e4}function probeWebgl2(){try{const gl=document.createElement("canvas").getContext("webgl2");if(!gl)return{ok:false,error:'getContext("webgl2") returned null'};const debug=gl.getExtension("WEBGL_debug_renderer_info");return{ok:true,version:String(gl.getParameter(gl.VERSION)),shadingLanguageVersion:String(gl.getParameter(gl.SHADING_LANGUAGE_VERSION)),vendor:String(gl.getParameter(gl.VENDOR)),renderer:String(gl.getParameter(gl.RENDERER)),unmaskedVendor:debug?String(gl.getParameter(debug.UNMASKED_VENDOR_WEBGL)):undefined,unmaskedRenderer:debug?String(gl.getParameter(debug.UNMASKED_RENDERER_WEBGL)):undefined,maxTextureSize:Number(gl.getParameter(gl.MAX_TEXTURE_SIZE)),maxSamples:Number(gl.getParameter(gl.MAX_SAMPLES)),extensions:gl.getSupportedExtensions()?.length??0}}catch(error){return{ok:false,error:errorText(error)}}}async function probeWebgpu(){const gpu=navigator.gpu;if(!gpu)return{present:false,adapter:false,device:false};try{const adapter=await withTimeout(gpu.requestAdapter(),5000,null);if(!adapter)return{present:true,adapter:false,device:false,error:"requestAdapter() resolved null or timed out"};const info=adapter.info??{};let device=false;let error;try{const created=await withTimeout(adapter.requestDevice(),5000,null);device=created!==null;created?.destroy?.();if(!device)error="requestDevice() timed out"}catch(deviceError){error=errorText(deviceError)}return{present:true,adapter:true,device,error,vendor:info.vendor||undefined,architecture:info.architecture||undefined,description:info.description||undefined,maxTextureDimension2D:adapter.limits?.maxTextureDimension2D,features:adapter.features?.size}}catch(error){return{present:true,adapter:false,device:false,error:errorText(error)}}}const VERTEX=`#version 300 es
|
|
2
2
|
layout(location = 0) in vec3 position;
|
|
3
3
|
layout(location = 1) in vec3 normal;
|
|
4
4
|
layout(location = 2) in vec4 offset;
|
|
@@ -15,8 +15,8 @@ void main() {
|
|
|
15
15
|
vec3 n = r * normal;
|
|
16
16
|
shade = vec3(0.35, 0.55, 0.95) * (0.35 + 0.65 * max(dot(n, normalize(vec3(0.4, 0.8, 0.6))), 0.0));
|
|
17
17
|
gl_Position = vec4(p.x / aspect, p.y, p.z * 0.5, 1.0);
|
|
18
|
-
}
|
|
18
|
+
}`;const FRAGMENT=`#version 300 es
|
|
19
19
|
precision mediump float;
|
|
20
20
|
in vec3 shade;
|
|
21
21
|
out vec4 color;
|
|
22
|
-
void main() { color = vec4(shade, 1.0); }`;function cubeGeometry(){const faces=[[[1,0,0],[0,1,0],[0,0,1]],[[-1,0,0],[0,0,1],[0,1,0]],[[0,1,0],[0,0,1],[1,0,0]],[[0,-1,0],[1,0,0],[0,0,1]],[[0,0,1],[1,0,0],[0,1,0]],[[0,0,-1],[0,1,0],[1,0,0]]],out=[];for(const[n,u,v]of faces){const corner=(su,sv)=>[0,1,2].map((i)=>n[i]+su*u[i]+sv*v[i]),quad=[corner(-1,-1),corner(1,-1),corner(1,1),corner(-1,-1),corner(1,1),corner(-1,1)];for(const p of quad)out.push(...p,...n)}return new Float32Array(out)}function webglScene(instances){const gl=canvas.getContext("webgl2",{antialias:!0,powerPreference:"high-performance"});if(!gl)return null;const compile=(type,source)=>{const shader=gl.createShader(type);gl.shaderSource(shader,source);gl.compileShader(shader);if(!gl.getShaderParameter(shader,gl.COMPILE_STATUS))throw Error(gl.getShaderInfoLog(shader)||"shader compile failed");return shader},program=gl.createProgram();gl.attachShader(program,compile(gl.VERTEX_SHADER,VERTEX));gl.attachShader(program,compile(gl.FRAGMENT_SHADER,FRAGMENT));gl.linkProgram(program);if(!gl.getProgramParameter(program,gl.LINK_STATUS))throw Error(gl.getProgramInfoLog(program)||"program link failed");const vao=gl.createVertexArray();gl.bindVertexArray(vao);const geometry=cubeGeometry();gl.bindBuffer(gl.ARRAY_BUFFER,gl.createBuffer());gl.bufferData(gl.ARRAY_BUFFER,geometry,gl.STATIC_DRAW);gl.enableVertexAttribArray(0);gl.vertexAttribPointer(0,3,gl.FLOAT,!1,24,0);gl.enableVertexAttribArray(1);gl.vertexAttribPointer(1,3,gl.FLOAT,!1,24,12);const offsets=new Float32Array(instances*4);for(let i=0;i<instances;i++){offsets[i*4]=Math.random()*2-1;offsets[i*4+1]=Math.random()*2-1;offsets[i*4+2]=Math.random()*2-1;offsets[i*4+3]=Math.random()*Math.PI*2}gl.bindBuffer(gl.ARRAY_BUFFER,gl.createBuffer());gl.bufferData(gl.ARRAY_BUFFER,offsets,gl.STATIC_DRAW);gl.enableVertexAttribArray(2);gl.vertexAttribPointer(2,4,gl.FLOAT,!1,16,0);gl.vertexAttribDivisor(2,1);gl.useProgram(program);gl.enable(gl.DEPTH_TEST);const timeLocation=gl.getUniformLocation(program,"time"),aspectLocation=gl.getUniformLocation(program,"aspect"),vertices=geometry.length/6;return{triangles:vertices/3*instances,draw(time){const width=Math.floor(canvas.clientWidth*devicePixelRatio),height=Math.floor(canvas.clientHeight*devicePixelRatio);if(canvas.width!==width||canvas.height!==height){canvas.width=width;canvas.height=height}gl.viewport(0,0,width,height);gl.clearColor(0.04,0.05,0.08,1);gl.clear(gl.COLOR_BUFFER_BIT|gl.DEPTH_BUFFER_BIT);gl.uniform1f(timeLocation,time/1000);gl.uniform1f(aspectLocation,width/Math.max(1,height));gl.drawArraysInstanced(gl.TRIANGLES,0,vertices,instances)}}}function canvas2dScene(){const context=canvas.getContext("2d");return{triangles:0,draw(time){canvas.width=canvas.clientWidth;canvas.height=canvas.clientHeight;context.fillStyle="#0a0d14";context.fillRect(0,0,canvas.width,canvas.height);context.fillStyle="#5b8cf2";for(let i=0;i<2000;i++)context.fillRect((i*37+time/4)%canvas.width,i*53%canvas.height,6,6)}}}function busyWait(ms){const until=performance.now()+ms;while(performance.now()<until);}async function sampleFrames(durationMs,onFrame){const timestamps=[];let hidden=document.visibilityState!=="visible";const onVisibility=()=>{if(document.visibilityState!=="visible")hidden=!0};document.addEventListener("visibilitychange",onVisibility);await nextFrame();const start=performance.now();await new Promise((resolve)=>{const tick=(time)=>{timestamps.push(time);onFrame?.(time);if(performance.now()-start<durationMs)requestAnimationFrame(tick);else resolve()};requestAnimationFrame(tick)});document.removeEventListener("visibilitychange",onVisibility);return{timestamps,hidden}}let audioContext=null;function snapshot(context){return{state:context.state,baseLatency:typeof context.baseLatency==="number"?context.baseLatency:null,outputLatency:typeof context.outputLatency==="number"?context.outputLatency:null,sampleRate:context.sampleRate}}async function probeAudio(){const Constructor=window.AudioContext;if(!Constructor)return{present:!1};try{audioContext=new Constructor({latencyHint:"interactive"});const initial=snapshot(audioContext);await withTimeout(audioContext.resume().catch(()=>{}),1500,void 0);await sleep(300);return{present:!0,initial,afterUngesturedResume:snapshot(audioContext)}}catch(error){return{present:!0,error:errorText(error)}}}function requestFullscreen(target){const{requestFullscreen:standard,webkitRequestFullscreen:legacy}=target;if(!standard&&!legacy)return Promise.resolve({outcome:"no-api"});return new Promise((resolve)=>{let settled=!1;const finish=(outcome)=>{if(settled)return;settled=!0;resolve(outcome)},entered=()=>finish({outcome:"entered",detail:"fullscreenchange"}),failed=()=>finish({outcome:"rejected",detail:"fullscreenerror"});document.addEventListener("fullscreenchange",entered,{once:!0});document.addEventListener("webkitfullscreenchange",entered,{once:!0});document.addEventListener("fullscreenerror",failed,{once:!0});document.addEventListener("webkitfullscreenerror",failed,{once:!0});try{if(standard)standard.call(target).then(()=>finish({outcome:"entered",detail:"promise resolved"}),(error)=>finish({outcome:"rejected",detail:errorText(error)}));else legacy.call(target)}catch(error){finish({outcome:"rejected",detail:errorText(error)})}setTimeout(()=>finish({outcome:"timeout"}),3000)})}async function exitFullscreen(){const exit=document.exitFullscreen;if(document.fullscreenElement&&exit)await exit.call(document).catch(()=>{})}function requestPointerLock(target){if(typeof target.requestPointerLock!=="function")return Promise.resolve({outcome:"no-api"});return new Promise((resolve)=>{let settled=!1;const finish=(outcome)=>{if(settled)return;settled=!0;document.removeEventListener("pointerlockchange",changed);document.removeEventListener("pointerlockerror",failed);resolve(outcome)},changed=()=>{if(document.pointerLockElement===target)finish({outcome:"entered",detail:"pointerlockchange"})},failed=()=>finish({outcome:"rejected",detail:"pointerlockerror"});document.addEventListener("pointerlockchange",changed);document.addEventListener("pointerlockerror",failed);try{target.requestPointerLock()?.then?.(()=>changed(),(error)=>finish({outcome:"rejected",detail:errorText(error)}))}catch(error){finish({outcome:"rejected",detail:errorText(error)})}setTimeout(()=>finish({outcome:"timeout"}),3000)})}async function nativeFullscreen(){const bridge=window.craft,set=bridge?.window?.setFullscreen;if(typeof set!=="function")return{outcome:"no-api"};const size=()=>`${innerWidth}x${innerHeight}`,sizeBefore=size();try{await withTimeout(Promise.resolve(set.call(bridge.window,!0)),3000,void 0);await sleep(2000);const sizeAfter=size(),entered=sizeAfter!==sizeBefore&&innerWidth>=screen.width-2;await withTimeout(Promise.resolve(set.call(bridge.window,!1)),3000,void 0);await sleep(1500);return{outcome:entered?"entered":"rejected",detail:entered?"viewport grew to the screen":"viewport did not change",sizeBefore,sizeAfter}}catch(error){return{outcome:"rejected",detail:errorText(error),sizeBefore}}}const samples={pointerdown:[],pointermove:[],keydown:[],eventTimingSupported:typeof PerformanceObserver<"u"&&(PerformanceObserver.supportedEntryTypes??[]).includes("event"),eventTimingDurations:[]};let sawRealInput=!1,movePending=!1;function timeEvent(event,into){if(!event.isTrusted)return;sawRealInput=!0;const stamp=event.timeStamp;requestAnimationFrame(()=>{const toFrameMs=performance.now()-stamp,channel=new MessageChannel;channel.port1.onmessage=()=>{into.push({toFrameMs,toPostFrameMs:performance.now()-stamp});movePending=!1};channel.port2.postMessage(0)})}function listenForInput(){const onDown=(event)=>timeEvent(event,samples.pointerdown),onKey=(event)=>timeEvent(event,samples.keydown),onMove=(event)=>{if(movePending||!event.isTrusted)return;movePending=!0;timeEvent(event,samples.pointermove)};addEventListener("pointerdown",onDown,!0);addEventListener("keydown",onKey,!0);addEventListener("pointermove",onMove,!0);let observer=null;if(samples.eventTimingSupported){observer=new PerformanceObserver((list)=>{for(const entry of list.getEntries())samples.eventTimingDurations.push(entry.duration)});try{observer.observe({type:"event",buffered:!0,durationThreshold:16})}catch{observer=null}}return()=>{removeEventListener("pointerdown",onDown,!0);removeEventListener("keydown",onKey,!0);removeEventListener("pointermove",onMove,!0);observer?.disconnect()}}async function interactivePhase(payload){if(config.interactionWindowMs<=0){payload.interaction.skipped=!0;return}panel.hidden=!1;const fullscreenButton=document.getElementById("fullscreen-button"),lockButton=document.getElementById("lock-button"),doneButton=document.getElementById("done-button"),countdown=document.getElementById("countdown");let fullscreenDone=!1,lockDone=!1,finish=()=>{};const finished=new Promise((resolve)=>finish=resolve),maybeFinish=()=>{if(fullscreenDone&&lockDone&&samples.keydown.length>=5)finish()};fullscreenButton.addEventListener("click",async(event)=>{if(!event.isTrusted||fullscreenDone)return;fullscreenDone=!0;fullscreenButton.setAttribute("disabled","");const resume=audioContext?.resume().catch(()=>{});payload.fullscreen.gestured=await requestFullscreen(document.documentElement);await resume;await sleep(300);if(audioContext)payload.audio.afterGesturedResume=snapshot(audioContext);await sleep(700);await exitFullscreen();maybeFinish()});lockButton.addEventListener("click",async(event)=>{if(!event.isTrusted||lockDone)return;lockDone=!0;lockButton.setAttribute("disabled","");payload.pointerLock.gestured=await requestPointerLock(canvas);await sleep(500);if(document.pointerLockElement)document.exitPointerLock();maybeFinish()});addEventListener("keydown",()=>setTimeout(maybeFinish,100));doneButton.addEventListener("click",(event)=>event.isTrusted&&finish());const deadline=performance.now()+config.interactionWindowMs,timer=setInterval(()=>{const left=Math.max(0,Math.ceil((deadline-performance.now())/1000));countdown.textContent=`${left}s left, ${samples.keydown.length} key presses so far`},250);await Promise.race([finished,sleep(config.interactionWindowMs)]);clearInterval(timer);await sleep(200);panel.hidden=!0}async function run(){const notAttempted={outcome:"not-attempted"},bridge=window.craft,payload={config,userAgent:navigator.userAgent,devicePixelRatio,screen:{width:screen.width,height:screen.height},isSecureContext,timerResolutionMs:timerResolution(),eventTimeStampComparable:eventTimeStampComparable(),bridge:{present:Boolean(bridge),setFullscreen:typeof bridge?.window?.setFullscreen==="function"},webgl2:{ok:!1},webgpu:{present:!1,adapter:!1,device:!1},frames:{idle:[],load:[],triangles:0,hiddenDuringSampling:!1,focused:!1},input:samples,audio:{present:!1},gamepad:{present:typeof navigator.getGamepads==="function",connected:0,ids:[],connectedEventSeen:!1},fullscreen:{elementApi:typeof document.documentElement.requestFullscreen==="function",webkitElementApi:typeof document.documentElement.webkitRequestFullscreen==="function",enabled:typeof document.fullscreenEnabled==="boolean"?document.fullscreenEnabled:null,ungestured:notAttempted,gestured:notAttempted,nativeBridge:notAttempted},pointerLock:{api:typeof canvas.requestPointerLock==="function",ungestured:notAttempted,gestured:notAttempted},interaction:{windowMs:config.interactionWindowMs,sawRealInput:!1,skipped:!1},errors};addEventListener("gamepadconnected",()=>{payload.gamepad.connectedEventSeen=!0});const stopListening=listenForInput();say("Probing WebGL2 and WebGPU");payload.webgl2=probeWebgl2();payload.webgpu=await probeWebgpu();say("Probing audio");payload.audio=await probeAudio();say("Requesting fullscreen and pointer lock without a gesture (expected to be refused)");payload.fullscreen.ungestured=await requestFullscreen(document.documentElement);await exitFullscreen();payload.pointerLock.ungestured=await requestPointerLock(canvas);say(`Frame pacing: idle for ${config.idleMs/1000}s`);const idle=await sampleFrames(config.idleMs);let scene;try{scene=webglScene(config.instances)??canvas2dScene()}catch(error){errors.push(`load scene: ${errorText(error)}`);scene=canvas2dScene()}for(let i=0;i<10;i++)scene.draw(await nextFrame());say(`Frame pacing: ${scene.triangles.toLocaleString()} triangles + ${config.cpuLoadMsPerFrame} ms CPU per frame for ${config.loadMs/1000}s`);const load=await sampleFrames(config.loadMs,(time)=>{busyWait(config.cpuLoadMsPerFrame);scene.draw(time)});payload.frames={idle:idle.timestamps,load:load.timestamps,triangles:scene.triangles,hiddenDuringSampling:idle.hidden||load.hidden,focused:document.hasFocus()};say("Waiting for real input (see the panel), or for the window to time out");await interactivePhase(payload);stopListening();const pads=typeof navigator.getGamepads==="function"?[...navigator.getGamepads()].filter(Boolean):[];payload.gamepad.connected=pads.length;payload.gamepad.ids=pads.map((pad)=>pad.id);if(config.tryNativeFullscreen&&payload.bridge.setFullscreen){say("Trying Craft's native window fullscreen through window.craft");payload.fullscreen.nativeBridge=await nativeFullscreen()}payload.interaction.sawRealInput=sawRealInput;await audioContext?.close().catch(()=>{});say("Sending results");await fetch("/results",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(payload)});say("Done. Results were sent to the runner; this window can close.")}run().catch((error)=>{const message=errorText(error);say(`Probe failed: ${message}`);fetch("/failed",{method:"POST",body:message}).catch(()=>{})});
|
|
22
|
+
void main() { color = vec4(shade, 1.0); }`;function cubeGeometry(){const faces=[[[1,0,0],[0,1,0],[0,0,1]],[[-1,0,0],[0,0,1],[0,1,0]],[[0,1,0],[0,0,1],[1,0,0]],[[0,-1,0],[1,0,0],[0,0,1]],[[0,0,1],[1,0,0],[0,1,0]],[[0,0,-1],[0,1,0],[1,0,0]]];const out=[];for(const[n,u,v]of faces){const corner=(su,sv)=>[0,1,2].map((i)=>n[i]+su*u[i]+sv*v[i]);const quad=[corner(-1,-1),corner(1,-1),corner(1,1),corner(-1,-1),corner(1,1),corner(-1,1)];for(const p of quad)out.push(...p,...n)}return new Float32Array(out)}function webglScene(instances){const gl=canvas.getContext("webgl2",{antialias:true,powerPreference:"high-performance"});if(!gl)return null;const compile=(type,source)=>{const shader=gl.createShader(type);gl.shaderSource(shader,source);gl.compileShader(shader);if(!gl.getShaderParameter(shader,gl.COMPILE_STATUS))throw new Error(gl.getShaderInfoLog(shader)||"shader compile failed");return shader};const program=gl.createProgram();gl.attachShader(program,compile(gl.VERTEX_SHADER,VERTEX));gl.attachShader(program,compile(gl.FRAGMENT_SHADER,FRAGMENT));gl.linkProgram(program);if(!gl.getProgramParameter(program,gl.LINK_STATUS))throw new Error(gl.getProgramInfoLog(program)||"program link failed");const vao=gl.createVertexArray();gl.bindVertexArray(vao);const geometry=cubeGeometry();gl.bindBuffer(gl.ARRAY_BUFFER,gl.createBuffer());gl.bufferData(gl.ARRAY_BUFFER,geometry,gl.STATIC_DRAW);gl.enableVertexAttribArray(0);gl.vertexAttribPointer(0,3,gl.FLOAT,false,24,0);gl.enableVertexAttribArray(1);gl.vertexAttribPointer(1,3,gl.FLOAT,false,24,12);const offsets=new Float32Array(instances*4);for(let i=0;i<instances;i++){offsets[i*4]=Math.random()*2-1;offsets[i*4+1]=Math.random()*2-1;offsets[i*4+2]=Math.random()*2-1;offsets[i*4+3]=Math.random()*Math.PI*2}gl.bindBuffer(gl.ARRAY_BUFFER,gl.createBuffer());gl.bufferData(gl.ARRAY_BUFFER,offsets,gl.STATIC_DRAW);gl.enableVertexAttribArray(2);gl.vertexAttribPointer(2,4,gl.FLOAT,false,16,0);gl.vertexAttribDivisor(2,1);gl.useProgram(program);gl.enable(gl.DEPTH_TEST);const timeLocation=gl.getUniformLocation(program,"time");const aspectLocation=gl.getUniformLocation(program,"aspect");const vertices=geometry.length/6;return{triangles:vertices/3*instances,draw(time){const width=Math.floor(canvas.clientWidth*devicePixelRatio);const height=Math.floor(canvas.clientHeight*devicePixelRatio);if(canvas.width!==width||canvas.height!==height){canvas.width=width;canvas.height=height}gl.viewport(0,0,width,height);gl.clearColor(0.04,0.05,0.08,1);gl.clear(gl.COLOR_BUFFER_BIT|gl.DEPTH_BUFFER_BIT);gl.uniform1f(timeLocation,time/1000);gl.uniform1f(aspectLocation,width/Math.max(1,height));gl.drawArraysInstanced(gl.TRIANGLES,0,vertices,instances)}}}function canvas2dScene(){const context=canvas.getContext("2d");return{triangles:0,draw(time){canvas.width=canvas.clientWidth;canvas.height=canvas.clientHeight;context.fillStyle="#0a0d14";context.fillRect(0,0,canvas.width,canvas.height);context.fillStyle="#5b8cf2";for(let i=0;i<2000;i++)context.fillRect((i*37+time/4)%canvas.width,i*53%canvas.height,6,6)}}}function busyWait(ms){const until=performance.now()+ms;while(performance.now()<until){}}async function sampleFrames(durationMs,onFrame){const timestamps=[];let hidden=document.visibilityState!=="visible";const onVisibility=()=>{if(document.visibilityState!=="visible")hidden=true};document.addEventListener("visibilitychange",onVisibility);await nextFrame();const start=performance.now();await new Promise((resolve)=>{const tick=(time)=>{timestamps.push(time);onFrame?.(time);if(performance.now()-start<durationMs)requestAnimationFrame(tick);else resolve()};requestAnimationFrame(tick)});document.removeEventListener("visibilitychange",onVisibility);return{timestamps,hidden}}let audioContext=null;function snapshot(context){return{state:context.state,baseLatency:typeof context.baseLatency==="number"?context.baseLatency:null,outputLatency:typeof context.outputLatency==="number"?context.outputLatency:null,sampleRate:context.sampleRate}}async function probeAudio(){const Constructor=window.AudioContext;if(!Constructor)return{present:false};try{audioContext=new Constructor({latencyHint:"interactive"});const initial=snapshot(audioContext);await withTimeout(audioContext.resume().catch(()=>{}),1500,undefined);await sleep(300);return{present:true,initial,afterUngesturedResume:snapshot(audioContext)}}catch(error){return{present:true,error:errorText(error)}}}function requestFullscreen(target){const standard=target.requestFullscreen;const legacy=target.webkitRequestFullscreen;if(!standard&&!legacy)return Promise.resolve({outcome:"no-api"});return new Promise((resolve)=>{let settled=false;const finish=(outcome)=>{if(settled)return;settled=true;resolve(outcome)};const entered=()=>finish({outcome:"entered",detail:"fullscreenchange"});const failed=()=>finish({outcome:"rejected",detail:"fullscreenerror"});document.addEventListener("fullscreenchange",entered,{once:true});document.addEventListener("webkitfullscreenchange",entered,{once:true});document.addEventListener("fullscreenerror",failed,{once:true});document.addEventListener("webkitfullscreenerror",failed,{once:true});try{if(standard){standard.call(target).then(()=>finish({outcome:"entered",detail:"promise resolved"}),(error)=>finish({outcome:"rejected",detail:errorText(error)}))}else{legacy.call(target)}}catch(error){finish({outcome:"rejected",detail:errorText(error)})}setTimeout(()=>finish({outcome:"timeout"}),3000)})}async function exitFullscreen(){const exit=document.exitFullscreen;if(document.fullscreenElement&&exit)await exit.call(document).catch(()=>{})}function requestPointerLock(target){if(typeof target.requestPointerLock!=="function")return Promise.resolve({outcome:"no-api"});return new Promise((resolve)=>{let settled=false;const finish=(outcome)=>{if(settled)return;settled=true;document.removeEventListener("pointerlockchange",changed);document.removeEventListener("pointerlockerror",failed);resolve(outcome)};const changed=()=>{if(document.pointerLockElement===target)finish({outcome:"entered",detail:"pointerlockchange"})};const failed=()=>finish({outcome:"rejected",detail:"pointerlockerror"});document.addEventListener("pointerlockchange",changed);document.addEventListener("pointerlockerror",failed);try{const result=target.requestPointerLock();result?.then?.(()=>changed(),(error)=>finish({outcome:"rejected",detail:errorText(error)}))}catch(error){finish({outcome:"rejected",detail:errorText(error)})}setTimeout(()=>finish({outcome:"timeout"}),3000)})}async function nativeFullscreen(){const bridge=window.craft;const set=bridge?.window?.setFullscreen;if(typeof set!=="function")return{outcome:"no-api"};const size=()=>`${innerWidth}x${innerHeight}`;const sizeBefore=size();try{await withTimeout(Promise.resolve(set.call(bridge.window,true)),3000,undefined);await sleep(2000);const sizeAfter=size();const entered=sizeAfter!==sizeBefore&&innerWidth>=screen.width-2;await withTimeout(Promise.resolve(set.call(bridge.window,false)),3000,undefined);await sleep(1500);return{outcome:entered?"entered":"rejected",detail:entered?"viewport grew to the screen":"viewport did not change",sizeBefore,sizeAfter}}catch(error){return{outcome:"rejected",detail:errorText(error),sizeBefore}}}const samples={pointerdown:[],pointermove:[],keydown:[],eventTimingSupported:typeof PerformanceObserver!=="undefined"&&(PerformanceObserver.supportedEntryTypes??[]).includes("event"),eventTimingDurations:[]};let sawRealInput=false;let movePending=false;function timeEvent(event,into){if(!event.isTrusted)return;sawRealInput=true;const stamp=event.timeStamp;requestAnimationFrame(()=>{const toFrameMs=performance.now()-stamp;const channel=new MessageChannel;channel.port1.onmessage=()=>{into.push({toFrameMs,toPostFrameMs:performance.now()-stamp});movePending=false};channel.port2.postMessage(0)})}function listenForInput(){const onDown=(event)=>timeEvent(event,samples.pointerdown);const onKey=(event)=>timeEvent(event,samples.keydown);const onMove=(event)=>{if(movePending||!event.isTrusted)return;movePending=true;timeEvent(event,samples.pointermove)};addEventListener("pointerdown",onDown,true);addEventListener("keydown",onKey,true);addEventListener("pointermove",onMove,true);let observer=null;if(samples.eventTimingSupported){observer=new PerformanceObserver((list)=>{for(const entry of list.getEntries())samples.eventTimingDurations.push(entry.duration)});try{observer.observe({type:"event",buffered:true,durationThreshold:16})}catch{observer=null}}return()=>{removeEventListener("pointerdown",onDown,true);removeEventListener("keydown",onKey,true);removeEventListener("pointermove",onMove,true);observer?.disconnect()}}async function interactivePhase(payload){if(config.interactionWindowMs<=0){payload.interaction.skipped=true;return}panel.hidden=false;const fullscreenButton=document.getElementById("fullscreen-button");const lockButton=document.getElementById("lock-button");const doneButton=document.getElementById("done-button");const countdown=document.getElementById("countdown");let fullscreenDone=false;let lockDone=false;let finish=()=>{};const finished=new Promise((resolve)=>finish=resolve);const maybeFinish=()=>{if(fullscreenDone&&lockDone&&samples.keydown.length>=5)finish()};fullscreenButton.addEventListener("click",async(event)=>{if(!event.isTrusted||fullscreenDone)return;fullscreenDone=true;fullscreenButton.setAttribute("disabled","");const resume=audioContext?.resume().catch(()=>{});payload.fullscreen.gestured=await requestFullscreen(document.documentElement);await resume;await sleep(300);if(audioContext)payload.audio.afterGesturedResume=snapshot(audioContext);await sleep(700);await exitFullscreen();maybeFinish()});lockButton.addEventListener("click",async(event)=>{if(!event.isTrusted||lockDone)return;lockDone=true;lockButton.setAttribute("disabled","");payload.pointerLock.gestured=await requestPointerLock(canvas);await sleep(500);if(document.pointerLockElement)document.exitPointerLock();maybeFinish()});addEventListener("keydown",()=>setTimeout(maybeFinish,100));doneButton.addEventListener("click",(event)=>event.isTrusted&&finish());const deadline=performance.now()+config.interactionWindowMs;const timer=setInterval(()=>{const left=Math.max(0,Math.ceil((deadline-performance.now())/1000));countdown.textContent=`${left}s left, ${samples.keydown.length} key presses so far`},250);await Promise.race([finished,sleep(config.interactionWindowMs)]);clearInterval(timer);await sleep(200);panel.hidden=true}async function run(){const notAttempted={outcome:"not-attempted"};const bridge=window.craft;const payload={config,userAgent:navigator.userAgent,devicePixelRatio,screen:{width:screen.width,height:screen.height},isSecureContext,timerResolutionMs:timerResolution(),eventTimeStampComparable:eventTimeStampComparable(),bridge:{present:Boolean(bridge),setFullscreen:typeof bridge?.window?.setFullscreen==="function"},webgl2:{ok:false},webgpu:{present:false,adapter:false,device:false},frames:{idle:[],load:[],triangles:0,hiddenDuringSampling:false,focused:false},input:samples,audio:{present:false},gamepad:{present:typeof navigator.getGamepads==="function",connected:0,ids:[],connectedEventSeen:false},fullscreen:{elementApi:typeof document.documentElement.requestFullscreen==="function",webkitElementApi:typeof document.documentElement.webkitRequestFullscreen==="function",enabled:typeof document.fullscreenEnabled==="boolean"?document.fullscreenEnabled:null,ungestured:notAttempted,gestured:notAttempted,nativeBridge:notAttempted},pointerLock:{api:typeof canvas.requestPointerLock==="function",ungestured:notAttempted,gestured:notAttempted},interaction:{windowMs:config.interactionWindowMs,sawRealInput:false,skipped:false},errors};addEventListener("gamepadconnected",()=>{payload.gamepad.connectedEventSeen=true});const stopListening=listenForInput();say("Probing WebGL2 and WebGPU");payload.webgl2=probeWebgl2();payload.webgpu=await probeWebgpu();say("Probing audio");payload.audio=await probeAudio();say("Requesting fullscreen and pointer lock without a gesture (expected to be refused)");payload.fullscreen.ungestured=await requestFullscreen(document.documentElement);await exitFullscreen();payload.pointerLock.ungestured=await requestPointerLock(canvas);say(`Frame pacing: idle for ${config.idleMs/1000}s`);const idle=await sampleFrames(config.idleMs);let scene;try{scene=webglScene(config.instances)??canvas2dScene()}catch(error){errors.push(`load scene: ${errorText(error)}`);scene=canvas2dScene()}for(let i=0;i<10;i++)scene.draw(await nextFrame());say(`Frame pacing: ${scene.triangles.toLocaleString()} triangles + ${config.cpuLoadMsPerFrame} ms CPU per frame for ${config.loadMs/1000}s`);const load=await sampleFrames(config.loadMs,(time)=>{busyWait(config.cpuLoadMsPerFrame);scene.draw(time)});payload.frames={idle:idle.timestamps,load:load.timestamps,triangles:scene.triangles,hiddenDuringSampling:idle.hidden||load.hidden,focused:document.hasFocus()};say("Waiting for real input (see the panel), or for the window to time out");await interactivePhase(payload);stopListening();const pads=typeof navigator.getGamepads==="function"?[...navigator.getGamepads()].filter(Boolean):[];payload.gamepad.connected=pads.length;payload.gamepad.ids=pads.map((pad)=>pad.id);if(config.tryNativeFullscreen&&payload.bridge.setFullscreen){say("Trying Craft's native window fullscreen through window.craft");payload.fullscreen.nativeBridge=await nativeFullscreen()}payload.interaction.sawRealInput=sawRealInput;await audioContext?.close().catch(()=>{});say("Sending results");await fetch("/results",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(payload)});say("Done. Results were sent to the runner; this window can close.")}run().catch((error)=>{const message=errorText(error);say(`Probe failed: ${message}`);fetch("/failed",{method:"POST",body:message}).catch(()=>{})});
|
package/dist/probe/payload.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const DEFAULT_PROBE_PAGE_CONFIG={idleMs:3000,loadMs:6000,cpuLoadMsPerFrame:6,instances:40000,interactionWindowMs:20000,tryNativeFullscreen
|
|
1
|
+
export const DEFAULT_PROBE_PAGE_CONFIG={idleMs:3000,loadMs:6000,cpuLoadMsPerFrame:6,instances:40000,interactionWindowMs:20000,tryNativeFullscreen:true};
|
package/dist/probe/record.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{PROBE_SCHEMA_VERSION}from"./schema";import{framePacing,intervals,latency,percentile,snapRefreshRate}from"./stats";export function browserFromUserAgent(userAgent){const patterns=[["Edge",/Edg\/([\d.]+)/],["Firefox",/Firefox\/([\d.]+)/],["Chrome",/Chrome\/([\d.]+)/],["Safari",/Version\/([\d.]+).*Safari\//],["WebKit",/AppleWebKit\/([\d.]+)/]];for(const[name,pattern]of patterns){const match=userAgent.match(pattern);if(match)return{name,version:match[1]}}return{name:"unknown",version:"unknown"}}function ms(seconds){return typeof seconds==="number"?`${Math.round(seconds*1e4)/10} ms`:"not reported"}function describeOutcome(outcome){return outcome.detail?`${outcome.outcome} (${outcome.detail})`:outcome.outcome}function webgl2(payload){const gl=payload.webgl2;if(!gl.ok)return{status:"unavailable",note:`No WebGL2 context: ${gl.error??"unknown reason"}.`,data:{...gl}};const renderer=gl.unmaskedRenderer||gl.renderer;return{status:"available",note:`WebGL2 context created (${gl.version}); renderer "${renderer}", max texture ${gl.maxTextureSize}, MSAA up to ${gl.maxSamples}x.`,data:{...gl}}}function webgpu(payload){const gpu=payload.webgpu;if(!gpu.present)return{status:"unavailable",note:"navigator.gpu is undefined.",data:{...gpu}};if(!gpu.adapter||!gpu.device)return{status:"unavailable",note:`navigator.gpu exists but ${gpu.adapter?"requestDevice()":"requestAdapter()"} failed: ${gpu.error??"no reason given"}.`,data:{...gpu}};
|
|
1
|
+
import{PROBE_SCHEMA_VERSION}from"./schema";import{framePacing,intervals,latency,percentile,snapRefreshRate}from"./stats";export function browserFromUserAgent(userAgent){const patterns=[["Edge",/Edg\/([\d.]+)/],["Firefox",/Firefox\/([\d.]+)/],["Chrome",/Chrome\/([\d.]+)/],["Safari",/Version\/([\d.]+).*Safari\//],["WebKit",/AppleWebKit\/([\d.]+)/]];for(const[name,pattern]of patterns){const match=userAgent.match(pattern);if(match)return{name,version:match[1]}}return{name:"unknown",version:"unknown"}}function ms(seconds){return typeof seconds==="number"?`${Math.round(seconds*1e4)/10} ms`:"not reported"}function describeOutcome(outcome){return outcome.detail?`${outcome.outcome} (${outcome.detail})`:outcome.outcome}function webgl2(payload){const gl=payload.webgl2;if(!gl.ok)return{status:"unavailable",note:`No WebGL2 context: ${gl.error??"unknown reason"}.`,data:{...gl}};const renderer=gl.unmaskedRenderer||gl.renderer;return{status:"available",note:`WebGL2 context created (${gl.version}); renderer "${renderer}", max texture ${gl.maxTextureSize}, MSAA up to ${gl.maxSamples}x.`,data:{...gl}}}function webgpu(payload){const gpu=payload.webgpu;if(!gpu.present)return{status:"unavailable",note:"navigator.gpu is undefined.",data:{...gpu}};if(!gpu.adapter||!gpu.device)return{status:"unavailable",note:`navigator.gpu exists but ${gpu.adapter?"requestDevice()":"requestAdapter()"} failed: ${gpu.error??"no reason given"}.`,data:{...gpu}};const name=[...new Set([gpu.vendor,gpu.architecture].filter(Boolean))].join(" ")||"unnamed adapter";return{status:"available",note:`Adapter (${name}) and device created; maxTextureDimension2D ${gpu.maxTextureDimension2D??"unknown"}.`,data:{...gpu}}}function pacing(payload,facts){const{frames,config}=payload;if(frames.idle.length<3||frames.load.length<3)return{status:"error",note:`Too few animation frames to measure (${frames.idle.length} idle, ${frames.load.length} under load).`};const rafHz=snapRefreshRate(percentile(intervals(frames.idle),50));const displayHz=facts.machine.display.refreshHz??rafHz;const idle=framePacing(frames.idle,displayHz);const load=framePacing(frames.load,displayHz);const loadAtRaf=framePacing(frames.load,rafHz);const data={rafHz,displayHz,timerResolutionMs:payload.timerResolutionMs,triangles:frames.triangles,cpuLoadMsPerFrame:config.cpuLoadMsPerFrame,hiddenDuringSampling:frames.hiddenDuringSampling,idle,load,loadAtRafRate:{droppedFrames:loadAtRaf.droppedFrames,longFrames:loadAtRaf.longFrames}};if(frames.hiddenDuringSampling){return{status:"error",note:"The page was hidden while sampling, which throttles requestAnimationFrame; these numbers are not representative. Re-run with the window visible.",data}}const cap=rafHz<displayHz-1?`requestAnimationFrame ran at ${rafHz} Hz on a ${displayHz} Hz display, so a game cannot reach the panel's rate. `:`requestAnimationFrame ran at the display's ${displayHz} Hz. `;const work=frames.triangles>0?`${frames.triangles.toLocaleString("en-US")} triangles`:"a 2D canvas fallback";return{status:"measured",note:`${cap}Under load (${work} + ${config.cpuLoadMsPerFrame} ms CPU per frame): p50 ${load.p50Ms} ms, p95 ${load.p95Ms} ms, p99 ${load.p99Ms} ms; ${loadAtRaf.droppedFrames} frames dropped at ${rafHz} Hz and ${load.droppedFrames} at the display's ${displayHz} Hz over ${Math.round(load.durationMs/100)/10} s.${payload.timerResolutionMs>=0.5?` The page clock is clamped to ${payload.timerResolutionMs} ms, so intervals read as whole milliseconds.`:""}`,data}}export const MIN_INPUT_SAMPLES=5;function inputLatency(payload){const{input}=payload;const context={eventTimeStampComparable:payload.eventTimeStampComparable,eventTimingSupported:input.eventTimingSupported,timerResolutionMs:payload.timerResolutionMs};if(!payload.eventTimeStampComparable)return{status:"error",note:"event.timeStamp does not share performance.now()'s time origin, so event-to-frame time cannot be computed.",data:context};const kinds={pointerdown:input.pointerdown,pointermove:input.pointermove,keydown:input.keydown};const total=Object.values(kinds).reduce((sum,list)=>sum+list.length,0);if(total===0){const window=payload.interaction.skipped?"The interactive window was skipped":`No trusted input reached the page in the ${payload.interaction.windowMs/1000} s window`;return{status:"requires-interaction",note:`${window}, and synthetic events are not counted. Observable: event.timeStamp is on the performance.now() clock, timer resolution ${payload.timerResolutionMs} ms, Event Timing API ${input.eventTimingSupported?"supported":"not supported"}.`,data:context}}const summary={...context};const parts=[];for(const[kind,list]of Object.entries(kinds)){const toFrame=latency(list.map((sample)=>sample.toFrameMs));const toPostFrame=latency(list.map((sample)=>sample.toPostFrameMs));summary[kind]={toFrame,toPostFrame};if(toFrame)parts.push(`${kind} p50 ${toFrame.p50Ms} ms to next frame (${toFrame.samples} ${toFrame.samples===1?"sample":"samples"})`)}summary.eventTiming=latency(input.eventTimingDurations);if(total<MIN_INPUT_SAMPLES){return{status:"requires-interaction",note:`Only ${total} trusted input ${total===1?"event":"events"} arrived, fewer than the ${MIN_INPUT_SAMPLES} needed to summarise. Seen: ${parts.join("; ")}. Re-run and use the panel's buttons and keys.`,data:summary}}return{status:"measured",note:`Event timestamp to the next rAF callback: ${parts.join("; ")}. Real input from the OS; no synthetic events.`,data:summary}}function audio(payload){const a=payload.audio;if(!a.present)return{status:"unavailable",note:"window.AudioContext is undefined."};if(a.error||!a.initial)return{status:"error",note:`Creating an AudioContext failed: ${a.error??"unknown reason"}.`};const best=a.afterGesturedResume??a.afterUngesturedResume??a.initial;const data={initial:a.initial,afterUngesturedResume:a.afterUngesturedResume??null,afterGesturedResume:a.afterGesturedResume??null};const figures=`baseLatency ${ms(best.baseLatency)}, outputLatency ${ms(best.outputLatency)} at ${best.sampleRate} Hz`;const unattended=a.afterUngesturedResume?.state==="running"?"The context started without a user gesture":"The context stayed suspended without a user gesture";if(best.state!=="running"){return{status:"requires-interaction",note:`${unattended}, so device latency was not observable. Reported before running: ${figures}.`,data}}if(best.baseLatency===null&&best.outputLatency===null)return{status:"unavailable",note:`${unattended}, but neither baseLatency nor outputLatency is implemented.`,data};return{status:"measured",note:`${unattended}. ${figures}${best.outputLatency===null?" (outputLatency not implemented)":""}.`,data}}function gamepad(payload){const g=payload.gamepad;if(!g.present)return{status:"unavailable",note:"navigator.getGamepads is undefined."};return{status:"available",note:g.connected>0?`navigator.getGamepads() is present and reported ${g.connected} controller(s).`:"navigator.getGamepads() is present; no controller was connected, so axis and button input was not exercised.",data:{...g,secureContext:payload.isSecureContext}}}function fullscreen(payload){const f=payload.fullscreen;const native=f.nativeBridge.outcome==="not-attempted"||f.nativeBridge.outcome==="no-api"?"":` Craft's own window.craft.window.setFullscreen(true), which needs no gesture: ${describeOutcome(f.nativeBridge)}.`;const data={...f};if(!f.elementApi&&!f.webkitElementApi)return{status:"unavailable",note:`Element.requestFullscreen and webkitRequestFullscreen are both undefined, so the standard Fullscreen API engines call does nothing.${native}`,data};const ungestured=`Without a gesture: ${describeOutcome(f.ungestured)}.`;switch(f.gestured.outcome){case"entered":return{status:"available",note:`requestFullscreen() from a real click entered fullscreen. ${ungestured}${native}`,data};case"rejected":case"timeout":return{status:"denied",note:`requestFullscreen() from a real click: ${describeOutcome(f.gestured)}. ${ungestured}${native}`,data};default:return{status:"requires-interaction",note:`The API exists (fullscreenEnabled ${String(f.enabled)}) but needs a real click to test. ${ungestured}${native}`,data}}}function pointerLock(payload){const p=payload.pointerLock;const data={...p};if(!p.api)return{status:"unavailable",note:"Element.requestPointerLock is undefined.",data};const ungestured=`Without a gesture: ${describeOutcome(p.ungestured)}.`;switch(p.gestured.outcome){case"entered":return{status:"available",note:`requestPointerLock() from a real click locked the pointer. ${ungestured}`,data};case"rejected":case"timeout":return{status:"denied",note:`requestPointerLock() from a real click: ${describeOutcome(p.gestured)}. ${ungestured}`,data};default:return{status:"requires-interaction",note:`The API exists but needs a real click to test. ${ungestured}`,data}}}export function buildProbeRecord(payload,facts){return{schema:PROBE_SCHEMA_VERSION,measuredAt:facts.measuredAt,host:{...facts.host,userAgent:payload.userAgent},os:facts.os,machine:{model:facts.machine.model,cpu:facts.machine.cpu,display:{...facts.machine.display,devicePixelRatio:payload.devicePixelRatio}},run:{idleMs:payload.config.idleMs,loadMs:payload.config.loadMs,cpuLoadMsPerFrame:payload.config.cpuLoadMsPerFrame,triangles:payload.frames.triangles,interactionWindowMs:payload.interaction.windowMs,sawRealInput:payload.interaction.sawRealInput},probes:{webgl2:webgl2(payload),webgpu:webgpu(payload),framePacing:pacing(payload,facts),inputLatency:inputLatency(payload),audioLatency:audio(payload),gamepad:gamepad(payload),fullscreen:fullscreen(payload),pointerLock:pointerLock(payload)}}}
|
package/dist/probe/records.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readdirSync,readFileSync}from"node:fs";import{join}from"node:path";import{fileURLToPath}from"node:url";import{assertProbeRecord}from"./schema";export const PROBE_RESULTS_DIR=fileURLToPath(new URL("./results",import.meta.url));function slug(value){return value.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}export function probeRecordFileName(record){
|
|
1
|
+
import{readdirSync,readFileSync}from"node:fs";import{join}from"node:path";import{fileURLToPath}from"node:url";import{assertProbeRecord}from"./schema";export const PROBE_RESULTS_DIR=fileURLToPath(new URL("./results",import.meta.url));function slug(value){return value.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}export function probeRecordFileName(record){const host=record.host.kind==="craft"?"craft":`browser-${slug(record.host.name)}`;return`${host}-${slug(record.os.platform)}-${slug(record.os.arch)}.json`}export function loadProbeRecords(dir=PROBE_RESULTS_DIR){let files;try{files=readdirSync(dir).filter((file)=>file.endsWith(".json")).sort()}catch{return[]}return files.map((file)=>{const path=join(dir,file);return assertProbeRecord(JSON.parse(readFileSync(path,"utf8")),path)})}
|
package/dist/probe/render.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{PROBE_NAMES}from"./schema";export const INTERACTIVE_BEGIN="<!-- interactive-capability:begin -->"
|
|
2
|
-
`," ")}export function renderInteractiveCapabilities(records){const ordered=orderRecords(records)
|
|
1
|
+
import{PROBE_NAMES}from"./schema";export const INTERACTIVE_BEGIN="<!-- interactive-capability:begin -->";export const INTERACTIVE_END="<!-- interactive-capability:end -->";export const PROBE_COMMAND="buddy desktop:probe";const OS_NAMES={darwin:"macOS",linux:"Linux",win32:"Windows"};export function recordLabel(record){return record.host.kind==="craft"?`Craft ${record.host.version}`:`${record.host.name} ${record.host.version}`}function environment(record){const os=OS_NAMES[record.os.platform]??record.os.name;return`${os} ${record.os.version} ${record.os.arch}, ${record.machine.cpu} (${record.machine.model})`}export function orderRecords(records){return[...records].sort((a,b)=>{if(a.host.kind!==b.host.kind)return a.host.kind==="craft"?-1:1;return`${a.host.name} ${a.os.platform} ${a.os.arch}`.localeCompare(`${b.host.name} ${b.os.platform} ${b.os.arch}`)})}function number(value){return typeof value==="number"&&Number.isFinite(value)?value:null}function nested(data,...path){let current=data;for(const key of path){if(typeof current!=="object"||current===null)return;current=current[key]}return current}export function headline(name,probe){const data=probe.data;if(probe.status!=="measured"||!data)return null;switch(name){case"framePacing":{const raf=number(data.rafHz);const display=number(data.displayHz);const p99=number(nested(data,"load","p99Ms"));if(raf===null||display===null||p99===null)return null;return`${raf} Hz rAF on a ${display} Hz display, p99 ${p99} ms under load`}case"inputLatency":{for(const kind of["pointerdown","keydown","pointermove"]){const p50=number(nested(data,kind,"toFrame","p50Ms"));if(p50!==null)return`${kind} p50 ${p50} ms to next frame`}return null}case"audioLatency":{const snapshot=data.afterGesturedResume??data.afterUngesturedResume;const base=number(snapshot?.baseLatency);const output=number(snapshot?.outputLatency);const format=(seconds)=>seconds===null?"n/a":`${Math.round(seconds*1e4)/10} ms`;return`base ${format(base)}, output ${format(output)}`}default:return null}}function cell(name,probe){if(!probe)return"not probed";const figure=headline(name,probe);return figure?`**${probe.status}** - ${figure}`:`**${probe.status}**`}function escapeCell(text){return text.replaceAll("|","\\|").replaceAll(`
|
|
2
|
+
`," ")}export function renderInteractiveCapabilities(records){const ordered=orderRecords(records);const lines=[INTERACTIVE_BEGIN,"","<!-- Generated by `buddy docs:capabilities` from the records in"," storage/framework/core/desktop/src/probe/results/. Re-measure with",` \`${PROBE_COMMAND} --record\`; do not edit this by hand. -->`,"","Whether a Craft window can host a game or other frame-driven content that somebody else","builds, measured by the probe harness in `@stacksjs/desktop-build`","([stacksjs/stacks#877](https://github.com/stacksjs/stacks/issues/877)). Ordinary browsers","on the same machine are measured alongside it for comparison.","","> **How current is this?** Unlike the driver tables above, these are measurements, not","> claims CI can re-check. Each column is one run on one machine, and says when, against","> which host version, on which OS and hardware. If your Craft is newer than the column,",`> the numbers describe something you are not running: re-measure with \`${PROBE_COMMAND} --record\`.`,""];if(ordered.length===0){lines.push(`No measurement has been recorded yet. Run \`${PROBE_COMMAND} --record\`.`,"",INTERACTIVE_END);return lines.join(`
|
|
3
3
|
`)}lines.push(`| Probe | ${ordered.map((record)=>escapeCell(recordLabel(record))).join(" | ")} |`,`|---|${ordered.map(()=>"---").join("|")}|`);for(const[name,label]of PROBE_NAMES)lines.push(`| ${label} | ${ordered.map((record)=>escapeCell(cell(name,record.probes[name]))).join(" | ")} |`);lines.push(`| Measured on | ${ordered.map((record)=>escapeCell(environment(record))).join(" | ")} |`,`| Measured at | ${ordered.map((record)=>record.measuredAt.slice(0,10)).join(" | ")} |`,"","- **available** / **measured** - the API exists and the probe exercised it.","- **unavailable** - the API is missing, or creating it failed.","- **requires-interaction** - needs a real click, key press or controller that the run did not have. What was still observable is in the notes; no number is invented.","- **denied** - requested from a real click and refused.","");for(const record of ordered){const refresh=record.machine.display.refreshHz===null?"unknown refresh rate":`${record.machine.display.refreshHz} Hz display`;lines.push(`**${recordLabel(record)}** - ${environment(record)}, ${refresh}`,"");for(const[name,label]of PROBE_NAMES){const probe=record.probes[name];if(probe)lines.push(`- **${label}** - ${probe.note}`)}lines.push("")}lines.push("**Out of scope.** Stacks is not shipping a game engine, a physics engine, an audio mixer or","an asset pipeline. This section establishes what a Craft window gives an engine somebody","else wrote; it is not a plan to write one.","",INTERACTIVE_END);return lines.join(`
|
|
4
4
|
`)}
|
package/dist/probe/runner.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{existsSync,mkdirSync,writeFileSync}from"node:fs";import os from"node:os";import{dirname,join,relative,resolve}from"node:path";import process from"node:process";import{fileURLToPath}from"node:url";import{probePageHtml}from"./html";import{DEFAULT_PROBE_PAGE_CONFIG}from"./payload";import{browserFromUserAgent,buildProbeRecord}from"./record";import{PROBE_RESULTS_DIR,probeRecordFileName}from"./records";import{headline}from"./render";import{assertProbeRecord,PROBE_NAMES}from"./schema";import{parseRefreshHz}from"./stats";function capture(command){try{const result=Bun.spawnSync(command,{stdout:"pipe",stderr:"ignore"});return result.exitCode===0?result.stdout.toString().trim():null}catch{return null}}export function parseCraftVersion(output){return output?.match(/craft version\s+(\d+\.\d+\.\d+\S*)/i)?.[1]??null}export function mainDisplayFromProfiler(json){if(!json)return null;try{const
|
|
1
|
+
import{existsSync,mkdirSync,writeFileSync}from"node:fs";import os from"node:os";import{dirname,join,relative,resolve}from"node:path";import process from"node:process";import{fileURLToPath}from"node:url";import{probePageHtml}from"./html";import{DEFAULT_PROBE_PAGE_CONFIG}from"./payload";import{browserFromUserAgent,buildProbeRecord}from"./record";import{PROBE_RESULTS_DIR,probeRecordFileName}from"./records";import{headline}from"./render";import{assertProbeRecord,PROBE_NAMES}from"./schema";import{parseRefreshHz}from"./stats";function capture(command){try{const result=Bun.spawnSync(command,{stdout:"pipe",stderr:"ignore"});return result.exitCode===0?result.stdout.toString().trim():null}catch{return null}}export function parseCraftVersion(output){return output?.match(/craft version\s+(\d+\.\d+\.\d+\S*)/i)?.[1]??null}export function mainDisplayFromProfiler(json){if(!json)return null;try{const parsed=JSON.parse(json);const displays=(parsed.SPDisplaysDataType??[]).flatMap((gpu)=>gpu.spdisplays_ndrvs??[]);const main=displays.find((display)=>display.spdisplays_main==="spdisplays_yes")??displays[0];if(!main)return null;const resolution=main._spdisplays_resolution??"unknown";return{name:main._name??"unknown",resolution,refreshHz:parseRefreshHz(resolution)}}catch{return null}}export function collectHostFacts(mode,craftVersion,userAgent){const platform=process.platform;let osName=OS_NAME[platform]??platform;let osVersion=os.release();let build;let model="unknown";let cpu=os.cpus()[0]?.model?.trim()||"unknown";let display={name:"unknown",resolution:"unknown",refreshHz:null};if(platform==="darwin"){osName="macOS";osVersion=capture(["sw_vers","-productVersion"])??osVersion;build=capture(["sw_vers","-buildVersion"])??undefined;model=capture(["sysctl","-n","hw.model"])??model;cpu=capture(["sysctl","-n","machdep.cpu.brand_string"])??cpu;display=mainDisplayFromProfiler(capture(["system_profiler","SPDisplaysDataType","-json"]))??display}else if(platform==="linux"){model=capture(["cat","/sys/devices/virtual/dmi/id/product_name"])??model}const browser=browserFromUserAgent(userAgent);return{measuredAt:new Date().toISOString(),host:mode==="craft"?{kind:"craft",name:"craft",version:craftVersion??"unknown"}:{kind:"browser",name:browser.name,version:browser.version},os:{platform,arch:process.arch,name:osName,version:osVersion,...build?{build}:{}},machine:{model,cpu,display}}}const OS_NAME={darwin:"macOS",linux:"Linux",win32:"Windows"};async function bundlePageScript(){const here=dirname(fileURLToPath(import.meta.url));const entry=[join(here,"page.ts"),join(here,"page.js")].find(existsSync);if(!entry)throw new Error("The probe page script is missing; reinstall @stacksjs/desktop-build.");const result=await Bun.build({entrypoints:[entry],target:"browser",format:"esm",minify:true});if(!result.success)throw new Error(`Bundling the probe page failed:
|
|
2
2
|
${result.logs.map(String).join(`
|
|
3
|
-
`)}`);return await result.outputs[0].text()}function openCommand(url,app){if(app
|
|
4
|
-
`)}function flag(name){const prefix=`--${name}=`;for(let i=0;i<process.argv.length;i++){const arg=process.argv[i];if(arg===`--${name}`){const next=process.argv[i+1];return next&&!next.startsWith("--")?next
|
|
3
|
+
`)}`);return await result.outputs[0].text()}function openCommand(url,app){if(app===false)return null;if(process.platform==="darwin")return typeof app==="string"?["open","-a",app,url]:["open",url];if(process.platform==="win32")return["cmd","/c","start","",url];return["xdg-open",url]}export async function runProbe(options){const log=options.log??((line)=>console.log(line));const config={...DEFAULT_PROBE_PAGE_CONFIG,...options.page};if(options.mode==="browser")config.tryNativeFullscreen=false;let craftBin=null;let craftVersion=null;if(options.mode==="craft"){const{resolveCraftExecutable}=await import("../index");craftBin=resolveCraftExecutable(options.craftBin);craftVersion=parseCraftVersion(capture([craftBin,"--version"]));if(!craftVersion)throw new Error(`Could not read a version from \`${craftBin} --version\`; is it a Craft binary?`)}const html=probePageHtml(await bundlePageScript(),config);let settle;let fail;const received=new Promise((resolve,reject)=>{settle=resolve;fail=reject});const server=Bun.serve({hostname:"127.0.0.1",port:options.port??0,async fetch(request){const{pathname}=new URL(request.url);if(request.method==="POST"&&pathname==="/results"){settle(await request.json());return new Response("ok")}if(request.method==="POST"&&pathname==="/progress"){log(` page: ${await request.text()}`);return new Response("ok")}if(request.method==="POST"&&pathname==="/failed"){fail(new Error(`The probe page failed: ${await request.text()}`));return new Response("ok")}if(pathname==="/")return new Response(html,{headers:{"content-type":"text/html; charset=utf-8","cache-control":"no-store"}});return new Response("not found",{status:404})}});const url=server.url.href;let craft=null;const interrupted=()=>{craft?.kill();process.exit(130)};process.once("SIGINT",interrupted);process.once("SIGTERM",interrupted);const budget=options.timeoutMs??config.idleMs+config.loadMs+config.interactionWindowMs+60000;const timer=setTimeout(()=>fail(new Error(`No results within ${Math.round(budget/1000)} s. Was the window visible?`)),budget);try{if(options.mode==="craft"){log(`Opening ${url} in Craft ${craftVersion} (${craftBin})`);craft=Bun.spawn([craftBin,url,"--title","Stacks interactive probe","--width","1280","--height","800"],{stdout:"ignore",stderr:"ignore"});craft.exited.then((code)=>fail(new Error(`Craft exited (code ${code}) before the probe finished`)))}else{log(`Probe page: ${url}`);const command=openCommand(url,options.open??true);if(command)Bun.spawn(command,{stdout:"ignore",stderr:"ignore"});else log("Open that URL in the browser to measure, and keep its window visible.")}const payload=await received;const facts=collectHostFacts(options.mode,craftVersion,payload.userAgent);return assertProbeRecord(buildProbeRecord(payload,facts),"the probe result")}finally{clearTimeout(timer);process.off("SIGINT",interrupted);process.off("SIGTERM",interrupted);craft?.kill();server.stop(true)}}export function summarize(record){const width=Math.max(...PROBE_NAMES.map(([,label])=>label.length));const lines=[`${record.host.kind==="craft"?`Craft ${record.host.version}`:`${record.host.name} ${record.host.version}`} on ${record.os.name} ${record.os.version} (${record.machine.model}, ${record.machine.cpu}), display ${record.machine.display.refreshHz??"unknown"} Hz`];for(const[name,label]of PROBE_NAMES){const probe=record.probes[name];const figure=headline(name,probe);lines.push(` ${label.padEnd(width)} ${probe.status}${figure?` - ${figure}`:""}`)}return lines.join(`
|
|
4
|
+
`)}function flag(name){const prefix=`--${name}=`;for(let i=0;i<process.argv.length;i++){const arg=process.argv[i];if(arg===`--${name}`){const next=process.argv[i+1];return next&&!next.startsWith("--")?next:true}if(arg.startsWith(prefix))return arg.slice(prefix.length)}return}function seconds(name){const value=flag(name);if(value===undefined||value===true)return;const parsed=Number(value);if(!Number.isFinite(parsed)||parsed<0)throw new Error(`--${name} must be a non-negative number of seconds`);return parsed*1000}const frameworkRoot=resolve(PROBE_RESULTS_DIR,"../../../../../../..");export async function run(){const browser=flag("browser");const record=flag("record")!==undefined;const out=flag("out");const cpu=flag("cpu-load");const instances=flag("instances");if(record){const rel=relative(frameworkRoot,process.cwd());if(rel.startsWith("..")||!existsSync(join(frameworkRoot,"storage/framework/core/buddy")))throw new Error("--record writes into the Stacks framework repository; run it from that checkout, or use --out <file>.")}const page={};const idle=seconds("idle");const load=seconds("load");const window=seconds("interaction-window");if(idle!==undefined)page.idleMs=idle;if(load!==undefined)page.loadMs=load;if(window!==undefined)page.interactionWindowMs=window;if(typeof cpu==="string")page.cpuLoadMsPerFrame=Number(cpu);if(typeof instances==="string")page.instances=Number(instances);let open=typeof browser==="string"?browser:true;if(flag("no-open")!==undefined)open=false;const craftBin=flag("craft-bin");const result=await runProbe({mode:browser===undefined?"craft":"browser",open,craftBin:typeof craftBin==="string"?craftBin:undefined,timeoutMs:seconds("timeout"),page});console.log(`
|
|
5
5
|
${summarize(result)}
|
|
6
6
|
`);const json=`${JSON.stringify(result,null,2)}
|
|
7
|
-
`;if(record){mkdirSync(PROBE_RESULTS_DIR,{recursive
|
|
8
|
-
`);process.exit(1)}
|
|
7
|
+
`;if(record){mkdirSync(PROBE_RESULTS_DIR,{recursive:true});const path=join(PROBE_RESULTS_DIR,probeRecordFileName(result));writeFileSync(path,json);console.log(`Recorded ${relative(process.cwd(),path)}. Run \`buddy docs:capabilities\` to publish it.`)}if(typeof out==="string"){writeFileSync(out,json);console.log(`Wrote ${out}`)}if(!record&&typeof out!=="string")console.log(json)}if(require.main==require.module){try{await run()}catch(error){process.stderr.write(`${error instanceof Error?error.message:String(error)}
|
|
8
|
+
`);process.exit(1)}}
|
package/dist/probe/schema.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export const PROBE_SCHEMA_VERSION=1
|
|
1
|
+
export const PROBE_SCHEMA_VERSION=1;export const PROBE_STATUSES=["available","unavailable","measured","requires-interaction","denied","error"];export const PROBE_NAMES=[["webgl2","WebGL2"],["webgpu","WebGPU"],["framePacing","Frame pacing"],["inputLatency","Input latency"],["audioLatency","Audio latency"],["gamepad","Gamepad API"],["fullscreen","Fullscreen"],["pointerLock","Pointer lock"]];function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function nonEmptyString(value){return typeof value==="string"&&value.trim().length>0}export function validateProbeRecord(value){const errors=[];if(!isRecord(value))return["record is not an object"];if(value.schema!==PROBE_SCHEMA_VERSION)errors.push(`schema must be ${PROBE_SCHEMA_VERSION}, got ${JSON.stringify(value.schema)}`);if(!nonEmptyString(value.measuredAt)||Number.isNaN(Date.parse(value.measuredAt)))errors.push("measuredAt must be an ISO 8601 timestamp");const host=value.host;if(!isRecord(host)){errors.push("host is missing")}else{if(host.kind!=="craft"&&host.kind!=="browser")errors.push(`host.kind must be craft or browser, got ${JSON.stringify(host.kind)}`);for(const key of["name","version","userAgent"]){if(!nonEmptyString(host[key]))errors.push(`host.${key} is required`)}if(host.kind==="craft"&&nonEmptyString(host.version)&&!/^\d+\.\d+\.\d+/.test(host.version))errors.push(`host.version must be a Craft release version, got ${JSON.stringify(host.version)}`)}const os=value.os;if(!isRecord(os)){errors.push("os is missing")}else{for(const key of["platform","arch","name","version"]){if(!nonEmptyString(os[key]))errors.push(`os.${key} is required`)}}const machine=value.machine;if(!isRecord(machine)){errors.push("machine is missing")}else{for(const key of["model","cpu"]){if(!nonEmptyString(machine[key]))errors.push(`machine.${key} is required`)}const display=machine.display;if(!isRecord(display)){errors.push("machine.display is missing")}else{if(display.refreshHz!==null&&!(typeof display.refreshHz==="number"&&display.refreshHz>0))errors.push("machine.display.refreshHz must be a positive number or null");if(!(typeof display.devicePixelRatio==="number"&&display.devicePixelRatio>0))errors.push("machine.display.devicePixelRatio must be a positive number")}}const run=value.run;if(!isRecord(run)){errors.push("run is missing")}else{for(const key of["idleMs","loadMs","cpuLoadMsPerFrame","triangles","interactionWindowMs"]){if(!(typeof run[key]==="number"&&run[key]>=0))errors.push(`run.${key} must be a non-negative number`)}if(typeof run.sawRealInput!=="boolean")errors.push("run.sawRealInput must be a boolean")}const probes=value.probes;if(!isRecord(probes)){errors.push("probes is missing");return errors}for(const[name]of PROBE_NAMES){const probe=probes[name];if(!isRecord(probe)){errors.push(`probes.${name} is missing`);continue}if(!PROBE_STATUSES.includes(probe.status))errors.push(`probes.${name}.status must be one of ${PROBE_STATUSES.join(", ")}, got ${JSON.stringify(probe.status)}`);if(!nonEmptyString(probe.note))errors.push(`probes.${name}.note is required: say what was observed, even on success`);if(probe.data!==undefined&&!isRecord(probe.data))errors.push(`probes.${name}.data must be an object when present`);if(probe.status==="measured"&&!isRecord(probe.data))errors.push(`probes.${name} is measured but carries no data`)}for(const name of Object.keys(probes)){if(!PROBE_NAMES.some(([known])=>known===name))errors.push(`probes.${name} is not a known probe`)}return errors}export function assertProbeRecord(value,source="probe record"){const errors=validateProbeRecord(value);if(errors.length>0)throw new Error(`${source} is invalid:
|
|
2
2
|
- ${errors.join(`
|
|
3
3
|
- `)}`);return value}
|
package/dist/probe/stats.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const COMMON_REFRESH_RATES=[24,30,48,50,60,72,75,90,100,120,144,165,240];export function percentile(values,p){if(values.length===0)return null;if(!Number.isFinite(p)||p<0||p>100)throw RangeError(`percentile must be between 0 and 100, got ${p}`);const sorted=[...values].sort((a,b)=>a-b)
|
|
1
|
+
export const COMMON_REFRESH_RATES=[24,30,48,50,60,72,75,90,100,120,144,165,240];export function percentile(values,p){if(values.length===0)return null;if(!Number.isFinite(p)||p<0||p>100)throw new RangeError(`percentile must be between 0 and 100, got ${p}`);const sorted=[...values].sort((a,b)=>a-b);const rank=p/100*(sorted.length-1);const lower=Math.floor(rank);const upper=Math.ceil(rank);const low=sorted[lower];const high=sorted[upper];return low+(high-low)*(rank-lower)}export function intervals(timestamps){const out=[];for(let i=1;i<timestamps.length;i++)out.push(timestamps[i]-timestamps[i-1]);return out}export function histogram(values,bucketMs=1,buckets=50){if(bucketMs<=0||!Number.isFinite(bucketMs))throw new RangeError(`bucketMs must be positive, got ${bucketMs}`);if(!Number.isInteger(buckets)||buckets<1)throw new RangeError(`buckets must be a positive integer, got ${buckets}`);const counts=Array.from({length:buckets},()=>0);let overflow=0;for(const value of values){const index=Math.floor(Math.max(0,value)/bucketMs);if(index>=buckets)overflow++;else counts[index]++}return{bucketMs,counts,overflow}}export function snapRefreshRate(periodMs,tolerance=0.03){if(!(periodMs>0))throw new RangeError(`period must be positive, got ${periodMs}`);const measured=1000/periodMs;let best=measured;let bestError=Number.POSITIVE_INFINITY;for(const rate of COMMON_REFRESH_RATES){const error=Math.abs(measured-rate)/rate;if(error<bestError){best=rate;bestError=error}}return bestError<=tolerance?best:Math.round(measured*100)/100}export function droppedFrames(frameIntervals,periodMs){if(!(periodMs>0))throw new RangeError(`period must be positive, got ${periodMs}`);let dropped=0;for(const interval of frameIntervals)dropped+=Math.max(0,Math.round(interval/periodMs)-1);return dropped}export function framePacing(timestamps,targetHz){if(timestamps.length<3)return null;if(!(targetHz>0))throw new RangeError(`targetHz must be positive, got ${targetHz}`);const frameIntervals=intervals(timestamps);const durationMs=timestamps[timestamps.length-1]-timestamps[0];const targetPeriodMs=1000/targetHz;const round=(value)=>Math.round(value*100)/100;return{frames:timestamps.length,durationMs:round(durationMs),fps:round(durationMs>0?frameIntervals.length*1000/durationMs:0),p50Ms:round(percentile(frameIntervals,50)),p95Ms:round(percentile(frameIntervals,95)),p99Ms:round(percentile(frameIntervals,99)),maxMs:round(Math.max(...frameIntervals)),targetPeriodMs:round(targetPeriodMs),targetHz,droppedFrames:droppedFrames(frameIntervals,targetPeriodMs),longFrames:frameIntervals.filter((interval)=>interval>targetPeriodMs*1.5).length,histogram:histogram(frameIntervals)}}export function latency(samples){const usable=samples.filter((sample)=>Number.isFinite(sample)&&sample>=0);if(usable.length===0)return null;const round=(value)=>Math.round(value*100)/100;return{samples:usable.length,p50Ms:round(percentile(usable,50)),p95Ms:round(percentile(usable,95)),maxMs:round(Math.max(...usable))}}export function parseRefreshHz(resolution){const match=resolution?.match(/@\s*([\d.]+)\s*Hz/i);if(!match)return null;const hz=Number(match[1]);return Number.isFinite(hz)&&hz>0?hz:null}
|
package/dist/support.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const desktopSupportMatrix=[{platform:"darwin",architecture:"arm64",status:"experimental",osVersions:["macOS 27.0 (local run, Craft v0.0.107 published archive)","macOS 15 runner (CI, Craft v0.0.48 from source)"],packageFormat:"DMG + PKG",signing:"pending",notarization:"pending",installLaunchEvidence:"https://github.com/stacksjs/stacks/blob/main/storage/framework/core/desktop/evidence/lifecycle-darwin-arm64.json",updateRollbackEvidence:"https://github.com/stacksjs/stacks/blob/main/storage/framework/core/desktop/evidence/lifecycle-darwin-arm64.json",packagingEvidence:"https://github.com/stacksjs/protocol/blob/main/evidence/craft.json",blockingIssues:["https://github.com/stacksjs/stacks/issues/2062"],limitations:["The Stacks-built app bundle, DMG and PKG are unsigned while platform identities remain unprovisioned. The Craft runtime inside them is Developer ID-signed by Craft's own release workflow, which does not make the app signed.","Lifecycle evidence was re-run on 2026-10-03 against the published Craft v0.0.107 archive (craft-darwin-arm64.zip, sha256 98e1a7ae478a8900256add2884d05cc07aea2f3de7d550590d9458abd4fe7725) with `storage/framework/core/desktop/evidence/lifecycle.ts`: PKG and DMG install, a real Craft window launched from the installed bundle, update, a refused truncated update, rollback and uninstall all passed.","That run was local on macOS 27.0, not CI, and installed into the user domain (~/Applications) rather than /Applications. Gatekeeper was not exercised, since nothing carried a quarantine flag. The last CI lifecycle run for this target (https://github.com/stacksjs/stacks/actions/runs/29890804159, macOS 15 runner) used Craft v0.0.48 built from source."]},{platform:"darwin",architecture:"x64",status:"experimental",osVersions:["macOS 15 Intel runner"],packageFormat:"DMG + PKG",signing:"pending",notarization:"pending",installLaunchEvidence:"https://github.com/stacksjs/stacks/actions/runs/29890804159",updateRollbackEvidence:"https://github.com/stacksjs/stacks/actions/runs/29890804159",packagingEvidence:"https://github.com/stacksjs/protocol/blob/main/evidence/craft.json",blockingIssues:["https://github.com/stacksjs/stacks/issues/2062"],limitations:["Lifecycle fixtures are unsigned while platform identities remain unprovisioned.","Lifecycle evidence was produced against Craft v0.0.48 built from source (bf75807). Craft now publishes a prebuilt craft-darwin-x64.zip with every release, and no Stacks lifecycle run has re-verified a prebuilt release yet."]},{platform:"linux",architecture:"x64",status:"experimental",osVersions:["Ubuntu 24.04 runner"],packageFormat:"DEB",signing:"pending",notarization:"not-applicable",installLaunchEvidence:"https://github.com/stacksjs/stacks/actions/runs/29890804159",updateRollbackEvidence:"https://github.com/stacksjs/stacks/actions/runs/29890804159",packagingEvidence:"https://github.com/stacksjs/protocol/blob/main/evidence/craft.json",blockingIssues:["https://github.com/stacksjs/stacks/issues/2062"],limitations:["The lifecycle fixture is unsigned and no package repository support policy is published.","Lifecycle evidence was produced against Craft v0.0.48 built from source (bf75807). Craft now publishes a prebuilt craft-linux-x64.zip with every release, and no Stacks lifecycle run has re-verified a prebuilt release yet."]},{platform:"win32",architecture:"x64",status:"experimental",osVersions:["Windows Server 2025 runner"],packageFormat:"MSI + ZIP",signing:"pending",notarization:"not-applicable",installLaunchEvidence:"https://github.com/stacksjs/stacks/actions/runs/29890804159",updateRollbackEvidence:"https://github.com/stacksjs/stacks/actions/runs/29890804159",packagingEvidence:"https://github.com/stacksjs/protocol/blob/main/evidence/craft.json",blockingIssues:["https://github.com/stacksjs/stacks/issues/2062"],limitations:["The lifecycle fixture is not Authenticode-signed.","Lifecycle evidence was produced against Craft v0.0.48 built from source (bf75807). Craft now publishes a prebuilt craft-windows-x64.zip with every release, and no Stacks lifecycle run has re-verified a prebuilt release yet."]}];export function desktopSupport(platform=process.platform,architecture=process.arch){return desktopSupportMatrix.find((row)=>row.platform===platform&&row.architecture===architecture)}export function assertDesktopReleaseChannel(channel,platform=process.platform,architecture=process.arch){const row=desktopSupport(platform,architecture);if(!row)throw Error(`Desktop target ${platform}/${architecture} is unsupported`);if(channel==="stable"&&(row.status!=="stable"||row.signing!=="enforced"||row.platform==="darwin"&&row.notarization!=="enforced"||!row.installLaunchEvidence||!row.updateRollbackEvidence))throw Error(`Desktop target ${platform}/${architecture} cannot be released as stable; complete stacksjs/stacks#2059, #2062, and #2063 first`);return row}
|
|
1
|
+
export const desktopSupportMatrix=[{platform:"darwin",architecture:"arm64",status:"experimental",osVersions:["macOS 27.0 (local run, Craft v0.0.107 published archive)","macOS 15 runner (CI, Craft v0.0.48 from source)"],packageFormat:"DMG + PKG",signing:"pending",notarization:"pending",installLaunchEvidence:"https://github.com/stacksjs/stacks/blob/main/storage/framework/core/desktop/evidence/lifecycle-darwin-arm64.json",updateRollbackEvidence:"https://github.com/stacksjs/stacks/blob/main/storage/framework/core/desktop/evidence/lifecycle-darwin-arm64.json",packagingEvidence:"https://github.com/stacksjs/protocol/blob/main/evidence/craft.json",blockingIssues:["https://github.com/stacksjs/stacks/issues/2062"],limitations:["The Stacks-built app bundle, DMG and PKG are unsigned while platform identities remain unprovisioned. The Craft runtime inside them is Developer ID-signed by Craft's own release workflow, which does not make the app signed.","Lifecycle evidence was re-run on 2026-10-03 against the published Craft v0.0.107 archive (craft-darwin-arm64.zip, sha256 98e1a7ae478a8900256add2884d05cc07aea2f3de7d550590d9458abd4fe7725) with `storage/framework/core/desktop/evidence/lifecycle.ts`: PKG and DMG install, a real Craft window launched from the installed bundle, update, a refused truncated update, rollback and uninstall all passed.","That run was local on macOS 27.0, not CI, and installed into the user domain (~/Applications) rather than /Applications. Gatekeeper was not exercised, since nothing carried a quarantine flag. The last CI lifecycle run for this target (https://github.com/stacksjs/stacks/actions/runs/29890804159, macOS 15 runner) used Craft v0.0.48 built from source."]},{platform:"darwin",architecture:"x64",status:"experimental",osVersions:["macOS 15 Intel runner"],packageFormat:"DMG + PKG",signing:"pending",notarization:"pending",installLaunchEvidence:"https://github.com/stacksjs/stacks/actions/runs/29890804159",updateRollbackEvidence:"https://github.com/stacksjs/stacks/actions/runs/29890804159",packagingEvidence:"https://github.com/stacksjs/protocol/blob/main/evidence/craft.json",blockingIssues:["https://github.com/stacksjs/stacks/issues/2062"],limitations:["Lifecycle fixtures are unsigned while platform identities remain unprovisioned.","Lifecycle evidence was produced against Craft v0.0.48 built from source (bf75807). Craft now publishes a prebuilt craft-darwin-x64.zip with every release, and no Stacks lifecycle run has re-verified a prebuilt release yet."]},{platform:"linux",architecture:"x64",status:"experimental",osVersions:["Ubuntu 24.04 runner"],packageFormat:"DEB",signing:"pending",notarization:"not-applicable",installLaunchEvidence:"https://github.com/stacksjs/stacks/actions/runs/29890804159",updateRollbackEvidence:"https://github.com/stacksjs/stacks/actions/runs/29890804159",packagingEvidence:"https://github.com/stacksjs/protocol/blob/main/evidence/craft.json",blockingIssues:["https://github.com/stacksjs/stacks/issues/2062"],limitations:["The lifecycle fixture is unsigned and no package repository support policy is published.","Lifecycle evidence was produced against Craft v0.0.48 built from source (bf75807). Craft now publishes a prebuilt craft-linux-x64.zip with every release, and no Stacks lifecycle run has re-verified a prebuilt release yet."]},{platform:"win32",architecture:"x64",status:"experimental",osVersions:["Windows Server 2025 runner"],packageFormat:"MSI + ZIP",signing:"pending",notarization:"not-applicable",installLaunchEvidence:"https://github.com/stacksjs/stacks/actions/runs/29890804159",updateRollbackEvidence:"https://github.com/stacksjs/stacks/actions/runs/29890804159",packagingEvidence:"https://github.com/stacksjs/protocol/blob/main/evidence/craft.json",blockingIssues:["https://github.com/stacksjs/stacks/issues/2062"],limitations:["The lifecycle fixture is not Authenticode-signed.","Lifecycle evidence was produced against Craft v0.0.48 built from source (bf75807). Craft now publishes a prebuilt craft-windows-x64.zip with every release, and no Stacks lifecycle run has re-verified a prebuilt release yet."]}];export function desktopSupport(platform=process.platform,architecture=process.arch){return desktopSupportMatrix.find((row)=>row.platform===platform&&row.architecture===architecture)}export function assertDesktopReleaseChannel(channel,platform=process.platform,architecture=process.arch){const row=desktopSupport(platform,architecture);if(!row)throw new Error(`Desktop target ${platform}/${architecture} is unsupported`);if(channel==="stable"&&(row.status!=="stable"||row.signing!=="enforced"||row.platform==="darwin"&&row.notarization!=="enforced"||!row.installLaunchEvidence||!row.updateRollbackEvidence))throw new Error(`Desktop target ${platform}/${architecture} cannot be released as stable; complete stacksjs/stacks#2059, #2062, and #2063 first`);return row}
|
package/dist/updater.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHash,createPublicKey,verify}from"node:crypto";import{mkdir,rename,rm,writeFile}from"node:fs/promises";import process from"node:process";import{dirname}from"node:path";export async function checkForDesktopUpdate(options){assertSecureUrl(options.manifestUrl);const response=await(options.fetcher||fetch)(options.manifestUrl,{headers:{Accept:"application/json"}});if(!response.ok)throw Error(`Desktop update check failed with HTTP ${response.status}`);const manifest=validateUpdateManifest(await response.json());verifyUpdateManifestSignature(manifest,options.trustedKeys);assertUpdateTarget(manifest,options.target);return compareVersions(manifest.version,options.currentVersion)>0?manifest:null}export async function stageDesktopUpdate(manifest,destination,fetcher=fetch,trustedKeys,target){validateUpdateManifest(manifest);if(!trustedKeys)throw Error("Desktop update staging requires trusted signing keys");verifyUpdateManifestSignature(manifest,trustedKeys);assertUpdateTarget(manifest,target);assertSecureUrl(manifest.url);const response=await fetcher(manifest.url);if(!response.ok)throw Error(`Desktop update download failed with HTTP ${response.status}`);const bytes=new Uint8Array(await response.arrayBuffer());if(bytes.byteLength!==manifest.size)throw Error(`Desktop update size mismatch: expected ${manifest.size}, received ${bytes.byteLength}`);
|
|
1
|
+
import{createHash,createPublicKey,verify}from"node:crypto";import{mkdir,rename,rm,writeFile}from"node:fs/promises";import process from"node:process";import{dirname}from"node:path";export async function checkForDesktopUpdate(options){assertSecureUrl(options.manifestUrl);const response=await(options.fetcher||fetch)(options.manifestUrl,{headers:{Accept:"application/json"}});if(!response.ok)throw new Error(`Desktop update check failed with HTTP ${response.status}`);const manifest=validateUpdateManifest(await response.json());verifyUpdateManifestSignature(manifest,options.trustedKeys);assertUpdateTarget(manifest,options.target);return compareVersions(manifest.version,options.currentVersion)>0?manifest:null}export async function stageDesktopUpdate(manifest,destination,fetcher=fetch,trustedKeys,target){validateUpdateManifest(manifest);if(!trustedKeys)throw new Error("Desktop update staging requires trusted signing keys");verifyUpdateManifestSignature(manifest,trustedKeys);assertUpdateTarget(manifest,target);assertSecureUrl(manifest.url);const response=await fetcher(manifest.url);if(!response.ok)throw new Error(`Desktop update download failed with HTTP ${response.status}`);const bytes=new Uint8Array(await response.arrayBuffer());if(bytes.byteLength!==manifest.size)throw new Error(`Desktop update size mismatch: expected ${manifest.size}, received ${bytes.byteLength}`);const checksum=createHash("sha256").update(bytes).digest("hex");if(checksum!==manifest.sha256.toLowerCase())throw new Error("Desktop update checksum mismatch");await mkdir(dirname(destination),{recursive:true});const temporaryPath=`${destination}.download-${crypto.randomUUID()}`;try{await writeFile(temporaryPath,bytes,{mode:448});await rename(temporaryPath,destination)}catch(error){await rm(temporaryPath,{force:true});throw error}return{manifest,path:destination,bytes:bytes.byteLength}}export function compareVersions(left,right){const leftParts=parseVersion(left);const rightParts=parseVersion(right);for(let index=0;index<3;index++){const difference=leftParts[index]-rightParts[index];if(difference!==0)return Math.sign(difference)}return 0}export function validateUpdateManifest(input){if(!input||typeof input!=="object")throw new Error("Desktop update manifest must be an object");const manifest=input;parseVersion(manifest.version||"");if(typeof manifest.url!=="string")throw new Error("Desktop update manifest requires a URL");if(typeof manifest.sha256!=="string"||!/^[a-f0-9]{64}$/i.test(manifest.sha256))throw new Error("Desktop update manifest requires a SHA-256 checksum");if(!Number.isInteger(manifest.size)||manifest.size<0)throw new Error("Desktop update manifest requires a non-negative integer size");if(typeof manifest.sourceRevision!=="string"||!/^[0-9a-f]{40}$/.test(manifest.sourceRevision))throw new Error("Desktop update manifest requires a full source revision");if(typeof manifest.platform!=="string"||!["darwin","linux","win32"].includes(manifest.platform))throw new Error("Desktop update manifest requires a supported platform identifier");if(typeof manifest.architecture!=="string"||!/^[a-z0-9_-]+$/.test(manifest.architecture))throw new Error("Desktop update manifest requires an architecture");if(typeof manifest.signingKeyId!=="string"||!/^[a-zA-Z0-9._-]+$/.test(manifest.signingKeyId))throw new Error("Desktop update manifest requires a signing key ID");if(typeof manifest.signature!=="string"||!/^[A-Za-z0-9_-]+$/.test(manifest.signature))throw new Error("Desktop update manifest requires an Ed25519 signature");return manifest}export function updateManifestPayload(manifest){return Buffer.from(JSON.stringify({version:manifest.version,url:manifest.url,sha256:manifest.sha256.toLowerCase(),size:manifest.size,sourceRevision:manifest.sourceRevision,platform:manifest.platform,architecture:manifest.architecture,signingKeyId:manifest.signingKeyId,publishedAt:manifest.publishedAt||null,notes:manifest.notes||null}),"utf8")}export function verifyUpdateManifestSignature(manifest,trustedKeys){const encodedKey=trustedKeys[manifest.signingKeyId];if(!encodedKey)throw new Error(`Desktop update signing key is not trusted: ${manifest.signingKeyId}`);const prefix="ed25519-public:";if(!encodedKey.startsWith(prefix))throw new Error("Desktop update signing key has an invalid encoding");try{const publicKey=createPublicKey({key:Buffer.from(encodedKey.slice(prefix.length),"base64url"),format:"der",type:"spki"});const signature=Buffer.from(manifest.signature,"base64url");if(publicKey.asymmetricKeyType!=="ed25519"||signature.length!==64||!verify(null,updateManifestPayload(manifest),publicKey,signature))throw new Error("invalid")}catch{throw new Error("Desktop update manifest signature verification failed")}}function assertUpdateTarget(manifest,target={platform:process.platform,architecture:process.arch}){if(manifest.platform!==target.platform||manifest.architecture!==target.architecture)throw new Error(`Desktop update is built for ${manifest.platform}-${manifest.architecture}, not this app's ${target.platform}-${target.architecture}`)}function parseVersion(version){const match=version.match(/^v?(\d+)\.(\d+)\.(\d+)(?:-[0-9A-Za-z.-]+)?$/);if(!match)throw new Error(`Invalid semantic version: ${version}`);return[Number(match[1]),Number(match[2]),Number(match[3])]}function assertSecureUrl(value){const url=new URL(value);const isLoopback=["localhost","127.0.0.1","::1"].includes(url.hostname);if(url.protocol!=="https:"&&!(url.protocol==="http:"&&isLoopback))throw new Error("Desktop updates require HTTPS outside loopback development")}
|
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.518",
|
|
6
6
|
"description": "Build and launch Craft desktop applications for Stacks",
|
|
7
7
|
"author": "Chris Breuer",
|
|
8
8
|
"contributors": [
|
|
@@ -73,15 +73,15 @@
|
|
|
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.
|
|
76
|
+
"@stacksjs/config": "0.75.518",
|
|
77
|
+
"@stacksjs/router": "0.75.518",
|
|
78
|
+
"@stacksjs/server": "0.75.518",
|
|
79
79
|
"craft-native": ">=0.0.443"
|
|
80
80
|
},
|
|
81
81
|
"peerDependencies": {
|
|
82
|
-
"@stacksjs/config": "0.75.
|
|
83
|
-
"@stacksjs/router": "0.75.
|
|
84
|
-
"@stacksjs/server": "0.75.
|
|
82
|
+
"@stacksjs/config": "0.75.518",
|
|
83
|
+
"@stacksjs/router": "0.75.518",
|
|
84
|
+
"@stacksjs/server": "0.75.518"
|
|
85
85
|
},
|
|
86
86
|
"peerDependenciesMeta": {
|
|
87
87
|
"@stacksjs/config": {
|
|
@@ -95,7 +95,7 @@
|
|
|
95
95
|
}
|
|
96
96
|
},
|
|
97
97
|
"devDependencies": {
|
|
98
|
-
"@stacksjs/build": "0.75.
|
|
98
|
+
"@stacksjs/build": "0.75.518",
|
|
99
99
|
"better-dx": "^0.2.24"
|
|
100
100
|
}
|
|
101
101
|
}
|