@stacksjs/actions 0.75.237 → 0.75.239

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bump.js CHANGED
@@ -1,8 +1,8 @@
1
- import{execSync,log,parseOptions}from"@stacksjs/cli";import{path as p}from"@stacksjs/path";import{incrementVersion,isReleaseType,isValidVersion,versionBump}from"@stacksjs/bumpx";import{isCalendarBump,nextCalendarVersion}from"./calendar-version";import{describeGitHubRelease,publishGitHubRelease}from"./github-release";import{pantryLockViolations}from"./pantry-lock";import{releasePushTarget}from"./release-push-target";import{generateChangelog,loadLogsmithConfig}from"@stacksjs/logsmith";import{existsSync,readdirSync,readFileSync,unlinkSync,writeFileSync}from"node:fs";import{join,relative}from"node:path";const options=parseOptions(),rawBump=options?.bump?.toString(),bumpArg=rawBump?isReleaseType(rawBump)||isCalendarBump(rawBump)||isValidVersion(rawBump)?rawBump:null:null;if(rawBump&&!bumpArg)throw Error(`Invalid --bump "${rawBump}"; expected a Bumpx release type, calendar, or semantic version`);const isDryRun=options?.dryRun===!0,isVerbose=options?.verbose===!0;async function readPackage(file){if(!existsSync(file))return;return await Bun.file(file).json()}const rootManifest=p.projectPath("package.json"),rootPkg=await readPackage(rootManifest),isFrameworkRelease=rootPkg?.name==="stacks"&&existsSync(p.frameworkPath("core/package.json")),bumpCwd=isFrameworkRelease?p.frameworkPath("core"):p.projectPath(),primaryManifest=isFrameworkRelease?p.frameworkPath("core/package.json"):rootManifest;async function resolveBumpArg(bump){if(!bump)return bump;if(isCalendarBump(bump)){const pkg=await readPackage(primaryManifest);return nextCalendarVersion(pkg?.version)}const pkg=await readPackage(primaryManifest);if(!pkg?.version)throw Error(`${primaryManifest} declares no version`);return incrementVersion(pkg.version,bump,options?.preid)}const resolvedBumpArg=await resolveBumpArg(bumpArg);async function git(args,cwd=p.projectPath(),options={}){return await execSync(["git",...args],{cwd,stdin:"inherit",stderr:"pipe",throwOnError:options.throwOnError??!0})}const pushTarget=isDryRun?void 0:releasePushTarget(p.projectPath());async function isGitIgnored(file){return(await git(["check-ignore","--",file],p.projectPath(),{throwOnError:!1})).trim().length>0}async function readVersion(file){const pkg=await readPackage(file);if(!pkg?.version||!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(pkg.version))throw Error(`Invalid version in ${file}: ${pkg?.version??"<missing>"}`);return pkg.version}function lockfileVersion(contents){const match=contents.match(/"lockfileVersion"\s*:\s*(\d+)/);return match?Number(match[1]):null}async function packageFilesFor(pattern,cwd){const glob=new Bun.Glob(pattern),files=[];for await(const file of glob.scan({cwd,absolute:!0,onlyFiles:!0})){if(file.includes("/node_modules/")||file.includes("/dist/")||file.includes("/pantry/"))continue;files.push(`./${relative(bumpCwd,file)}`)}return files}async function existingPackageFiles(files){const existing=[];for(const file of files){const absolutePath=join(bumpCwd,file);if(await Bun.file(absolutePath).exists())existing.push(file)}return existing}async function frameworkBumpFiles(){return Array.from(new Set([...await packageFilesFor("package.json",bumpCwd),...await packageFilesFor("*/package.json",bumpCwd),...await packageFilesFor("*/*/package.json",bumpCwd),...await existingPackageFiles(["../package.json","../defaults/ide/vscode/package.json","../api/package.json","../cloud/package.json","../docs/package.json","../orm/package.json","../server/package.json"]),...await packageFilesFor("../libs/**/package.json",bumpCwd)]))}const bumpFiles=isFrameworkRelease?await frameworkBumpFiles():["./package.json"];log.debug(`Release mode: ${isFrameworkRelease?"framework monorepo":"consumer app"} (${rootPkg?.name??"unknown"})`);log.debug(`Bumping ${bumpFiles.length} package manifest(s) in ${bumpCwd}`);await versionBump({release:resolvedBumpArg??void 0,preid:options?.preid,files:bumpFiles,cwd:bumpCwd,recursive:!1,commit:!1,tag:!1,push:!1,changelog:!1,noGitCheck:!0,dryRun:isDryRun,yes:Boolean(resolvedBumpArg),verbose:isVerbose});const nextVersion=isDryRun&&resolvedBumpArg&&isValidVersion(resolvedBumpArg)?resolvedBumpArg:await readVersion(primaryManifest),latestTag=(await git(["describe","--abbrev=0","--tags"],p.projectPath(),{throwOnError:!1}).catch(()=>"")).trim();async function writeChangelog(){const config=await loadLogsmithConfig({dir:p.projectPath(),from:latestTag||void 0,to:"HEAD",output:isDryRun?!1:"CHANGELOG.md",theme:"github",verbose:isVerbose}),result=await generateChangelog(config);if(isDryRun){log.info(result.content);return}const changelogPath=p.projectPath("CHANGELOG.md");if(!existsSync(changelogPath))return;let content=readFileSync(changelogPath,"utf-8");const versionSeen=new RegExp(`\\bv?${nextVersion.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`);if(/\/compare\/[^)\s]+\.\.\.HEAD\)/.test(content))content=content.replace(/(\/compare\/[^)\s]+\.\.\.)HEAD(\))/,`$1v${nextVersion}$2`);else if(!versionSeen.test(content.split(`
1
+ import{execSync,log,parseOptions}from"@stacksjs/cli";import{path as p}from"@stacksjs/path";import{incrementVersion,isReleaseType,isValidVersion,versionBump}from"@stacksjs/bumpx";import{isCalendarBump,nextCalendarVersion}from"./calendar-version";import{describeGitHubRelease,publishGitHubRelease}from"./github-release";import{pantryLockViolations}from"./pantry-lock";import{resolvePantryToolchain}from"./pantry-toolchain";import{releasePushTarget}from"./release-push-target";import{generateChangelog,loadLogsmithConfig}from"@stacksjs/logsmith";import{existsSync,readdirSync,readFileSync,unlinkSync,writeFileSync}from"node:fs";import{join,relative}from"node:path";const options=parseOptions(),rawBump=options?.bump?.toString(),bumpArg=rawBump?isReleaseType(rawBump)||isCalendarBump(rawBump)||isValidVersion(rawBump)?rawBump:null:null;if(rawBump&&!bumpArg)throw Error(`Invalid --bump "${rawBump}"; expected a Bumpx release type, calendar, or semantic version`);const isDryRun=options?.dryRun===!0,isVerbose=options?.verbose===!0;async function readPackage(file){if(!existsSync(file))return;return await Bun.file(file).json()}const rootManifest=p.projectPath("package.json"),rootPkg=await readPackage(rootManifest),isFrameworkRelease=rootPkg?.name==="stacks"&&existsSync(p.frameworkPath("core/package.json")),bumpCwd=isFrameworkRelease?p.frameworkPath("core"):p.projectPath(),primaryManifest=isFrameworkRelease?p.frameworkPath("core/package.json"):rootManifest;async function resolveBumpArg(bump){if(!bump)return bump;if(isCalendarBump(bump)){const pkg=await readPackage(primaryManifest);return nextCalendarVersion(pkg?.version)}const pkg=await readPackage(primaryManifest);if(!pkg?.version)throw Error(`${primaryManifest} declares no version`);return incrementVersion(pkg.version,bump,options?.preid)}const resolvedBumpArg=await resolveBumpArg(bumpArg);async function git(args,cwd=p.projectPath(),options={}){return await execSync(["git",...args],{cwd,stdin:"inherit",stderr:"pipe",throwOnError:options.throwOnError??!0})}const pushTarget=isDryRun?void 0:releasePushTarget(p.projectPath());async function isGitIgnored(file){return(await git(["check-ignore","--",file],p.projectPath(),{throwOnError:!1})).trim().length>0}async function readVersion(file){const pkg=await readPackage(file);if(!pkg?.version||!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(pkg.version))throw Error(`Invalid version in ${file}: ${pkg?.version??"<missing>"}`);return pkg.version}function lockfileVersion(contents){const match=contents.match(/"lockfileVersion"\s*:\s*(\d+)/);return match?Number(match[1]):null}async function packageFilesFor(pattern,cwd){const glob=new Bun.Glob(pattern),files=[];for await(const file of glob.scan({cwd,absolute:!0,onlyFiles:!0})){if(file.includes("/node_modules/")||file.includes("/dist/")||file.includes("/pantry/"))continue;files.push(`./${relative(bumpCwd,file)}`)}return files}async function existingPackageFiles(files){const existing=[];for(const file of files){const absolutePath=join(bumpCwd,file);if(await Bun.file(absolutePath).exists())existing.push(file)}return existing}async function frameworkBumpFiles(){return Array.from(new Set([...await packageFilesFor("package.json",bumpCwd),...await packageFilesFor("*/package.json",bumpCwd),...await packageFilesFor("*/*/package.json",bumpCwd),...await existingPackageFiles(["../package.json","../defaults/ide/vscode/package.json","../api/package.json","../cloud/package.json","../docs/package.json","../orm/package.json","../server/package.json"]),...await packageFilesFor("../libs/**/package.json",bumpCwd)]))}const bumpFiles=isFrameworkRelease?await frameworkBumpFiles():["./package.json"],pantryToolchain=!isDryRun&&existsSync(p.projectPath("pantry.lock"))?resolvePantryToolchain({cwd:p.projectPath()}):void 0;if(pantryToolchain&&!pantryToolchain.ok)throw Error(pantryToolchain.message);log.debug(`Release mode: ${isFrameworkRelease?"framework monorepo":"consumer app"} (${rootPkg?.name??"unknown"})`);log.debug(`Bumping ${bumpFiles.length} package manifest(s) in ${bumpCwd}`);await versionBump({release:resolvedBumpArg??void 0,preid:options?.preid,files:bumpFiles,cwd:bumpCwd,recursive:!1,commit:!1,tag:!1,push:!1,changelog:!1,noGitCheck:!0,dryRun:isDryRun,yes:Boolean(resolvedBumpArg),verbose:isVerbose});const nextVersion=isDryRun&&resolvedBumpArg&&isValidVersion(resolvedBumpArg)?resolvedBumpArg:await readVersion(primaryManifest),latestTag=(await git(["describe","--abbrev=0","--tags"],p.projectPath(),{throwOnError:!1}).catch(()=>"")).trim();async function writeChangelog(){const config=await loadLogsmithConfig({dir:p.projectPath(),from:latestTag||void 0,to:"HEAD",output:isDryRun?!1:"CHANGELOG.md",theme:"github",verbose:isVerbose}),result=await generateChangelog(config);if(isDryRun){log.info(result.content);return}const changelogPath=p.projectPath("CHANGELOG.md");if(!existsSync(changelogPath))return;let content=readFileSync(changelogPath,"utf-8");const versionSeen=new RegExp(`\\bv?${nextVersion.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`);if(/\/compare\/[^)\s]+\.\.\.HEAD\)/.test(content))content=content.replace(/(\/compare\/[^)\s]+\.\.\.)HEAD(\))/,`$1v${nextVersion}$2`);else if(!versionSeen.test(content.split(`
2
2
  `).slice(0,4).join(`
3
3
  `)))content=content.replace(/^(#\s.*\n+)?/,(match)=>`${match??""}## v${nextVersion}
4
4
 
5
- `);writeFileSync(changelogPath,content)}await writeChangelog();if(!isDryRun&&isFrameworkRelease)pinLockstepDeps(nextVersion);async function refreshPantryLock(){const lockPath=p.projectPath("pantry.lock");if(!existsSync(lockPath))return;const previousLock=readFileSync(lockPath);try{await execSync(["pantry","install","--ignore-scripts","--quiet"],{cwd:p.projectPath(),stdin:"inherit",throwOnError:!0});if(!existsSync(lockPath))throw Error("Pantry completed without writing pantry.lock")}catch(error){writeFileSync(lockPath,previousLock);throw Error("Release aborted: Pantry could not refresh pantry.lock without lifecycle scripts. The previous lockfile was restored.",{cause:error})}const declarations=existsSync(bunLockPath)?Bun.JSONC.parse(readFileSync(bunLockPath,"utf8")).workspaces:void 0,violations=pantryLockViolations(readFileSync(lockPath,"utf8"),previousLock.toString("utf8"),declarations);if(violations.length>0){writeFileSync(lockPath,previousLock);throw Error(`Release aborted: refreshing pantry.lock produced a lockfile that does not describe this workspace, so the previous one has been restored.
5
+ `);writeFileSync(changelogPath,content)}await writeChangelog();if(!isDryRun&&isFrameworkRelease)pinLockstepDeps(nextVersion);async function refreshPantryLock(){const lockPath=p.projectPath("pantry.lock");if(!existsSync(lockPath))return;const previousLock=readFileSync(lockPath);try{await execSync([pantryToolchain?.ok?pantryToolchain.bin:"pantry","install","--ignore-scripts","--quiet"],{cwd:p.projectPath(),stdin:"inherit",throwOnError:!0});if(!existsSync(lockPath))throw Error("Pantry completed without writing pantry.lock")}catch(error){writeFileSync(lockPath,previousLock);throw Error("Release aborted: Pantry could not refresh pantry.lock without lifecycle scripts. The previous lockfile was restored.",{cause:error})}const declarations=existsSync(bunLockPath)?Bun.JSONC.parse(readFileSync(bunLockPath,"utf8")).workspaces:void 0,violations=pantryLockViolations(readFileSync(lockPath,"utf8"),previousLock.toString("utf8"),declarations);if(violations.length>0){writeFileSync(lockPath,previousLock);throw Error(`Release aborted: refreshing pantry.lock produced a lockfile that does not describe this workspace, so the previous one has been restored.
6
6
  `+violations.map((violation)=>` - ${violation}`).join(`
7
7
  `)+"\n\nThis is platform divergence in `pantry install`, not something the version bump did. Regenerate pantry.lock on the platform CI validates against, commit that on its own, then re-run the release.")}}const bunLockPath=p.projectPath("bun.lock"),pantryLockPath=p.projectPath("pantry.lock"),committedBunLock=existsSync(bunLockPath)?readFileSync(bunLockPath):null,committedPantryLock=existsSync(pantryLockPath)?readFileSync(pantryLockPath):null;function restoreCommittedLockfiles(){if(committedBunLock)writeFileSync(bunLockPath,committedBunLock);if(committedPantryLock)writeFileSync(pantryLockPath,committedPantryLock)}if(!isDryRun&&committedBunLock){const lockPath=bunLockPath;unlinkSync(lockPath);try{await execSync(["bun","install","--lockfile-only"],{cwd:p.projectPath(),stdin:"inherit"})}catch(error){restoreCommittedLockfiles();throw error}if(!existsSync(lockPath)){restoreCommittedLockfiles();throw Error("Release aborted: `bun install --lockfile-only` wrote no lockfile, so the previous one has been restored. This usually means a dependency range this bump just raised names a version that is not published yet - release that package first, then re-run.")}}if(!isDryRun)try{await refreshPantryLock()}catch(error){restoreCommittedLockfiles();throw error}if(!isDryRun&&committedBunLock){const lockPath=bunLockPath,expectedLockfileVersion=lockfileVersion(committedBunLock.toString("utf8")),regeneratedLock=readFileSync(lockPath,"utf8"),producedVersion=lockfileVersion(regeneratedLock);if(expectedLockfileVersion==null||producedVersion!==expectedLockfileVersion){restoreCommittedLockfiles();const remedy=producedVersion!=null&&expectedLockfileVersion!=null&&producedVersion>expectedLockfileVersion?"the committed lockfile predates the Bun this repository declares. Regenerate it once with that toolchain (`bun install --lockfile-only`) and commit the result as its own change, then re-run the release.":"this machine's Bun is older than the one that wrote the committed lockfile. Re-run the release with the repository's declared Bun toolchain through `pantry install`.";throw Error(`Release aborted: regenerating bun.lock produced lockfileVersion ${producedVersion??"unknown"}, but the committed one is v${expectedLockfileVersion??"unknown"} \u2014 ${remedy}`)}}function lockstepPackages(version){const names=new Set;for(const entry of readdirSync(p.frameworkPath("core"),{withFileTypes:!0})){if(!entry.isDirectory())continue;const manifest=p.frameworkPath(`core/${entry.name}/package.json`);if(!existsSync(manifest))continue;const pkg=JSON.parse(readFileSync(manifest,"utf-8"));if(pkg.name?.startsWith("@stacksjs/")&&pkg.version===version)names.add(pkg.name)}return names}function pinLockstepDeps(version){const lockstep=lockstepPackages(version),next=version,manifests=[p.frameworkPath("core/package.json"),...readdirSync(p.frameworkPath("core"),{withFileTypes:!0}).filter((entry)=>entry.isDirectory()).map((entry)=>p.frameworkPath(`core/${entry.name}/package.json`)).filter((path)=>existsSync(path))];let pinned=0;for(const manifestPath of manifests){const manifest=JSON.parse(readFileSync(manifestPath,"utf-8"));let changed=!1;for(const field of["dependencies","devDependencies"]){const deps=manifest[field];if(!deps)continue;for(const name of Object.keys(deps)){if(!lockstep.has(name)||deps[name].startsWith("workspace:")||deps[name]===next)continue;deps[name]=next;changed=!0;pinned++}}if(changed)writeFileSync(manifestPath,`${JSON.stringify(manifest,null,2)}
8
8
  `)}if(pinned>0)log.debug(`Pinned ${pinned} lockstep core dep(s) to ${version}`)}async function stageReleaseArtifacts(){const pathspecs=isFrameworkRelease?[":(glob)storage/framework/**/package.json","package.json"]:["package.json"];for(const file of["CHANGELOG.md","bun.lock","pantry.lock"]){if(!existsSync(p.projectPath(file)))continue;if(await isGitIgnored(file))continue;pathspecs.push(file)}await git(["add","--",...pathspecs]);const leftover=(await git(["status","--porcelain"])).split(`
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{seedCsrfPageResponse}from"./csrf";import{resolveDefaultsResources}from"./defaults-resources";import{exitWithParent}from"./exit-with-parent";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{applyViewSecurityHeaders,describeApiProxyRules,describeRedirectRules,describeRewriteRules,injectGlobalAutoImports,isApiBoundRequest,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(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({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)=>{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 secured=applyViewSecurityHeaders(req,response,embeddableRules),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}`)}return await seedCsrfPageResponse(req,current)??(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{seedCsrfPageResponse}from"./csrf";import{resolveDefaultsResources}from"./defaults-resources";import{exitWithParent}from"./exit-with-parent";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{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({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)=>{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 secured=applyViewSecurityHeaders(req,response,embeddableRules),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}`)}return await seedCsrfPageResponse(req,current)??(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,5 +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";async function collectNamedRoutes(){const registryFile=p.appPath("Routes.ts");if(!existsSync(registryFile))return{};try{const{listNamedRoutes,loadRoutes}=await import("@stacksjs/router"),{default:routeRegistry}=await import(registryFile);await loadRoutes(routeRegistry);return listNamedRoutes()}catch(error){log.debug("[generate:types] Could not load routes for named-route types",{error});return{}}}export async function generateRouteNames(){log.info("Generating route names...");const namedRoutes=await collectNamedRoutes(),entries=Object.entries(namedRoutes).sort(([left],[right])=>left.localeCompare(right)).map(([name,routePath])=>`
2
- '${name}': '${routePath}',`).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"),{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.
3
4
  //
4
5
  // Every named route, and the path it resolves to. Read as a type by
5
6
  // \`storage/framework/types/registries.d.ts\`, so \`url('users.show')\` is checked
@@ -9,4 +10,10 @@ import{existsSync}from"node:fs";import{log}from"@stacksjs/logging";import{path a
9
10
  // For more information, please visit: https://stacksjs.com/docs
10
11
  export const routeNames = {${entries?`${entries}
11
12
  `:""}} as const
13
+
14
+ // Every \`route.redirect()\` and \`route.permanentRedirect()\` on a page path. The
15
+ // views server answers these before it looks for a page: it never loads the
16
+ // route files, which belong to the API process.
17
+ export const routeRedirects = {${redirectEntries?`${redirectEntries}
18
+ `:""}} as const
12
19
  `;await storage.writeFile(p.storagePath("framework/auto-imports/routes.ts"),contents);log.debug(`[generate:types] Wrote ${Object.keys(namedRoutes).length} named routes`)}
@@ -0,0 +1,17 @@
1
+ /** `pantry 0.11.103 (986749281)` → `0.11.103`. */
2
+ export declare function parsePantryVersion(output: string): string | undefined;
3
+ /**
4
+ * The `ts-pantry` range this workspace declares, and the manifest it came from.
5
+ * The framework declares it on `@stacksjs/buddy`, which runs Pantry; an app
6
+ * declares it in its own manifest, if at all.
7
+ */
8
+ export declare function declaredPantryRange(cwd: string): { range: string, file: string } | undefined;
9
+ /** Resolve the Pantry this release will run, and check it against the declared toolchain. */
10
+ export declare function resolvePantryToolchain(options: PantryToolchainOptions): PantryToolchain;
11
+ export declare interface PantryToolchainOptions {
12
+ cwd: string
13
+ env?: Record<string, string | undefined>
14
+ probe?: (bin: string) => { exitCode: number, stdout: string }
15
+ }
16
+ export type PantryToolchain = | { ok: true, bin: string, version: string, declared?: string, declaredIn?: string }
17
+ | { ok: false, bin: string, message: string }
@@ -0,0 +1 @@
1
+ import{existsSync,readFileSync}from"node:fs";import{join}from"node:path";export function parsePantryVersion(output){return/\bpantry\s+v?(\d+\.\d+\.\d+(?:-[\w.]+)?)/i.exec(output)?.[1]}export function declaredPantryRange(cwd){for(const file of["storage/framework/core/buddy/package.json","package.json"]){const path=join(cwd,file);if(!existsSync(path))continue;try{const manifest=JSON.parse(readFileSync(path,"utf8")),range=manifest.dependencies?.["ts-pantry"]??manifest.devDependencies?.["ts-pantry"];if(range)return{range,file}}catch{}}return}function probeVersion(bin){try{const result=Bun.spawnSync([bin,"--version"],{stdout:"pipe",stderr:"pipe"});return{exitCode:result.exitCode??1,stdout:`${result.stdout.toString()}${result.stderr.toString()}`}}catch{return{exitCode:127,stdout:""}}}export function resolvePantryToolchain(options){const bin=(options.env??process.env).PANTRY_BIN?.trim()||"pantry",result=(options.probe??probeVersion)(bin),version=result.exitCode===0?parsePantryVersion(result.stdout):void 0;if(!version)return{ok:!1,bin,message:`Release aborted: could not run \`${bin} --version\`, so the Pantry that would regenerate pantry.lock is unknown. Install the declared Pantry, or set PANTRY_BIN to it, then re-run.`};const declared=declaredPantryRange(options.cwd);if(declared&&!Bun.semver.satisfies(version,declared.range))return{ok:!1,bin,message:`Release aborted before any file changed: \`${bin}\` is Pantry ${version}, but ${declared.file} declares ts-pantry ${declared.range}. A different Pantry writes a different pantry.lock than the one CI validates. Set PANTRY_BIN to a Pantry that satisfies the declared range (or put one first on PATH), then re-run.`};return{ok:!0,bin,version,declared:declared?.range,declaredIn:declared?.file}}
package/dist/release.js CHANGED
@@ -1 +1 @@
1
- import{parseOptions}from"@stacksjs/cli";import{app}from"@stacksjs/config";import{Action}from"@stacksjs/enums";import{log}from"@stacksjs/logging";import{projectPath}from"@stacksjs/path";import{runActions}from"./helpers/utils";import{BYPASS_ENV,formatPreflightFailure,runPinnedChecks}from"./release-preflight";const raw=parseOptions()??{},passthrough={};for(const[k,v]of Object.entries(raw)){if(k==="--"||k==="_")continue;passthrough[k]=v}const isDryRun=passthrough.dryRun===!0||passthrough.dryRun==="true",actions=[Action.GenerateLibraryEntries,Action.Bump],preflight=await runPinnedChecks({cwd:projectPath()});if(preflight.bypassed)log.warn(`${BYPASS_ENV} is set, so the pinned checks were skipped for this release.`);else if(preflight.failures.length>0){await log.flush();await log.exit(formatPreflightFailure(preflight.failures),1)}const result=await runActions(actions,{cwd:projectPath(),...passthrough});if(result&&result.isErr)await log.exit(`Release failed: ${result.error?.message??String(result.error)}`,1);log.success(isDryRun?`Dry run complete for ${app.name}. Nothing was committed, tagged or pushed.`:`Successfully released ${app.name}`);
1
+ import{parseOptions}from"@stacksjs/cli";import{app}from"@stacksjs/config";import{Action}from"@stacksjs/enums";import{log}from"@stacksjs/logging";import{projectPath}from"@stacksjs/path";import{runActions}from"./helpers/utils";import{resolvePantryToolchain}from"./pantry-toolchain";import{BYPASS_ENV,formatPreflightFailure,runPinnedChecks}from"./release-preflight";const raw=parseOptions()??{},passthrough={};for(const[k,v]of Object.entries(raw)){if(k==="--"||k==="_")continue;passthrough[k]=v}const isDryRun=passthrough.dryRun===!0||passthrough.dryRun==="true",actions=[Action.GenerateLibraryEntries,Action.Bump],preflight=await runPinnedChecks({cwd:projectPath()});if(preflight.bypassed)log.warn(`${BYPASS_ENV} is set, so the pinned checks were skipped for this release.`);else if(preflight.failures.length>0){await log.flush();await log.exit(formatPreflightFailure(preflight.failures),1)}const pantryToolchain=resolvePantryToolchain({cwd:projectPath()});if(!pantryToolchain.ok){await log.flush();await log.exit(pantryToolchain.message,1)}else log.info(`Pantry ${pantryToolchain.version} (${pantryToolchain.bin})${pantryToolchain.declared?` satisfies ts-pantry ${pantryToolchain.declared}`:""}`);const result=await runActions(actions,{cwd:projectPath(),...passthrough});if(result&&result.isErr)await log.exit(`Release failed: ${result.error?.message??String(result.error)}`,1);log.success(isDryRun?`Dry run complete for ${app.name}. Nothing was committed, tagged or pushed.`:`Successfully released ${app.name}`);
package/dist/serve/api.js CHANGED
@@ -1 +1 @@
1
- import{existsSync}from"node:fs";import{dirname,join}from"node:path";import process from"node:process";import{config,overridesReady}from"@stacksjs/config";import{log}from"@stacksjs/logging";import{appPath,frameworkPath}from"@stacksjs/path";import{disableViewRouting,route}from"@stacksjs/router";import{ensureDiscoveredPackages}from"../discover-packages";import{resolveApiHost}from"../helpers/api-host";function resolveDefaultsFile(rel){if(rel.startsWith("app/")){const published=appPath(rel.slice(4));if(existsSync(published))return published}const vendored=frameworkPath(`defaults/${rel}`);if(existsSync(vendored))return vendored;try{const pkgJson=Bun.resolveSync("@stacksjs/defaults/package.json",process.cwd());return join(dirname(pkgJson),rel)}catch{return vendored}}await overridesReady;const port=Number(process.env.PORT)||config.ports?.api||3008,hostname=resolveApiHost();log.info("[Stacks API] Starting server...");log.info(`[Stacks API] Environment: ${process.env.APP_ENV||"development"}`);const corsMod=await import(resolveDefaultsFile("app/Middleware/Cors.ts")),corsMiddleware=corsMod.default;route.use(corsMiddleware.toRouterHandler());await ensureDiscoveredPackages();const{reportStripeAvailability}=await import("@stacksjs/payments");reportStripeAvailability();const{autoImportsAreStale,generateAutoImportFiles,injectGlobalAutoImports,warnShadowedSecurityDefaults}=await import("@stacksjs/server");try{if(autoImportsAreStale()){log.info("[Stacks API] Installed packages moved since the auto-import barrel was written; rebuilding it.");await generateAutoImportFiles({declarations:!1})}}catch(error){log.warn(`[Stacks API] Could not refresh the auto-import barrel: ${error instanceof Error?error.message:String(error)}`)}await injectGlobalAutoImports();warnShadowedSecurityDefaults();await route.importRoutes();try{const{describeUnforwardableRoutes,resolveApiProxyRules,unforwardableRoutes}=await import("@stacksjs/server"),{listRootMountedAppRoutes}=await import("@stacksjs/router"),unreachable=unforwardableRoutes(listRootMountedAppRoutes().filter((entry)=>entry.method==="GET"||entry.method==="HEAD"),resolveApiProxyRules(config.server?.proxy));if(unreachable.length>0)log.warn(describeUnforwardableRoutes(unreachable))}catch(error){log.debug(`[Stacks API] Route reachability check skipped: ${error instanceof Error?error.message:String(error)}`)}disableViewRouting(route.bunRouter);const isDeployed=["production","staging","development"].includes((process.env.APP_ENV||"").toLowerCase()),server=await route.serve({port,hostname,reusePort:isDeployed});process.on("SIGTERM",()=>{const graceMs=Number(process.env.SHUTDOWN_GRACE_MS)||15000;setTimeout(()=>process.exit(0),graceMs).unref();Promise.resolve(server?.stop()).then(()=>process.exit(0))});log.info(`[Stacks API] Server running at http://${hostname}:${port}`);
1
+ import{existsSync}from"node:fs";import{dirname,join}from"node:path";import process from"node:process";import{config,overridesReady}from"@stacksjs/config";import{log}from"@stacksjs/logging";import{appPath,frameworkPath}from"@stacksjs/path";import{disableViewRouting,route}from"@stacksjs/router";import{ensureDiscoveredPackages}from"../discover-packages";import{resolveApiHost}from"../helpers/api-host";function resolveDefaultsFile(rel){if(rel.startsWith("app/")){const published=appPath(rel.slice(4));if(existsSync(published))return published}const vendored=frameworkPath(`defaults/${rel}`);if(existsSync(vendored))return vendored;try{const pkgJson=Bun.resolveSync("@stacksjs/defaults/package.json",process.cwd());return join(dirname(pkgJson),rel)}catch{return vendored}}await overridesReady;const port=Number(process.env.PORT)||config.ports?.api||3008,hostname=resolveApiHost();log.info("[Stacks API] Starting server...");log.info(`[Stacks API] Environment: ${process.env.APP_ENV||"development"}`);const corsMod=await import(resolveDefaultsFile("app/Middleware/Cors.ts")),corsMiddleware=corsMod.default;route.use(corsMiddleware.toRouterHandler());await ensureDiscoveredPackages();const{reportStripeAvailability}=await import("@stacksjs/payments");reportStripeAvailability();const{autoImportsAreStale,generateAutoImportFiles,injectGlobalAutoImports,warnShadowedSecurityDefaults}=await import("@stacksjs/server");try{if(autoImportsAreStale()){log.info("[Stacks API] Installed packages moved since the auto-import barrel was written; rebuilding it.");await generateAutoImportFiles({declarations:!1})}}catch(error){log.warn(`[Stacks API] Could not refresh the auto-import barrel: ${error instanceof Error?error.message:String(error)}`)}await injectGlobalAutoImports();warnShadowedSecurityDefaults();await route.importRoutes();try{const{describeUnforwardableRoutes,resolveApiProxyRules,unforwardableRoutes}=await import("@stacksjs/server"),{listRedirectRoutes,listRootMountedAppRoutes}=await import("@stacksjs/router"),redirected=new Set(listRedirectRoutes().map((entry)=>entry.path)),unreachable=unforwardableRoutes(listRootMountedAppRoutes().filter((entry)=>(entry.method==="GET"||entry.method==="HEAD")&&!redirected.has(entry.path)),resolveApiProxyRules(config.server?.proxy));if(unreachable.length>0)log.warn(describeUnforwardableRoutes(unreachable))}catch(error){log.debug(`[Stacks API] Route reachability check skipped: ${error instanceof Error?error.message:String(error)}`)}disableViewRouting(route.bunRouter);const isDeployed=["production","staging","development"].includes((process.env.APP_ENV||"").toLowerCase()),server=await route.serve({port,hostname,reusePort:isDeployed});process.on("SIGTERM",()=>{const graceMs=Number(process.env.SHUTDOWN_GRACE_MS)||15000;setTimeout(()=>process.exit(0),graceMs).unref();Promise.resolve(server?.stop()).then(()=>process.exit(0))});log.info(`[Stacks API] Server running at http://${hostname}:${port}`);
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/actions",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.75.237",
5
+ "version": "0.75.239",
6
6
  "description": "The Stacks actions.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -66,55 +66,55 @@
66
66
  "prepublishOnly": "bun run build"
67
67
  },
68
68
  "dependencies": {
69
- "@stacksjs/action-runner": "0.75.237",
70
- "@stacksjs/ai": "0.75.237",
71
- "@stacksjs/analytics": "0.75.237",
72
- "@stacksjs/api": "0.75.237",
73
- "@stacksjs/auth": "0.75.237",
74
- "@stacksjs/build": "0.75.237",
75
- "@stacksjs/bumpx": "^0.2.24",
69
+ "@stacksjs/action-runner": "0.75.239",
70
+ "@stacksjs/ai": "0.75.239",
71
+ "@stacksjs/analytics": "0.75.239",
72
+ "@stacksjs/api": "0.75.239",
73
+ "@stacksjs/auth": "0.75.239",
74
+ "@stacksjs/build": "0.75.239",
75
+ "@stacksjs/bumpx": "^0.2.25",
76
76
  "@stacksjs/bunpress": "^0.2.15",
77
- "@stacksjs/cli": "0.75.237",
78
- "@stacksjs/cloud": "0.75.237",
79
- "@stacksjs/cms": "0.75.237",
80
- "@stacksjs/components": "^0.2.574",
81
- "@stacksjs/config": "0.75.237",
82
- "@stacksjs/database": "0.75.237",
83
- "@stacksjs/desktop-build": "0.75.237",
84
- "@stacksjs/dns": "0.75.237",
85
- "@stacksjs/enums": "0.75.237",
86
- "@stacksjs/env": "0.75.237",
87
- "@stacksjs/error-handling": "0.75.237",
88
- "@stacksjs/github": "0.75.237",
77
+ "@stacksjs/cli": "0.75.239",
78
+ "@stacksjs/cloud": "0.75.239",
79
+ "@stacksjs/cms": "0.75.239",
80
+ "@stacksjs/components": "^0.2.604",
81
+ "@stacksjs/config": "0.75.239",
82
+ "@stacksjs/database": "0.75.239",
83
+ "@stacksjs/desktop-build": "0.75.239",
84
+ "@stacksjs/dns": "0.75.239",
85
+ "@stacksjs/enums": "0.75.239",
86
+ "@stacksjs/env": "0.75.239",
87
+ "@stacksjs/error-handling": "0.75.239",
88
+ "@stacksjs/github": "0.75.239",
89
89
  "@stacksjs/gitit": "^0.2.5",
90
- "@stacksjs/i18n": "0.75.237",
91
- "@stacksjs/image": "0.75.237",
92
- "@stacksjs/logging": "0.75.237",
90
+ "@stacksjs/i18n": "0.75.239",
91
+ "@stacksjs/image": "0.75.239",
92
+ "@stacksjs/logging": "0.75.239",
93
93
  "@stacksjs/logsmith": "^0.2.11",
94
- "@stacksjs/mobile": "0.75.237",
95
- "@stacksjs/orm": "0.75.237",
96
- "@stacksjs/path": "0.75.237",
97
- "@stacksjs/payments": "0.75.237",
98
- "@stacksjs/queue": "0.75.237",
99
- "@stacksjs/registry": "0.75.237",
100
- "@stacksjs/router": "0.75.237",
94
+ "@stacksjs/mobile": "0.75.239",
95
+ "@stacksjs/orm": "0.75.239",
96
+ "@stacksjs/path": "0.75.239",
97
+ "@stacksjs/payments": "0.75.239",
98
+ "@stacksjs/queue": "0.75.239",
99
+ "@stacksjs/registry": "0.75.239",
100
+ "@stacksjs/router": "0.75.239",
101
101
  "@stacksjs/rpx": "^0.11.54",
102
- "@stacksjs/scheduler": "0.75.237",
103
- "@stacksjs/search-engine": "0.75.237",
104
- "@stacksjs/security": "0.75.237",
105
- "@stacksjs/server": "0.75.237",
106
- "@stacksjs/sites": "0.75.237",
107
- "@stacksjs/storage": "0.75.237",
108
- "@stacksjs/strings": "0.75.237",
109
- "@stacksjs/stx": "^0.2.574",
102
+ "@stacksjs/scheduler": "0.75.239",
103
+ "@stacksjs/search-engine": "0.75.239",
104
+ "@stacksjs/security": "0.75.239",
105
+ "@stacksjs/server": "0.75.239",
106
+ "@stacksjs/sites": "0.75.239",
107
+ "@stacksjs/storage": "0.75.239",
108
+ "@stacksjs/strings": "0.75.239",
109
+ "@stacksjs/stx": "^0.2.604",
110
110
  "@stacksjs/tlsx": "^0.13.19",
111
111
  "@stacksjs/ts-cloud": "^0.16.58",
112
112
  "@stacksjs/ts-md": "^0.1.1",
113
- "@stacksjs/tunnel": "0.75.237",
114
- "@stacksjs/types": "0.75.237",
115
- "@stacksjs/utils": "0.75.237",
116
- "@stacksjs/whois": "0.75.237",
117
- "bun-plugin-stx": "^0.2.574"
113
+ "@stacksjs/tunnel": "0.75.239",
114
+ "@stacksjs/types": "0.75.239",
115
+ "@stacksjs/utils": "0.75.239",
116
+ "@stacksjs/whois": "0.75.239",
117
+ "bun-plugin-stx": "^0.2.604"
118
118
  },
119
119
  "peerDependencies": {
120
120
  "craft-native": ">=0.0.163",
@@ -129,7 +129,7 @@
129
129
  }
130
130
  },
131
131
  "devDependencies": {
132
- "@stacksjs/validation": "0.75.237",
132
+ "@stacksjs/validation": "0.75.239",
133
133
  "better-dx": "^0.2.24"
134
134
  }
135
135
  }