@stacksjs/actions 0.75.515 → 0.75.519

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.
Files changed (151) hide show
  1. package/dist/action.js +1 -1
  2. package/dist/auth/client-options.js +1 -1
  3. package/dist/auth/client.js +1 -1
  4. package/dist/auth/prune.js +1 -1
  5. package/dist/auth/setup.js +2 -2
  6. package/dist/blog-admin.js +3 -3
  7. package/dist/blog.js +23 -23
  8. package/dist/build/android-config.js +1 -1
  9. package/dist/build/android-icons.js +1 -1
  10. package/dist/build/android.js +1 -1
  11. package/dist/build/component-library.js +1 -1
  12. package/dist/build/core.js +1 -1
  13. package/dist/build/craft-entry.js +1 -1
  14. package/dist/build/craft-provenance.js +1 -1
  15. package/dist/build/desktop-macos.js +2 -2
  16. package/dist/build/desktop.js +2 -2
  17. package/dist/build/dmg-macos.js +1 -1
  18. package/dist/build/dmg.js +1 -1
  19. package/dist/build/docs.js +1 -1
  20. package/dist/build/frontend-static.js +5 -5
  21. package/dist/build/ios-config.js +3 -3
  22. package/dist/build/ios-shell.js +3 -3
  23. package/dist/build/ios-toolchain.js +2 -2
  24. package/dist/build/ios.js +2 -2
  25. package/dist/build/macos-native.js +3 -3
  26. package/dist/build/mobile-splash.js +1 -1
  27. package/dist/build/mobile-target.js +1 -1
  28. package/dist/build/native-screens.js +1 -1
  29. package/dist/build/native-sensors.js +1 -1
  30. package/dist/build/notarize.js +2 -2
  31. package/dist/build/run-build-step.js +1 -1
  32. package/dist/build/stacks.js +1 -1
  33. package/dist/build/views.js +1 -1
  34. package/dist/build.js +1 -1
  35. package/dist/bump.js +7 -7
  36. package/dist/calendar-version.js +1 -1
  37. package/dist/changelog.js +1 -1
  38. package/dist/check/ports.js +1 -1
  39. package/dist/commit.js +1 -1
  40. package/dist/database/seed.js +1 -1
  41. package/dist/deploy/create-receipt-rule.js +1 -1
  42. package/dist/deploy/hooks.js +1 -1
  43. package/dist/deploy/index.js +17 -17
  44. package/dist/deploy/stack.js +6 -6
  45. package/dist/dev/api.js +1 -1
  46. package/dist/dev/components.js +1 -1
  47. package/dist/dev/csrf.js +1 -1
  48. package/dist/dev/dashboard-native.js +1 -1
  49. package/dist/dev/dashboard-request-routing.js +1 -1
  50. package/dist/dev/dashboard-supervisor.js +2 -2
  51. package/dist/dev/dashboard-utils.js +1 -1
  52. package/dist/dev/dashboard.js +4 -4
  53. package/dist/dev/defaults-resources.js +1 -1
  54. package/dist/dev/docs.js +1 -1
  55. package/dist/dev/exit-with-parent.js +1 -1
  56. package/dist/dev/migrate-watcher.js +1 -1
  57. package/dist/dev/system-tray.js +2 -2
  58. package/dist/dev/tray-origin.js +1 -1
  59. package/dist/dev/views.js +1 -1
  60. package/dist/discover-packages.js +1 -1
  61. package/dist/domains/add.js +1 -1
  62. package/dist/domains/purchase.js +1 -1
  63. package/dist/domains/remove.js +1 -1
  64. package/dist/examples.js +1 -1
  65. package/dist/find-projects.js +1 -1
  66. package/dist/generate/action-types.js +3 -3
  67. package/dist/generate/erd.js +2 -2
  68. package/dist/generate/ide-helpers.js +1 -1
  69. package/dist/generate/images.js +1 -1
  70. package/dist/generate/index.js +1 -1
  71. package/dist/generate/lib-entries.js +1 -1
  72. package/dist/generate/vschema.js +2 -2
  73. package/dist/github-release.js +5 -5
  74. package/dist/helpers/api-host.js +3 -3
  75. package/dist/helpers/api-shutdown.js +1 -1
  76. package/dist/helpers/component-meta.js +3 -3
  77. package/dist/helpers/utils.js +1 -1
  78. package/dist/helpers/vscode-custom-data.js +1 -1
  79. package/dist/key-generate.js +1 -1
  80. package/dist/library/build.js +2 -2
  81. package/dist/library/entries.js +1 -1
  82. package/dist/library/globals.js +1 -1
  83. package/dist/library/manifest.js +2 -2
  84. package/dist/library/packages.js +1 -1
  85. package/dist/library/publish.js +2 -2
  86. package/dist/library-publish.js +1 -1
  87. package/dist/lint/files.js +1 -1
  88. package/dist/lint/lint.js +1 -1
  89. package/dist/lint/stx-gate.js +3 -3
  90. package/dist/make-command.js +2 -2
  91. package/dist/make-job.js +2 -2
  92. package/dist/make-policy.js +2 -2
  93. package/dist/make-resource.js +1 -1
  94. package/dist/make.js +7 -7
  95. package/dist/migrate/database.js +1 -1
  96. package/dist/migrate/fresh.js +1 -1
  97. package/dist/pantry-lock.js +1 -1
  98. package/dist/pantry-toolchain.js +1 -1
  99. package/dist/project-scripts.js +1 -1
  100. package/dist/publication-preflight.js +1 -1
  101. package/dist/queue/clear.js +1 -1
  102. package/dist/queue/dlq-purge.js +1 -1
  103. package/dist/queue/dlq-retry.js +1 -1
  104. package/dist/queue/dlq.js +2 -2
  105. package/dist/queue/failed.js +2 -2
  106. package/dist/queue/flush.js +1 -1
  107. package/dist/queue/inspect.js +6 -6
  108. package/dist/queue/list.js +2 -2
  109. package/dist/queue/monitor.js +5 -5
  110. package/dist/queue/options.js +1 -1
  111. package/dist/queue/pause.js +1 -1
  112. package/dist/queue/quarantine.js +1 -1
  113. package/dist/queue/resume.js +1 -1
  114. package/dist/queue/retry.js +1 -1
  115. package/dist/queue/schedule-list.js +2 -2
  116. package/dist/queue/status.js +2 -2
  117. package/dist/queue/unquarantine.js +1 -1
  118. package/dist/queue/work.js +1 -1
  119. package/dist/release-evidence.js +1 -1
  120. package/dist/release-notes.js +5 -5
  121. package/dist/release-preflight.js +2 -2
  122. package/dist/release-push-target.js +3 -3
  123. package/dist/release.js +1 -1
  124. package/dist/reviewos-evidence.js +1 -1
  125. package/dist/route/list.js +1 -1
  126. package/dist/saas/setup.js +1 -1
  127. package/dist/scaffold-crud.js +7 -7
  128. package/dist/search/flush.js +1 -1
  129. package/dist/search/import.js +1 -1
  130. package/dist/search/settings-list.js +1 -1
  131. package/dist/seo.js +4 -4
  132. package/dist/serve/api.js +1 -1
  133. package/dist/serve/dashboard-gate.js +1 -1
  134. package/dist/serve/dashboard.js +1 -1
  135. package/dist/setup/ssl.js +2 -2
  136. package/dist/stacks.js +1 -1
  137. package/dist/stx-source.js +1 -1
  138. package/dist/test/feature.js +1 -1
  139. package/dist/test/runner.js +1 -1
  140. package/dist/test/unit.js +1 -1
  141. package/dist/upgrade/binary.js +1 -1
  142. package/dist/upgrade/framework-hooks.d.ts +6 -0
  143. package/dist/upgrade/framework-hooks.js +1 -1
  144. package/dist/upgrade/framework-utils.js +2 -2
  145. package/dist/upgrade/framework.js +10 -10
  146. package/dist/upgrade/package-project.js +2 -2
  147. package/dist/upgrade/packages.js +23 -22
  148. package/dist/upgrade/route-actions.js +3 -3
  149. package/dist/upgrade/shell.js +4 -4
  150. package/dist/upgrade.js +1 -1
  151. package/package.json +40 -40
@@ -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";import{isTrustedTrayRequest,trayOrigins}from"./tray-origin";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}`,allowedOrigins=trayOrigins(port,trayDomain);function forbidden(request){return isTrustedTrayRequest(request,allowedOrigins)?null:Response.json({ok:!1,error:"This request did not come from the system tray"},{status:403})}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(request)=>forbidden(request)??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 forbidden(request)??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";import{isTrustedTrayRequest,trayOrigins}from"./tray-origin";const preferredPort=Number(process.env.PORT_SYSTEM_TRAY)||3009;const port=await findAvailablePort(preferredPort);const trayViews=defaultsPath("views/system-tray");const userTrayViews=projectPath("resources/views/system-tray");const appUrl=process.env.APP_URL||"stacks.test";const domain=appUrl.replace(/^https?:\/\//,"").replace(/\/$/,"");const hasPrettyDomain=!domain.includes("localhost:")&&domain!=="localhost";const trayDomain=hasPrettyDomain?`tray.${domain}`:null;const localUrl=`http://localhost:${port}`;const allowedOrigins=trayOrigins(port,trayDomain);function forbidden(request){return isTrustedTrayRequest(request,allowedOrigins)?null:Response.json({ok:false,error:"This request did not come from the system tray"},{status:403})}let cachedProjects;async function discoverProjects(refresh=false){if(cachedProjects&&!refresh)return cachedProjects;const discovered=await findStacksProjects(join(homedir(),"Code"),{quiet:true}).catch(()=>[]);const candidates=[...new Set([projectPath(),...discovered])];const checks=await Promise.all(candidates.map(async(project)=>({project,valid:await Bun.file(join(project,"buddy")).exists()})));cachedProjects=checks.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"});const[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=""){const base=hasPrettyDomain?`https://dashboard.${domain}`:`http://localhost:${Number(process.env.PORT_ADMIN)||3002}`;return`${base}${path}`}async function handleAction(input){const projects=await discoverProjects();const project=input.project||projectPath();if(!projects.includes(project))return Response.json({ok:false,error:"Unknown Stacks project"},{status:400});switch(input.action){case"refresh":return Response.json({ok:true,projects:await discoverProjects(true)});case"open-terminal":openTerminal(project);return Response.json({ok:true,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:true,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:true,value:localIpAddress(),message:"IP address ready to copy"});case"open-dashboard":openPath(dashboardUrl());return Response.json({ok:true,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:false,confirmationRequired:true,error:"Deployment confirmation required"},{status:409});const child=Bun.spawn([join(project,"buddy"),"deploy","--no-interaction"],{cwd:project,stdout:"inherit",stderr:"inherit"});child.unref();return Response.json({ok:true,message:`Deployment started for ${basename(project)}`})}case"deploy-logs":openPath(join(project,"storage/logs"));return Response.json({ok:true,message:"Opened deployment logs"});case"site-logs":openPath(join(project,"storage/logs"));return Response.json({ok:true,message:"Opened site logs"});case"error-logs":openPath(join(project,"storage/logs"));return Response.json({ok:true,message:"Opened error logs"});case"edit-env":openPath(join(project,".env"));return Response.json({ok:true,message:"Opened .env"});case"edit-dns":openPath(join(project,"config/dns.ts"));return Response.json({ok:true,message:"Opened DNS configuration"});case"edit-email":openPath(join(project,"config/email.ts"));return Response.json({ok:true,message:"Opened email configuration"});case"ask-buddy":openPath(dashboardUrl("/buddy"));return Response.json({ok:true,message:"Opened Ask Buddy"});default:return Response.json({ok:false,error:"Unknown tray action"},{status:400})}}const{serve}=await import("bun-plugin-stx/serve");const serverPromise=serve({patterns:[userTrayViews,trayViews],port,componentsDir:projectPath("resources/components"),additionalComponentsDirs:[defaultsPath("resources/components")],quiet:true,auth:false,routes:{"/api/tray/projects":async(request)=>forbidden(request)??Response.json({ok:true,projects:await discoverProjects()}),"/api/tray/action":async(request)=>{if(request.method!=="POST")return Response.json({ok:false,error:"Method not allowed"},{status:405});return forbidden(request)??handleAction(await request.json())}}});serverPromise.catch((error)=>{console.error(`System tray server failed: ${error.message}`);process.exit(1)});let proxyStarted=false;if(trayDomain&&!process.env.STACKS_PROXY_MANAGED){try{const{startProxies}=await import("@stacksjs/rpx");await startProxies({proxies:[{from:`localhost:${port}`,to:trayDomain,cleanUrls:false}],https:{basePath:`${process.env.HOME}/.stacks/ssl`,validityDays:825},regenerateUntrustedCerts:false});proxyStarted=true}catch{proxyStarted=false}}await waitForServer(port,2000);const url=trayDomain&&proxyStarted?`https://${trayDomain}`:localUrl;console.log();console.log(` ${bold(cyan("stacks tray"))}`);console.log();console.log(` ${green("➜")} ${bold("Local")}: ${cyan(url)}`);if(trayDomain)console.log(` ${dim("➜")} ${dim("Origin")}: ${dim(localUrl)}`);console.log();await openDevWindow(port,{url,title:"Stacks",width:440,height:680,systemTray:true,hideDockIcon:true,hotReload:true});const stop=()=>{process.exit(0)};process.on("SIGINT",stop);process.on("SIGTERM",stop);await new Promise(()=>{});
@@ -1 +1 @@
1
- export function isTrustedTrayRequest(request,trayOrigins){const origin=request.headers.get("origin");if(origin!==null&&!trayOrigins.includes(origin))return!1;if(request.method==="GET"||request.method==="HEAD")return!0;return(request.headers.get("content-type")??"").split(";")[0].trim().toLowerCase()==="application/json"}export function trayOrigins(port,trayDomain){const origins=[`http://localhost:${port}`,`http://127.0.0.1:${port}`];if(trayDomain)origins.push(`https://${trayDomain}`);return origins}
1
+ export function isTrustedTrayRequest(request,trayOrigins){const origin=request.headers.get("origin");if(origin!==null&&!trayOrigins.includes(origin))return false;if(request.method==="GET"||request.method==="HEAD")return true;const type=(request.headers.get("content-type")??"").split(";")[0].trim().toLowerCase();return type==="application/json"}export function trayOrigins(port,trayDomain){const origins=[`http://localhost:${port}`,`http://127.0.0.1:${port}`];if(trayDomain)origins.push(`https://${trayDomain}`);return origins}
package/dist/dev/views.js CHANGED
@@ -1 +1 @@
1
- import{existsSync}from"node:fs";import{join}from"node:path";import{config,enterRequestScope,feature,installRequestScope,overridesReady,resolveViewPatterns}from"@stacksjs/config";import{log}from"@stacksjs/logging";import{projectPath,siteConfigPath}from"@stacksjs/path";import{serverRequestBodyOptions}from"@stacksjs/server/request-body";import{seedCsrfPageResponse}from"./csrf";import{resolveDefaultsResources}from"./defaults-resources";import{exitWithParent}from"./exit-with-parent";import{beginRequestCapture,finishRequestCapture}from"@stacksjs/router/request-capture";installRequestScope();exitWithParent();const projectServe=projectPath("serve.ts");try{if(await Bun.file(projectServe).exists())await import(projectServe);else await startDefaultServer()}catch{await startDefaultServer()}async function startDefaultServer(){await overridesReady;const{applyResponseHeaders,applyViewSecurityHeaders,describeApiProxyRules,describeRedirectRules,describeRewriteRules,injectGlobalAutoImports,isApiBoundRequest,loadRouteRedirects,proxyToBackend,resolveApiProxyRules,resolveEmbeddableRules,resolveRedirect,resolveRedirectRules,resolveRewrite,resolveRewriteRules,viewClientAddress}=await import("@stacksjs/server"),{applyRequestLocale}=await import("@stacksjs/i18n");await injectGlobalAutoImports();const{serve}=await import("bun-plugin-stx/serve"),{site:siteConfig,i18n:i18nConfig}=await loadStxSiteConfig(),defaultsResources=resolveDefaultsResources(),userViewsPath="resources/views",defaultViewsPath=join(defaultsResources,"views"),userComponentsPath=await firstExistingPath(["resources/components","components"])??"resources/components",userLayoutsPath=await firstExistingPath(["resources/views/layouts","resources/layouts"])??"resources/views/layouts",defaultLayoutsPath=join(defaultsResources,"layouts"),userPartialsPath=await firstExistingPath(["resources/partials","resources/views/partials","partials","resources/components"]),preferredPort=Number(process.env.PORT)||3000,apiPort=Number(process.env.PORT_API)||3008,docsPort=Number(process.env.PORT_DOCS)||config.ports?.docs||3006,apiBase=`http://127.0.0.1:${apiPort}`,docsBase=`http://127.0.0.1:${docsPort}`,apiProxyRules=resolveApiProxyRules(config.server?.proxy),redirectRules=resolveRedirectRules({...await loadRouteRedirects(),...config.server?.redirects}),rewriteRules=resolveRewriteRules(config.server?.rewrites),embeddableRules=resolveEmbeddableRules(config.server?.security?.embeddable);if(apiProxyRules.paths.length>0||apiProxyRules.prefixes.length>1)console.log(` API proxy: ${describeApiProxyRules(apiProxyRules)}`);if(embeddableRules.paths.length>0||embeddableRules.prefixes.length>0)console.log(` Frameable by other origins: ${[...embeddableRules.paths,...embeddableRules.prefixes].join(" ")}`);if(redirectRules.size>0)console.log(` Redirects: ${describeRedirectRules(redirectRules)}`);if(rewriteRules.size>0)console.log(` Rewrites: ${describeRewriteRules(rewriteRules)}`);const{createSiteSeoHandler,describeSeoAtBoot}=await import("../seo"),seoOptions={root:projectPath(),seo:config.app?.seo,appUrl:config.app?.url},siteSeo=createSiteSeoHandler({...seoOptions,cacheTtlMs:0});for(const note of await describeSeoAtBoot(seoOptions).catch(()=>[]))log.warn(note);const hasUserDocsView=["docs.stx","docs/index.stx"].some((rel)=>existsSync(projectPath(`${userViewsPath}/${rel}`))),hasDocsSite=existsSync(projectPath("docs")),docsProxyEnabled=!hasUserDocsView&&hasDocsSite,{authCookieName,stxPageAuthMiddleware}=await import("@stacksjs/auth"),{enhanceRequest,loadMiddlewareHandlers,registerPeerSource}=await import("@stacksjs/router"),authCookie=authCookieName(),pageMiddleware=await loadMiddlewareHandlers(),{mountedDefaultRouteBundles}=await import("@stacksjs/router"),viewPatterns=resolveViewPatterns(userViewsPath,defaultViewsPath,config?.ui?.defaultViews,(path)=>existsSync(projectPath(path)),void 0,mountedDefaultRouteBundles(feature));for(const name of viewPatterns.missing)log.warn(`ui.defaultViews lists "${name}", which does not exist under ${defaultViewsPath} - ignoring.`);if(viewPatterns.withheld.length>0)log.debug(`Default views without a mounted route bundle behind them, not served: ${viewPatterns.withheld.join(", ")}`);await serve({...serverRequestBodyOptions(config.server?.maxRequestBodySize),patterns:viewPatterns.patterns,exclude:viewPatterns.exclude,port:preferredPort,componentsDir:userComponentsPath,fallbackComponentsDir:join(defaultsResources,"components"),layoutsDir:userLayoutsPath,...userPartialsPath&&{partialsDir:userPartialsPath},fallbackLayoutsDir:defaultLayoutsPath,fallbackPartialsDir:defaultViewsPath,quiet:!0,openPath:process.env.STACKS_DEV_ENTRY_PATH||"/",...i18nConfig&&{i18n:i18nConfig},...siteConfig?.url&&{site:siteConfig},...config.server?.domains&&{domains:config.server.domains},auth:{cookieName:authCookie,redirectTo:"/login"},middleware:{...pageMiddleware,...stxPageAuthMiddleware({cookieName:authCookie,redirectTo:"/login"})},prepareMiddlewareRequest:(request)=>enhanceRequest(request),clientAddress:viewClientAddress,onRequest:async(req,server)=>{beginRequestCapture(req);const snapshot=enterRequestScope(req);registerPeerSource(server);const url=new URL(req.url),{maintenanceGate}=await import("@stacksjs/server"),gated=await maintenanceGate(req);if(gated)return gated;const redirected=resolveRedirect(url,redirectRules);if(redirected)return redirected;const rewritten=resolveRewrite(url.pathname,rewriteRules);if(rewritten){const target=new URL(`${rewritten}${url.search}`,url.origin);return proxyToBackend(new Request(target,req),apiBase,void 0,req)}const seoFile=await siteSeo(req);if(seoFile)return seoFile;if(existsSync(projectPath("resources/views/blog.stx"))){const{renderBlogFeed}=await import("../blog"),feed=await renderBlogFeed(req);if(feed)return feed}else{const{renderBlog}=await import("../blog"),blogResponse=await renderBlog(req);if(blogResponse)return blogResponse}if(docsProxyEnabled&&(url.pathname==="/docs"||url.pathname.startsWith("/docs/")))return proxyToBackend(req,docsBase,"/docs");if(isApiBoundRequest(req,url.pathname,apiProxyRules))return proxyToBackend(req,apiBase);if(i18nConfig&&req.method==="GET"){const localeSwitch=url.pathname.match(/^\/locale\/([a-z]{2}(?:-[a-z]{2})?)\/?$/i);if(localeSwitch){const{createLocaleSwitchResponse}=await import("@stacksjs/i18n");return createLocaleSwitchResponse(req,localeSwitch[1],i18nConfig)}}snapshot.locale=await applyRequestLocale(req);if(config.sites?.enabled){const sites=await import("@stacksjs/sites"),resolved=await sites.resolveSiteByHost(sites.requestHost(req.headers,sites.sitesOptions()));sites.setCurrentSite(resolved);snapshot.site=sites.toSiteSnapshot(resolved)}if(config.analytics?.capturePageviews)import("@stacksjs/analytics").then(({recordPageview})=>recordPageview(req)).catch(()=>{});return null},onResponse:async(req,response)=>{const securityResponse=applyViewSecurityHeaders(req,response,embeddableRules),secured=applyResponseHeaders(req,securityResponse??response,config.server?.headers)??securityResponse,baseline=secured??response;let current=baseline;if(current.status===404&&config.sites?.enabled)try{const{cmsNotFoundFallback}=await import("@stacksjs/cms"),cmsResponse=await cmsNotFoundFallback(req);if(cmsResponse)current=cmsResponse}catch(error){log.debug(`CMS fallback skipped: ${error.message}`)}const seeded=await seedCsrfPageResponse(req,current);finishRequestCapture(req,seeded??current);return seeded??(current===baseline?secured:current)}})}async function firstExistingPath(candidates){const existing=candidates.filter((candidate)=>existsSync(projectPath(candidate)));if(existing.length===0)return null;for(const candidate of existing)if(containsTemplates(projectPath(candidate)))return candidate;return existing[0]}function containsTemplates(dir){try{return[...new Bun.Glob("**/*.stx").scanSync({cwd:dir,onlyFiles:!0})].length>0}catch{return!1}}function fallbackI18nFromSite(site){const locales=site.i18n.locales,defaultLocale=site.i18n.defaultLocale??locales[0];return{locales,defaultLocale,labels:site.i18n.labels??Object.fromEntries(locales.map((c)=>[c,c.toUpperCase()])),translations:{},pickerSelector:site.i18n.pickerSelector??"#lang-picker"}}async function resolveSiteI18n(site){try{const{resolveI18n}=await import("@stacksjs/stx");if(typeof resolveI18n==="function"){const i18n=resolveI18n(site,projectPath());if(i18n)return i18n}}catch{}return fallbackI18nFromSite(site)}async function loadStxSiteConfig(){const sitePath=siteConfigPath();if(!existsSync(sitePath))return{};try{const mod=await import(sitePath),site=mod.default??mod.site??mod.config;if(!site)return{};if(!site.i18n)return{site};const i18n=await resolveSiteI18n(site);return{site,i18n}}catch{}return{}}
1
+ import{existsSync}from"node:fs";import{join}from"node:path";import{config,enterRequestScope,feature,installRequestScope,overridesReady,resolveViewPatterns}from"@stacksjs/config";import{log}from"@stacksjs/logging";import{projectPath,siteConfigPath}from"@stacksjs/path";import{serverRequestBodyOptions}from"@stacksjs/server/request-body";import{seedCsrfPageResponse}from"./csrf";import{resolveDefaultsResources}from"./defaults-resources";import{exitWithParent}from"./exit-with-parent";import{beginRequestCapture,finishRequestCapture}from"@stacksjs/router/request-capture";installRequestScope();exitWithParent();const projectServe=projectPath("serve.ts");try{const file=Bun.file(projectServe);if(await file.exists()){await import(projectServe)}else{await startDefaultServer()}}catch{await startDefaultServer()}async function startDefaultServer(){await overridesReady;const{applyResponseHeaders,applyViewSecurityHeaders,describeApiProxyRules,describeRedirectRules,describeRewriteRules,injectGlobalAutoImports,isApiBoundRequest,loadRouteRedirects,proxyToBackend,resolveApiProxyRules,resolveEmbeddableRules,resolveRedirect,resolveRedirectRules,resolveRewrite,resolveRewriteRules,viewClientAddress}=await import("@stacksjs/server");const{applyRequestLocale}=await import("@stacksjs/i18n");await injectGlobalAutoImports();const{serve}=await import("bun-plugin-stx/serve");const{site:siteConfig,i18n:i18nConfig}=await loadStxSiteConfig();const defaultsResources=resolveDefaultsResources();const userViewsPath="resources/views";const defaultViewsPath=join(defaultsResources,"views");const userComponentsPath=await firstExistingPath(["resources/components","components"])??"resources/components";const userLayoutsPath=await firstExistingPath(["resources/views/layouts","resources/layouts"])??"resources/views/layouts";const defaultLayoutsPath=join(defaultsResources,"layouts");const userPartialsPath=await firstExistingPath(["resources/partials","resources/views/partials","partials","resources/components"]);const preferredPort=Number(process.env.PORT)||3000;const apiPort=Number(process.env.PORT_API)||3008;const docsPort=Number(process.env.PORT_DOCS)||config.ports?.docs||3006;const apiBase=`http://127.0.0.1:${apiPort}`;const docsBase=`http://127.0.0.1:${docsPort}`;const apiProxyRules=resolveApiProxyRules(config.server?.proxy);const redirectRules=resolveRedirectRules({...await loadRouteRedirects(),...config.server?.redirects});const rewriteRules=resolveRewriteRules(config.server?.rewrites);const embeddableRules=resolveEmbeddableRules(config.server?.security?.embeddable);if(apiProxyRules.paths.length>0||apiProxyRules.prefixes.length>1){console.log(` API proxy: ${describeApiProxyRules(apiProxyRules)}`)}if(embeddableRules.paths.length>0||embeddableRules.prefixes.length>0){console.log(` Frameable by other origins: ${[...embeddableRules.paths,...embeddableRules.prefixes].join(" ")}`)}if(redirectRules.size>0){console.log(` Redirects: ${describeRedirectRules(redirectRules)}`)}if(rewriteRules.size>0){console.log(` Rewrites: ${describeRewriteRules(rewriteRules)}`)}const{createSiteSeoHandler,describeSeoAtBoot}=await import("../seo");const seoOptions={root:projectPath(),seo:config.app?.seo,appUrl:config.app?.url};const siteSeo=createSiteSeoHandler({...seoOptions,cacheTtlMs:0});for(const note of await describeSeoAtBoot(seoOptions).catch(()=>[]))log.warn(note);const hasUserDocsView=["docs.stx","docs/index.stx"].some((rel)=>existsSync(projectPath(`${userViewsPath}/${rel}`)));const hasDocsSite=existsSync(projectPath("docs"));const docsProxyEnabled=!hasUserDocsView&&hasDocsSite;const{authCookieName,stxPageAuthMiddleware}=await import("@stacksjs/auth");const{enhanceRequest,loadMiddlewareHandlers,registerPeerSource}=await import("@stacksjs/router");const authCookie=authCookieName();const pageMiddleware=await loadMiddlewareHandlers();const{mountedDefaultRouteBundles}=await import("@stacksjs/router");const viewPatterns=resolveViewPatterns(userViewsPath,defaultViewsPath,config?.ui?.defaultViews,(path)=>existsSync(projectPath(path)),undefined,mountedDefaultRouteBundles(feature));for(const name of viewPatterns.missing)log.warn(`ui.defaultViews lists "${name}", which does not exist under ${defaultViewsPath} - ignoring.`);if(viewPatterns.withheld.length>0)log.debug(`Default views without a mounted route bundle behind them, not served: ${viewPatterns.withheld.join(", ")}`);await serve({...serverRequestBodyOptions(config.server?.maxRequestBodySize),patterns:viewPatterns.patterns,exclude:viewPatterns.exclude,port:preferredPort,componentsDir:userComponentsPath,fallbackComponentsDir:join(defaultsResources,"components"),layoutsDir:userLayoutsPath,...userPartialsPath&&{partialsDir:userPartialsPath},fallbackLayoutsDir:defaultLayoutsPath,fallbackPartialsDir:defaultViewsPath,quiet:true,openPath:process.env.STACKS_DEV_ENTRY_PATH||"/",...i18nConfig&&{i18n:i18nConfig},...siteConfig?.url&&{site:siteConfig},...config.server?.domains&&{domains:config.server.domains},auth:{cookieName:authCookie,redirectTo:"/login"},middleware:{...pageMiddleware,...stxPageAuthMiddleware({cookieName:authCookie,redirectTo:"/login"})},prepareMiddlewareRequest:(request)=>enhanceRequest(request),clientAddress:viewClientAddress,onRequest:async(req,server)=>{beginRequestCapture(req);const snapshot=enterRequestScope(req);registerPeerSource(server);const url=new URL(req.url);const{maintenanceGate}=await import("@stacksjs/server");const gated=await maintenanceGate(req);if(gated)return gated;const redirected=resolveRedirect(url,redirectRules);if(redirected)return redirected;const rewritten=resolveRewrite(url.pathname,rewriteRules);if(rewritten){const target=new URL(`${rewritten}${url.search}`,url.origin);return proxyToBackend(new Request(target,req),apiBase,undefined,req)}const seoFile=await siteSeo(req);if(seoFile)return seoFile;if(existsSync(projectPath("resources/views/blog.stx"))){const{renderBlogFeed}=await import("../blog");const feed=await renderBlogFeed(req);if(feed)return feed}else{const{renderBlog}=await import("../blog");const blogResponse=await renderBlog(req);if(blogResponse)return blogResponse}if(docsProxyEnabled&&(url.pathname==="/docs"||url.pathname.startsWith("/docs/")))return proxyToBackend(req,docsBase,"/docs");if(isApiBoundRequest(req,url.pathname,apiProxyRules))return proxyToBackend(req,apiBase);if(i18nConfig&&req.method==="GET"){const localeSwitch=url.pathname.match(/^\/locale\/([a-z]{2}(?:-[a-z]{2})?)\/?$/i);if(localeSwitch){const{createLocaleSwitchResponse}=await import("@stacksjs/i18n");return createLocaleSwitchResponse(req,localeSwitch[1],i18nConfig)}}snapshot.locale=await applyRequestLocale(req);if(config.sites?.enabled){const sites=await import("@stacksjs/sites");const resolved=await sites.resolveSiteByHost(sites.requestHost(req.headers,sites.sitesOptions()));sites.setCurrentSite(resolved);snapshot.site=sites.toSiteSnapshot(resolved)}if(config.analytics?.capturePageviews){import("@stacksjs/analytics").then(({recordPageview})=>recordPageview(req)).catch(()=>{})}return null},onResponse:async(req,response)=>{const securityResponse=applyViewSecurityHeaders(req,response,embeddableRules);const secured=applyResponseHeaders(req,securityResponse??response,config.server?.headers)??securityResponse;const baseline=secured??response;let current=baseline;if(current.status===404&&config.sites?.enabled){try{const{cmsNotFoundFallback}=await import("@stacksjs/cms");const cmsResponse=await cmsNotFoundFallback(req);if(cmsResponse)current=cmsResponse}catch(error){log.debug(`CMS fallback skipped: ${error.message}`)}}const seeded=await seedCsrfPageResponse(req,current);finishRequestCapture(req,seeded??current);return seeded??(current===baseline?secured:current)}})}async function firstExistingPath(candidates){const existing=candidates.filter((candidate)=>existsSync(projectPath(candidate)));if(existing.length===0)return null;for(const candidate of existing){if(containsTemplates(projectPath(candidate)))return candidate}return existing[0]}function containsTemplates(dir){try{return[...new Bun.Glob("**/*.stx").scanSync({cwd:dir,onlyFiles:true})].length>0}catch{return false}}function fallbackI18nFromSite(site){const locales=site.i18n.locales;const defaultLocale=site.i18n.defaultLocale??locales[0];return{locales,defaultLocale,labels:site.i18n.labels??Object.fromEntries(locales.map((c)=>[c,c.toUpperCase()])),translations:{},pickerSelector:site.i18n.pickerSelector??"#lang-picker"}}async function resolveSiteI18n(site){try{const{resolveI18n}=await import("@stacksjs/stx");if(typeof resolveI18n==="function"){const i18n=resolveI18n(site,projectPath());if(i18n)return i18n}}catch{}return fallbackI18nFromSite(site)}async function loadStxSiteConfig(){const sitePath=siteConfigPath();if(!existsSync(sitePath))return{};try{const mod=await import(sitePath);const site=mod.default??mod.site??mod.config;if(!site)return{};if(!site.i18n)return{site};const i18n=await resolveSiteI18n(site);return{site,i18n}}catch{}return{}}
@@ -1,2 +1,2 @@
1
- import{existsSync,renameSync,unlinkSync}from"node:fs";import process from"node:process";import{isAbsolute,join,relative}from"node:path";import{projectPath,storagePath}from"@stacksjs/path";async function readManifest(file){try{return await Bun.file(file).json()}catch{return null}}async function directDependencies(projectRoot){const pkg=await readManifest(join(projectRoot,"package.json"));if(!pkg)return[];const names=new Set;for(const field of["dependencies","devDependencies","peerDependencies"]){const block=pkg[field];if(block&&typeof block==="object")for(const name of Object.keys(block))names.add(name)}return[...names].sort()}async function fromNodeModules(projectRoot){const root=join(projectRoot,"node_modules");if(!existsSync(root))return[];const out=[];for(const name of await directDependencies(projectRoot)){const dir=join(root,name),pkg=await readManifest(join(dir,"package.json"));if(!pkg?.name||!pkg.stacks||typeof pkg.stacks!=="object")continue;out.push({name:pkg.name,meta:pkg.stacks,dir})}return out}async function fromPantry(projectRoot){const root=join(projectRoot,"pantry");if(!existsSync(root))return[];const out=[];for(const pattern of["*/package.json","@*/*/package.json"]){const glob=new Bun.Glob(pattern);for await(const file of glob.scan({cwd:root,absolute:!0,onlyFiles:!0})){const pkg=await readManifest(file);if(!pkg?.name||!pkg.stacks||typeof pkg.stacks!=="object")continue;out.push({name:pkg.name,meta:pkg.stacks,dir:join(file,"..")})}}return out.sort((a,b)=>a.name.localeCompare(b.name))}async function dontDiscover(projectRoot){const list=(await readManifest(join(projectRoot,"package.json")))?.stacks?.["dont-discover"];return new Set(Array.isArray(list)?list:[])}export async function discoverPackages(options={}){const projectRoot=options.projectRoot??projectPath(),manifestPath=options.manifestPath??storagePath("framework/discovered-packages.json"),excluded=await dontDiscover(projectRoot),found=[...await fromNodeModules(projectRoot),...await fromPantry(projectRoot)],packages={},shadowed=[],chosen=new Map;for(const candidate of found){if(excluded.has(candidate.name))continue;const root=toRelative(projectRoot,candidate.dir),already=chosen.get(candidate.name);if(already!==void 0){shadowed.push({name:candidate.name,used:already,ignored:root});continue}chosen.set(candidate.name,root);packages[candidate.name]={...candidate.meta,root}}const manifest={generated_at:new Date().toISOString(),packages,...shadowed.length>0?{shadowed}:{}};if(options.dryRun)return manifest;try{const current=await Bun.file(manifestPath).json();if(JSON.stringify(current.packages??{})===JSON.stringify(manifest.packages)&&JSON.stringify(current.shadowed??[])===JSON.stringify(shadowed))return current}catch{}const temp=`${manifestPath}.${process.pid}.tmp`;try{await Bun.write(temp,`${JSON.stringify(manifest,null,2)}
1
+ import{existsSync,renameSync,unlinkSync}from"node:fs";import process from"node:process";import{isAbsolute,join,relative}from"node:path";import{projectPath,storagePath}from"@stacksjs/path";async function readManifest(file){try{return await Bun.file(file).json()}catch{return null}}async function directDependencies(projectRoot){const pkg=await readManifest(join(projectRoot,"package.json"));if(!pkg)return[];const names=new Set;for(const field of["dependencies","devDependencies","peerDependencies"]){const block=pkg[field];if(block&&typeof block==="object"){for(const name of Object.keys(block))names.add(name)}}return[...names].sort()}async function fromNodeModules(projectRoot){const root=join(projectRoot,"node_modules");if(!existsSync(root))return[];const out=[];for(const name of await directDependencies(projectRoot)){const dir=join(root,name);const pkg=await readManifest(join(dir,"package.json"));if(!pkg?.name||!pkg.stacks||typeof pkg.stacks!=="object")continue;out.push({name:pkg.name,meta:pkg.stacks,dir})}return out}async function fromPantry(projectRoot){const root=join(projectRoot,"pantry");if(!existsSync(root))return[];const out=[];for(const pattern of["*/package.json","@*/*/package.json"]){const glob=new Bun.Glob(pattern);for await(const file of glob.scan({cwd:root,absolute:true,onlyFiles:true})){const pkg=await readManifest(file);if(!pkg?.name||!pkg.stacks||typeof pkg.stacks!=="object")continue;out.push({name:pkg.name,meta:pkg.stacks,dir:join(file,"..")})}}return out.sort((a,b)=>a.name.localeCompare(b.name))}async function dontDiscover(projectRoot){const pkg=await readManifest(join(projectRoot,"package.json"));const list=pkg?.stacks?.["dont-discover"];return new Set(Array.isArray(list)?list:[])}export async function discoverPackages(options={}){const projectRoot=options.projectRoot??projectPath();const manifestPath=options.manifestPath??storagePath("framework/discovered-packages.json");const excluded=await dontDiscover(projectRoot);const found=[...await fromNodeModules(projectRoot),...await fromPantry(projectRoot)];const packages={};const shadowed=[];const chosen=new Map;for(const candidate of found){if(excluded.has(candidate.name))continue;const root=toRelative(projectRoot,candidate.dir);const already=chosen.get(candidate.name);if(already!==undefined){shadowed.push({name:candidate.name,used:already,ignored:root});continue}chosen.set(candidate.name,root);packages[candidate.name]={...candidate.meta,root}}const manifest={generated_at:new Date().toISOString(),packages,...shadowed.length>0?{shadowed}:{}};if(options.dryRun)return manifest;try{const current=await Bun.file(manifestPath).json();if(JSON.stringify(current.packages??{})===JSON.stringify(manifest.packages)&&JSON.stringify(current.shadowed??[])===JSON.stringify(shadowed)){return current}}catch{}const temp=`${manifestPath}.${process.pid}.tmp`;try{await Bun.write(temp,`${JSON.stringify(manifest,null,2)}
2
2
  `);renameSync(temp,manifestPath)}catch(error){try{unlinkSync(temp)}catch{}throw error}return manifest}export async function ensureDiscoveredPackages(){try{await discoverPackages()}catch(error){const{log}=await import("@stacksjs/logging");log.warn(`[discovery] Could not refresh the package manifest: ${error instanceof Error?error.message:String(error)}`)}}function toRelative(projectRoot,dir){const rel=relative(projectRoot,dir);return rel&&!rel.startsWith("..")&&!isAbsolute(rel)?rel:dir}
@@ -1 +1 @@
1
- import process from"node:process";import{italic,log,parseOptions,runCommand}from"@stacksjs/cli";import{createHostedZone,getHostedZoneNameservers,updateNameservers}from"@stacksjs/dns";import{loadEnv}from"@stacksjs/env";import{handleError}from"@stacksjs/error-handling";import{projectConfigPath}from"@stacksjs/path";import{whois}from"@stacksjs/whois";loadEnv({path:[".env",".env.production"],overload:!0});const options=parseOptions();function normalizeDomain(url){if(!url)return;return url.replace(/^https?:\/\//,"").replace(/\/$/,"")}const domain=normalizeDomain(options.domain??process.env.APP_URL);if(!domain){await log.error("There was no Domain or App URL provided. Please provide a domain using the --domain flag or add a url to your app config.");process.exit(1)}const result=await createHostedZone(domain);if(result.isErr){handleError(result.error);process.exit(1)}const nameServers=await getHostedZoneNameservers(domain);if(!nameServers||nameServers.length===0){handleError(`No nameservers found for domain: ${domain}. Please ensure the Hosted Zone exists in Route53.`);process.exit(1)}await updateNameservers(nameServers);const registrar=(await whois(domain,!0)).parsedData.Registrar;if(registrar.includes("Amazon")){if(options.deploy)await runCommand("buddy deploy");else{log.info("");log.info("You can now continue your deployment process by re-running:");log.info("");log.info(` \u27A1\uFE0F ${italic("buddy deploy")}`);log.info("")}await log.flush();process.exit(0)}log.info("");log.info("\u2139\uFE0F Please note, before continuing your deployment process,");log.info(` update your ${registrar} nameservers to the following:`);const emojis=["1\uFE0F\u20E3","2\uFE0F\u20E3","3\uFE0F\u20E3","4\uFE0F\u20E3"];log.info("");nameServers.forEach((nameserver,index)=>{log.info(` ${emojis[index]} Nameserver: ${nameserver}`)});log.info("");log.info(italic(`stored in ${projectConfigPath("dns.ts")}`));log.info("");log.info("Once the nameservers have been updated, re-run the following command:");log.info("");log.info(` \u27A1\uFE0F ${italic("buddy deploy")}`);log.info("");
1
+ import process from"node:process";import{italic,log,parseOptions,runCommand}from"@stacksjs/cli";import{createHostedZone,getHostedZoneNameservers,updateNameservers}from"@stacksjs/dns";import{loadEnv}from"@stacksjs/env";import{handleError}from"@stacksjs/error-handling";import{projectConfigPath}from"@stacksjs/path";import{whois}from"@stacksjs/whois";loadEnv({path:[".env",".env.production"],overload:true});const options=parseOptions();function normalizeDomain(url){if(!url)return;return url.replace(/^https?:\/\//,"").replace(/\/$/,"")}const domain=normalizeDomain(options.domain??process.env.APP_URL);if(!domain){await log.error("There was no Domain or App URL provided. Please provide a domain using the --domain flag or add a url to your app config.");process.exit(1)}const result=await createHostedZone(domain);if(result.isErr){handleError(result.error);process.exit(1)}const nameServers=await getHostedZoneNameservers(domain);if(!nameServers||nameServers.length===0){handleError(`No nameservers found for domain: ${domain}. Please ensure the Hosted Zone exists in Route53.`);process.exit(1)}await updateNameservers(nameServers);const registrar=(await whois(domain,true)).parsedData.Registrar;if(registrar.includes("Amazon")){if(options.deploy){await runCommand("buddy deploy")}else{log.info("");log.info("You can now continue your deployment process by re-running:");log.info("");log.info(` ➡️ ${italic("buddy deploy")}`);log.info("")}await log.flush();process.exit(0)}log.info("");log.info("ℹ️ Please note, before continuing your deployment process,");log.info(` update your ${registrar} nameservers to the following:`);const emojis=["1️⃣","2️⃣","3️⃣","4️⃣"];log.info("");nameServers.forEach((nameserver,index)=>{log.info(` ${emojis[index]} Nameserver: ${nameserver}`)});log.info("");log.info(italic(`stored in ${projectConfigPath("dns.ts")}`));log.info("");log.info("Once the nameservers have been updated, re-run the following command:");log.info("");log.info(` ➡️ ${italic("buddy deploy")}`);log.info("");
@@ -1 +1 @@
1
- import process from"node:process";import{log,parseOptions}from"@stacksjs/cli";import{applyPurchaseFlags,purchaseDomain,purchaseOptionsFromContactInfo}from"@stacksjs/cloud";import{awaitConfig}from"@stacksjs/config";import{handleError}from"@stacksjs/error-handling";import{ExitCode}from"@stacksjs/types";const{dns}=await awaitConfig(),contactInfo=dns?.contactInfo;if(!contactInfo||Object.keys(contactInfo).length===0){handleError("You must provide contact info in config/dns.ts (`contactInfo`) to register a domain.");process.exit(ExitCode.FatalError)}const options=applyPurchaseFlags(purchaseOptionsFromContactInfo(contactInfo),parseOptions());if(!options.domain){handleError("You must provide a domain name to purchase.");process.exit(ExitCode.FatalError)}const result=await purchaseDomain(options.domain,options);if(result.isErr){handleError(result.error);process.exit(ExitCode.FatalError)}log.success(`Route 53 accepted the registration of ${options.domain} (operation ${result.value.OperationId}). It completes at AWS within minutes to hours; the registrant email receives a confirmation.`);await log.flush();process.exit(ExitCode.Success);
1
+ import process from"node:process";import{log,parseOptions}from"@stacksjs/cli";import{applyPurchaseFlags,purchaseDomain,purchaseOptionsFromContactInfo}from"@stacksjs/cloud";import{awaitConfig}from"@stacksjs/config";import{handleError}from"@stacksjs/error-handling";import{ExitCode}from"@stacksjs/types";const{dns}=await awaitConfig();const contactInfo=dns?.contactInfo;if(!contactInfo||Object.keys(contactInfo).length===0){handleError("You must provide contact info in config/dns.ts (`contactInfo`) to register a domain.");process.exit(ExitCode.FatalError)}const options=applyPurchaseFlags(purchaseOptionsFromContactInfo(contactInfo),parseOptions());if(!options.domain){handleError("You must provide a domain name to purchase.");process.exit(ExitCode.FatalError)}const result=await purchaseDomain(options.domain,options);if(result.isErr){handleError(result.error);process.exit(ExitCode.FatalError)}log.success(`Route 53 accepted the registration of ${options.domain} (operation ${result.value.OperationId}). It completes at AWS within minutes to hours; the registrant email receives a confirmation.`);await log.flush();process.exit(ExitCode.Success);
@@ -1 +1 @@
1
- import process from"node:process";import{parseOptions}from"@stacksjs/cli";import{deleteHostedZoneRecords}from"@stacksjs/dns";import{handleError}from"@stacksjs/error-handling";import{log}from"@stacksjs/logging";const parsedOptions=parseOptions(),options={domain:parsedOptions.domain,verbose:parsedOptions.verbose};if(!options.domain){handleError("No domain was given to remove. Run `buddy domains:remove <domain>`.");process.exit(1)}if(options.verbose)log.info(`Removing domain: ${options.domain}`);const result=await deleteHostedZoneRecords(options.domain);if(result.isErr){handleError(result.error);process.exit(1)}
1
+ import process from"node:process";import{parseOptions}from"@stacksjs/cli";import{deleteHostedZoneRecords}from"@stacksjs/dns";import{handleError}from"@stacksjs/error-handling";import{log}from"@stacksjs/logging";const parsedOptions=parseOptions();const options={domain:parsedOptions.domain,verbose:parsedOptions.verbose};if(!options.domain){handleError("No domain was given to remove. Run `buddy domains:remove <domain>`.");process.exit(1)}if(options.verbose)log.info(`Removing domain: ${options.domain}`);const result=await deleteHostedZoneRecords(options.domain);if(result.isErr){handleError(result.error);process.exit(1)}
package/dist/examples.js CHANGED
@@ -1 +1 @@
1
- import process from"node:process";import{NpmScript}from"@stacksjs/enums";import{log}from"@stacksjs/logging";import{hasComponents}from"@stacksjs/storage";import{ExitCode}from"@stacksjs/types";import{runNpmScript}from"@stacksjs/utils";export async function invoke(options){if(options.components)await componentExample(options);else if(options.webComponents||options.elements)await webComponentExample(options);else log.error("An unsupported option was used. Please try again, check the documentation & report the issue, if needed.")}export async function examples(options){return await invoke(options)}export async function componentExample(options){if(hasComponents()){await runNpmScript(NpmScript.Example,options);log.success("Your component library was built successfully")}else log.info("No components found.")}export async function webComponentExample(options){if(hasComponents()){log.info("Building your Web Component library...");await runNpmScript(NpmScript.BuildWebComponents,options);log.success("Your Web Component library was built successfully")}else{log.info("No components found.");await log.flush();process.exit(ExitCode.FatalError)}}
1
+ import process from"node:process";import{NpmScript}from"@stacksjs/enums";import{log}from"@stacksjs/logging";import{hasComponents}from"@stacksjs/storage";import{ExitCode}from"@stacksjs/types";import{runNpmScript}from"@stacksjs/utils";export async function invoke(options){if(options.components){await componentExample(options)}else if(options.webComponents||options.elements){await webComponentExample(options)}else{log.error("An unsupported option was used. Please try again, check the documentation & report the issue, if needed.")}}export async function examples(options){return await invoke(options)}export async function componentExample(options){if(hasComponents()){await runNpmScript(NpmScript.Example,options);log.success("Your component library was built successfully")}else{log.info("No components found.")}}export async function webComponentExample(options){if(hasComponents()){log.info("Building your Web Component library...");await runNpmScript(NpmScript.BuildWebComponents,options);log.success("Your Web Component library was built successfully")}else{log.info("No components found.");await log.flush();process.exit(ExitCode.FatalError)}}
@@ -1 +1 @@
1
- import process from"node:process";import{parseOptions}from"@stacksjs/cli";import{log}from"@stacksjs/logging";import{ExitCode}from"@stacksjs/types";import{findStacksProjects}from"@stacksjs/utils";try{const options=parseOptions(),projects=await findStacksProjects(void 0,options);if(projects.length>0){log.info("Found Projects:");projects.forEach((project)=>console.log(` - ${project}`));await log.flush();process.exit(ExitCode.Success)}log.info("No Stacks Projects found.")}catch(error){log.error("Error searching for Stacks projects:",error)}
1
+ import process from"node:process";import{parseOptions}from"@stacksjs/cli";import{log}from"@stacksjs/logging";import{ExitCode}from"@stacksjs/types";import{findStacksProjects}from"@stacksjs/utils";try{const options=parseOptions();const projects=await findStacksProjects(undefined,options);if(projects.length>0){log.info("Found Projects:");projects.forEach((project)=>console.log(` - ${project}`));await log.flush();process.exit(ExitCode.Success)}log.info("No Stacks Projects found.")}catch(error){log.error("Error searching for Stacks projects:",error)}
@@ -1,6 +1,6 @@
1
- import{existsSync}from"node:fs";import{log}from"@stacksjs/logging";import{path as p}from"@stacksjs/path";import{storage}from"@stacksjs/storage";function quoted(value){return`'${value.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}'`}async function collectRoutes(){const registryFile=p.appPath("Routes.ts");if(!existsSync(registryFile))return{named:{},redirects:[]};try{const{listNamedRoutes,listRedirectRoutes,loadRoutes}=await import("@stacksjs/router"),{default:routeRegistry}=await import(registryFile);await loadRoutes(routeRegistry);const redirects=listRedirectRoutes().filter((entry)=>entry.path!=="/api"&&!entry.path.startsWith("/api/"));return{named:listNamedRoutes(),redirects}}catch(error){log.debug("[generate:types] Could not load routes for named-route types",{error});return{named:{},redirects:[]}}}export async function generateRouteNames(){log.info("Generating route names...");const{named:namedRoutes,redirects}=await collectRoutes(),entries=Object.entries(namedRoutes).sort(([left],[right])=>left.localeCompare(right)).map(([name,routePath])=>`
2
- '${name}': '${routePath}',`).join(""),redirectEntries=redirects.map((entry)=>`
3
- ${quoted(entry.path)}: { to: ${quoted(entry.to)}, status: ${entry.status} },`).join(""),contents=`// This file is auto-generated by Stacks. Do not edit this file manually.
1
+ import{existsSync}from"node:fs";import{log}from"@stacksjs/logging";import{path as p}from"@stacksjs/path";import{storage}from"@stacksjs/storage";function quoted(value){return`'${value.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}'`}async function collectRoutes(){const registryFile=p.appPath("Routes.ts");if(!existsSync(registryFile))return{named:{},redirects:[]};try{const{listNamedRoutes,listRedirectRoutes,loadRoutes}=await import("@stacksjs/router");const{default:routeRegistry}=await import(registryFile);await loadRoutes(routeRegistry);const redirects=listRedirectRoutes().filter((entry)=>entry.path!=="/api"&&!entry.path.startsWith("/api/"));return{named:listNamedRoutes(),redirects}}catch(error){log.debug("[generate:types] Could not load routes for named-route types",{error});return{named:{},redirects:[]}}}export async function generateRouteNames(){log.info("Generating route names...");const{named:namedRoutes,redirects}=await collectRoutes();const entries=Object.entries(namedRoutes).sort(([left],[right])=>left.localeCompare(right)).map(([name,routePath])=>`
2
+ '${name}': '${routePath}',`).join("");const redirectEntries=redirects.map((entry)=>`
3
+ ${quoted(entry.path)}: { to: ${quoted(entry.to)}, status: ${entry.status} },`).join("");const contents=`// This file is auto-generated by Stacks. Do not edit this file manually.
4
4
  //
5
5
  // Every named route, and the path it resolves to. Read as a type by
6
6
  // \`storage/framework/types/registries.d.ts\`, so \`url('users.show')\` is checked
@@ -1,4 +1,4 @@
1
- import{dirname}from"node:path";import{MERMAID_MAX_TEXT_SIZE,renderErd,resolveModelSources,toDiagrammableModel}from"@stacksjs/database";import{log}from"@stacksjs/logging";import{path}from"@stacksjs/path";import{fs}from"@stacksjs/storage";const DETAIL_STEPS=["full","keys","none"];function fitDiagram(models,options){const only=options.only&&options.only.length>0?{only:options.only}:{},asked=options.detail??(options.noColumns?"none":void 0);if(asked)return{diagram:renderErd(models,{detail:asked,...only}),detail:asked};let last="";for(const detail of DETAIL_STEPS){last=renderErd(models,{detail,...only});if(last.length<=MERMAID_MAX_TEXT_SIZE)return{diagram:last,detail}}return{diagram:last,detail:DETAIL_STEPS[DETAIL_STEPS.length-1]}}function tableNameFor(definition,fileName){if(definition?.table)return definition.table;const snake=(definition?.name??fileName).replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase();if(/(?:s|x|z|ch|sh)$/.test(snake))return`${snake}es`;if(/[^aeiou]y$/.test(snake))return`${snake.slice(0,-1)}ies`;return`${snake}s`}export function wrapForTarget(diagram,outPath){return outPath.endsWith(".md")?`# Entity Relationships
1
+ import{dirname}from"node:path";import{MERMAID_MAX_TEXT_SIZE,renderErd,resolveModelSources,toDiagrammableModel}from"@stacksjs/database";import{log}from"@stacksjs/logging";import{path}from"@stacksjs/path";import{fs}from"@stacksjs/storage";const DETAIL_STEPS=["full","keys","none"];function fitDiagram(models,options){const only=options.only&&options.only.length>0?{only:options.only}:{};const asked=options.detail??(options.noColumns?"none":undefined);if(asked)return{diagram:renderErd(models,{detail:asked,...only}),detail:asked};let last="";for(const detail of DETAIL_STEPS){last=renderErd(models,{detail,...only});if(last.length<=MERMAID_MAX_TEXT_SIZE)return{diagram:last,detail}}return{diagram:last,detail:DETAIL_STEPS[DETAIL_STEPS.length-1]}}function tableNameFor(definition,fileName){if(definition?.table)return definition.table;const name=definition?.name??fileName;const snake=name.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase();if(/(?:s|x|z|ch|sh)$/.test(snake))return`${snake}es`;if(/[^aeiou]y$/.test(snake))return`${snake.slice(0,-1)}ies`;return`${snake}s`}export function wrapForTarget(diagram,outPath){return outPath.endsWith(".md")?`# Entity Relationships
2
2
 
3
3
  <!-- Generated by \`buddy generate:erd\`. Edit your models, not this. -->
4
4
 
@@ -6,4 +6,4 @@ import{dirname}from"node:path";import{MERMAID_MAX_TEXT_SIZE,renderErd,resolveMod
6
6
  ${diagram}
7
7
  \`\`\`
8
8
  `:`${diagram}
9
- `}export async function generateErd(options={}){const sources=resolveModelSources();if(!sources||sources.models.length===0)return{ok:!1,error:"No models found. The diagram is derived from your models, so there is nothing to generate."};const models=[],skipped=[];for(const source of sources.models)try{const definition=(await import(source.file)).default;if(!definition)continue;models.push(toDiagrammableModel(definition,tableNameFor(definition,source.name)))}catch(error){skipped.push(`${source.name}: ${error.message}`)}for(const failure of skipped)log.warn(`[generate:erd] skipped ${failure}`);if(models.length===0)return{ok:!1,error:"Every model failed to load; nothing to diagram."};const{diagram,detail}=fitDiagram(models,options),truncated=diagram.length>MERMAID_MAX_TEXT_SIZE;if(truncated)log.warn(`[generate:erd] ${diagram.length} characters is past Mermaid's ${MERMAID_MAX_TEXT_SIZE} limit; it will draw an error box rather than a diagram. Narrow it with --only.`);else if(detail!=="full")log.info(`[generate:erd] drew ${detail==="keys"?"key columns only":"relationships only"}, so the diagram stays inside Mermaid's ${MERMAID_MAX_TEXT_SIZE}-character limit.`);const outPath=path.projectPath(options.out??"docs/erd.md");if(!options.dryRun){fs.mkdirSync(dirname(outPath),{recursive:!0});await Bun.write(outPath,wrapForTarget(diagram,outPath))}return{ok:!0,diagram,path:outPath,modelCount:models.length,skipped,detail,characters:diagram.length,truncated}}
9
+ `}export async function generateErd(options={}){const sources=resolveModelSources();if(!sources||sources.models.length===0)return{ok:false,error:"No models found. The diagram is derived from your models, so there is nothing to generate."};const models=[];const skipped=[];for(const source of sources.models){try{const definition=(await import(source.file)).default;if(!definition)continue;models.push(toDiagrammableModel(definition,tableNameFor(definition,source.name)))}catch(error){skipped.push(`${source.name}: ${error.message}`)}}for(const failure of skipped)log.warn(`[generate:erd] skipped ${failure}`);if(models.length===0)return{ok:false,error:"Every model failed to load; nothing to diagram."};const{diagram,detail}=fitDiagram(models,options);const truncated=diagram.length>MERMAID_MAX_TEXT_SIZE;if(truncated)log.warn(`[generate:erd] ${diagram.length} characters is past Mermaid's ${MERMAID_MAX_TEXT_SIZE} limit; it will draw an error box rather than a diagram. Narrow it with --only.`);else if(detail!=="full")log.info(`[generate:erd] drew ${detail==="keys"?"key columns only":"relationships only"}, so the diagram stays inside Mermaid's ${MERMAID_MAX_TEXT_SIZE}-character limit.`);const outPath=path.projectPath(options.out??"docs/erd.md");if(!options.dryRun){fs.mkdirSync(dirname(outPath),{recursive:true});await Bun.write(outPath,wrapForTarget(diagram,outPath))}return{ok:true,diagram,path:outPath,modelCount:models.length,skipped,detail,characters:diagram.length,truncated}}
@@ -1 +1 @@
1
- import{log}from"@stacksjs/logging";import{hasComponents}from"@stacksjs/storage";import{generateVsCodeCustomData,generateWebTypes}from"../helpers/vscode-custom-data";if(hasComponents()){await generateWebTypes();await generateVsCodeCustomData()}else log.info("No components found. Skipping IDE helper generation.");
1
+ import{log}from"@stacksjs/logging";import{hasComponents}from"@stacksjs/storage";import{generateVsCodeCustomData,generateWebTypes}from"../helpers/vscode-custom-data";if(hasComponents()){await generateWebTypes();await generateVsCodeCustomData()}else{log.info("No components found. Skipping IDE helper generation.")}
@@ -1 +1 @@
1
- import{awaitConfig}from"@stacksjs/config";import{log}from"@stacksjs/logging";import{projectPath}from"@stacksjs/path";export async function generateProjectImages(options={}){const images=(await awaitConfig()).images;if(!images||!images.social?.enabled&&!images.appStore?.enabled&&!images.appIcons?.enabled){log.debug("[generate:images] nothing declared in config/images.ts - skipping");return}const{countGeneratedImages,generateImages}=await import("@stacksjs/image"),result=await generateImages(images,{only:options.only,root:projectPath()}),counts=countGeneratedImages(result);if(options.verbose){for(const card of result.social)log.info(`[generate:images] ${card.path} \u2192 ${Object.values(card.files).join(", ")}`);for(const[display,paths]of Object.entries(result.appStore))log.info(`[generate:images] ${display} \u2192 ${paths.length} screenshot(s)`)}const summary=[counts.social?`${counts.social} social card(s)`:"",counts.appStore?`${counts.appStore} App Store screenshot(s)`:"",counts.appIcons?`${counts.appIcons} icon(s)`:""].filter(Boolean).join(", ");if(summary)log.success(`Generated ${summary}`);else log.info("[generate:images] nothing to generate")}
1
+ import{awaitConfig}from"@stacksjs/config";import{log}from"@stacksjs/logging";import{projectPath}from"@stacksjs/path";export async function generateProjectImages(options={}){const config=await awaitConfig();const images=config.images;if(!images||!images.social?.enabled&&!images.appStore?.enabled&&!images.appIcons?.enabled){log.debug("[generate:images] nothing declared in config/images.ts - skipping");return}const{countGeneratedImages,generateImages}=await import("@stacksjs/image");const result=await generateImages(images,{only:options.only,root:projectPath()});const counts=countGeneratedImages(result);if(options.verbose){for(const card of result.social)log.info(`[generate:images] ${card.path} → ${Object.values(card.files).join(", ")}`);for(const[display,paths]of Object.entries(result.appStore))log.info(`[generate:images] ${display} → ${paths.length} screenshot(s)`)}const summary=[counts.social?`${counts.social} social card(s)`:"",counts.appStore?`${counts.appStore} App Store screenshot(s)`:"",counts.appIcons?`${counts.appIcons} icon(s)`:""].filter(Boolean).join(", ");if(summary)log.success(`Generated ${summary}`);else log.info("[generate:images] nothing to generate")}
@@ -1 +1 @@
1
- import*as fs from"node:fs";import process from"node:process";import{Action,NpmScript}from"@stacksjs/enums";import{log}from"@stacksjs/logging";import{frameworkPath,projectPath}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";import{runNpmScript}from"@stacksjs/utils";import{runAction}from"../helpers";import{generateVsCodeCustomData as genVsCodeCustomData,generateWebTypes as genWebTypes}from"../helpers/vscode-custom-data";import{generateProjectImages}from"./images";import{generateRouteNames}from"./action-types";export{generateProjectImages}from"./images";export{generateErd,wrapForTarget}from"./erd";export{generateVSchema}from"./vschema";export async function invoke(options){if(options?.types)await generateTypes(options);else if(options?.entries)await generateLibEntries(options);else if(options?.webTypes)await generateWebTypes();else if(options?.customData)await generateVsCodeCustomData();else if(options?.ideHelpers)await generateIdeHelpers();else if(options?.componentMeta)await generateComponentMeta();else if(options?.coreSymlink)await generateCoreSymlink();else if(options?.openApiSpec)await generateOpenApiSpec();else if(options?.images)await generateProjectImages({verbose:options?.verbose});else await generateEverything(options)}async function generateEverything(options){log.info("Generating types, entry points, component meta and the OpenAPI spec...");try{const{discoverPackages}=await import("../discover-packages");await discoverPackages()}catch{}await generateTypes({...options,types:!0});await generateLibEntries({...options,entries:!0});await generateOpenApiSpec();log.success("Generated")}export function generate(options){return invoke(options)}export async function generateLibEntries(options){const result=await runAction(Action.GenerateLibraryEntries,{...options,cwd:projectPath()});if(result.isErr){await log.error("There was an error generating your library entry points",result.error);process.exit(ExitCode.FatalError)}log.success("Library entry points generated successfully")}export async function generateWebTypes(){await genWebTypes()}export async function generateVsCodeCustomData(){const result=await genVsCodeCustomData();if(result.isErr){await log.error("There was an error generating the custom-elements.json file.",result.error);process.exit(ExitCode.FatalError)}await runAction(Action.LintFix,{verbose:!0,cwd:projectPath()});log.success("Successfully generated the custom-elements.json file")}export async function generateIdeHelpers(){await genWebTypes();await genVsCodeCustomData();await runAction(Action.LintFix,{verbose:!0,cwd:projectPath()});log.success("Successfully generated IDE helpers")}export async function generateComponentMeta(){const result=await genVsCodeCustomData();if(result.isErr){await log.error("There was an error generating your component meta information.",result.error);process.exit(ExitCode.FatalError)}await runAction(Action.LintFix,{verbose:!0,cwd:projectPath()});log.success("Successfully generated component meta information")}export async function generateTypes(options){try{const{generateAutoImportFiles}=await import("@stacksjs/server");await generateAutoImportFiles()}catch(error){log.debug("[generate:types] Could not refresh the auto-import registries",{error})}await generateRouteNames();try{const previous=process.env.STACKS_CANONICAL_FEATURES;process.env.STACKS_CANONICAL_FEATURES="1";try{const{generateServerAutoImportTypes}=await import("@stacksjs/server");await generateServerAutoImportTypes()}finally{if(previous===void 0)delete process.env.STACKS_CANONICAL_FEATURES;else process.env.STACKS_CANONICAL_FEATURES=previous}}catch(error){log.debug("[generate:types] Could not refresh server auto-import declarations",{error})}const entry=frameworkPath("core/actions/src/generate/types.ts");if(!fs.existsSync(entry)){await import(`./types?t=${Date.now()}`);return}const result=await runNpmScript(NpmScript.GenerateTypes,{cwd:frameworkPath(),...options});if(result.isErr){log.error("There was an error generating your types.",result.error);throw result.error instanceof Error?result.error:Error(String(result.error))}log.success("Types were generated successfully")}export async function watchTypes(options){try{const manifestPath=`${frameworkPath()}/package.json`,text=fs.existsSync(manifestPath)?fs.readFileSync(manifestPath,"utf-8"):"";if(!(text?JSON.parse(text):{})?.scripts?.["generate:types"]){log.warn("[generate:types --watch] no `generate:types` script in framework package.json - type regeneration disabled. dev:api will keep running, but type definitions won't auto-refresh on model/config changes.");return}}catch{}const watched=[...await(async()=>{try{const{autoImportSourceDirs}=await import("@stacksjs/server");return autoImportSourceDirs()}catch{return[]}})(),projectPath("config"),projectPath("database/migrations"),projectPath("app"),projectPath("routes")].filter((dir,index,all)=>all.indexOf(dir)===index);log.info(`[generate:types --watch] watching ${watched.length} directories`);let pending=null,inflight=!1;const trigger=()=>{if(pending)clearTimeout(pending);pending=setTimeout(async()=>{if(inflight)return;inflight=!0;try{log.info("[generate:types --watch] change detected, regenerating\u2026");await generateTypes(options);log.success("[generate:types --watch] types up to date")}catch(err){log.error("[generate:types --watch] regeneration failed:",err)}finally{inflight=!1}},200)},watchers=[];for(const dir of watched)try{if(!fs.existsSync(dir))continue;const w=fs.watch(dir,{recursive:!0},()=>trigger());watchers.push(w)}catch(err){log.warn(`[generate:types --watch] cannot watch ${dir}: ${err}`)}if(watchers.length===0){log.warn("[generate:types --watch] no directories to watch - exiting");return}await new Promise((resolve)=>{process.once("SIGINT",()=>{log.info("[generate:types --watch] stopping");for(const w of watchers)try{w.close()}catch{}resolve()})})}export function generatePantryConfig(){log.success("Successfully generated `./pantry.yaml` based on your config")}export async function generateSeeder(){}export async function generateCoreSymlink(){const link=projectPath(".framework");try{if(!fs.lstatSync(link).isSymbolicLink())return;fs.unlinkSync(link)}catch{}fs.symlinkSync(frameworkPath(),link)}export async function generateOpenApiSpec(){const{generateOpenApi}=await import("@stacksjs/api");await generateOpenApi();log.success("Successfully generated Open API Spec")}
1
+ import*as fs from"node:fs";import process from"node:process";import{Action,NpmScript}from"@stacksjs/enums";import{log}from"@stacksjs/logging";import{frameworkPath,projectPath}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";import{runNpmScript}from"@stacksjs/utils";import{runAction}from"../helpers";import{generateVsCodeCustomData as genVsCodeCustomData,generateWebTypes as genWebTypes}from"../helpers/vscode-custom-data";import{generateProjectImages}from"./images";import{generateRouteNames}from"./action-types";export{generateProjectImages}from"./images";export{generateErd,wrapForTarget}from"./erd";export{generateVSchema}from"./vschema";export async function invoke(options){if(options?.types)await generateTypes(options);else if(options?.entries)await generateLibEntries(options);else if(options?.webTypes)await generateWebTypes();else if(options?.customData)await generateVsCodeCustomData();else if(options?.ideHelpers)await generateIdeHelpers();else if(options?.componentMeta)await generateComponentMeta();else if(options?.coreSymlink)await generateCoreSymlink();else if(options?.openApiSpec)await generateOpenApiSpec();else if(options?.images)await generateProjectImages({verbose:options?.verbose});else await generateEverything(options)}async function generateEverything(options){log.info("Generating types, entry points, component meta and the OpenAPI spec...");try{const{discoverPackages}=await import("../discover-packages");await discoverPackages()}catch{}await generateTypes({...options,types:true});await generateLibEntries({...options,entries:true});await generateOpenApiSpec();log.success("Generated")}export function generate(options){return invoke(options)}export async function generateLibEntries(options){const result=await runAction(Action.GenerateLibraryEntries,{...options,cwd:projectPath()});if(result.isErr){await log.error("There was an error generating your library entry points",result.error);process.exit(ExitCode.FatalError)}log.success("Library entry points generated successfully")}export async function generateWebTypes(){await genWebTypes()}export async function generateVsCodeCustomData(){const result=await genVsCodeCustomData();if(result.isErr){await log.error("There was an error generating the custom-elements.json file.",result.error);process.exit(ExitCode.FatalError)}await runAction(Action.LintFix,{verbose:true,cwd:projectPath()});log.success("Successfully generated the custom-elements.json file")}export async function generateIdeHelpers(){await genWebTypes();await genVsCodeCustomData();await runAction(Action.LintFix,{verbose:true,cwd:projectPath()});log.success("Successfully generated IDE helpers")}export async function generateComponentMeta(){const result=await genVsCodeCustomData();if(result.isErr){await log.error("There was an error generating your component meta information.",result.error);process.exit(ExitCode.FatalError)}await runAction(Action.LintFix,{verbose:true,cwd:projectPath()});log.success("Successfully generated component meta information")}export async function generateTypes(options){try{const{generateAutoImportFiles}=await import("@stacksjs/server");await generateAutoImportFiles()}catch(error){log.debug("[generate:types] Could not refresh the auto-import registries",{error})}await generateRouteNames();try{const previous=process.env.STACKS_CANONICAL_FEATURES;process.env.STACKS_CANONICAL_FEATURES="1";try{const{generateServerAutoImportTypes}=await import("@stacksjs/server");await generateServerAutoImportTypes()}finally{if(previous===undefined)delete process.env.STACKS_CANONICAL_FEATURES;else process.env.STACKS_CANONICAL_FEATURES=previous}}catch(error){log.debug("[generate:types] Could not refresh server auto-import declarations",{error})}const entry=frameworkPath("core/actions/src/generate/types.ts");if(!fs.existsSync(entry)){await import(`./types?t=${Date.now()}`);return}const result=await runNpmScript(NpmScript.GenerateTypes,{cwd:frameworkPath(),...options});if(result.isErr){log.error("There was an error generating your types.",result.error);throw result.error instanceof Error?result.error:new Error(String(result.error))}log.success("Types were generated successfully")}export async function watchTypes(options){try{const manifestPath=`${frameworkPath()}/package.json`;const text=fs.existsSync(manifestPath)?fs.readFileSync(manifestPath,"utf-8"):"";const manifest=text?JSON.parse(text):{};if(!manifest?.scripts?.["generate:types"]){log.warn("[generate:types --watch] no `generate:types` script in framework package.json - type regeneration disabled. dev:api will keep running, but type definitions won't auto-refresh on model/config changes.");return}}catch{}const registrySources=await(async()=>{try{const{autoImportSourceDirs}=await import("@stacksjs/server");return autoImportSourceDirs()}catch{return[]}})();const watched=[...registrySources,projectPath("config"),projectPath("database/migrations"),projectPath("app"),projectPath("routes")].filter((dir,index,all)=>all.indexOf(dir)===index);log.info(`[generate:types --watch] watching ${watched.length} directories`);let pending=null;let inflight=false;const trigger=()=>{if(pending)clearTimeout(pending);pending=setTimeout(async()=>{if(inflight)return;inflight=true;try{log.info("[generate:types --watch] change detected, regenerating…");await generateTypes(options);log.success("[generate:types --watch] types up to date")}catch(err){log.error("[generate:types --watch] regeneration failed:",err)}finally{inflight=false}},200)};const watchers=[];for(const dir of watched){try{if(!fs.existsSync(dir))continue;const w=fs.watch(dir,{recursive:true},()=>trigger());watchers.push(w)}catch(err){log.warn(`[generate:types --watch] cannot watch ${dir}: ${err}`)}}if(watchers.length===0){log.warn("[generate:types --watch] no directories to watch - exiting");return}await new Promise((resolve)=>{process.once("SIGINT",()=>{log.info("[generate:types --watch] stopping");for(const w of watchers){try{w.close()}catch{}}resolve()})})}export function generatePantryConfig(){log.success("Successfully generated `./pantry.yaml` based on your config")}export async function generateSeeder(){}export async function generateCoreSymlink(){const link=projectPath(".framework");try{if(!fs.lstatSync(link).isSymbolicLink())return;fs.unlinkSync(link)}catch{}fs.symlinkSync(frameworkPath(),link)}export async function generateOpenApiSpec(){const{generateOpenApi}=await import("@stacksjs/api");await generateOpenApi();log.success("Successfully generated Open API Spec")}
@@ -1 +1 @@
1
- import{awaitConfig,library}from"@stacksjs/config";import{log}from"@stacksjs/logging";import{generateLibraryPackages}from"../library/build";export async function generateLibEntries(){await awaitConfig();if(library?.releaseable===!1){log.info("library.releaseable is false. Skipping library entry points.");return}log.info("Generating library entry points...");const reports=await generateLibraryPackages({allowEmpty:!0});for(const report of reports)log.success(`Generated ${report.name} (${report.kind}, ${report.sources} sources)`)}await generateLibEntries();
1
+ import{awaitConfig,library}from"@stacksjs/config";import{log}from"@stacksjs/logging";import{generateLibraryPackages}from"../library/build";export async function generateLibEntries(){await awaitConfig();if(library?.releaseable===false){log.info("library.releaseable is false. Skipping library entry points.");return}log.info("Generating library entry points...");const reports=await generateLibraryPackages({allowEmpty:true});for(const report of reports)log.success(`Generated ${report.name} (${report.kind}, ${report.sources} sources)`)}await generateLibEntries();
@@ -1,2 +1,2 @@
1
- import{dirname}from"node:path";import{deriveVSchema,formatShardingReport,resolveModelSources,toShardableModel}from"@stacksjs/database";import{log}from"@stacksjs/logging";import{path}from"@stacksjs/path";import{fs}from"@stacksjs/storage";function tableNameFor(definition,fileName){if(definition?.table)return definition.table;const snake=(definition?.name??fileName).replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase();if(/(?:s|x|z|ch|sh)$/.test(snake))return`${snake}es`;if(/[^aeiou]y$/.test(snake))return`${snake.slice(0,-1)}ies`;return`${snake}s`}export async function generateVSchema(options={}){const sources=resolveModelSources();if(!sources||sources.models.length===0)return{ok:!1,error:"No models found. A VSchema is derived from your models, so there is nothing to generate."};const models=[],failed=[];for(const source of sources.models)try{const definition=(await import(source.file)).default;if(!definition)continue;models.push(toShardableModel(definition,tableNameFor(definition,source.name)))}catch(error){failed.push(`${source.name}: ${error.message}`)}for(const failure of failed)log.warn(`[generate:vschema] skipped ${failure}`);if(models.length===0)return{ok:!1,error:"Every model failed to load; nothing to derive a VSchema from."};const{vschema,decisions}=deriveVSchema(models),report=formatShardingReport(decisions),outPath=path.projectPath(options.out??"database/vschema.json");if(!options.dryRun){fs.mkdirSync(dirname(outPath),{recursive:!0});await Bun.write(outPath,`${JSON.stringify(vschema,null,2)}
2
- `)}return{ok:!0,vschema,report,path:outPath,tableCount:Object.keys(vschema.tables).length}}
1
+ import{dirname}from"node:path";import{deriveVSchema,formatShardingReport,resolveModelSources,toShardableModel}from"@stacksjs/database";import{log}from"@stacksjs/logging";import{path}from"@stacksjs/path";import{fs}from"@stacksjs/storage";function tableNameFor(definition,fileName){if(definition?.table)return definition.table;const name=definition?.name??fileName;const snake=name.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase();if(/(?:s|x|z|ch|sh)$/.test(snake))return`${snake}es`;if(/[^aeiou]y$/.test(snake))return`${snake.slice(0,-1)}ies`;return`${snake}s`}export async function generateVSchema(options={}){const sources=resolveModelSources();if(!sources||sources.models.length===0)return{ok:false,error:"No models found. A VSchema is derived from your models, so there is nothing to generate."};const models=[];const failed=[];for(const source of sources.models){try{const definition=(await import(source.file)).default;if(!definition)continue;models.push(toShardableModel(definition,tableNameFor(definition,source.name)))}catch(error){failed.push(`${source.name}: ${error.message}`)}}for(const failure of failed)log.warn(`[generate:vschema] skipped ${failure}`);if(models.length===0)return{ok:false,error:"Every model failed to load; nothing to derive a VSchema from."};const{vschema,decisions}=deriveVSchema(models);const report=formatShardingReport(decisions);const outPath=path.projectPath(options.out??"database/vschema.json");if(!options.dryRun){fs.mkdirSync(dirname(outPath),{recursive:true});await Bun.write(outPath,`${JSON.stringify(vschema,null,2)}
2
+ `)}return{ok:true,vschema,report,path:outPath,tableCount:Object.keys(vschema.tables).length}}
@@ -1,11 +1,11 @@
1
- import{githubHeaders}from"@stacksjs/github";import process from"node:process";export const GITHUB_API_URL="https://api.github.com",MAX_RELEASE_BODY=120000;function runCommand(cmd,input){try{const result=Bun.spawnSync(cmd,{stdin:input===void 0?"ignore":Buffer.from(input),stdout:"pipe",stderr:"ignore",env:{...process.env,GIT_TERMINAL_PROMPT:"0",GH_PROMPT_DISABLED:"1"}});return{exitCode:result.exitCode??1,stdout:result.stdout?.toString()??""}}catch{return{exitCode:127,stdout:""}}}export function parseGitHubRemote(url){const match=url?.trim().match(/^(?:https?:\/\/(?:[^@/]+@)?github\.com\/|(?:ssh:\/\/)?git@github\.com[:/])([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/);if(!match)return null;return{owner:match[1],repo:match[2]}}export function resolveGitHubToken(env=process.env,run=runCommand){for(const key of["GITHUB_TOKEN","GH_TOKEN"]){const value=env[key]?.trim();if(value)return value}const gh=run(["gh","auth","token","--hostname","github.com"]);if(gh.exitCode===0&&gh.stdout.trim())return gh.stdout.trim();const credential=run(["git","credential","fill"],`protocol=https
1
+ import{githubHeaders}from"@stacksjs/github";import process from"node:process";export const GITHUB_API_URL="https://api.github.com";export const MAX_RELEASE_BODY=120000;function runCommand(cmd,input){try{const result=Bun.spawnSync(cmd,{stdin:input===undefined?"ignore":Buffer.from(input),stdout:"pipe",stderr:"ignore",env:{...process.env,GIT_TERMINAL_PROMPT:"0",GH_PROMPT_DISABLED:"1"}});return{exitCode:result.exitCode??1,stdout:result.stdout?.toString()??""}}catch{return{exitCode:127,stdout:""}}}export function parseGitHubRemote(url){const match=url?.trim().match(/^(?:https?:\/\/(?:[^@/]+@)?github\.com\/|(?:ssh:\/\/)?git@github\.com[:/])([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/);if(!match)return null;return{owner:match[1],repo:match[2]}}export function resolveGitHubToken(env=process.env,run=runCommand){for(const key of["GITHUB_TOKEN","GH_TOKEN"]){const value=env[key]?.trim();if(value)return value}const gh=run(["gh","auth","token","--hostname","github.com"]);if(gh.exitCode===0&&gh.stdout.trim())return gh.stdout.trim();const credential=run(["git","credential","fill"],`protocol=https
2
2
  host=github.com
3
3
 
4
4
  `);if(credential.exitCode===0){const password=credential.stdout.split(`
5
- `).find((line)=>line.startsWith("password="))?.slice(9).trim();if(password)return password}return null}export function fitReleaseBody(body,compareUrl){if(body.length<=MAX_RELEASE_BODY)return body;const note=`
5
+ `).find((line)=>line.startsWith("password="))?.slice("password=".length).trim();if(password)return password}return null}export function fitReleaseBody(body,compareUrl){if(body.length<=MAX_RELEASE_BODY)return body;const note=`
6
6
 
7
- \u2026the notes were longer than GitHub allows${compareUrl?`; see [every change](${compareUrl})`:""}.
8
- `,cut=body.slice(0,MAX_RELEASE_BODY-note.length);return`${cut.slice(0,Math.max(0,cut.lastIndexOf(`
9
- `)))}${note}`}export async function createGitHubRelease(repository,draft,options){const fetcher=options.fetch??globalThis.fetch,base=`${(options.apiUrl??GITHUB_API_URL).replace(/\/$/,"")}/repos/${repository.owner}/${repository.repo}/releases`,headers=githubHeaders(options.token),existing=await fetcher(`${base}/tags/${encodeURIComponent(draft.tag)}`,{headers});if(existing.ok)return{url:(await existing.json()).html_url,created:!1};if(existing.status!==404)throw Error(`GitHub API ${existing.status} looking up the release for ${draft.tag}: ${await apiMessage(existing)}`);const response=await fetcher(base,{method:"POST",headers:{...headers,"Content-Type":"application/json"},body:JSON.stringify({tag_name:draft.tag,name:draft.name,body:draft.body,draft:!1,prerelease:draft.prerelease??!1})});if(!response.ok)throw Error(`GitHub API ${response.status} creating the release for ${draft.tag}: ${await apiMessage(response)}`);return{url:(await response.json()).html_url,created:!0}}async function apiMessage(response){const text=await response.text().catch(()=>"");try{return JSON.parse(text).message||text||response.statusText}catch{return text||response.statusText}}function git(cwd,args){const result=Bun.spawnSync(["git",...args],{cwd,stdout:"pipe",stderr:"ignore"});return result.exitCode===0?result.stdout.toString().trim():null}export function previousTag(cwd,tag){return git(cwd,["describe","--tags","--abbrev=0",`${tag}^`])||void 0}export function latestTag(cwd,ref="HEAD"){return git(cwd,["describe","--tags","--abbrev=0",ref])||void 0}export function originRepository(cwd){return parseGitHubRemote(git(cwd,["remote","get-url","origin"])??void 0)}export async function releaseNotes(options){const{generateChangelog,loadLogsmithConfig}=await import("@stacksjs/logsmith"),repoUrl=`https://github.com/${options.repository.owner}/${options.repository.repo}`,config=await loadLogsmithConfig({dir:options.cwd,from:options.from,to:options.tag,output:!1,theme:"github",repo:repoUrl,hideAuthorEmail:!0});return(await generateChangelog(config)).content.trim()||`No changes since ${options.from??"the start of the history"}.`}export async function publishGitHubRelease(options){const repository=originRepository(options.cwd);if(!repository)return{status:"skipped",reason:"origin is not a GitHub repository"};try{const from=options.ref?latestTag(options.cwd,options.ref):previousTag(options.cwd,options.tag),notes=await releaseNotes({cwd:options.cwd,tag:options.ref??options.tag,from,repository}),compareUrl=from?`https://github.com/${repository.owner}/${repository.repo}/compare/${from}...${options.tag}`:void 0,draft={tag:options.tag,name:options.name??options.tag,body:fitReleaseBody(options.summary?`${options.summary.trim()}
7
+ …the notes were longer than GitHub allows${compareUrl?`; see [every change](${compareUrl})`:""}.
8
+ `;const cut=body.slice(0,MAX_RELEASE_BODY-note.length);return`${cut.slice(0,Math.max(0,cut.lastIndexOf(`
9
+ `)))}${note}`}export async function createGitHubRelease(repository,draft,options){const fetcher=options.fetch??globalThis.fetch;const base=`${(options.apiUrl??GITHUB_API_URL).replace(/\/$/,"")}/repos/${repository.owner}/${repository.repo}/releases`;const headers=githubHeaders(options.token);const existing=await fetcher(`${base}/tags/${encodeURIComponent(draft.tag)}`,{headers});if(existing.ok)return{url:(await existing.json()).html_url,created:false};if(existing.status!==404)throw new Error(`GitHub API ${existing.status} looking up the release for ${draft.tag}: ${await apiMessage(existing)}`);const response=await fetcher(base,{method:"POST",headers:{...headers,"Content-Type":"application/json"},body:JSON.stringify({tag_name:draft.tag,name:draft.name,body:draft.body,draft:false,prerelease:draft.prerelease??false})});if(!response.ok)throw new Error(`GitHub API ${response.status} creating the release for ${draft.tag}: ${await apiMessage(response)}`);return{url:(await response.json()).html_url,created:true}}async function apiMessage(response){const text=await response.text().catch(()=>"");try{return JSON.parse(text).message||text||response.statusText}catch{return text||response.statusText}}function git(cwd,args){const result=Bun.spawnSync(["git",...args],{cwd,stdout:"pipe",stderr:"ignore"});return result.exitCode===0?result.stdout.toString().trim():null}export function previousTag(cwd,tag){return git(cwd,["describe","--tags","--abbrev=0",`${tag}^`])||undefined}export function latestTag(cwd,ref="HEAD"){return git(cwd,["describe","--tags","--abbrev=0",ref])||undefined}export function originRepository(cwd){return parseGitHubRemote(git(cwd,["remote","get-url","origin"])??undefined)}export async function releaseNotes(options){const{generateChangelog,loadLogsmithConfig}=await import("@stacksjs/logsmith");const repoUrl=`https://github.com/${options.repository.owner}/${options.repository.repo}`;const config=await loadLogsmithConfig({dir:options.cwd,from:options.from,to:options.tag,output:false,theme:"github",repo:repoUrl,hideAuthorEmail:true});const content=(await generateChangelog(config)).content.trim();return content||`No changes since ${options.from??"the start of the history"}.`}export async function publishGitHubRelease(options){const repository=originRepository(options.cwd);if(!repository)return{status:"skipped",reason:"origin is not a GitHub repository"};try{const from=options.ref?latestTag(options.cwd,options.ref):previousTag(options.cwd,options.tag);const notes=await releaseNotes({cwd:options.cwd,tag:options.ref??options.tag,from,repository});const compareUrl=from?`https://github.com/${repository.owner}/${repository.repo}/compare/${from}...${options.tag}`:undefined;const draft={tag:options.tag,name:options.name??options.tag,body:fitReleaseBody(options.summary?`${options.summary.trim()}
10
10
 
11
11
  ${notes}`:notes,compareUrl),prerelease:options.prerelease};if(options.dryRun)return{status:"skipped",reason:"dry run",draft};const token=resolveGitHubToken(options.env,options.run);if(!token)return{status:"failed",reason:"no GitHub token (set GITHUB_TOKEN, or sign in with `gh auth login`)",draft};const release=await createGitHubRelease(repository,draft,{token,fetch:options.fetch});return{status:release.created?"created":"exists",url:release.url,draft}}catch(error){return{status:"failed",reason:error instanceof Error?error.message:String(error)}}}export function describeGitHubRelease(tag,result){switch(result.status){case"created":return`Created the GitHub release ${result.url}`;case"exists":return`${tag} already has a GitHub release: ${result.url}`;case"skipped":return`No GitHub release for ${tag}: ${result.reason}`;case"failed":return`Could not create the GitHub release for ${tag} (${result.reason}). The tag is pushed; run \`buddy release:github ${tag}\` to finish it.`}}
@@ -1,3 +1,3 @@
1
- import process from"node:process";export function resolveApiPort(value,configured=3008){const port=value?.trim()?Number(value):configured;if(!Number.isInteger(port)||port<0||port>65535)throw RangeError("PORT_API must be an integer between 0 and 65535");return port}export function reportApiReady(server){process.send?.({type:"stacks:api-ready",port:server.port,url:server.url.href});console.log(`
2
- \u279C API server ready: ${server.url.origin}
3
- `)}export function resolveApiHost(env=process.env){if(env.API_HOST)return env.API_HOST;if(env.HOST)return env.HOST;return env.NODE_ENV==="production"||env.APP_ENV==="production"?"0.0.0.0":"127.0.0.1"}
1
+ import process from"node:process";export function resolveApiPort(value,configured=3008){const port=value?.trim()?Number(value):configured;if(!Number.isInteger(port)||port<0||port>65535)throw new RangeError("PORT_API must be an integer between 0 and 65535");return port}export function reportApiReady(server){process.send?.({type:"stacks:api-ready",port:server.port,url:server.url.href});console.log(`
2
+ ➜ API server ready: ${server.url.origin}
3
+ `)}export function resolveApiHost(env=process.env){if(env.API_HOST)return env.API_HOST;if(env.HOST)return env.HOST;const isProduction=env.NODE_ENV==="production"||env.APP_ENV==="production";return isProduction?"0.0.0.0":"127.0.0.1"}
@@ -1 +1 @@
1
- import{runShutdownHooks}from"@stacksjs/router";export async function shutDownApiServer(server,options){let exited=!1;const exit=()=>{if(exited)return;exited=!0;options.exit(0)},deadline=setTimeout(exit,options.graceMs);deadline.unref?.();await Promise.allSettled([(options.hooks??runShutdownHooks)(),Promise.resolve().then(()=>server?.stop())]);clearTimeout(deadline);exit()}
1
+ import{runShutdownHooks}from"@stacksjs/router";export async function shutDownApiServer(server,options){let exited=false;const exit=()=>{if(exited)return;exited=true;options.exit(0)};const deadline=setTimeout(exit,options.graceMs);deadline.unref?.();await Promise.allSettled([(options.hooks??runShutdownHooks)(),Promise.resolve().then(()=>server?.stop())]);clearTimeout(deadline);exit()}
@@ -1,5 +1,5 @@
1
- import{frameworkPath,join,path,projectPath}from"@stacksjs/path";import{existsSync,globSync,mkdirSync,writeFileSync}from"@stacksjs/storage";import{readFileSync}from"node:fs";let parseMarkdownFn=null;async function getMarkdownParser(){if(parseMarkdownFn)return parseMarkdownFn;try{parseMarkdownFn=(await import("@stacksjs/ts-md")).parseMarkdown}catch{parseMarkdownFn=(s)=>s}return parseMarkdownFn}function renderDescription(raw){if(!raw)return"";return parseMarkdownFn?parseMarkdownFn(raw):raw}export async function generateComponentMeta(){await getMarkdownParser();const components=[...globSync(["components/*.stx","components/**/*.stx","resources/components/**/*.stx"],{cwd:projectPath(),absolute:!0}),...globSync(["resources/components/**/*.stx"],{cwd:frameworkPath("defaults"),absolute:!0})],metaDirPath=frameworkPath("component-meta");if(!existsSync(metaDirPath))mkdirSync(metaDirPath,{recursive:!0});for(const componentPath of components){const componentExportName=path.parse(componentPath).name,meta=parseStxComponentMeta(componentPath),metaJsonFilePath=join(metaDirPath,`${componentExportName}.json`);writeFileSync(metaJsonFilePath,JSON.stringify(meta,null,2))}}export function parseStxComponentMeta(componentPath){const source=readFileSync(componentPath,"utf8"),scriptBlock=extractFirstScriptBlock(source),templateBlock=extractTemplate(source),props=scriptBlock?extractProps(scriptBlock):[],events=scriptBlock?extractEvents(scriptBlock):[],slots=extractSlots(templateBlock);return{props,events,slots}}function extractFirstScriptBlock(source){const serverMatch=/<script\b[^>]*\bserver\b[^>]*>([\s\S]*?)<\/script>/i.exec(source);if(serverMatch?.[1])return serverMatch[1];return/<script\b[^>]*>([\s\S]*?)<\/script>/i.exec(source)?.[1]??null}function extractTemplate(source){const templateMatch=/<template\b[^>]*>([\s\S]*?)<\/template>/i.exec(source);if(templateMatch?.[1])return templateMatch[1];return source.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"")}function extractProps(script){const interfaces=collectInterfaces(script),propsTypeBody=locatePropsType(script,interfaces);if(!propsTypeBody)return[];const fields=parseTypeBody(propsTypeBody,interfaces),defaults=extractDefaults(script);return fields.map((field)=>{return{name:field.required?field.name:`${field.name}?`,description:renderDescription(field.description),type:field.type,default:defaults[field.name]??field.default??"unknown",required:field.required}})}function collectInterfaces(script){const interfaces=new Map,ifaceRe=/(?:export\s+)?interface\s+([A-Z][\w$]*)\s*(?:extends\s+[\w$,\s]+)?\s*\{/g;let m;while((m=ifaceRe.exec(script))!==null){const name=m[1];if(!name)continue;const start=m.index+m[0].length,body=sliceBalanced(script,start-1,"{","}");if(body!==null)interfaces.set(name,body)}const typeAliasRe=/(?:export\s+)?type\s+([A-Z][\w$]*)\s*=\s*\{/g;while((m=typeAliasRe.exec(script))!==null){const name=m[1];if(!name)continue;const start=m.index+m[0].length,body=sliceBalanced(script,start-1,"{","}");if(body!==null)interfaces.set(name,body)}return interfaces}function locatePropsType(script,interfaces){const match=/defineProps\s*<\s*([\s\S]+?)\s*>\s*\(/.exec(script),generic=match?.[1]?.trim();if(!match||!generic)return null;if(generic.startsWith("{")){const braceStart=script.indexOf("{",match.index);return sliceBalanced(script,braceStart,"{","}")}const ref=generic.replace(/[<>(].*$/,"").split("&")[0]?.trim();if(!ref)return null;return interfaces.get(ref)??null}function parseTypeBody(body,interfaces){const fields=[],statements=splitTopLevel(body,[";",`
1
+ import{frameworkPath,join,path,projectPath}from"@stacksjs/path";import{existsSync,globSync,mkdirSync,writeFileSync}from"@stacksjs/storage";import{readFileSync}from"node:fs";let parseMarkdownFn=null;async function getMarkdownParser(){if(parseMarkdownFn)return parseMarkdownFn;try{const mod=await import("@stacksjs/ts-md");parseMarkdownFn=mod.parseMarkdown}catch{parseMarkdownFn=(s)=>s}return parseMarkdownFn}function renderDescription(raw){if(!raw)return"";return parseMarkdownFn?parseMarkdownFn(raw):raw}export async function generateComponentMeta(){await getMarkdownParser();const components=[...globSync(["components/*.stx","components/**/*.stx","resources/components/**/*.stx"],{cwd:projectPath(),absolute:true}),...globSync(["resources/components/**/*.stx"],{cwd:frameworkPath("defaults"),absolute:true})];const metaDirPath=frameworkPath("component-meta");if(!existsSync(metaDirPath)){mkdirSync(metaDirPath,{recursive:true})}for(const componentPath of components){const componentExportName=path.parse(componentPath).name;const meta=parseStxComponentMeta(componentPath);const metaJsonFilePath=join(metaDirPath,`${componentExportName}.json`);writeFileSync(metaJsonFilePath,JSON.stringify(meta,null,2))}}export function parseStxComponentMeta(componentPath){const source=readFileSync(componentPath,"utf8");const scriptBlock=extractFirstScriptBlock(source);const templateBlock=extractTemplate(source);const props=scriptBlock?extractProps(scriptBlock):[];const events=scriptBlock?extractEvents(scriptBlock):[];const slots=extractSlots(templateBlock);return{props,events,slots}}function extractFirstScriptBlock(source){const serverMatch=/<script\b[^>]*\bserver\b[^>]*>([\s\S]*?)<\/script>/i.exec(source);if(serverMatch?.[1])return serverMatch[1];const anyMatch=/<script\b[^>]*>([\s\S]*?)<\/script>/i.exec(source);return anyMatch?.[1]??null}function extractTemplate(source){const templateMatch=/<template\b[^>]*>([\s\S]*?)<\/template>/i.exec(source);if(templateMatch?.[1])return templateMatch[1];return source.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"")}function extractProps(script){const interfaces=collectInterfaces(script);const propsTypeBody=locatePropsType(script,interfaces);if(!propsTypeBody)return[];const fields=parseTypeBody(propsTypeBody,interfaces);const defaults=extractDefaults(script);return fields.map((field)=>{const merged={name:field.required?field.name:`${field.name}?`,description:renderDescription(field.description),type:field.type,default:defaults[field.name]??field.default??"unknown",required:field.required};return merged})}function collectInterfaces(script){const interfaces=new Map;const ifaceRe=/(?:export\s+)?interface\s+([A-Z][\w$]*)\s*(?:extends\s+[\w$,\s]+)?\s*\{/g;let m;while((m=ifaceRe.exec(script))!==null){const name=m[1];if(!name)continue;const start=m.index+m[0].length;const body=sliceBalanced(script,start-1,"{","}");if(body!==null)interfaces.set(name,body)}const typeAliasRe=/(?:export\s+)?type\s+([A-Z][\w$]*)\s*=\s*\{/g;while((m=typeAliasRe.exec(script))!==null){const name=m[1];if(!name)continue;const start=m.index+m[0].length;const body=sliceBalanced(script,start-1,"{","}");if(body!==null)interfaces.set(name,body)}return interfaces}function locatePropsType(script,interfaces){const defineRe=/defineProps\s*<\s*([\s\S]+?)\s*>\s*\(/;const match=defineRe.exec(script);const generic=match?.[1]?.trim();if(!match||!generic)return null;if(generic.startsWith("{")){const braceStart=script.indexOf("{",match.index);return sliceBalanced(script,braceStart,"{","}")}const ref=generic.replace(/[<>(].*$/,"").split("&")[0]?.trim();if(!ref)return null;return interfaces.get(ref)??null}function parseTypeBody(body,interfaces){const fields=[];const statements=splitTopLevel(body,[";",`
2
2
  `]);let pendingDoc="";for(const raw of statements){const stmt=raw.trim();if(!stmt)continue;const docMatch=/^\/\*\*([\s\S]*?)\*\/\s*([\s\S]*)$/.exec(stmt);if(docMatch){pendingDoc=(docMatch[1]??"").split(`
3
3
  `).map((l)=>l.replace(/^\s*\*\s?/,"")).join(`
4
- `).trim();const remainder=(docMatch[2]??"").trim();if(!remainder)continue;const field=parseFieldLine(remainder,pendingDoc,interfaces);if(field)fields.push(field);pendingDoc="";continue}if(stmt.startsWith("//")){pendingDoc=stmt.replace(/^\/\/\s?/,"");continue}const field=parseFieldLine(stmt,pendingDoc,interfaces);if(field)fields.push(field);pendingDoc=""}return fields}function parseFieldLine(line,description,_interfaces){if(/^[a-zA-Z_$][\w$]*\s*\(/.test(line.trimStart()))return null;const m=/^([a-zA-Z_$][\w$]*)\s*(\??)\s*:\s*([\s\S]+?)\s*[;,]?\s*$/.exec(line);if(!m)return null;const name=m[1],optional=m[2]??"",type=m[3];if(!name||!type)return null;return{name,type:collapseWhitespace(type),required:optional!=="?",description}}function extractDefaults(script){const defaults={},destructRe=/const\s*\{\s*([\s\S]*?)\s*\}\s*=\s*(?:withDefaults\s*\(\s*)?defineProps/g;let m;while((m=destructRe.exec(script))!==null)if(m[1])parseDestructDefaults(m[1],defaults);const withDefaultsIdx=script.indexOf("withDefaults(");if(withDefaultsIdx>=0){const afterDefine=script.indexOf("defineProps",withDefaultsIdx);if(afterDefine>0){const generic=script.indexOf(">",afterDefine),closeParen=script.indexOf(")",generic>=0?generic:afterDefine);if(closeParen>0){const commaIdx=script.indexOf(",",closeParen),objStart=commaIdx>=0?script.indexOf("{",commaIdx):-1;if(objStart>0){const body=sliceBalanced(script,objStart,"{","}");if(body)parseObjectDefaults(body,defaults)}}}}return defaults}function parseDestructDefaults(destructBody,out){for(const part of splitTopLevel(destructBody,[","])){const m=/^\s*([a-zA-Z_$][\w$]*)\s*=\s*([\s\S]+?)\s*$/.exec(part),key=m?.[1],value=m?.[2];if(key&&value)out[key]=collapseWhitespace(value)}}function parseObjectDefaults(objectBody,out){for(const part of splitTopLevel(objectBody,[","])){const m=/^\s*([a-zA-Z_$][\w$]*)\s*:\s*([\s\S]+?)\s*$/.exec(part.trim()),key=m?.[1],value=m?.[2];if(key&&value)out[key]=collapseWhitespace(value)}}function extractEvents(script){const m=/defineEmits\s*<\s*\{([\s\S]*?)\}\s*>\s*\(/.exec(script);if(!m?.[1])return[];const events=[];for(const part of splitTopLevel(m[1],[";",`
5
- `])){const trimmed=part.trim();if(!trimmed)continue;const tuple=/^['"]?([\w-]+)['"]?\s*:\s*\[(.*?)\]\s*$/.exec(trimmed);if(tuple){const name=tuple[1];if(!name)continue;events.push({name,type:tuple[2]?.trim()||"void",description:""});continue}const fn=/^([a-zA-Z_$][\w$]*)\s*\(([\s\S]*?)\)\s*:\s*([\s\S]+)$/.exec(trimmed);if(fn){const name=fn[1];if(!name)continue;events.push({name,type:fn[2]?.trim()||"void",description:""})}}return events}function extractSlots(template){const slots=[],seen=new Set,slotRe=/<slot\b([^>]*)>/g;let m;while((m=slotRe.exec(template))!==null){const attrs=m[1]??"",name=/\bname\s*=\s*["']([^"']+)["']/.exec(attrs)?.[1]??"default";if(seen.has(name))continue;seen.add(name);slots.push({name,description:""})}return slots}function sliceBalanced(source,openIdx,open,close){if(source[openIdx]!==open)return null;let depth=0,i=openIdx,inString=null;while(i<source.length){const ch=source[i];if(ch===void 0)break;if(inString){if(ch==="\\"){i+=2;continue}if(ch===inString)inString=null;i++;continue}if(ch==='"'||ch==="'"||ch==="`"){inString=ch;i++;continue}if(ch===open)depth++;else if(ch===close){depth--;if(depth===0)return source.slice(openIdx+1,i)}i++}return null}function splitTopLevel(source,separators){const out=[],sepSet=new Set(separators);let depth=0,inString=null,start=0;for(let i=0;i<source.length;i++){const ch=source[i];if(ch===void 0)break;if(inString){if(ch==="\\"){i++;continue}if(ch===inString)inString=null;continue}if(ch==='"'||ch==="'"||ch==="`"){inString=ch;continue}if(ch==="{"||ch==="["||ch==="("||ch==="<")depth++;else if(ch==="}"||ch==="]"||ch===")"||ch===">")depth--;else if(depth===0&&sepSet.has(ch)){out.push(source.slice(start,i));start=i+1}}out.push(source.slice(start));return out}function collapseWhitespace(s){return s.replace(/\s+/g," ").trim()}
4
+ `).trim();const remainder=(docMatch[2]??"").trim();if(!remainder)continue;const field=parseFieldLine(remainder,pendingDoc,interfaces);if(field)fields.push(field);pendingDoc="";continue}if(stmt.startsWith("//")){pendingDoc=stmt.replace(/^\/\/\s?/,"");continue}const field=parseFieldLine(stmt,pendingDoc,interfaces);if(field)fields.push(field);pendingDoc=""}return fields}function parseFieldLine(line,description,_interfaces){if(/^[a-zA-Z_$][\w$]*\s*\(/.test(line.trimStart()))return null;const m=/^([a-zA-Z_$][\w$]*)\s*(\??)\s*:\s*([\s\S]+?)\s*[;,]?\s*$/.exec(line);if(!m)return null;const name=m[1];const optional=m[2]??"";const type=m[3];if(!name||!type)return null;return{name,type:collapseWhitespace(type),required:optional!=="?",description}}function extractDefaults(script){const defaults={};const destructRe=/const\s*\{\s*([\s\S]*?)\s*\}\s*=\s*(?:withDefaults\s*\(\s*)?defineProps/g;let m;while((m=destructRe.exec(script))!==null){if(m[1])parseDestructDefaults(m[1],defaults)}const withDefaultsIdx=script.indexOf("withDefaults(");if(withDefaultsIdx>=0){const afterDefine=script.indexOf("defineProps",withDefaultsIdx);if(afterDefine>0){const generic=script.indexOf(">",afterDefine);const closeParen=script.indexOf(")",generic>=0?generic:afterDefine);if(closeParen>0){const commaIdx=script.indexOf(",",closeParen);const objStart=commaIdx>=0?script.indexOf("{",commaIdx):-1;if(objStart>0){const body=sliceBalanced(script,objStart,"{","}");if(body)parseObjectDefaults(body,defaults)}}}}return defaults}function parseDestructDefaults(destructBody,out){for(const part of splitTopLevel(destructBody,[","])){const m=/^\s*([a-zA-Z_$][\w$]*)\s*=\s*([\s\S]+?)\s*$/.exec(part);const key=m?.[1];const value=m?.[2];if(key&&value)out[key]=collapseWhitespace(value)}}function parseObjectDefaults(objectBody,out){for(const part of splitTopLevel(objectBody,[","])){const m=/^\s*([a-zA-Z_$][\w$]*)\s*:\s*([\s\S]+?)\s*$/.exec(part.trim());const key=m?.[1];const value=m?.[2];if(key&&value)out[key]=collapseWhitespace(value)}}function extractEvents(script){const m=/defineEmits\s*<\s*\{([\s\S]*?)\}\s*>\s*\(/.exec(script);if(!m?.[1])return[];const events=[];for(const part of splitTopLevel(m[1],[";",`
5
+ `])){const trimmed=part.trim();if(!trimmed)continue;const tuple=/^['"]?([\w-]+)['"]?\s*:\s*\[(.*?)\]\s*$/.exec(trimmed);if(tuple){const name=tuple[1];if(!name)continue;events.push({name,type:tuple[2]?.trim()||"void",description:""});continue}const fn=/^([a-zA-Z_$][\w$]*)\s*\(([\s\S]*?)\)\s*:\s*([\s\S]+)$/.exec(trimmed);if(fn){const name=fn[1];if(!name)continue;events.push({name,type:fn[2]?.trim()||"void",description:""})}}return events}function extractSlots(template){const slots=[];const seen=new Set;const slotRe=/<slot\b([^>]*)>/g;let m;while((m=slotRe.exec(template))!==null){const attrs=m[1]??"";const nameMatch=/\bname\s*=\s*["']([^"']+)["']/.exec(attrs);const name=nameMatch?.[1]??"default";if(seen.has(name))continue;seen.add(name);slots.push({name,description:""})}return slots}function sliceBalanced(source,openIdx,open,close){if(source[openIdx]!==open)return null;let depth=0;let i=openIdx;let inString=null;while(i<source.length){const ch=source[i];if(ch===undefined)break;if(inString){if(ch==="\\"){i+=2;continue}if(ch===inString)inString=null;i++;continue}if(ch==='"'||ch==="'"||ch==="`"){inString=ch;i++;continue}if(ch===open)depth++;else if(ch===close){depth--;if(depth===0)return source.slice(openIdx+1,i)}i++}return null}function splitTopLevel(source,separators){const out=[];const sepSet=new Set(separators);let depth=0;let inString=null;let start=0;for(let i=0;i<source.length;i++){const ch=source[i];if(ch===undefined)break;if(inString){if(ch==="\\"){i++;continue}if(ch===inString)inString=null;continue}if(ch==='"'||ch==="'"||ch==="`"){inString=ch;continue}if(ch==="{"||ch==="["||ch==="("||ch==="<")depth++;else if(ch==="}"||ch==="]"||ch===")"||ch===">")depth--;else if(depth===0&&sepSet.has(ch)){out.push(source.slice(start,i));start=i+1}}out.push(source.slice(start));return out}function collapseWhitespace(s){return s.replace(/\s+/g," ").trim()}
@@ -1 +1 @@
1
- var {require}=import.meta;import{existsSync}from"node:fs";import{delimiter,join}from"node:path";import process from"node:process";import{buddyOptionArgs,runCommand}from"@stacksjs/cli";import{app}from"@stacksjs/config";import{Action as ActionEnum}from"@stacksjs/enums";import{err,handleError,ok}from"@stacksjs/error-handling";import{log}from"@stacksjs/logging";import*as p from"@stacksjs/path";const coreActionNames=new Set(Object.values(ActionEnum));export function publishedActionCandidates(action,packageRoot){let root=packageRoot;if(!root)try{const pkgUrl=import.meta.resolve("@stacksjs/actions/package.json");if(pkgUrl){const pkgPath=new URL(pkgUrl).pathname;root=pkgPath.slice(0,pkgPath.lastIndexOf("/"))}}catch{return[]}if(!root)return[];return[`${root}/dist/${action}.js`,`${root}/dist/src/${action}.js`,`${root}/src/${action}.ts`]}export function developmentConditionForProject(projectRoot){return existsSync(join(projectRoot,"storage/framework/core"))&&existsSync(join(projectRoot,"node_modules/@stacksjs/env/src/index.ts"))?"--conditions development":""}export function actionNodePath(projectRoot,existingNodePath){const nodeModulesPath=join(projectRoot,"node_modules"),pantryPath=join(projectRoot,"pantry"),paths=[nodeModulesPath];for(const entry of existingNodePath?.split(delimiter)??[])if(entry&&entry!==nodeModulesPath&&entry!==pantryPath&&!paths.includes(entry))paths.push(entry);paths.push(pantryPath);return paths.join(delimiter)}async function resolveActionFile(action,projectRoot){const candidates=[];if(projectRoot)candidates.push(join(projectRoot,`storage/framework/core/actions/src/${action}.ts`));candidates.push(p.actionsPath(`src/${action}.ts`));candidates.push(...publishedActionCandidates(action));for(const candidate of candidates)if(await Bun.file(candidate).exists())return candidate;return null}export async function runAction(action,options){log.debug(`[action] Running: ${action}`);if(action==="dev/views")try{const nodePath=actionNodePath(p.projectPath(),process.env.NODE_PATH);if(process.env.NODE_PATH!==nodePath){process.env.NODE_PATH=nodePath;require("module").Module._initPaths?.()}const viewsEntries=[p.projectPath("storage/framework/core/actions/src/dev/views.ts"),p.frameworkPath("actions/src/dev/views.ts"),...publishedActionCandidates("dev/views")];for(const entry of viewsEntries)if(existsSync(entry)){await import(entry);return ok({})}return err(Error("dev/views entry not found"))}catch(error){return err(Error(`Failed to start dev server: ${error}`))}const isLikelyCoreAction=action.includes("/")||["dev","build","install","upgrade","migrate"].some((prefix)=>action.startsWith(prefix)),userActionsBase=options?.cwd?join(String(options.cwd),"app/Actions"):p.userActionsPath();if(!isLikelyCoreAction&&existsSync(userActionsBase)){const glob=new Bun.Glob("**/*.{ts,js}"),scanOptions={cwd:userActionsBase,onlyFiles:!0,absolute:!0},matchingFiles=[],basePath=userActionsBase;for await(const file of glob.scan(scanOptions)){if(file.replace(`${basePath}/`,"").replace(/\.(ts|js)$/,"")===action||file.endsWith(`${action}.ts`)||file.endsWith(`${action}.js`)){log.debug(`[action] Resolved: ${action} \u2192 ${file}`);return await(await import(file)).default.handle(void 0)}matchingFiles.push(file)}for(const file of coreActionNames.has(action)?[]:matchingFiles)try{const a=await import(file);if(a.name===action){log.debug(`[action] Resolved: ${action} \u2192 ${file}`);return await a.handle()}}catch(error){}}const path=await resolveActionFile(action,options?.cwd?String(options.cwd):void 0);if(!path)return err(Error(`Action '${action}' not found in storage/framework/core/actions/src or @stacksjs/actions`));log.debug(`[action] Resolved: ${action} \u2192 ${path}`);const isDevAction=action.startsWith("dev/"),watchFlag=developmentWatchFlag(action),developmentCondition=developmentConditionForProject(p.projectPath()),opts=isDevAction||!options?[]:buddyOptionArgs(options),cmd=[...["bun",developmentCondition,watchFlag,path].filter(Boolean),...opts],nodePath=actionNodePath(p.projectPath(),process.env.NODE_PATH),shouldInherit=options?.verbose||isDevAction&&!options?.quiet,optionsWithCwd={cwd:options?.cwd||p.projectPath(),...options,forwardSignals:action===ActionEnum.QueueWork||options?.forwardSignals,stdout:shouldInherit?"inherit":void 0,stderr:shouldInherit?"inherit":void 0,env:{...options?.env,NODE_PATH:nodePath,...isDevAction?{STACKS_DEV_SERVER:"1"}:{}}},result=await runCommand(cmd,optionsWithCwd);log.debug(`[action] Completed: ${action}`);return result}export function developmentWatchFlag(action){if(!action.startsWith("dev/"))return"";return action==="dev/dashboard"||action==="dev/desktop"?"":"--watch"}export async function runActions(actions,options){if(!actions.length)return err("No actions were specified");for(const action of actions)if(!hasAction(action))return err(`The specified action "${action}" does not exist`);return await runActionSequence(actions,options)}export async function runActionSequence(actions,options,runner=runAction){let result;for(const action of actions){result=await runner(action,options);if(result?.isErr)return result}return result}export function hasAction(action){const userActionPatterns=[`${action}.ts`,`${action}`,`Dashboard/${action}.ts`,`Dashboard/${action}`,`Buddy/${action}.ts`,`Buddy/${action}`],actionPatterns=[`src/${action}.ts`,`src/${action}`,`${action}.ts`,`${action}`];return[...userActionPatterns.map((pattern)=>p.userActionsPath(pattern)),...actionPatterns.map((pattern)=>p.actionsPath(pattern)),...publishedActionCandidates(action)].some((candidate)=>existsSync(candidate))}export async function initProject(){if(app.env!=="production")log.info("Project not yet initialized, generating application key...");else handleError("Please run `buddy key:generate` to generate an application key");const result=await runAction(ActionEnum.KeyGenerate,{cwd:p.projectPath()});if(result.isErr)return err(handleError(result.error));log.info("Application key generated.");return ok(result.value)}
1
+ import{existsSync}from"node:fs";import{delimiter,join}from"node:path";import process from"node:process";import{buddyOptionArgs,runCommand}from"@stacksjs/cli";import{app}from"@stacksjs/config";import{Action as ActionEnum}from"@stacksjs/enums";import{err,handleError,ok}from"@stacksjs/error-handling";import{log}from"@stacksjs/logging";import*as p from"@stacksjs/path";const coreActionNames=new Set(Object.values(ActionEnum));export function publishedActionCandidates(action,packageRoot){let root=packageRoot;if(!root){try{const pkgUrl=import.meta.resolve("@stacksjs/actions/package.json");if(pkgUrl){const pkgPath=new URL(pkgUrl).pathname;root=pkgPath.slice(0,pkgPath.lastIndexOf("/"))}}catch{return[]}}if(!root)return[];return[`${root}/dist/${action}.js`,`${root}/dist/src/${action}.js`,`${root}/src/${action}.ts`]}export function developmentConditionForProject(projectRoot){return existsSync(join(projectRoot,"storage/framework/core"))&&existsSync(join(projectRoot,"node_modules/@stacksjs/env/src/index.ts"))?"--conditions development":""}export function actionNodePath(projectRoot,existingNodePath){const nodeModulesPath=join(projectRoot,"node_modules");const pantryPath=join(projectRoot,"pantry");const paths=[nodeModulesPath];for(const entry of existingNodePath?.split(delimiter)??[]){if(entry&&entry!==nodeModulesPath&&entry!==pantryPath&&!paths.includes(entry))paths.push(entry)}paths.push(pantryPath);return paths.join(delimiter)}async function resolveActionFile(action,projectRoot){const candidates=[];if(projectRoot)candidates.push(join(projectRoot,`storage/framework/core/actions/src/${action}.ts`));candidates.push(p.actionsPath(`src/${action}.ts`));candidates.push(...publishedActionCandidates(action));for(const candidate of candidates){if(await Bun.file(candidate).exists())return candidate}return null}export async function runAction(action,options){log.debug(`[action] Running: ${action}`);if(action==="dev/views"){try{const nodePath=actionNodePath(p.projectPath(),process.env.NODE_PATH);if(process.env.NODE_PATH!==nodePath){process.env.NODE_PATH=nodePath;require("module").Module._initPaths?.()}const viewsEntries=[p.projectPath("storage/framework/core/actions/src/dev/views.ts"),p.frameworkPath("actions/src/dev/views.ts"),...publishedActionCandidates("dev/views")];for(const entry of viewsEntries){if(existsSync(entry)){await import(entry);return ok({})}}return err(new Error("dev/views entry not found"))}catch(error){return err(new Error(`Failed to start dev server: ${error}`))}}const isLikelyCoreAction=action.includes("/")||["dev","build","install","upgrade","migrate"].some((prefix)=>action.startsWith(prefix));const userActionsBase=options?.cwd?join(String(options.cwd),"app/Actions"):p.userActionsPath();if(!isLikelyCoreAction&&existsSync(userActionsBase)){const glob=new Bun.Glob("**/*.{ts,js}");const scanOptions={cwd:userActionsBase,onlyFiles:true,absolute:true};const matchingFiles=[];const basePath=userActionsBase;for await(const file of glob.scan(scanOptions)){const relativePath=file.replace(`${basePath}/`,"").replace(/\.(ts|js)$/,"");if(relativePath===action||file.endsWith(`${action}.ts`)||file.endsWith(`${action}.js`)){log.debug(`[action] Resolved: ${action} → ${file}`);return await(await import(file)).default.handle(undefined)}matchingFiles.push(file)}for(const file of coreActionNames.has(action)?[]:matchingFiles){try{const a=await import(file);if(a.name===action){log.debug(`[action] Resolved: ${action} → ${file}`);return await a.handle()}}catch(error){}}}const path=await resolveActionFile(action,options?.cwd?String(options.cwd):undefined);if(!path){return err(new Error(`Action '${action}' not found in storage/framework/core/actions/src or @stacksjs/actions`))}log.debug(`[action] Resolved: ${action} → ${path}`);const isDevAction=action.startsWith("dev/");const watchFlag=developmentWatchFlag(action);const developmentCondition=developmentConditionForProject(p.projectPath());const opts=isDevAction||!options?[]:buddyOptionArgs(options);const cmd=[...["bun",developmentCondition,watchFlag,path].filter(Boolean),...opts];const nodePath=actionNodePath(p.projectPath(),process.env.NODE_PATH);const shouldInherit=options?.verbose||isDevAction&&!options?.quiet;const optionsWithCwd={cwd:options?.cwd||p.projectPath(),...options,forwardSignals:action===ActionEnum.QueueWork||options?.forwardSignals,stdout:shouldInherit?"inherit":undefined,stderr:shouldInherit?"inherit":undefined,env:{...options?.env,NODE_PATH:nodePath,...isDevAction?{STACKS_DEV_SERVER:"1"}:{}}};const result=await runCommand(cmd,optionsWithCwd);log.debug(`[action] Completed: ${action}`);return result}export function developmentWatchFlag(action){if(!action.startsWith("dev/"))return"";return action==="dev/dashboard"||action==="dev/desktop"?"":"--watch"}export async function runActions(actions,options){if(!actions.length)return err("No actions were specified");for(const action of actions){if(!hasAction(action))return err(`The specified action "${action}" does not exist`)}return await runActionSequence(actions,options)}export async function runActionSequence(actions,options,runner=runAction){let result;for(const action of actions){result=await runner(action,options);if(result?.isErr)return result}return result}export function hasAction(action){const userActionPatterns=[`${action}.ts`,`${action}`,`Dashboard/${action}.ts`,`Dashboard/${action}`,`Buddy/${action}.ts`,`Buddy/${action}`];const actionPatterns=[`src/${action}.ts`,`src/${action}`,`${action}.ts`,`${action}`];const candidates=[...userActionPatterns.map((pattern)=>p.userActionsPath(pattern)),...actionPatterns.map((pattern)=>p.actionsPath(pattern)),...publishedActionCandidates(action)];return candidates.some((candidate)=>existsSync(candidate))}export async function initProject(){if(app.env!=="production")log.info("Project not yet initialized, generating application key...");else handleError("Please run `buddy key:generate` to generate an application key");const result=await runAction(ActionEnum.KeyGenerate,{cwd:p.projectPath()});if(result.isErr)return err(handleError(result.error));log.info("Application key generated.");return ok(result.value)}
@@ -1,3 +1,3 @@
1
1
  import{config,overridesReady}from"@stacksjs/config";import{err,ok}from"@stacksjs/error-handling";import{log}from"@stacksjs/logging";import{customElementsDataPath,frameworkPath}from"@stacksjs/path";import{writeTextFile}from"@stacksjs/storage";async function generateComponentInfoData(){await overridesReady;const tags=config.library?.webComponents?.tags??[];return`${JSON.stringify({version:1.1,tags},null,2)}
2
- `}export async function generateVsCodeCustomData(){try{log.info("Generating custom-elements.json...");await writeTextFile({path:customElementsDataPath(),data:await generateComponentInfoData()});log.success("Generated custom-elements.json for IDEs.");return ok(void 0)}catch(e){log.error("There was an error generating the custom-elements.json file.",e);return err("There was an error generating the custom-elements.json file.")}}export async function generateWebTypes(){log.info("Generating web-types.json...");await writeTextFile({path:frameworkPath("core/web-types.json"),data:await generateWebTypesData()});log.success("Generated web-types.json for IDEs.")}export async function generateWebTypesData(){await overridesReady;const library=config.library??{},tags=(library.webComponents?.tags??[]).map((tag)=>{const sourceName=Array.isArray(tag.name)?tag.name[0]:tag.name;return{name:Array.isArray(tag.name)?tag.name[1]:tag.name,description:tag.description??"",attributes:tag.attributes??[],source:{module:`../../defaults/resources/components/${sourceName}.stx`,symbol:"default"}}});return`${JSON.stringify({framework:"stx",name:library.name,contributions:{html:{"description-markup":"markdown","types-syntax":"typescript",tags}}},null,2)}
2
+ `}export async function generateVsCodeCustomData(){try{log.info("Generating custom-elements.json...");await writeTextFile({path:customElementsDataPath(),data:await generateComponentInfoData()});log.success("Generated custom-elements.json for IDEs.");return ok(undefined)}catch(e){log.error("There was an error generating the custom-elements.json file.",e);return err("There was an error generating the custom-elements.json file.")}}export async function generateWebTypes(){log.info("Generating web-types.json...");await writeTextFile({path:frameworkPath("core/web-types.json"),data:await generateWebTypesData()});log.success("Generated web-types.json for IDEs.")}export async function generateWebTypesData(){await overridesReady;const library=config.library??{};const tags=(library.webComponents?.tags??[]).map((tag)=>{const sourceName=Array.isArray(tag.name)?tag.name[0]:tag.name;const publicName=Array.isArray(tag.name)?tag.name[1]:tag.name;return{name:publicName,description:tag.description??"",attributes:tag.attributes??[],source:{module:`../../defaults/resources/components/${sourceName}.stx`,symbol:"default"}}});return`${JSON.stringify({framework:"stx",name:library.name,contributions:{html:{"description-markup":"markdown","types-syntax":"typescript",tags}}},null,2)}
3
3
  `}
@@ -1 +1 @@
1
- import{readFileSync}from"node:fs";import{runCommand}from"@stacksjs/cli";import{generateKeypair}from"@stacksjs/env";import{projectPath}from"@stacksjs/path";import{generateAppKey}from"@stacksjs/security";import{existsSync}from"@stacksjs/storage";import{setEnvValue}from"@stacksjs/utils";if(!existsSync(".env"))await runCommand("cp .env.example .env",{cwd:projectPath()});await setEnvValue("APP_KEY",generateAppKey());const envText=(()=>{try{return readFileSync(projectPath(".env"),"utf-8")}catch{return""}})(),hasPublic=/^DOTENV_PUBLIC_KEY=.+$/m.test(envText),hasPrivate=/^DOTENV_PRIVATE_KEY=.+$/m.test(envText);if(!hasPublic||!hasPrivate){const{publicKey,privateKey}=generateKeypair();if(!hasPublic)await setEnvValue("DOTENV_PUBLIC_KEY",publicKey);if(!hasPrivate)await setEnvValue("DOTENV_PRIVATE_KEY",privateKey)}
1
+ import{readFileSync}from"node:fs";import{runCommand}from"@stacksjs/cli";import{generateKeypair}from"@stacksjs/env";import{projectPath}from"@stacksjs/path";import{generateAppKey}from"@stacksjs/security";import{existsSync}from"@stacksjs/storage";import{setEnvValue}from"@stacksjs/utils";if(!existsSync(".env"))await runCommand("cp .env.example .env",{cwd:projectPath()});await setEnvValue("APP_KEY",generateAppKey());const envText=(()=>{try{return readFileSync(projectPath(".env"),"utf-8")}catch{return""}})();const hasPublic=/^DOTENV_PUBLIC_KEY=.+$/m.test(envText);const hasPrivate=/^DOTENV_PRIVATE_KEY=.+$/m.test(envText);if(!hasPublic||!hasPrivate){const{publicKey,privateKey}=generateKeypair();if(!hasPublic)await setEnvValue("DOTENV_PUBLIC_KEY",publicKey);if(!hasPrivate)await setEnvValue("DOTENV_PRIVATE_KEY",privateKey)}
@@ -1,5 +1,5 @@
1
- import{existsSync}from"node:fs";import{cp,mkdir,rm}from"node:fs/promises";import{dirname,relative,resolve}from"node:path";import{transpilePackage,validateDeclarations,validateRuntimeExports}from"@stacksjs/build";import{log}from"@stacksjs/logging";import{projectPath}from"@stacksjs/path";import{buildComponentLibrary}from"@stacksjs/stx";import{functionEntryData}from"./entries";import{ambientGlobalsUsed,stxAmbientGlobals}from"./globals";import{generatedReadme,libraryManifest,serializeManifest}from"./manifest";import{configuredLibrary,LibraryConfigError,resolveLibraryPackages}from"./packages";export async function buildLibraryPackages(options={}){const config=options.config??await configuredLibrary(),kinds=options.kinds,compile=options.compile??!0,all=await resolveLibraryPackages(config,{onUnmatched:options.allowEmpty?"skip":"error"}),packages=kinds?all.filter((pkg)=>kinds.includes(pkg.kind)):all;if(!packages.length){if(options.allowEmpty){log.info("No library packages are configured. Nothing to build.");return[]}throw new LibraryConfigError(kinds?`No ${kinds.join("/")} packages are configured. Add one to \`packages\` in config/library.ts.`:"No library packages are configured. Add one to `packages` in config/library.ts.")}const version=await projectVersion(),reports=[];for(const pkg of packages){const verb=compile?"Building":"Generating";log.info(`${verb} ${pkg.name} (${pkg.kind}, ${pkg.sources.length} source${pkg.sources.length===1?"":"s"})...`);if(compile)await rm(resolve(pkg.dir,"dist"),{recursive:!0,force:!0});await mkdir(pkg.dir,{recursive:!0});if(compile)runPrebuild(pkg);if(pkg.kind==="functions")await buildFunctionPackage(pkg,config,version,compile);else await buildComponentPackage(pkg,config,version,compile);if(compile)await copyAssets(pkg);reports.push({name:pkg.name,kind:pkg.kind,dir:pkg.dir,sources:pkg.sources.length});if(compile)log.success(`Built ${pkg.name} \u2192 ${relative(projectPath(),pkg.dir)}/dist`)}return reports}export async function generateLibraryPackages(options={}){return buildLibraryPackages({...options,compile:!1})}async function buildFunctionPackage(pkg,config,version,compile){await assertPublishable(pkg);const srcDir=resolve(pkg.dir,"src");await rm(srcDir,{recursive:!0,force:!0});const staged=[];for(const source of pkg.sources){const destination=resolve(srcDir,relative(pkg.sourceDir,source));await mkdir(dirname(destination),{recursive:!0});await Bun.write(destination,await Bun.file(source).text());staged.push(destination)}const entry=resolve(srcDir,"index.ts");if(staged.includes(entry))throw new LibraryConfigError(`Package "${pkg.name}" claims resources/functions/index.ts, which collides with the generated barrel. Rename it or exclude it.`);await Bun.write(entry,functionEntryData(pkg,staged));await writeManifest(pkg,config,version);if(!compile)return;await transpilePackage({dir:pkg.dir,pkgName:pkg.name,external:["@stacksjs/*","bun",...Object.keys(pkg.dependencies),...Object.keys(pkg.peerDependencies)]});await validateDeclarations(pkg.dir);await validateRuntimeExports(pkg.dir)}async function buildComponentPackage(pkg,config,version,compile){if(!compile){await writeManifest(pkg,config,version);return}const result=await buildComponentLibrary({inputDir:pkg.sourceDir,outputDir:resolve(pkg.dir,"dist"),prefix:pkg.prefix,components:pkg.sources.map((source)=>{const file=relative(pkg.sourceDir,source),stem=file.replace(/\.stx$/,"").split("/").at(-1);return pkg.names[stem]?{file,name:pkg.names[stem]}:{file}}),progressive:!0,manifest:!0,declarations:!0,css:!0,bundle:!0,minify:!0,sourcemap:pkg.sourcemap?"external":!1});log.debug(`${pkg.name}: compiled ${result.components.length} components (${result.totalBytes} bytes)`);await writeManifest(pkg,config,version);await validateDeclarations(pkg.dir);await validateRuntimeExports(pkg.dir)}function runPrebuild(pkg){if(!pkg.prebuild)return;log.info(`${pkg.name}: ${pkg.prebuild}`);const proc=Bun.spawnSync({cmd:["sh","-c",pkg.prebuild],cwd:projectPath(),stdout:"inherit",stderr:"inherit"});if(proc.exitCode!==0)throw new LibraryConfigError(`Package "${pkg.name}": prebuild \`${pkg.prebuild}\` exited with code ${proc.exitCode}.`)}async function copyAssets(pkg){for(const asset of pkg.assets){const source=projectPath(asset.source),destination=resolve(pkg.dir,"dist",asset.dest);if(!existsSync(source))throw new LibraryConfigError(`Package "${pkg.name}" ships "${asset.source}" as ${asset.dest}, but it does not exist.`+(pkg.prebuild?" The prebuild command did not produce it.":" Build it first, or set `prebuild` to the command that does."));if(existsSync(destination))throw new LibraryConfigError(`Package "${pkg.name}": asset ${asset.dest} collides with a file the build wrote to dist/${asset.dest}.`);await mkdir(dirname(destination),{recursive:!0});await cp(source,destination,{recursive:!0})}}async function assertPublishable(pkg){if(pkg.runtime==="stx")return;const globals=await stxAmbientGlobals();if(!globals.size)return;const offenders=[];for(const source of pkg.sources){const used=ambientGlobalsUsed(await Bun.file(source).text(),globals);if(used.length)offenders.push(` ${relative(projectPath(),source)} \u2192 ${used.join(", ")}`)}if(!offenders.length)return;throw new LibraryConfigError(`Package "${pkg.name}" uses stx's ambient globals, which no module exports:
1
+ import{existsSync}from"node:fs";import{cp,mkdir,rm}from"node:fs/promises";import{dirname,relative,resolve}from"node:path";import{transpilePackage,validateDeclarations,validateRuntimeExports}from"@stacksjs/build";import{log}from"@stacksjs/logging";import{projectPath}from"@stacksjs/path";import{buildComponentLibrary}from"@stacksjs/stx";import{functionEntryData}from"./entries";import{ambientGlobalsUsed,stxAmbientGlobals}from"./globals";import{generatedReadme,libraryManifest,serializeManifest}from"./manifest";import{configuredLibrary,LibraryConfigError,resolveLibraryPackages}from"./packages";export async function buildLibraryPackages(options={}){const config=options.config??await configuredLibrary();const kinds=options.kinds;const compile=options.compile??true;const all=await resolveLibraryPackages(config,{onUnmatched:options.allowEmpty?"skip":"error"});const packages=kinds?all.filter((pkg)=>kinds.includes(pkg.kind)):all;if(!packages.length){if(options.allowEmpty){log.info("No library packages are configured. Nothing to build.");return[]}throw new LibraryConfigError(kinds?`No ${kinds.join("/")} packages are configured. Add one to \`packages\` in config/library.ts.`:"No library packages are configured. Add one to `packages` in config/library.ts.")}const version=await projectVersion();const reports=[];for(const pkg of packages){const verb=compile?"Building":"Generating";log.info(`${verb} ${pkg.name} (${pkg.kind}, ${pkg.sources.length} source${pkg.sources.length===1?"":"s"})...`);if(compile)await rm(resolve(pkg.dir,"dist"),{recursive:true,force:true});await mkdir(pkg.dir,{recursive:true});if(compile)runPrebuild(pkg);if(pkg.kind==="functions")await buildFunctionPackage(pkg,config,version,compile);else await buildComponentPackage(pkg,config,version,compile);if(compile)await copyAssets(pkg);reports.push({name:pkg.name,kind:pkg.kind,dir:pkg.dir,sources:pkg.sources.length});if(compile)log.success(`Built ${pkg.name} → ${relative(projectPath(),pkg.dir)}/dist`)}return reports}export async function generateLibraryPackages(options={}){return buildLibraryPackages({...options,compile:false})}async function buildFunctionPackage(pkg,config,version,compile){await assertPublishable(pkg);const srcDir=resolve(pkg.dir,"src");await rm(srcDir,{recursive:true,force:true});const staged=[];for(const source of pkg.sources){const destination=resolve(srcDir,relative(pkg.sourceDir,source));await mkdir(dirname(destination),{recursive:true});await Bun.write(destination,await Bun.file(source).text());staged.push(destination)}const entry=resolve(srcDir,"index.ts");if(staged.includes(entry)){throw new LibraryConfigError(`Package "${pkg.name}" claims resources/functions/index.ts, which collides with the generated barrel. Rename it or exclude it.`)}await Bun.write(entry,functionEntryData(pkg,staged));await writeManifest(pkg,config,version);if(!compile)return;await transpilePackage({dir:pkg.dir,pkgName:pkg.name,external:["@stacksjs/*","bun",...Object.keys(pkg.dependencies),...Object.keys(pkg.peerDependencies)]});await validateDeclarations(pkg.dir);await validateRuntimeExports(pkg.dir)}async function buildComponentPackage(pkg,config,version,compile){if(!compile){await writeManifest(pkg,config,version);return}const result=await buildComponentLibrary({inputDir:pkg.sourceDir,outputDir:resolve(pkg.dir,"dist"),prefix:pkg.prefix,components:pkg.sources.map((source)=>{const file=relative(pkg.sourceDir,source);const stem=file.replace(/\.stx$/,"").split("/").at(-1);return pkg.names[stem]?{file,name:pkg.names[stem]}:{file}}),progressive:true,manifest:true,declarations:true,css:true,bundle:true,minify:true,sourcemap:pkg.sourcemap?"external":false});log.debug(`${pkg.name}: compiled ${result.components.length} components (${result.totalBytes} bytes)`);await writeManifest(pkg,config,version);await validateDeclarations(pkg.dir);await validateRuntimeExports(pkg.dir)}function runPrebuild(pkg){if(!pkg.prebuild)return;log.info(`${pkg.name}: ${pkg.prebuild}`);const proc=Bun.spawnSync({cmd:["sh","-c",pkg.prebuild],cwd:projectPath(),stdout:"inherit",stderr:"inherit"});if(proc.exitCode!==0)throw new LibraryConfigError(`Package "${pkg.name}": prebuild \`${pkg.prebuild}\` exited with code ${proc.exitCode}.`)}async function copyAssets(pkg){for(const asset of pkg.assets){const source=projectPath(asset.source);const destination=resolve(pkg.dir,"dist",asset.dest);if(!existsSync(source)){throw new LibraryConfigError(`Package "${pkg.name}" ships "${asset.source}" as ${asset.dest}, but it does not exist.`+(pkg.prebuild?` The prebuild command did not produce it.`:" Build it first, or set `prebuild` to the command that does."))}if(existsSync(destination))throw new LibraryConfigError(`Package "${pkg.name}": asset ${asset.dest} collides with a file the build wrote to dist/${asset.dest}.`);await mkdir(dirname(destination),{recursive:true});await cp(source,destination,{recursive:true})}}async function assertPublishable(pkg){if(pkg.runtime==="stx")return;const globals=await stxAmbientGlobals();if(!globals.size)return;const offenders=[];for(const source of pkg.sources){const used=ambientGlobalsUsed(await Bun.file(source).text(),globals);if(used.length)offenders.push(` ${relative(projectPath(),source)} → ${used.join(", ")}`)}if(!offenders.length)return;throw new LibraryConfigError(`Package "${pkg.name}" uses stx's ambient globals, which no module exports:
2
2
  ${offenders.join(`
3
3
  `)}
4
4
 
5
- A consumer importing the published package would hit a ReferenceError. Either import those names explicitly in the source, or set \`runtime: 'stx'\` on the package in config/library.ts to declare that it is only ever consumed from inside an stx app.`)}async function writeManifest(pkg,config,version){const manifest=libraryManifest(pkg,config,version,pkg.sources.map((source)=>relative(projectPath(),source)));await Bun.write(resolve(pkg.dir,"package.json"),serializeManifest(withRuntime(manifest,pkg)));await Bun.write(resolve(pkg.dir,"README.md"),await readme(pkg,config))}async function readme(pkg,config){if(!pkg.readme)return generatedReadme(pkg,config);const file=Bun.file(projectPath(pkg.readme));if(!await file.exists())throw new LibraryConfigError(`Package "${pkg.name}" names readme "${pkg.readme}", which does not exist.`);return file.text()}function withRuntime(manifest,pkg){if(pkg.runtime!=="stx")return manifest;return{...manifest,stacks:{...manifest.stacks,runtime:"stx"}}}export async function projectVersion(){return(await Bun.file(projectPath("package.json")).json()).version??"0.0.0"}
5
+ `+"A consumer importing the published package would hit a ReferenceError. Either import those names explicitly "+`in the source, or set \`runtime: 'stx'\` on the package in config/library.ts to declare that it is only ever `+"consumed from inside an stx app.")}async function writeManifest(pkg,config,version){const manifest=libraryManifest(pkg,config,version,pkg.sources.map((source)=>relative(projectPath(),source)));await Bun.write(resolve(pkg.dir,"package.json"),serializeManifest(withRuntime(manifest,pkg)));await Bun.write(resolve(pkg.dir,"README.md"),await readme(pkg,config))}async function readme(pkg,config){if(!pkg.readme)return generatedReadme(pkg,config);const file=Bun.file(projectPath(pkg.readme));if(!await file.exists())throw new LibraryConfigError(`Package "${pkg.name}" names readme "${pkg.readme}", which does not exist.`);return file.text()}function withRuntime(manifest,pkg){if(pkg.runtime!=="stx")return manifest;return{...manifest,stacks:{...manifest.stacks,runtime:"stx"}}}export async function projectVersion(){const manifest=await Bun.file(projectPath("package.json")).json();return manifest.version??"0.0.0"}
@@ -1,3 +1,3 @@
1
- import{relative}from"node:path";export function functionEntryData(pkg,stagedSources){const lines=[`// Generated by \`buddy generate:entries\` for ${pkg.name}. Do not edit.`,""];for(const source of stagedSources){const path=relative(`${pkg.dir}/src`,source),specifier=`./${path}`,alias=pkg.aliases[path.replace(/\.ts$/,"")];lines.push(alias?`export * as ${alias} from '${specifier}'`:`export * from '${specifier}'`)}return`${lines.join(`
1
+ import{relative}from"node:path";export function functionEntryData(pkg,stagedSources){const lines=[`// Generated by \`buddy generate:entries\` for ${pkg.name}. Do not edit.`,""];for(const source of stagedSources){const path=relative(`${pkg.dir}/src`,source);const specifier=`./${path}`;const alias=pkg.aliases[path.replace(/\.ts$/,"")];lines.push(alias?`export * as ${alias} from '${specifier}'`:`export * from '${specifier}'`)}return`${lines.join(`
2
2
  `)}
3
3
  `}
@@ -1 +1 @@
1
- import{existsSync}from"node:fs";import{projectPath}from"@stacksjs/path";export async function stxAmbientGlobals(){const file=[projectPath("node_modules/@stacksjs/stx/stx.d.ts"),projectPath("storage/framework/core/stx/stx.d.ts")].find((candidate)=>existsSync(candidate));if(!file)return new Set;const source=await Bun.file(file).text(),names=new Set;for(const match of source.matchAll(/^declare (?:function|const|class)\s+([A-Za-z_$][\w$]*)/gm))names.add(match[1]);return names}export function ambientGlobalsUsed(source,globals){const stripped=source.replace(/\/\*[\s\S]*?\*\//g," ").replace(/\/\/[^\n]*/g," ").replace(/(['"`])(?:\\.|(?!\1)[^\\])*\1/g,'""'),used=new Set;for(const match of stripped.matchAll(/(^|[^.\w$])([A-Za-z_$][\w$]*)\s*(?=[([<.,;)\]}=+\-*/?:]|$)/gm)){const name=match[2];if(globals.has(name))used.add(name)}if(!used.size)return[];for(const name of[...used]){const declared=new RegExp(`(?:^|[^.\\w$])(?:const|let|var|function|class)\\s+${name}\\b`,"m").test(stripped),imported=new RegExp(`import[^;]*\\b${name}\\b[^;]*from`,"m").test(stripped);if(declared||imported)used.delete(name)}return[...used].sort()}
1
+ import{existsSync}from"node:fs";import{projectPath}from"@stacksjs/path";export async function stxAmbientGlobals(){const candidates=[projectPath("node_modules/@stacksjs/stx/stx.d.ts"),projectPath("storage/framework/core/stx/stx.d.ts")];const file=candidates.find((candidate)=>existsSync(candidate));if(!file)return new Set;const source=await Bun.file(file).text();const names=new Set;for(const match of source.matchAll(/^declare (?:function|const|class)\s+([A-Za-z_$][\w$]*)/gm))names.add(match[1]);return names}export function ambientGlobalsUsed(source,globals){const stripped=source.replace(/\/\*[\s\S]*?\*\//g," ").replace(/\/\/[^\n]*/g," ").replace(/(['"`])(?:\\.|(?!\1)[^\\])*\1/g,'""');const used=new Set;for(const match of stripped.matchAll(/(^|[^.\w$])([A-Za-z_$][\w$]*)\s*(?=[([<.,;)\]}=+\-*/?:]|$)/gm)){const name=match[2];if(globals.has(name))used.add(name)}if(!used.size)return[];for(const name of[...used]){const declared=new RegExp(`(?:^|[^.\\w$])(?:const|let|var|function|class)\\s+${name}\\b`,"m").test(stripped);const imported=new RegExp(`import[^;]*\\b${name}\\b[^;]*from`,"m").test(stripped);if(declared||imported)used.delete(name)}return[...used].sort()}
@@ -1,3 +1,3 @@
1
- export function generatedReadme(pkg,config){const lines=[`# ${pkg.name}`,"",pkg.description,"","## Install","","```sh",`bun add ${pkg.name}`,"```",""],license=pkg.license??config?.license;if(config?.repository)lines.push(`Source: https://github.com/${config.repository}`,"");if(license)lines.push(`License: ${license}`,"");return lines.join(`
2
- `)}export function libraryManifest(pkg,config,version,sourcesRelativeToProject){const cfg=config??{},repository=cfg.repository,manifest={name:pkg.name,type:"module",version:pkg.version??version,description:pkg.description,author:cfg.author,contributors:cfg.contributors,license:pkg.license??cfg.license,homepage:repository?`https://github.com/${repository}#readme`:void 0,repository:repository?{type:"git",url:`git+https://github.com/${repository}.git`}:void 0,bugs:repository?{url:`https://github.com/${repository}/issues`}:void 0,keywords:pkg.keywords.length?pkg.keywords:void 0,exports:{".":{types:"./dist/index.d.ts",import:pkg.kind==="web-components"?"./dist/bundle.js":"./dist/index.js",default:pkg.kind==="web-components"?"./dist/bundle.js":"./dist/index.js"},"./*":{types:"./dist/*.d.ts",import:"./dist/*.js",default:"./dist/*.js"}},module:pkg.kind==="web-components"?"dist/bundle.js":"dist/index.js",types:"dist/index.d.ts",files:["README.md","dist"],dependencies:Object.keys(pkg.dependencies).length?pkg.dependencies:void 0,peerDependencies:Object.keys(pkg.peerDependencies).length?pkg.peerDependencies:void 0,stacks:{kind:pkg.kind,sources:sourcesRelativeToProject}};if(pkg.private)manifest.private=!0;else manifest.publishConfig={access:pkg.access};if(pkg.kind!=="functions"){manifest.exports["./style.css"]="./dist/bundle.css";manifest.exports["./custom-elements.json"]="./dist/custom-elements.json"}const assets=pkg.assets??[],exports=manifest.exports;for(const{dest}of assets)if(/\.[^/]+$/.test(dest))exports[`./${dest}`]=`./dist/${dest}`;else exports[`./${dest}/*`]=`./dist/${dest}/*`;if(assets.length)manifest.stacks.assets=assets.map((asset)=>asset.dest);return manifest}export function serializeManifest(manifest){return`${JSON.stringify(manifest,(_key,value)=>value===void 0?void 0:value,2)}
1
+ export function generatedReadme(pkg,config){const lines=[`# ${pkg.name}`,"",pkg.description,"","## Install","","```sh",`bun add ${pkg.name}`,"```",""];const license=pkg.license??config?.license;if(config?.repository)lines.push(`Source: https://github.com/${config.repository}`,"");if(license)lines.push(`License: ${license}`,"");return lines.join(`
2
+ `)}export function libraryManifest(pkg,config,version,sourcesRelativeToProject){const cfg=config??{};const repository=cfg.repository;const manifest={name:pkg.name,type:"module",version:pkg.version??version,description:pkg.description,author:cfg.author,contributors:cfg.contributors,license:pkg.license??cfg.license,homepage:repository?`https://github.com/${repository}#readme`:undefined,repository:repository?{type:"git",url:`git+https://github.com/${repository}.git`}:undefined,bugs:repository?{url:`https://github.com/${repository}/issues`}:undefined,keywords:pkg.keywords.length?pkg.keywords:undefined,exports:{".":{types:"./dist/index.d.ts",import:pkg.kind==="web-components"?"./dist/bundle.js":"./dist/index.js",default:pkg.kind==="web-components"?"./dist/bundle.js":"./dist/index.js"},"./*":{types:"./dist/*.d.ts",import:"./dist/*.js",default:"./dist/*.js"}},module:pkg.kind==="web-components"?"dist/bundle.js":"dist/index.js",types:"dist/index.d.ts",files:["README.md","dist"],dependencies:Object.keys(pkg.dependencies).length?pkg.dependencies:undefined,peerDependencies:Object.keys(pkg.peerDependencies).length?pkg.peerDependencies:undefined,stacks:{kind:pkg.kind,sources:sourcesRelativeToProject}};if(pkg.private)manifest.private=true;else manifest.publishConfig={access:pkg.access};if(pkg.kind!=="functions"){manifest.exports["./style.css"]="./dist/bundle.css";manifest.exports["./custom-elements.json"]="./dist/custom-elements.json"}const assets=pkg.assets??[];const exports=manifest.exports;for(const{dest}of assets){if(/\.[^/]+$/.test(dest))exports[`./${dest}`]=`./dist/${dest}`;else exports[`./${dest}/*`]=`./dist/${dest}/*`}if(assets.length)manifest.stacks.assets=assets.map((asset)=>asset.dest);return manifest}export function serializeManifest(manifest){return`${JSON.stringify(manifest,(_key,value)=>value===undefined?undefined:value,2)}
3
3
  `}
@@ -1 +1 @@
1
- import{existsSync}from"node:fs";import{relative,resolve}from"node:path";import process from"node:process";import{awaitConfig,library}from"@stacksjs/config";import{componentsPath,functionsPath,libraryPackagePath}from"@stacksjs/path";export async function configuredLibrary(){await awaitConfig();return library}export class LibraryConfigError extends Error{name="LibraryConfigError"}const DEFAULT_FUNCTION_INCLUDE=["**/*.ts"],DEFAULT_FUNCTION_EXCLUDE=["**/*.test.ts","**/*.spec.ts","**/*.d.ts","**/_*.ts"],DEFAULT_COMPONENT_INCLUDE=["**/*.stx"],DEFAULT_COMPONENT_EXCLUDE=[];export function libraryPackageSourceDir(kind){return kind==="functions"?functionsPath():componentsPath()}export function unscopedName(name){return name.split("/").at(-1)??name}function includeFromFilesEntry(entry){const[file,alias]=Array.isArray(entry)?entry:[entry,void 0],stem=file.replace(/\.ts$/,""),include=stem==="*"?"*.ts":`${stem}.ts`;return alias?{include,alias:[stem,alias]}:{include}}function toDefinition(option,fallback){const name=option.name?.trim();if(!name)throw new LibraryConfigError(`library.packages[${fallback.index}] has no name. Every package needs the name it is published under.`);if(name.startsWith(".")||name.includes("\\")||name.split("/").length>2)throw new LibraryConfigError(`library.packages[${fallback.index}] has an invalid npm name: "${name}".`);const kind=option.kind??"functions";if(kind!=="functions"&&kind!=="components"&&kind!=="web-components")throw new LibraryConfigError(`Package "${name}" has an unknown kind "${kind}". Expected 'functions', 'components' or 'web-components'.`);const slug=(option.dir??unscopedName(name)).replace(/^@/,"");if(!/^[\w.-]+$/.test(slug))throw new LibraryConfigError(`Package "${name}" resolves to the directory "${slug}", which is not a single safe path segment. Set \`dir\` explicitly.`);const aliases={},includeFromFiles=[];for(const entry of option.files??[]){const{include,alias}=includeFromFilesEntry(entry);includeFromFiles.push(include);if(alias)aliases[alias[0]]=alias[1]}const names={};for(const tag of option.tags??[])if(Array.isArray(tag.name))names[tag.name[0]]=tag.name[1];const defaultInclude=kind==="functions"?DEFAULT_FUNCTION_INCLUDE:DEFAULT_COMPONENT_INCLUDE,defaultExclude=kind==="functions"?DEFAULT_FUNCTION_EXCLUDE:DEFAULT_COMPONENT_EXCLUDE,includeFromTags=option.tags?.length&&!option.include?.length?option.tags.map((tag)=>`${Array.isArray(tag.name)?tag.name[0]:tag.name}.stx`):[],include=option.include?.length?option.include:includeFromFiles.length?includeFromFiles:includeFromTags.length?includeFromTags:defaultInclude,assets=Object.entries(option.assets??{}).map(([dest,source])=>{const clean=dest.replace(/^\.\//,"").replace(/\/+$/,"");if(!clean||clean.startsWith("/")||clean.split("/").some((part)=>part===".."||part==="."||part===""))throw new LibraryConfigError(`Package "${name}" has an asset path "${dest}" that is not a plain path inside the package.`);if(/^index(\.d)?\.[cm]?[jt]s$/.test(clean)||clean==="bundle.js"||clean==="bundle.css")throw new LibraryConfigError(`Package "${name}" has an asset at "${dest}", which the build itself writes.`);if(!source||typeof source!=="string")throw new LibraryConfigError(`Package "${name}" has an asset "${dest}" with no source path.`);return{dest:clean,source}});return{name,kind,slug,description:option.description??`The ${name} library.`,keywords:option.keywords??[],license:option.license??fallback.license,version:option.version,private:option.private??!1,access:option.access??"public",registry:option.registry??"pantry",readme:option.readme,assets,prebuild:option.prebuild,runtime:option.runtime??"standalone",sourcemap:option.shouldGenerateSourcemap??!1,include,exclude:option.exclude??defaultExclude,prefix:option.prefix??unscopedName(name).replace(/[^a-z0-9]+/gi,"-").replace(/^-+|-+$/g,"").toLowerCase(),dependencies:option.dependencies??{},peerDependencies:option.peerDependencies??{},aliases,names}}export function normalizeLibraryPackages(config){const cfg=config??{},options=[];if(cfg.packages?.length)options.push(...cfg.packages);else{if(cfg.functions?.name)options.push({...cfg.functions,kind:"functions"});if(cfg.webComponents?.name)options.push({...cfg.webComponents,kind:"web-components"})}const definitions=options.map((option,index)=>toDefinition(option,{license:cfg.license,index})),byName=new Map,bySlug=new Map;for(const definition of definitions){if(byName.has(definition.name))throw new LibraryConfigError(`Two packages are both named "${definition.name}". npm names must be unique.`);byName.set(definition.name,1);const owner=bySlug.get(definition.slug);if(owner)throw new LibraryConfigError(`"${owner}" and "${definition.name}" both build in storage/framework/libs/packages/${definition.slug}. Give one of them a \`dir\`.`);bySlug.set(definition.slug,definition.name)}return definitions}export async function resolveLibraryPackages(config,options={}){const definitions=normalizeLibraryPackages(config),resolved=[];for(const definition of definitions){const sourceDir=libraryPackageSourceDir(definition.kind),sources=await matchSources(sourceDir,definition.include,definition.exclude);if(!sources.length){if(options.onUnmatched==="skip")continue;throw new LibraryConfigError(`Package "${definition.name}" matched no files in ${relative(process.cwd(),sourceDir)} (include: ${definition.include.join(", ")}${definition.exclude.length?`; exclude: ${definition.exclude.join(", ")}`:""}).`)}resolved.push({...definition,sourceDir,sources,dir:libraryPackagePath(definition.slug),entry:libraryPackagePath(definition.slug,"src/index.ts")})}return resolved}export async function matchSources(sourceDir,include,exclude){if(!existsSync(sourceDir))return[];const expand=async(patterns)=>{const files=new Set;for(const pattern of patterns)for await(const file of new Bun.Glob(pattern).scan({cwd:sourceDir,absolute:!0,onlyFiles:!0}))files.add(resolve(file));return files},included=await expand(include),excluded=exclude.length?await expand(exclude):new Set;return[...included].filter((file)=>!excluded.has(file)).sort()}export function entrySpecifier(entry,source){const path=relative(resolve(entry,".."),source).replace(/\.ts$/,"");return path.startsWith(".")?path:`./${path}`}
1
+ import{existsSync}from"node:fs";import{relative,resolve}from"node:path";import process from"node:process";import{awaitConfig,library}from"@stacksjs/config";import{componentsPath,functionsPath,libraryPackagePath}from"@stacksjs/path";export async function configuredLibrary(){await awaitConfig();return library}export class LibraryConfigError extends Error{name="LibraryConfigError"}const DEFAULT_FUNCTION_INCLUDE=["**/*.ts"];const DEFAULT_FUNCTION_EXCLUDE=["**/*.test.ts","**/*.spec.ts","**/*.d.ts","**/_*.ts"];const DEFAULT_COMPONENT_INCLUDE=["**/*.stx"];const DEFAULT_COMPONENT_EXCLUDE=[];export function libraryPackageSourceDir(kind){return kind==="functions"?functionsPath():componentsPath()}export function unscopedName(name){return name.split("/").at(-1)??name}function includeFromFilesEntry(entry){const[file,alias]=Array.isArray(entry)?entry:[entry,undefined];const stem=file.replace(/\.ts$/,"");const include=stem==="*"?"*.ts":`${stem}.ts`;return alias?{include,alias:[stem,alias]}:{include}}function toDefinition(option,fallback){const name=option.name?.trim();if(!name)throw new LibraryConfigError(`library.packages[${fallback.index}] has no name. Every package needs the name it is published under.`);if(name.startsWith(".")||name.includes("\\")||name.split("/").length>2)throw new LibraryConfigError(`library.packages[${fallback.index}] has an invalid npm name: "${name}".`);const kind=option.kind??"functions";if(kind!=="functions"&&kind!=="components"&&kind!=="web-components")throw new LibraryConfigError(`Package "${name}" has an unknown kind "${kind}". Expected 'functions', 'components' or 'web-components'.`);const slug=(option.dir??unscopedName(name)).replace(/^@/,"");if(!/^[\w.-]+$/.test(slug))throw new LibraryConfigError(`Package "${name}" resolves to the directory "${slug}", which is not a single safe path segment. Set \`dir\` explicitly.`);const aliases={};const includeFromFiles=[];for(const entry of option.files??[]){const{include,alias}=includeFromFilesEntry(entry);includeFromFiles.push(include);if(alias)aliases[alias[0]]=alias[1]}const names={};for(const tag of option.tags??[]){if(Array.isArray(tag.name))names[tag.name[0]]=tag.name[1]}const defaultInclude=kind==="functions"?DEFAULT_FUNCTION_INCLUDE:DEFAULT_COMPONENT_INCLUDE;const defaultExclude=kind==="functions"?DEFAULT_FUNCTION_EXCLUDE:DEFAULT_COMPONENT_EXCLUDE;const includeFromTags=option.tags?.length&&!option.include?.length?option.tags.map((tag)=>`${Array.isArray(tag.name)?tag.name[0]:tag.name}.stx`):[];const include=option.include?.length?option.include:includeFromFiles.length?includeFromFiles:includeFromTags.length?includeFromTags:defaultInclude;const assets=Object.entries(option.assets??{}).map(([dest,source])=>{const clean=dest.replace(/^\.\//,"").replace(/\/+$/,"");if(!clean||clean.startsWith("/")||clean.split("/").some((part)=>part===".."||part==="."||part===""))throw new LibraryConfigError(`Package "${name}" has an asset path "${dest}" that is not a plain path inside the package.`);if(/^index(\.d)?\.[cm]?[jt]s$/.test(clean)||clean==="bundle.js"||clean==="bundle.css")throw new LibraryConfigError(`Package "${name}" has an asset at "${dest}", which the build itself writes.`);if(!source||typeof source!=="string")throw new LibraryConfigError(`Package "${name}" has an asset "${dest}" with no source path.`);return{dest:clean,source}});return{name,kind,slug,description:option.description??`The ${name} library.`,keywords:option.keywords??[],license:option.license??fallback.license,version:option.version,private:option.private??false,access:option.access??"public",registry:option.registry??"pantry",readme:option.readme,assets,prebuild:option.prebuild,runtime:option.runtime??"standalone",sourcemap:option.shouldGenerateSourcemap??false,include,exclude:option.exclude??defaultExclude,prefix:option.prefix??unscopedName(name).replace(/[^a-z0-9]+/gi,"-").replace(/^-+|-+$/g,"").toLowerCase(),dependencies:option.dependencies??{},peerDependencies:option.peerDependencies??{},aliases,names}}export function normalizeLibraryPackages(config){const cfg=config??{};const options=[];if(cfg.packages?.length){options.push(...cfg.packages)}else{if(cfg.functions?.name)options.push({...cfg.functions,kind:"functions"});if(cfg.webComponents?.name)options.push({...cfg.webComponents,kind:"web-components"})}const definitions=options.map((option,index)=>toDefinition(option,{license:cfg.license,index}));const byName=new Map;const bySlug=new Map;for(const definition of definitions){if(byName.has(definition.name))throw new LibraryConfigError(`Two packages are both named "${definition.name}". npm names must be unique.`);byName.set(definition.name,1);const owner=bySlug.get(definition.slug);if(owner){throw new LibraryConfigError(`"${owner}" and "${definition.name}" both build in storage/framework/libs/packages/${definition.slug}. Give one of them a \`dir\`.`)}bySlug.set(definition.slug,definition.name)}return definitions}export async function resolveLibraryPackages(config,options={}){const definitions=normalizeLibraryPackages(config);const resolved=[];for(const definition of definitions){const sourceDir=libraryPackageSourceDir(definition.kind);const sources=await matchSources(sourceDir,definition.include,definition.exclude);if(!sources.length){if(options.onUnmatched==="skip")continue;throw new LibraryConfigError(`Package "${definition.name}" matched no files in ${relative(process.cwd(),sourceDir)} `+`(include: ${definition.include.join(", ")}${definition.exclude.length?`; exclude: ${definition.exclude.join(", ")}`:""}).`)}resolved.push({...definition,sourceDir,sources,dir:libraryPackagePath(definition.slug),entry:libraryPackagePath(definition.slug,"src/index.ts")})}return resolved}export async function matchSources(sourceDir,include,exclude){if(!existsSync(sourceDir))return[];const expand=async(patterns)=>{const files=new Set;for(const pattern of patterns){for await(const file of new Bun.Glob(pattern).scan({cwd:sourceDir,absolute:true,onlyFiles:true}))files.add(resolve(file))}return files};const included=await expand(include);const excluded=exclude.length?await expand(exclude):new Set;return[...included].filter((file)=>!excluded.has(file)).sort()}export function entrySpecifier(entry,source){const path=relative(resolve(entry,".."),source).replace(/\.ts$/,"");return path.startsWith(".")?path:`./${path}`}