@stacksjs/actions 0.75.334 → 0.75.336

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/bump.js CHANGED
@@ -2,7 +2,7 @@ import{execSync,log,parseOptions}from"@stacksjs/cli";import{path as p}from"@stac
2
2
  `).slice(0,4).join(`
3
3
  `)))content=content.replace(/^(#\s.*\n+)?/,(match)=>`${match??""}## v${nextVersion}
4
4
 
5
- `);writeFileSync(changelogPath,content)}await writeChangelog();if(!isDryRun&&isFrameworkRelease)pinLockstepDeps(nextVersion);async function refreshPantryLock(){const lockPath=p.projectPath("pantry.lock");if(!existsSync(lockPath))return;const previousLock=readFileSync(lockPath);try{await execSync([pantryToolchain?.ok?pantryToolchain.bin:"pantry","install","--ignore-scripts","--quiet"],{cwd:p.projectPath(),stdin:"inherit",throwOnError:!0});if(!existsSync(lockPath))throw Error("Pantry completed without writing pantry.lock")}catch(error){writeFileSync(lockPath,previousLock);throw Error("Release aborted: Pantry could not refresh pantry.lock without lifecycle scripts. The previous lockfile was restored.",{cause:error})}const declarations=existsSync(bunLockPath)?Bun.JSONC.parse(readFileSync(bunLockPath,"utf8")).workspaces:void 0,violations=pantryLockViolations(readFileSync(lockPath,"utf8"),previousLock.toString("utf8"),declarations);if(violations.length>0){writeFileSync(lockPath,previousLock);throw Error(`Release aborted: refreshing pantry.lock produced a lockfile that does not describe this workspace, so the previous one has been restored.
5
+ `);writeFileSync(changelogPath,content)}await writeChangelog();if(!isDryRun&&isFrameworkRelease)pinLockstepDeps(nextVersion);async function refreshPantryLock(){const lockPath=p.projectPath("pantry.lock");if(!existsSync(lockPath))return;const previousLock=readFileSync(lockPath);try{await execSync([pantryToolchain?.ok?pantryToolchain.bin:"pantry","install","--ignore-scripts","--quiet"],{cwd:p.projectPath(),stdin:"inherit",throwOnError:!0,env:{PANTRY_ENV_DEPS:"0"}});if(!existsSync(lockPath))throw Error("Pantry completed without writing pantry.lock")}catch(error){writeFileSync(lockPath,previousLock);throw Error("Release aborted: Pantry could not refresh pantry.lock without lifecycle scripts. The previous lockfile was restored.",{cause:error})}const declarations=existsSync(bunLockPath)?Bun.JSONC.parse(readFileSync(bunLockPath,"utf8")).workspaces:void 0,violations=pantryLockViolations(readFileSync(lockPath,"utf8"),previousLock.toString("utf8"),declarations);if(violations.length>0){writeFileSync(lockPath,previousLock);throw Error(`Release aborted: refreshing pantry.lock produced a lockfile that does not describe this workspace, so the previous one has been restored.
6
6
  `+violations.map((violation)=>` - ${violation}`).join(`
7
7
  `)+"\n\nThis is platform divergence in `pantry install`, not something the version bump did. Regenerate pantry.lock on the platform CI validates against, commit that on its own, then re-run the release.")}}const bunLockPath=p.projectPath("bun.lock"),pantryLockPath=p.projectPath("pantry.lock"),committedBunLock=existsSync(bunLockPath)?readFileSync(bunLockPath):null,committedPantryLock=existsSync(pantryLockPath)?readFileSync(pantryLockPath):null;function restoreCommittedLockfiles(){if(committedBunLock)writeFileSync(bunLockPath,committedBunLock);if(committedPantryLock)writeFileSync(pantryLockPath,committedPantryLock)}if(!isDryRun&&committedBunLock){const lockPath=bunLockPath;unlinkSync(lockPath);try{await execSync(["bun","install","--lockfile-only"],{cwd:p.projectPath(),stdin:"inherit"})}catch(error){restoreCommittedLockfiles();throw error}if(!existsSync(lockPath)){restoreCommittedLockfiles();throw Error("Release aborted: `bun install --lockfile-only` wrote no lockfile, so the previous one has been restored. This usually means a dependency range this bump just raised names a version that is not published yet - release that package first, then re-run.")}}if(!isDryRun)try{await refreshPantryLock()}catch(error){restoreCommittedLockfiles();throw error}if(!isDryRun&&committedBunLock){const lockPath=bunLockPath,expectedLockfileVersion=lockfileVersion(committedBunLock.toString("utf8")),regeneratedLock=readFileSync(lockPath,"utf8"),producedVersion=lockfileVersion(regeneratedLock);if(expectedLockfileVersion==null||producedVersion!==expectedLockfileVersion){restoreCommittedLockfiles();const remedy=producedVersion!=null&&expectedLockfileVersion!=null&&producedVersion>expectedLockfileVersion?"the committed lockfile predates the Bun this repository declares. Regenerate it once with that toolchain (`bun install --lockfile-only`) and commit the result as its own change, then re-run the release.":"this machine's Bun is older than the one that wrote the committed lockfile. Re-run the release with the repository's declared Bun toolchain through `pantry install`.";throw Error(`Release aborted: regenerating bun.lock produced lockfileVersion ${producedVersion??"unknown"}, but the committed one is v${expectedLockfileVersion??"unknown"} \u2014 ${remedy}`)}}function lockstepPackages(version){const names=new Set;for(const entry of readdirSync(p.frameworkPath("core"),{withFileTypes:!0})){if(!entry.isDirectory())continue;const manifest=p.frameworkPath(`core/${entry.name}/package.json`);if(!existsSync(manifest))continue;const pkg=JSON.parse(readFileSync(manifest,"utf-8"));if(pkg.name?.startsWith("@stacksjs/")&&pkg.version===version)names.add(pkg.name)}return names}function pinLockstepDeps(version){const lockstep=lockstepPackages(version),next=version,manifests=[p.frameworkPath("core/package.json"),...readdirSync(p.frameworkPath("core"),{withFileTypes:!0}).filter((entry)=>entry.isDirectory()).map((entry)=>p.frameworkPath(`core/${entry.name}/package.json`)).filter((path)=>existsSync(path))];let pinned=0;for(const manifestPath of manifests){const manifest=JSON.parse(readFileSync(manifestPath,"utf-8"));let changed=!1;for(const field of["dependencies","devDependencies"]){const deps=manifest[field];if(!deps)continue;for(const name of Object.keys(deps)){if(!lockstep.has(name)||deps[name].startsWith("workspace:")||deps[name]===next)continue;deps[name]=next;changed=!0;pinned++}}if(changed)writeFileSync(manifestPath,`${JSON.stringify(manifest,null,2)}
8
8
  `)}if(pinned>0)log.debug(`Pinned ${pinned} lockstep core dep(s) to ${version}`)}async function stageReleaseArtifacts(){const pathspecs=isFrameworkRelease?[":(glob)storage/framework/**/package.json","package.json"]:["package.json"];for(const file of["CHANGELOG.md","bun.lock","pantry.lock"]){if(!existsSync(p.projectPath(file)))continue;if(await isGitIgnored(file))continue;pathspecs.push(file)}await git(["add","--",...pathspecs]);const leftover=(await git(["status","--porcelain"])).split(`
@@ -1,5 +1,5 @@
1
- import process from"node:process";import{randomUUID}from"node:crypto";import{existsSync,mkdirSync,renameSync,unlinkSync,writeFileSync}from"node:fs";import{connect}from"node:net";import{bold,cyan,dim,green}from"@stacksjs/cli";import{defaultsPath,projectPath,publicPath,storagePath}from"@stacksjs/path";import{seedCsrfPageResponse,validateDevCsrfRequest}from"./csrf";import{resolveComponentsLibraryRoot}from"./defaults-resources";import{shouldDelegateDashboardRequest}from"./dashboard-request-routing";import{resolveDashboardCraftExecutable}from"./dashboard-native";import{resolveDashboardDomain,resolveDashboardProxyStrategy}from"./dashboard-proxy";import{buildManifest,discoverModels,findAvailablePort,waitForServer}from"./dashboard-utils";import{runDashboardSupervisor}from"./dashboard-supervisor";import{ensureDiscoveredPackages}from"../discover-packages";import{resolveStxSource}from"../stx-source";if(process.env.STACKS_DASHBOARD_WORKER!=="1"){const exitCode=await runDashboardSupervisor(import.meta.path,process.argv.slice(2));process.exit(exitCode)}const verboseIdx=process.argv.indexOf("--verbose"),verbose=verboseIdx!==-1&&process.argv[verboseIdx+1]!=="false",startTime=Bun.nanoseconds(),{log:originalConsoleLog,warn:originalConsoleWarn}=console,bufferedLogs=[];console.log=(...args)=>{bufferedLogs.push(args.map(String).join(" "))};console.warn=(...args)=>{bufferedLogs.push(args.map(String).join(" "))};const dashboardPath=defaultsPath("views/dashboard"),userDashboardPath=projectPath("resources/views/dashboard"),preferredPort=Number(process.env.PORT_ADMIN)||3002,dashboardPort=await findAvailablePort(preferredPort),appUrl=process.env.APP_URL||"",dashboardDomain=resolveDashboardDomain(appUrl),sslBasePath=`${process.env.HOME}/.stacks/ssl`;function restoreConsole(){console.log=originalConsoleLog;console.warn=(...args)=>{const msg=args.map(String).join(" ");if(msg.includes("[STX] DOM API violation")||msg.includes("unsafe expression"))return;originalConsoleWarn(...args)}}async function startStxServer(){const{overridesReady}=await import("@stacksjs/config"),{autoImportsAreStale,generateAutoImportFiles,injectGlobalAutoImports}=await import("@stacksjs/server");await overridesReady;await ensureDiscoveredPackages();if(!existsSync(storagePath("framework/auto-imports/models.ts"))||autoImportsAreStale())await generateAutoImportFiles();await injectGlobalAutoImports();const serveSource=resolveStxSource({value:process.env.BUN_PLUGIN_STX_SRC});if(serveSource.kind==="missing")throw Error(`BUN_PLUGIN_STX_SRC points at ${serveSource.path}, which does not exist. Unset it to use the installed bun-plugin-stx.`);let serve;if(serveSource.kind==="override"){serve=(await import(serveSource.path)).serve;console.log(`[Dashboard] bun-plugin-stx from ${serveSource.path}`)}else serve=(await import("bun-plugin-stx/serve")).serve;const stxSource=resolveStxSource({value:process.env.STX_SRC});if(stxSource.kind==="missing")throw Error(`STX_SRC points at ${stxSource.path}, which does not exist. Unset it to use the installed @stacksjs/stx.`);let stxModule;if(stxSource.kind==="override"){stxModule=await import(stxSource.path);console.log(`[Dashboard] stx from ${stxSource.path}`)}const{listConfigFiles,readConfig,updateConfigKeys}=await import(defaultsPath("resources/functions/dashboard/config-io.ts")),localTsChartsRoot=process.env.TS_CHARTS_SRC,dependencyBundles=new Map;function resolveTsChartsSource(packageName){return[...localTsChartsRoot?[`${localTsChartsRoot}/packages/${packageName}/src/index.ts`]:[],projectPath(`node_modules/@ts-charts/${packageName}/src/index.ts`)].find(existsSync)||null}const tsChartsEntry=[...localTsChartsRoot?[`${localTsChartsRoot}/packages/ts-charts/src/index.ts`]:[],projectPath("node_modules/ts-charts/src/index.ts")].find(existsSync);async function buildDashboardDependency(entrypoint){const cached=dependencyBundles.get(entrypoint);if(cached)return cached;const build=(async()=>{const result=await Bun.build({entrypoints:[entrypoint],target:"browser",format:"esm",minify:!0,plugins:[{name:"dashboard-ts-charts-source",setup(builder){builder.onResolve({filter:/^@ts-charts\/[a-z0-9-]+$/},(args)=>{const packageName=args.path.slice(11),source=resolveTsChartsSource(packageName);if(source)return{path:source};return null})}}]});if(!result.success){const errors=result.logs.filter((log)=>log.level==="error").map((log)=>log.message).join(`
2
- `);throw Error(errors||`Failed to bundle ${entrypoint}`)}const output=result.outputs.find((file)=>file.path.endsWith(".js"));if(!output)throw Error(`No JavaScript output produced for ${entrypoint}`);return output.text()})();dependencyBundles.set(entrypoint,build);return build}function browserDependencyRoute(entrypoint){return async()=>{try{return new Response(await buildDashboardDependency(entrypoint),{headers:{"content-type":"text/javascript; charset=utf-8","cache-control":"no-cache"}})}catch(error){dependencyBundles.delete(entrypoint);return new Response(`throw new Error(${JSON.stringify(error.message)})`,{status:500,headers:{"content-type":"text/javascript; charset=utf-8"}})}}}let dashboardIconCss=null;async function buildDashboardIconCss(){const{generateCss}=await import("@stacksjs/stx"),dirs=[dashboardPath,userDashboardPath,defaultsPath("resources/components/Dashboard")],icons=new Set;for(const dir of dirs){if(!existsSync(dir))continue;const glob=new Bun.Glob("**/*.{stx,ts}");for await(const file of glob.scan({cwd:dir,absolute:!0})){const text=await Bun.file(file).text();for(const match of text.matchAll(/\bi-[a-z][a-z0-9]*(?:-[a-z0-9]+)+/g))icons.add(match[0])}}if(icons.size===0)return"";return generateCss(`<div class="${[...icons].join(" ")}"></div>`,process.cwd())}const configRoutes={"/__deps/charts.js":browserDependencyRoute(storagePath("framework/core/charts/src/index.ts")),"/__deps/ts-charts.js":browserDependencyRoute(tsChartsEntry||`${localTsChartsRoot}/packages/ts-charts/src/index.ts`),"/__deps/dashboard-icons.css":async()=>{if(!dashboardIconCss)dashboardIconCss=buildDashboardIconCss();return new Response(await dashboardIconCss,{headers:{"content-type":"text/css; charset=utf-8","cache-control":"no-cache"}})},"/api/config/list":async()=>{try{return Response.json({ok:!0,files:listConfigFiles()})}catch(e){return Response.json({ok:!1,error:e?.message},{status:500})}},"/api/config/read":async(req)=>{try{const name=new URL(req.url).searchParams.get("name")||"";if(!/^[\w-]+$/.test(name))return Response.json({ok:!1,error:"Invalid config name"},{status:400});const result=await readConfig(name);if(!result)return Response.json({ok:!1,error:"Not found"},{status:404});return Response.json({ok:!0,name,fields:result.fields})}catch(e){return Response.json({ok:!1,error:e?.message},{status:500})}},"/api/config/source":async(req)=>{try{const name=new URL(req.url).searchParams.get("name")||"";if(!/^[\w-]+$/.test(name))return Response.json({ok:!1,error:"Invalid config name"},{status:400});const result=await readConfig(name);if(!result)return Response.json({ok:!1,error:"Not found"},{status:404});return new Response(result.source,{headers:{"content-type":"text/plain; charset=utf-8"}})}catch(e){return Response.json({ok:!1,error:e?.message},{status:500})}},"/api/config/update":async(req)=>{if(req.method!=="POST")return Response.json({ok:!1,error:"Method not allowed"},{status:405});try{await validateDevCsrfRequest(req);const body=await req.json(),file=body.file?.replace(/\.ts$/,"");if(!file||!/^[\w-]+$/.test(file))return Response.json({ok:!1,error:"Invalid file"},{status:400});const updates=[];if(Array.isArray(body.updates))for(const u of body.updates){const k=u.key??u.path;if(typeof k==="string")updates.push({key:k,value:u.value})}else if(body.key)updates.push({key:body.key,value:body.value});if(updates.length===0)return Response.json({ok:!1,error:"No updates supplied"},{status:400});const invalid=updates.find((update)=>!/^[A-Za-z_$][\w$]*$/.test(update.key)||typeof update.value!=="string"&&typeof update.value!=="number"&&typeof update.value!=="boolean"||typeof update.value==="number"&&!Number.isFinite(update.value));if(invalid)return Response.json({ok:!1,error:`Invalid value for configuration key "${invalid.key}"`},{status:400});const typedUpdates=updates;try{await updateConfigKeys(file,typedUpdates)}catch(err){const error=err?.message||"Configuration values could not be updated.",results=typedUpdates.map((update)=>({key:update.key,ok:!1,error}));return Response.json({ok:!1,file,results,error},{status:422})}const results=typedUpdates.map((update)=>({key:update.key,ok:!0,newValue:update.value}));return Response.json({ok:!0,file,results})}catch(e){if(e?.status===403)return Response.json({ok:!1,error:"Forbidden",message:"CSRF token mismatch"},{status:403});return Response.json({ok:!1,error:e?.message},{status:500})}}},router=await import("@stacksjs/router");await router.loadRoutes(await router.appRouteRegistry());const stacksRoute=router.route;serve({root:projectPath("resources"),patterns:[userDashboardPath,dashboardPath],port:dashboardPort,componentsDir:defaultsPath("resources/components/Dashboard"),fallbackComponentsDir:resolveComponentsLibraryRoot(),layoutsDir:dashboardPath,partialsDir:dashboardPath,publicDir:publicPath(),renderCache:!0,renderCacheVary:"source",prewarmRenderCache:!1,watchDirs:[projectPath("resources/functions"),defaultsPath("resources/functions")],quiet:!0,routes:configRoutes,onRequest:async(req)=>{const pathname=new URL(req.url).pathname;if(shouldDelegateDashboardRequest(pathname,req.method))return stacksRoute.handleRequest(req);return null},onResponse:seedCsrfPageResponse,auth:!1,...stxModule&&{stxModule}}).catch((err)=>{restoreConsole();console.error(`
1
+ import process from"node:process";import{randomUUID}from"node:crypto";import{existsSync,mkdirSync,renameSync,unlinkSync,writeFileSync}from"node:fs";import{connect}from"node:net";import{bold,cyan,dim,green}from"@stacksjs/cli";import{defaultsPath,projectPath,publicPath,storagePath}from"@stacksjs/path";import{seedCsrfPageResponse,validateDevCsrfRequest}from"./csrf";import{resolveComponentsLibraryRoot}from"./defaults-resources";import{shouldDelegateDashboardRequest}from"./dashboard-request-routing";import{resolveDashboardCraftExecutable}from"./dashboard-native";import{resolveDashboardDomain,resolveDashboardProxyStrategy}from"./dashboard-proxy";import{buildManifest,discoverModels,findAvailablePort,waitForServer}from"./dashboard-utils";import{runDashboardSupervisor}from"./dashboard-supervisor";import{ensureDiscoveredPackages}from"../discover-packages";import{resolveStxSource}from"../stx-source";if(process.env.STACKS_DASHBOARD_WORKER!=="1"){const exitCode=await runDashboardSupervisor(import.meta.path,process.argv.slice(2));process.exit(exitCode)}const verboseIdx=process.argv.indexOf("--verbose"),verbose=verboseIdx!==-1&&process.argv[verboseIdx+1]!=="false",startTime=Bun.nanoseconds(),{log:originalConsoleLog,warn:originalConsoleWarn}=console,bufferedLogs=[];console.log=(...args)=>{bufferedLogs.push(args.map(String).join(" "))};console.warn=(...args)=>{bufferedLogs.push(args.map(String).join(" "))};const dashboardPath=defaultsPath("views/dashboard"),userDashboardPath=projectPath("resources/views/dashboard"),dashboardComponentsPath=defaultsPath("resources/components/Dashboard"),userDashboardComponentsPath=projectPath("resources/components/Dashboard"),preferredPort=Number(process.env.PORT_ADMIN)||3002,dashboardPort=await findAvailablePort(preferredPort),appUrl=process.env.APP_URL||"",dashboardDomain=resolveDashboardDomain(appUrl),sslBasePath=`${process.env.HOME}/.stacks/ssl`;function restoreConsole(){console.log=originalConsoleLog;console.warn=(...args)=>{const msg=args.map(String).join(" ");if(msg.includes("[STX] DOM API violation")||msg.includes("unsafe expression"))return;originalConsoleWarn(...args)}}async function startStxServer(){const{overridesReady}=await import("@stacksjs/config"),{autoImportsAreStale,generateAutoImportFiles,injectGlobalAutoImports}=await import("@stacksjs/server");await overridesReady;await ensureDiscoveredPackages();if(!existsSync(storagePath("framework/auto-imports/models.ts"))||autoImportsAreStale())await generateAutoImportFiles();await injectGlobalAutoImports();const serveSource=resolveStxSource({value:process.env.BUN_PLUGIN_STX_SRC});if(serveSource.kind==="missing")throw Error(`BUN_PLUGIN_STX_SRC points at ${serveSource.path}, which does not exist. Unset it to use the installed bun-plugin-stx.`);let serve;if(serveSource.kind==="override"){serve=(await import(serveSource.path)).serve;console.log(`[Dashboard] bun-plugin-stx from ${serveSource.path}`)}else serve=(await import("bun-plugin-stx/serve")).serve;const stxSource=resolveStxSource({value:process.env.STX_SRC});if(stxSource.kind==="missing")throw Error(`STX_SRC points at ${stxSource.path}, which does not exist. Unset it to use the installed @stacksjs/stx.`);let stxModule;if(stxSource.kind==="override"){stxModule=await import(stxSource.path);console.log(`[Dashboard] stx from ${stxSource.path}`)}const{listConfigFiles,readConfig,updateConfigKeys}=await import(defaultsPath("resources/functions/dashboard/config-io.ts")),localTsChartsRoot=process.env.TS_CHARTS_SRC,dependencyBundles=new Map;function resolveTsChartsSource(packageName){return[...localTsChartsRoot?[`${localTsChartsRoot}/packages/${packageName}/src/index.ts`]:[],projectPath(`node_modules/@ts-charts/${packageName}/src/index.ts`)].find(existsSync)||null}const tsChartsEntry=[...localTsChartsRoot?[`${localTsChartsRoot}/packages/ts-charts/src/index.ts`]:[],projectPath("node_modules/ts-charts/src/index.ts")].find(existsSync);async function buildDashboardDependency(entrypoint){const cached=dependencyBundles.get(entrypoint);if(cached)return cached;const build=(async()=>{const result=await Bun.build({entrypoints:[entrypoint],target:"browser",format:"esm",minify:!0,plugins:[{name:"dashboard-ts-charts-source",setup(builder){builder.onResolve({filter:/^@ts-charts\/[a-z0-9-]+$/},(args)=>{const packageName=args.path.slice(11),source=resolveTsChartsSource(packageName);if(source)return{path:source};return null})}}]});if(!result.success){const errors=result.logs.filter((log)=>log.level==="error").map((log)=>log.message).join(`
2
+ `);throw Error(errors||`Failed to bundle ${entrypoint}`)}const output=result.outputs.find((file)=>file.path.endsWith(".js"));if(!output)throw Error(`No JavaScript output produced for ${entrypoint}`);return output.text()})();dependencyBundles.set(entrypoint,build);return build}function browserDependencyRoute(entrypoint){return async()=>{try{return new Response(await buildDashboardDependency(entrypoint),{headers:{"content-type":"text/javascript; charset=utf-8","cache-control":"no-cache"}})}catch(error){dependencyBundles.delete(entrypoint);return new Response(`throw new Error(${JSON.stringify(error.message)})`,{status:500,headers:{"content-type":"text/javascript; charset=utf-8"}})}}}let dashboardIconCss=null;async function buildDashboardIconCss(){const{generateCss}=await import("@stacksjs/stx"),dirs=[dashboardPath,userDashboardPath,dashboardComponentsPath,userDashboardComponentsPath],icons=new Set;for(const dir of dirs){if(!existsSync(dir))continue;const glob=new Bun.Glob("**/*.{stx,ts}");for await(const file of glob.scan({cwd:dir,absolute:!0})){const text=await Bun.file(file).text();for(const match of text.matchAll(/\bi-[a-z][a-z0-9]*(?:-[a-z0-9]+)+/g))icons.add(match[0])}}if(icons.size===0)return"";return generateCss(`<div class="${[...icons].join(" ")}"></div>`,process.cwd())}const configRoutes={"/__deps/charts.js":browserDependencyRoute(storagePath("framework/core/charts/src/index.ts")),"/__deps/ts-charts.js":browserDependencyRoute(tsChartsEntry||`${localTsChartsRoot}/packages/ts-charts/src/index.ts`),"/__deps/dashboard-icons.css":async()=>{if(!dashboardIconCss)dashboardIconCss=buildDashboardIconCss();return new Response(await dashboardIconCss,{headers:{"content-type":"text/css; charset=utf-8","cache-control":"no-cache"}})},"/api/config/list":async()=>{try{return Response.json({ok:!0,files:listConfigFiles()})}catch(e){return Response.json({ok:!1,error:e?.message},{status:500})}},"/api/config/read":async(req)=>{try{const name=new URL(req.url).searchParams.get("name")||"";if(!/^[\w-]+$/.test(name))return Response.json({ok:!1,error:"Invalid config name"},{status:400});const result=await readConfig(name);if(!result)return Response.json({ok:!1,error:"Not found"},{status:404});return Response.json({ok:!0,name,fields:result.fields})}catch(e){return Response.json({ok:!1,error:e?.message},{status:500})}},"/api/config/source":async(req)=>{try{const name=new URL(req.url).searchParams.get("name")||"";if(!/^[\w-]+$/.test(name))return Response.json({ok:!1,error:"Invalid config name"},{status:400});const result=await readConfig(name);if(!result)return Response.json({ok:!1,error:"Not found"},{status:404});return new Response(result.source,{headers:{"content-type":"text/plain; charset=utf-8"}})}catch(e){return Response.json({ok:!1,error:e?.message},{status:500})}},"/api/config/update":async(req)=>{if(req.method!=="POST")return Response.json({ok:!1,error:"Method not allowed"},{status:405});try{await validateDevCsrfRequest(req);const body=await req.json(),file=body.file?.replace(/\.ts$/,"");if(!file||!/^[\w-]+$/.test(file))return Response.json({ok:!1,error:"Invalid file"},{status:400});const updates=[];if(Array.isArray(body.updates))for(const u of body.updates){const k=u.key??u.path;if(typeof k==="string")updates.push({key:k,value:u.value})}else if(body.key)updates.push({key:body.key,value:body.value});if(updates.length===0)return Response.json({ok:!1,error:"No updates supplied"},{status:400});const invalid=updates.find((update)=>!/^[A-Za-z_$][\w$]*$/.test(update.key)||typeof update.value!=="string"&&typeof update.value!=="number"&&typeof update.value!=="boolean"||typeof update.value==="number"&&!Number.isFinite(update.value));if(invalid)return Response.json({ok:!1,error:`Invalid value for configuration key "${invalid.key}"`},{status:400});const typedUpdates=updates;try{await updateConfigKeys(file,typedUpdates)}catch(err){const error=err?.message||"Configuration values could not be updated.",results=typedUpdates.map((update)=>({key:update.key,ok:!1,error}));return Response.json({ok:!1,file,results,error},{status:422})}const results=typedUpdates.map((update)=>({key:update.key,ok:!0,newValue:update.value}));return Response.json({ok:!0,file,results})}catch(e){if(e?.status===403)return Response.json({ok:!1,error:"Forbidden",message:"CSRF token mismatch"},{status:403});return Response.json({ok:!1,error:e?.message},{status:500})}}},router=await import("@stacksjs/router");await router.loadRoutes(await router.appRouteRegistry());const stacksRoute=router.route;serve({root:projectPath("resources"),patterns:[userDashboardPath,dashboardPath],port:dashboardPort,componentsDir:userDashboardComponentsPath,additionalComponentsDirs:[dashboardComponentsPath],fallbackComponentsDir:resolveComponentsLibraryRoot(),layoutsDir:projectPath("resources/views/dashboard/layouts"),fallbackLayoutsDir:defaultsPath("views/dashboard/layouts"),partialsDir:dashboardPath,publicDir:publicPath(),renderCache:!0,renderCacheVary:"source",prewarmRenderCache:!1,watchDirs:[projectPath("resources/functions"),defaultsPath("resources/functions")],quiet:!0,routes:configRoutes,onRequest:async(req)=>{const pathname=new URL(req.url).pathname;if(shouldDelegateDashboardRequest(pathname,req.method))return stacksRoute.handleRequest(req);return null},onResponse:seedCsrfPageResponse,auth:!1,...stxModule&&{stxModule}}).catch((err)=>{restoreConsole();console.error(`
3
3
  Failed to start dashboard server: ${err?.message||err}
4
4
  `);process.exit(1)})}function portAnswers(port,timeoutMs=800){return new Promise((resolve)=>{const socket=connect({port,host:"127.0.0.1"}),finish=(answered)=>{try{socket.destroy()}catch{}resolve(answered)};socket.once("connect",()=>finish(!0));socket.once("error",()=>finish(!1));setTimeout(()=>finish(!1),timeoutMs).unref?.()})}async function registerWithRpxDaemon(domainToServe){const{writeEntry}=await import("@stacksjs/rpx");await writeEntry({id:`${domainToServe}-dashboard`,from:`localhost:${dashboardPort}`,to:domainToServe,cwd:process.cwd(),createdAt:new Date().toISOString(),pid:process.pid},void 0,verbose);return!0}async function startReverseProxy(){if(!dashboardDomain)return!1;try{let rpx;const loadRpx=async()=>rpx??=await import("@stacksjs/rpx"),strategy=await resolveDashboardProxyStrategy(dashboardDomain,{proxyManagedExternally:Boolean(process.env.STACKS_PROXY_MANAGED),isDaemonRunning:async()=>(await loadRpx()).isDaemonRunning(),httpsPortAnswers:()=>portAnswers(443)});if(strategy==="origin-only")return!1;if(strategy==="parent-managed")return!0;if(strategy==="daemon-route")return await registerWithRpxDaemon(dashboardDomain);await(await loadRpx()).startProxies({proxies:[{from:`localhost:${dashboardPort}`,to:dashboardDomain,cleanUrls:!1}],https:{basePath:sslBasePath,validityDays:825},regenerateUntrustedCerts:!1,verbose});return await portAnswers(443)}catch(error){if(verbose)originalConsoleLog(` ${dim(`Proxy: ${error}`)}`);return!1}}const[,discoveredModels]=await Promise.all([startStxServer(),discoverModels(projectPath("app/Models"),defaultsPath("app/Models"))]),{loadDashboardConfig}=await import(defaultsPath("resources/functions/dashboard/toggles.ts")),{feature:featureEnabled}=await import("@stacksjs/config"),{toggles:dashboardToggles,nav:dashboardNav}=await loadDashboardConfig(projectPath("config/dashboard.ts"),featureEnabled),manifestDir=storagePath("framework/runtime/dashboard"),manifestPath=storagePath("framework/runtime/dashboard/.discovered-models.json");mkdirSync(manifestDir,{recursive:!0});const manifestPayload={models:buildManifest(discoveredModels),sections:dashboardToggles,nav:dashboardNav},manifestTempPath=`${manifestPath}.${process.pid}.${randomUUID()}.tmp`;try{writeFileSync(manifestTempPath,JSON.stringify(manifestPayload,null,2),{flag:"wx"});renameSync(manifestTempPath,manifestPath)}finally{if(existsSync(manifestTempPath))unlinkSync(manifestTempPath)}const serverReady=await waitForServer(dashboardPort);restoreConsole();const proxyStarted=await startReverseProxy().catch((err)=>{if(verbose)console.warn("[Dashboard] Reverse proxy failed:",err);return!1}),dashboardHttpsUrl=dashboardDomain?`https://${dashboardDomain}`:null,dashboardLocalUrl=`http://localhost:${dashboardPort}`,initialUrl=dashboardHttpsUrl&&proxyStarted?`${dashboardHttpsUrl}/`:`${dashboardLocalUrl}/`,elapsedMs=(Bun.nanoseconds()-startTime)/1e6;console.log();console.log(` ${bold(cyan("stacks dashboard"))}`);console.log();if(dashboardHttpsUrl&&proxyStarted){console.log(` ${green("\u279C")} ${bold("Local")}: ${cyan(dashboardHttpsUrl)}`);console.log(` ${dim("\u279C")} ${dim("Origin")}: ${dim(dashboardLocalUrl)}`)}else{console.log(` ${green("\u279C")} ${bold("Local")}: ${cyan(dashboardLocalUrl)}`);if(dashboardHttpsUrl)console.log(` ${dim("\u279C")} ${dim("Pretty")}: ${dim(`${dashboardHttpsUrl} needs the rpx proxy - run \`buddy dev\``)}`)}console.log(` ${green("\u279C")} ${bold("Window")}: ${dim("Stacks Dashboard")} ${dim("1400\xD7900")}`);console.log(` ${green("\u279C")} ${bold("Models")}: ${dim(`${discoveredModels.length} discovered`)}`);if(dashboardPort!==preferredPort)console.log(` ${dim("\u279C")} ${dim(`Port ${preferredPort} in use, using ${dashboardPort}`)}`);if(!serverReady)console.log(` ${dim("\u26A0")} ${dim("Dev server may not be ready yet")}`);console.log();console.log(` ${dim(`ready in ${elapsedMs.toFixed(0)} ms`)}`);if(verbose){console.log();console.log(` ${dim("\u279C")} ${dim("URL")}: ${dim(initialUrl)}`);if(dashboardDomain){console.log(` ${dim("\u279C")} ${dim("SSL")}: ${dim(sslBasePath)}`);console.log(` ${dim("\u279C")} ${dim("Proxy")}: ${dim(`localhost:${dashboardPort} \u2192 ${dashboardDomain}`)}`)}if(bufferedLogs.length>0){console.log();for(const line of bufferedLogs)console.log(` ${dim(line)}`)}}console.log();let createApp,resolveCraftBinary;const nativeDisabled=process.env.STACKS_NO_NATIVE==="1",explicitCraftSdk=process.env.CRAFT_SDK_SRC;if(!nativeDisabled&&explicitCraftSdk){if(!existsSync(explicitCraftSdk))throw Error(`CRAFT_SDK_SRC not found: ${explicitCraftSdk}`);try{({createApp,resolveCraftBinary}=await import(explicitCraftSdk));if(!createApp||!resolveCraftBinary)throw Error("CRAFT_SDK_SRC must export createApp and resolveCraftBinary")}catch(error){throw Error(`Could not load CRAFT_SDK_SRC ${explicitCraftSdk}: ${error instanceof Error?error.message:String(error)}`)}}if(!nativeDisabled&&!explicitCraftSdk)try{({createApp,resolveCraftBinary}=await import("craft-native"))}catch{}const craftBinaryPath=createApp&&resolveCraftBinary?resolveDashboardCraftExecutable(resolveCraftBinary):void 0;if(createApp&&craftBinaryPath){const userIconPath=projectPath("resources/assets/images/app-icon.png"),defaultIconPath=defaultsPath("resources/assets/images/app-icon.png"),appIconPath=await Bun.file(userIconPath).exists()?userIconPath:await Bun.file(defaultIconPath).exists()?defaultIconPath:void 0,app=createApp({url:dashboardLocalUrl,quiet:!verbose,craftPath:craftBinaryPath,window:{title:"Stacks Dashboard",width:1400,height:900,titlebarHidden:!0,webSidebarMaterial:!0,webSidebarWidth:250,...appIconPath&&{icon:appIconPath}}});process.on("SIGINT",()=>{app.close();process.exit(0)});process.on("SIGTERM",()=>{app.close();process.exit(0)});try{await app.show();process.exit(0)}catch(error){const fallbackUrl=dashboardHttpsUrl||dashboardLocalUrl;console.log(` ${dim("Native Craft window failed:")} ${dim(error instanceof Error?error.message:String(error))}`);console.log(` ${dim("Dashboard available at:")} ${cyan(fallbackUrl)}
5
5
  `);await new Promise(()=>{})}}else{console.log(` ${dim(nativeDisabled?"Native window disabled by STACKS_NO_NATIVE=1. Open the URL above in a browser.":"Native window unavailable. Run pantry install craft, set CRAFT_BIN, or open the URL above in a browser.")}
@@ -1,2 +1,2 @@
1
- import{homedir,networkInterfaces}from"node:os";import{basename,join}from"node:path";import process from"node:process";import{bold,cyan,dim,green}from"@stacksjs/cli";import{openDevWindow}from"@stacksjs/desktop-build";import{defaultsPath,projectPath}from"@stacksjs/path";import{findStacksProjects}from"@stacksjs/utils";import{findAvailablePort,waitForServer}from"./dashboard-utils";const preferredPort=Number(process.env.PORT_SYSTEM_TRAY)||3009,port=await findAvailablePort(preferredPort),trayViews=defaultsPath("views/system-tray"),appUrl=process.env.APP_URL||"stacks.test",domain=appUrl.replace(/^https?:\/\//,"").replace(/\/$/,""),hasPrettyDomain=!domain.includes("localhost:")&&domain!=="localhost",trayDomain=hasPrettyDomain?`tray.${domain}`:null,localUrl=`http://localhost:${port}`;let cachedProjects;async function discoverProjects(refresh=!1){if(cachedProjects&&!refresh)return cachedProjects;const discovered=await findStacksProjects(join(homedir(),"Code"),{quiet:!0}).catch(()=>[]),candidates=[...new Set([projectPath(),...discovered])];cachedProjects=(await Promise.all(candidates.map(async(project)=>({project,valid:await Bun.file(join(project,"buddy")).exists()})))).filter((check)=>check.valid).map((check)=>check.project).sort((a,b)=>basename(a).localeCompare(basename(b)));return cachedProjects}async function runBuddy(project,args){const child=Bun.spawn([join(project,"buddy"),...args,"--no-interaction"],{cwd:project,stdout:"pipe",stderr:"pipe"}),[stdout,stderr,exitCode]=await Promise.all([new Response(child.stdout).text(),new Response(child.stderr).text(),child.exited]);return{output:[stdout,stderr].filter(Boolean).join(`
2
- `).trim(),exitCode}}function openPath(path){const command=process.platform==="darwin"?["open",path]:process.platform==="win32"?["cmd","/c","start","",path]:["xdg-open",path];Bun.spawn(command,{stdout:"ignore",stderr:"ignore"}).unref()}function openTerminal(project){const command=process.platform==="darwin"?["open","-a","Terminal",project]:process.platform==="win32"?["cmd","/c","start","cmd","/K",`cd /d ${project}`]:["x-terminal-emulator","--working-directory",project];Bun.spawn(command,{stdout:"ignore",stderr:"ignore"}).unref()}function localIpAddress(){for(const addresses of Object.values(networkInterfaces()))for(const address of addresses||[])if(address.family==="IPv4"&&!address.internal)return address.address;return"127.0.0.1"}function dashboardUrl(path=""){return`${hasPrettyDomain?`https://dashboard.${domain}`:`http://localhost:${Number(process.env.PORT_ADMIN)||3002}`}${path}`}async function handleAction(input){const projects=await discoverProjects(),project=input.project||projectPath();if(!projects.includes(project))return Response.json({ok:!1,error:"Unknown Stacks project"},{status:400});switch(input.action){case"refresh":return Response.json({ok:!0,projects:await discoverProjects(!0)});case"open-terminal":openTerminal(project);return Response.json({ok:!0,message:`Opened Terminal in ${basename(project)}`});case"env-check":{const result=await runBuddy(project,["doctor"]);return Response.json({ok:result.exitCode===0,...result})}case"settings":openPath(dashboardUrl("/settings"));return Response.json({ok:!0,message:"Opened dashboard settings"});case"check-updates":{const result=await runBuddy(project,["outdated"]);return Response.json({ok:result.exitCode===0,...result})}case"copy-ip":return Response.json({ok:!0,value:localIpAddress(),message:"IP address ready to copy"});case"open-dashboard":openPath(dashboardUrl());return Response.json({ok:!0,message:"Opened dashboard"});case"buddy-commands":{const result=await runBuddy(project,["list"]);return Response.json({ok:result.exitCode===0,...result})}case"deploy":{if(!input.confirmed)return Response.json({ok:!1,confirmationRequired:!0,error:"Deployment confirmation required"},{status:409});Bun.spawn([join(project,"buddy"),"deploy","--no-interaction"],{cwd:project,stdout:"inherit",stderr:"inherit"}).unref();return Response.json({ok:!0,message:`Deployment started for ${basename(project)}`})}case"deploy-logs":openPath(join(project,"storage/logs"));return Response.json({ok:!0,message:"Opened deployment logs"});case"site-logs":openPath(join(project,"storage/logs"));return Response.json({ok:!0,message:"Opened site logs"});case"error-logs":openPath(join(project,"storage/logs"));return Response.json({ok:!0,message:"Opened error logs"});case"edit-env":openPath(join(project,".env"));return Response.json({ok:!0,message:"Opened .env"});case"edit-dns":openPath(join(project,"config/dns.ts"));return Response.json({ok:!0,message:"Opened DNS configuration"});case"edit-email":openPath(join(project,"config/email.ts"));return Response.json({ok:!0,message:"Opened email configuration"});case"ask-buddy":openPath(dashboardUrl("/buddy"));return Response.json({ok:!0,message:"Opened Ask Buddy"});default:return Response.json({ok:!1,error:"Unknown tray action"},{status:400})}}const{serve}=await import("bun-plugin-stx/serve"),serverPromise=serve({patterns:[trayViews],port,componentsDir:defaultsPath("resources/components"),quiet:!0,auth:!1,routes:{"/api/tray/projects":async()=>Response.json({ok:!0,projects:await discoverProjects()}),"/api/tray/action":async(request)=>{if(request.method!=="POST")return Response.json({ok:!1,error:"Method not allowed"},{status:405});return handleAction(await request.json())}}});serverPromise.catch((error)=>{console.error(`System tray server failed: ${error.message}`);process.exit(1)});let proxyStarted=!1;if(trayDomain&&!process.env.STACKS_PROXY_MANAGED)try{const{startProxies}=await import("@stacksjs/rpx");await startProxies({proxies:[{from:`localhost:${port}`,to:trayDomain,cleanUrls:!1}],https:{basePath:`${process.env.HOME}/.stacks/ssl`,validityDays:825},regenerateUntrustedCerts:!1});proxyStarted=!0}catch{proxyStarted=!1}await waitForServer(port,2000);const url=trayDomain&&proxyStarted?`https://${trayDomain}`:localUrl;console.log();console.log(` ${bold(cyan("stacks tray"))}`);console.log();console.log(` ${green("\u279C")} ${bold("Local")}: ${cyan(url)}`);if(trayDomain)console.log(` ${dim("\u279C")} ${dim("Origin")}: ${dim(localUrl)}`);console.log();await openDevWindow(port,{url,title:"Stacks",width:440,height:680,systemTray:!0,hideDockIcon:!0,hotReload:!0});const stop=()=>{process.exit(0)};process.on("SIGINT",stop);process.on("SIGTERM",stop);await new Promise(()=>{});
1
+ import{homedir,networkInterfaces}from"node:os";import{basename,join}from"node:path";import process from"node:process";import{bold,cyan,dim,green}from"@stacksjs/cli";import{openDevWindow}from"@stacksjs/desktop-build";import{defaultsPath,projectPath}from"@stacksjs/path";import{findStacksProjects}from"@stacksjs/utils";import{findAvailablePort,waitForServer}from"./dashboard-utils";const preferredPort=Number(process.env.PORT_SYSTEM_TRAY)||3009,port=await findAvailablePort(preferredPort),trayViews=defaultsPath("views/system-tray"),userTrayViews=projectPath("resources/views/system-tray"),appUrl=process.env.APP_URL||"stacks.test",domain=appUrl.replace(/^https?:\/\//,"").replace(/\/$/,""),hasPrettyDomain=!domain.includes("localhost:")&&domain!=="localhost",trayDomain=hasPrettyDomain?`tray.${domain}`:null,localUrl=`http://localhost:${port}`;let cachedProjects;async function discoverProjects(refresh=!1){if(cachedProjects&&!refresh)return cachedProjects;const discovered=await findStacksProjects(join(homedir(),"Code"),{quiet:!0}).catch(()=>[]),candidates=[...new Set([projectPath(),...discovered])];cachedProjects=(await Promise.all(candidates.map(async(project)=>({project,valid:await Bun.file(join(project,"buddy")).exists()})))).filter((check)=>check.valid).map((check)=>check.project).sort((a,b)=>basename(a).localeCompare(basename(b)));return cachedProjects}async function runBuddy(project,args){const child=Bun.spawn([join(project,"buddy"),...args,"--no-interaction"],{cwd:project,stdout:"pipe",stderr:"pipe"}),[stdout,stderr,exitCode]=await Promise.all([new Response(child.stdout).text(),new Response(child.stderr).text(),child.exited]);return{output:[stdout,stderr].filter(Boolean).join(`
2
+ `).trim(),exitCode}}function openPath(path){const command=process.platform==="darwin"?["open",path]:process.platform==="win32"?["cmd","/c","start","",path]:["xdg-open",path];Bun.spawn(command,{stdout:"ignore",stderr:"ignore"}).unref()}function openTerminal(project){const command=process.platform==="darwin"?["open","-a","Terminal",project]:process.platform==="win32"?["cmd","/c","start","cmd","/K",`cd /d ${project}`]:["x-terminal-emulator","--working-directory",project];Bun.spawn(command,{stdout:"ignore",stderr:"ignore"}).unref()}function localIpAddress(){for(const addresses of Object.values(networkInterfaces()))for(const address of addresses||[])if(address.family==="IPv4"&&!address.internal)return address.address;return"127.0.0.1"}function dashboardUrl(path=""){return`${hasPrettyDomain?`https://dashboard.${domain}`:`http://localhost:${Number(process.env.PORT_ADMIN)||3002}`}${path}`}async function handleAction(input){const projects=await discoverProjects(),project=input.project||projectPath();if(!projects.includes(project))return Response.json({ok:!1,error:"Unknown Stacks project"},{status:400});switch(input.action){case"refresh":return Response.json({ok:!0,projects:await discoverProjects(!0)});case"open-terminal":openTerminal(project);return Response.json({ok:!0,message:`Opened Terminal in ${basename(project)}`});case"env-check":{const result=await runBuddy(project,["doctor"]);return Response.json({ok:result.exitCode===0,...result})}case"settings":openPath(dashboardUrl("/settings"));return Response.json({ok:!0,message:"Opened dashboard settings"});case"check-updates":{const result=await runBuddy(project,["outdated"]);return Response.json({ok:result.exitCode===0,...result})}case"copy-ip":return Response.json({ok:!0,value:localIpAddress(),message:"IP address ready to copy"});case"open-dashboard":openPath(dashboardUrl());return Response.json({ok:!0,message:"Opened dashboard"});case"buddy-commands":{const result=await runBuddy(project,["list"]);return Response.json({ok:result.exitCode===0,...result})}case"deploy":{if(!input.confirmed)return Response.json({ok:!1,confirmationRequired:!0,error:"Deployment confirmation required"},{status:409});Bun.spawn([join(project,"buddy"),"deploy","--no-interaction"],{cwd:project,stdout:"inherit",stderr:"inherit"}).unref();return Response.json({ok:!0,message:`Deployment started for ${basename(project)}`})}case"deploy-logs":openPath(join(project,"storage/logs"));return Response.json({ok:!0,message:"Opened deployment logs"});case"site-logs":openPath(join(project,"storage/logs"));return Response.json({ok:!0,message:"Opened site logs"});case"error-logs":openPath(join(project,"storage/logs"));return Response.json({ok:!0,message:"Opened error logs"});case"edit-env":openPath(join(project,".env"));return Response.json({ok:!0,message:"Opened .env"});case"edit-dns":openPath(join(project,"config/dns.ts"));return Response.json({ok:!0,message:"Opened DNS configuration"});case"edit-email":openPath(join(project,"config/email.ts"));return Response.json({ok:!0,message:"Opened email configuration"});case"ask-buddy":openPath(dashboardUrl("/buddy"));return Response.json({ok:!0,message:"Opened Ask Buddy"});default:return Response.json({ok:!1,error:"Unknown tray action"},{status:400})}}const{serve}=await import("bun-plugin-stx/serve"),serverPromise=serve({patterns:[userTrayViews,trayViews],port,componentsDir:projectPath("resources/components"),additionalComponentsDirs:[defaultsPath("resources/components")],quiet:!0,auth:!1,routes:{"/api/tray/projects":async()=>Response.json({ok:!0,projects:await discoverProjects()}),"/api/tray/action":async(request)=>{if(request.method!=="POST")return Response.json({ok:!1,error:"Method not allowed"},{status:405});return handleAction(await request.json())}}});serverPromise.catch((error)=>{console.error(`System tray server failed: ${error.message}`);process.exit(1)});let proxyStarted=!1;if(trayDomain&&!process.env.STACKS_PROXY_MANAGED)try{const{startProxies}=await import("@stacksjs/rpx");await startProxies({proxies:[{from:`localhost:${port}`,to:trayDomain,cleanUrls:!1}],https:{basePath:`${process.env.HOME}/.stacks/ssl`,validityDays:825},regenerateUntrustedCerts:!1});proxyStarted=!0}catch{proxyStarted=!1}await waitForServer(port,2000);const url=trayDomain&&proxyStarted?`https://${trayDomain}`:localUrl;console.log();console.log(` ${bold(cyan("stacks tray"))}`);console.log();console.log(` ${green("\u279C")} ${bold("Local")}: ${cyan(url)}`);if(trayDomain)console.log(` ${dim("\u279C")} ${dim("Origin")}: ${dim(localUrl)}`);console.log();await openDevWindow(port,{url,title:"Stacks",width:440,height:680,systemTray:!0,hideDockIcon:!0,hotReload:!0});const stop=()=>{process.exit(0)};process.on("SIGINT",stop);process.on("SIGTERM",stop);await new Promise(()=>{});
@@ -1 +1 @@
1
- import{existsSync}from"node:fs";import{join}from"node:path";import process from"node:process";import{config}from"@stacksjs/config";import{log}from"@stacksjs/logging";import{projectPath,publicPath}from"@stacksjs/path";import{resolveComponentsLibraryRoot,resolveDefaultsRoot}from"../dev/defaults-resources";import{decideDashboardAccess}from"./dashboard-gate";process.env.APP_ENV||="production";process.env.NODE_ENV||="production";const port=Number(process.env.PORT_DASHBOARD||process.env.PORT)||3002,defaultsRoot=resolveDefaultsRoot(),frameworkDashboard=join(defaultsRoot,"views/dashboard"),appDashboard=projectPath("resources/views/dashboard"),{authCookieName}=await import("@stacksjs/auth"),authCookie=authCookieName();function readCookie(header,name){if(!header)return;for(const part of header.split(";")){const raw=part.trim(),eq=raw.indexOf("=");if(eq<1)continue;if(raw.slice(0,eq)===name)return decodeURIComponent(raw.slice(eq+1))}return}const{isApiBoundRequest,proxyToBackend,resolveApiBase,resolveApiProxyRules,viewClientAddress}=await import("@stacksjs/server"),apiBase=resolveApiBase(config.ports?.api),apiProxyRules=resolveApiProxyRules(config.server?.proxy),{Auth}=await import("@stacksjs/auth"),{registerPeerSource}=await import("@stacksjs/router"),{serve}=await import("bun-plugin-stx/serve");await serve({patterns:[appDashboard,frameworkDashboard].filter((dir)=>existsSync(dir)),port,layoutsDir:frameworkDashboard,partialsDir:frameworkDashboard,componentsDir:join(defaultsRoot,"resources/components/Dashboard"),fallbackComponentsDir:resolveComponentsLibraryRoot(),publicDir:publicPath(),quiet:!0,clientAddress:viewClientAddress,onRequest:async(req,server)=>{registerPeerSource(server);const url=new URL(req.url);if((await decideDashboardAccess({method:req.method,pathname:url.pathname,token:readCookie(req.headers.get("cookie"),authCookie)},(token)=>Auth.getUserFromToken(token))).allow){if(isApiBoundRequest(req,url.pathname,apiProxyRules)){if(!apiBase){log.error(`No API target configured for ${url.pathname}. This dashboard shares its host with other deployments, so there is no safe default port to guess - refusing to proxy. Set PORT_API (or API_URL) for this site.`);return new Response("Bad Gateway",{status:502})}try{return await proxyToBackend(req,apiBase)}catch(error){log.error(`API proxy to ${apiBase} failed: ${error.message}`);return new Response("Bad Gateway",{status:502})}}return null}const next=encodeURIComponent(url.pathname+url.search);return new Response(null,{status:302,headers:{location:`/login?next=${next}`,"cache-control":"no-store, private"}})}});console.log(`Dashboard server listening on port ${port}`);
1
+ import{existsSync}from"node:fs";import{join}from"node:path";import process from"node:process";import{config}from"@stacksjs/config";import{log}from"@stacksjs/logging";import{projectPath,publicPath}from"@stacksjs/path";import{resolveComponentsLibraryRoot,resolveDefaultsRoot}from"../dev/defaults-resources";import{decideDashboardAccess}from"./dashboard-gate";process.env.APP_ENV||="production";process.env.NODE_ENV||="production";const port=Number(process.env.PORT_DASHBOARD||process.env.PORT)||3002,defaultsRoot=resolveDefaultsRoot(),frameworkDashboard=join(defaultsRoot,"views/dashboard"),appDashboard=projectPath("resources/views/dashboard"),{authCookieName}=await import("@stacksjs/auth"),authCookie=authCookieName();function readCookie(header,name){if(!header)return;for(const part of header.split(";")){const raw=part.trim(),eq=raw.indexOf("=");if(eq<1)continue;if(raw.slice(0,eq)===name)return decodeURIComponent(raw.slice(eq+1))}return}const{isApiBoundRequest,proxyToBackend,resolveApiBase,resolveApiProxyRules,viewClientAddress}=await import("@stacksjs/server"),apiBase=resolveApiBase(config.ports?.api),apiProxyRules=resolveApiProxyRules(config.server?.proxy),{Auth}=await import("@stacksjs/auth"),{registerPeerSource}=await import("@stacksjs/router"),{serve}=await import("bun-plugin-stx/serve");await serve({patterns:[appDashboard,frameworkDashboard].filter((dir)=>existsSync(dir)),port,layoutsDir:join(appDashboard,"layouts"),fallbackLayoutsDir:join(frameworkDashboard,"layouts"),partialsDir:frameworkDashboard,componentsDir:projectPath("resources/components/Dashboard"),additionalComponentsDirs:[join(defaultsRoot,"resources/components/Dashboard")],fallbackComponentsDir:resolveComponentsLibraryRoot(),publicDir:publicPath(),quiet:!0,clientAddress:viewClientAddress,onRequest:async(req,server)=>{registerPeerSource(server);const url=new URL(req.url);if((await decideDashboardAccess({method:req.method,pathname:url.pathname,token:readCookie(req.headers.get("cookie"),authCookie)},(token)=>Auth.getUserFromToken(token))).allow){if(isApiBoundRequest(req,url.pathname,apiProxyRules)){if(!apiBase){log.error(`No API target configured for ${url.pathname}. This dashboard shares its host with other deployments, so there is no safe default port to guess - refusing to proxy. Set PORT_API (or API_URL) for this site.`);return new Response("Bad Gateway",{status:502})}try{return await proxyToBackend(req,apiBase)}catch(error){log.error(`API proxy to ${apiBase} failed: ${error.message}`);return new Response("Bad Gateway",{status:502})}}return null}const next=encodeURIComponent(url.pathname+url.search);return new Response(null,{status:302,headers:{location:`/login?next=${next}`,"cache-control":"no-store, private"}})}});console.log(`Dashboard server listening on port ${port}`);
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/actions",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.75.334",
5
+ "version": "0.75.336",
6
6
  "description": "The Stacks actions.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -66,55 +66,55 @@
66
66
  "prepublishOnly": "bun run build"
67
67
  },
68
68
  "dependencies": {
69
- "@stacksjs/action-runner": "0.75.334",
70
- "@stacksjs/ai": "0.75.334",
71
- "@stacksjs/analytics": "0.75.334",
72
- "@stacksjs/api": "0.75.334",
73
- "@stacksjs/auth": "0.75.334",
74
- "@stacksjs/build": "0.75.334",
69
+ "@stacksjs/action-runner": "0.75.336",
70
+ "@stacksjs/ai": "0.75.336",
71
+ "@stacksjs/analytics": "0.75.336",
72
+ "@stacksjs/api": "0.75.336",
73
+ "@stacksjs/auth": "0.75.336",
74
+ "@stacksjs/build": "0.75.336",
75
75
  "@stacksjs/bumpx": "^0.2.26",
76
76
  "@stacksjs/bunpress": "^0.2.15",
77
- "@stacksjs/cli": "0.75.334",
78
- "@stacksjs/cloud": "0.75.334",
79
- "@stacksjs/cms": "0.75.334",
80
- "@stacksjs/components": "0.2.723",
81
- "@stacksjs/config": "0.75.334",
82
- "@stacksjs/database": "0.75.334",
83
- "@stacksjs/desktop-build": "0.75.334",
84
- "@stacksjs/dns": "0.75.334",
85
- "@stacksjs/enums": "0.75.334",
86
- "@stacksjs/env": "0.75.334",
87
- "@stacksjs/error-handling": "0.75.334",
88
- "@stacksjs/github": "0.75.334",
77
+ "@stacksjs/cli": "0.75.336",
78
+ "@stacksjs/cloud": "0.75.336",
79
+ "@stacksjs/cms": "0.75.336",
80
+ "@stacksjs/components": "0.2.736",
81
+ "@stacksjs/config": "0.75.336",
82
+ "@stacksjs/database": "0.75.336",
83
+ "@stacksjs/desktop-build": "0.75.336",
84
+ "@stacksjs/dns": "0.75.336",
85
+ "@stacksjs/enums": "0.75.336",
86
+ "@stacksjs/env": "0.75.336",
87
+ "@stacksjs/error-handling": "0.75.336",
88
+ "@stacksjs/github": "0.75.336",
89
89
  "@stacksjs/gitit": "^0.2.5",
90
- "@stacksjs/i18n": "0.75.334",
91
- "@stacksjs/image": "0.75.334",
92
- "@stacksjs/logging": "0.75.334",
90
+ "@stacksjs/i18n": "0.75.336",
91
+ "@stacksjs/image": "0.75.336",
92
+ "@stacksjs/logging": "0.75.336",
93
93
  "@stacksjs/logsmith": "^0.2.11",
94
- "@stacksjs/mobile": "0.75.334",
95
- "@stacksjs/orm": "0.75.334",
96
- "@stacksjs/path": "0.75.334",
97
- "@stacksjs/payments": "0.75.334",
98
- "@stacksjs/queue": "0.75.334",
99
- "@stacksjs/registry": "0.75.334",
100
- "@stacksjs/router": "0.75.334",
94
+ "@stacksjs/mobile": "0.75.336",
95
+ "@stacksjs/orm": "0.75.336",
96
+ "@stacksjs/path": "0.75.336",
97
+ "@stacksjs/payments": "0.75.336",
98
+ "@stacksjs/queue": "0.75.336",
99
+ "@stacksjs/registry": "0.75.336",
100
+ "@stacksjs/router": "0.75.336",
101
101
  "@stacksjs/rpx": "^0.11.54",
102
- "@stacksjs/scheduler": "0.75.334",
103
- "@stacksjs/search-engine": "0.75.334",
104
- "@stacksjs/security": "0.75.334",
105
- "@stacksjs/server": "0.75.334",
106
- "@stacksjs/sites": "0.75.334",
107
- "@stacksjs/storage": "0.75.334",
108
- "@stacksjs/strings": "0.75.334",
109
- "@stacksjs/stx": "0.2.723",
102
+ "@stacksjs/scheduler": "0.75.336",
103
+ "@stacksjs/search-engine": "0.75.336",
104
+ "@stacksjs/security": "0.75.336",
105
+ "@stacksjs/server": "0.75.336",
106
+ "@stacksjs/sites": "0.75.336",
107
+ "@stacksjs/storage": "0.75.336",
108
+ "@stacksjs/strings": "0.75.336",
109
+ "@stacksjs/stx": "0.2.736",
110
110
  "@stacksjs/tlsx": "^0.13.19",
111
111
  "@stacksjs/ts-cloud": "^0.16.69",
112
112
  "@stacksjs/ts-md": "^0.1.1",
113
- "@stacksjs/tunnel": "0.75.334",
114
- "@stacksjs/types": "0.75.334",
115
- "@stacksjs/utils": "0.75.334",
116
- "@stacksjs/whois": "0.75.334",
117
- "bun-plugin-stx": "0.2.723"
113
+ "@stacksjs/tunnel": "0.75.336",
114
+ "@stacksjs/types": "0.75.336",
115
+ "@stacksjs/utils": "0.75.336",
116
+ "@stacksjs/whois": "0.75.336",
117
+ "bun-plugin-stx": "0.2.736"
118
118
  },
119
119
  "peerDependencies": {
120
120
  "craft-native": ">=0.0.341",
@@ -129,7 +129,7 @@
129
129
  }
130
130
  },
131
131
  "devDependencies": {
132
- "@stacksjs/validation": "0.75.334",
132
+ "@stacksjs/validation": "0.75.336",
133
133
  "better-dx": "^0.2.24"
134
134
  }
135
135
  }