@stacksjs/actions 0.75.495 → 0.75.497
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 +2 -2
- package/dist/dev/dashboard-utils.js +1 -1
- package/dist/dev/dashboard.js +1 -1
- package/dist/pantry-lock.d.ts +2 -0
- package/dist/pantry-lock.js +2 -1
- package/package.json +40 -40
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{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(),isFrameworkRelease?"main":void 0);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(`
|
|
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,preservePantrySystemPins}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(),isFrameworkRelease?"main":void 0);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([pantryToolchain?.ok?pantryToolchain.bin:"pantry","install","--ignore-scripts","--quiet"],{cwd:p.projectPath(),stdin:"inherit",throwOnError:!0,env:{PANTRY_ENV_DEPS:"0"}});if(!existsSync(lockPath))throw Error("Pantry completed without writing pantry.lock")}catch(error){writeFileSync(lockPath,previousLock);throw Error("Release aborted: Pantry could not refresh pantry.lock without lifecycle scripts. The previous lockfile was restored.",{cause:error})}const declarations=existsSync(bunLockPath)?Bun.JSONC.parse(readFileSync(bunLockPath,"utf8")).workspaces:void 0,violations=pantryLockViolations(readFileSync(lockPath,"utf8"),previousLock.toString("utf8"),declarations);if(violations.length>0){writeFileSync(lockPath,previousLock);throw Error(`Release aborted: refreshing pantry.lock produced a lockfile that does not describe this workspace, so the previous one has been restored.
|
|
5
|
+
`);writeFileSync(changelogPath,content)}await writeChangelog();if(!isDryRun&&isFrameworkRelease)pinLockstepDeps(nextVersion);async function refreshPantryLock(){const lockPath=p.projectPath("pantry.lock");if(!existsSync(lockPath))return;const previousLock=readFileSync(lockPath);try{await execSync([pantryToolchain?.ok?pantryToolchain.bin:"pantry","install","--ignore-scripts","--quiet"],{cwd:p.projectPath(),stdin:"inherit",throwOnError:!0,env:{PANTRY_ENV_DEPS:"0"}});if(!existsSync(lockPath))throw Error("Pantry completed without writing pantry.lock");if(isFrameworkRelease)writeFileSync(lockPath,preservePantrySystemPins(readFileSync(lockPath,"utf8"),previousLock.toString("utf8")))}catch(error){writeFileSync(lockPath,previousLock);throw Error("Release aborted: Pantry could not refresh pantry.lock without lifecycle scripts. The previous lockfile was restored.",{cause:error})}const declarations=existsSync(bunLockPath)?Bun.JSONC.parse(readFileSync(bunLockPath,"utf8")).workspaces:void 0,violations=pantryLockViolations(readFileSync(lockPath,"utf8"),previousLock.toString("utf8"),declarations);if(violations.length>0){writeFileSync(lockPath,previousLock);throw Error(`Release aborted: refreshing pantry.lock produced a lockfile that does not describe this workspace, so the previous one has been restored.
|
|
6
6
|
`+violations.map((violation)=>` - ${violation}`).join(`
|
|
7
7
|
`)+"\n\nThis is platform divergence in `pantry install`, not something the version bump did. Regenerate pantry.lock on the platform CI validates against, commit that on its own, then re-run the release.")}}const bunLockPath=p.projectPath("bun.lock"),pantryLockPath=p.projectPath("pantry.lock"),committedBunLock=existsSync(bunLockPath)?readFileSync(bunLockPath):null,committedPantryLock=existsSync(pantryLockPath)?readFileSync(pantryLockPath):null;function restoreCommittedLockfiles(){if(committedBunLock)writeFileSync(bunLockPath,committedBunLock);if(committedPantryLock)writeFileSync(pantryLockPath,committedPantryLock)}if(!isDryRun&&committedBunLock){const lockPath=bunLockPath;unlinkSync(lockPath);try{await execSync(["bun","install","--lockfile-only"],{cwd:p.projectPath(),stdin:"inherit"})}catch(error){restoreCommittedLockfiles();throw error}if(!existsSync(lockPath)){restoreCommittedLockfiles();throw Error("Release aborted: `bun install --lockfile-only` wrote no lockfile, so the previous one has been restored. This usually means a dependency range this bump just raised names a version that is not published yet - release that package first, then re-run.")}}if(!isDryRun)try{await refreshPantryLock()}catch(error){restoreCommittedLockfiles();throw error}if(!isDryRun&&committedBunLock){const lockPath=bunLockPath,expectedLockfileVersion=lockfileVersion(committedBunLock.toString("utf8")),regeneratedLock=readFileSync(lockPath,"utf8"),producedVersion=lockfileVersion(regeneratedLock);if(expectedLockfileVersion==null||producedVersion!==expectedLockfileVersion){restoreCommittedLockfiles();const remedy=producedVersion!=null&&expectedLockfileVersion!=null&&producedVersion>expectedLockfileVersion?"the committed lockfile predates the Bun this repository declares. Regenerate it once with that toolchain (`bun install --lockfile-only`) and commit the result as its own change, then re-run the release.":"this machine's Bun is older than the one that wrote the committed lockfile. Re-run the release with the repository's declared Bun toolchain through `pantry install`.";throw Error(`Release aborted: regenerating bun.lock produced lockfileVersion ${producedVersion??"unknown"}, but the committed one is v${expectedLockfileVersion??"unknown"} \u2014 ${remedy}`)}}function lockstepPackages(version){const names=new Set;for(const entry of readdirSync(p.frameworkPath("core"),{withFileTypes:!0})){if(!entry.isDirectory())continue;const manifest=p.frameworkPath(`core/${entry.name}/package.json`);if(!existsSync(manifest))continue;const pkg=JSON.parse(readFileSync(manifest,"utf-8"));if(pkg.name?.startsWith("@stacksjs/")&&pkg.version===version)names.add(pkg.name)}return names}function pinLockstepDeps(version){const lockstep=lockstepPackages(version),next=version,manifests=[p.frameworkPath("core/package.json"),...readdirSync(p.frameworkPath("core"),{withFileTypes:!0}).filter((entry)=>entry.isDirectory()).map((entry)=>p.frameworkPath(`core/${entry.name}/package.json`)).filter((path)=>existsSync(path))];let pinned=0;for(const manifestPath of manifests){const manifest=JSON.parse(readFileSync(manifestPath,"utf-8"));let changed=!1;for(const field of["dependencies","devDependencies"]){const deps=manifest[field];if(!deps)continue;for(const name of Object.keys(deps)){if(!lockstep.has(name)||deps[name].startsWith("workspace:")||deps[name]===next)continue;deps[name]=next;changed=!0;pinned++}}if(changed)writeFileSync(manifestPath,`${JSON.stringify(manifest,null,2)}
|
|
8
8
|
`)}if(pinned>0)log.debug(`Pinned ${pinned} lockstep core dep(s) to ${version}`)}async function stageReleaseArtifacts(){const pathspecs=isFrameworkRelease?[":(glob)storage/framework/**/package.json","package.json"]:["package.json"];for(const file of["CHANGELOG.md","bun.lock","pantry.lock"]){if(!existsSync(p.projectPath(file)))continue;if(await isGitIgnored(file))continue;pathspecs.push(file)}await git(["add","--",...pathspecs]);const leftover=(await git(["status","--porcelain"])).split(`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Glob}from"bun";import{randomUUID}from"node:crypto";import{existsSync,readFileSync,renameSync,unlinkSync,writeFileSync}from"node:fs";import{connect}from"node:net";import path from"node:path";import{pathToFileURL}from"node:url";export const iconMap={user:"person.fill",team:"person.2.fill",subscriber:"envelope.open.fill",subscriberemail:"envelope.fill",post:"doc.text.fill",page:"doc.fill",product:"cube.box.fill",productvariant:"cube.fill",productunit:"scalemass.fill",order:"list.clipboard.fill",orderitem:"list.bullet.clipboard.fill",customer:"person.crop.circle.fill",payment:"creditcard.fill",paymentmethod:"creditcard.and.123",paymentproduct:"creditcard.fill",paymenttransaction:"creditcard.fill",category:"tag.fill",tag:"tag",comment:"bubble.left.fill",author:"person.text.rectangle.fill",notification:"bell.fill",job:"briefcase.fill",log:"list.bullet.rectangle.portrait.fill",campaign:"megaphone.fill",review:"star.fill",coupon:"ticket.fill",giftcard:"giftcard.fill",cart:"cart.fill",cartitem:"cart.badge.plus",taxrate:"percent",transaction:"arrow.left.arrow.right.circle.fill",subscription:"repeat.circle.fill",emaillist:"envelope.badge.person.crop",socialpost:"bubble.left.and.bubble.right.fill",manufacturer:"building.2.fill",shippingmethod:"shippingbox.fill",shippingzone:"map.fill",shippingrate:"dollarsign.circle.fill",deliveryroute:"map.fill",driver:"car.fill",digitaldelivery:"arrow.down.doc.fill",licensekey:"key.fill",loyaltypoint:"star.circle.fill",loyaltyreward:"gift.fill",printdevice:"printer.fill",receipt:"doc.text.fill",waitlistproduct:"clock.fill",waitlistrestaurant:"clock.badge.checkmark.fill",websocket:"antenna.radiowaves.left.and.right",default:"tablecells.fill"},excludeModels=new Set(["activity","request","error","failedjob"]),dedicatedPages=new Set(["user","team","subscriber","post","page","product","order","customer","payment","coupon","category","tag","comment","author","notification","job","campaign","review","gift-card"]);const ROOT_MODEL_CATEGORY={user:"data",team:"data",subscriber:"data",activity:"data",campaign:"marketing",emaillist:"marketing",socialpost:"marketing",subscriberemail:"marketing",comment:"content",tag:"content",paymentmethod:"commerce",paymentproduct:"commerce",paymenttransaction:"commerce",subscription:"commerce",deployment:"system",error:"system",failedjob:"system",job:"system",log:"system",notification:"system",release:"system",request:"system"};export function modelsWithEnabledFeatures(models,featureOf,enabled){return models.filter((model)=>{if(model.dashboard?.access===!1)return!1;if(model.category==="userland")return!0;const gate=featureOf(model.name);return gate===void 0||enabled(gate)})}export function modelNameToId(name){return name.replace(/([A-Z])/g,"-$1").toLowerCase().replace(/^-/,"")}export function getModelIcon(name){return iconMap[name.toLowerCase()]||iconMap.default||"database"}function categorizeModel(relativePath,modelId,defaultCategory){if(defaultCategory)return defaultCategory;const firstSeg=relativePath.includes("/")?(relativePath.split("/")[0]??"").toLowerCase():"";if(firstSeg==="commerce")return"commerce";if(firstSeg==="content")return"content";if(firstSeg==="realtime")return"system";return ROOT_MODEL_CATEGORY[modelId.replace(/-/g,"")]??"data"}async function readModelDashboardConfig(absolutePath){try{const mod=await import(pathToFileURL(absolutePath).href);return(mod.default??mod).dashboard}catch(error){throw Error(`Could not discover dashboard model ${absolutePath}: ${error instanceof Error?error.message:String(error)}`)}}export async function scanModelsDir(dir,seenNames,models,defaultCategory){if(!existsSync(dir))return;const glob=new Glob("**/*.ts");for await(const file of glob.scan({cwd:dir})){if(file.includes("README")||file.includes(".d.ts"))continue;const name=file.replace(/\.ts$/,"").split("/").pop()||"",nameLower=name.toLowerCase();if(name&&!seenNames.has(nameLower)&&!excludeModels.has(nameLower)){seenNames.add(nameLower);const id=modelNameToId(name),absolutePath=path.resolve(dir,file),dashboard=await readModelDashboardConfig(absolutePath);models.push({name,icon:dashboard?.icon??getModelIcon(name),id,category:categorizeModel(file,id,defaultCategory),dashboard})}}}export async function discoverModels(userModelsPath,defaultModelsPath){const models=[],seenNames=new Set;await scanModelsDir(userModelsPath,seenNames,models,"userland");await scanModelsDir(defaultModelsPath,seenNames,models);return models.sort((a,b)=>a.name.localeCompare(b.name))}export async function discoverProjectModels(){const{overridesReady}=await import("@stacksjs/config"),{resolveModelSources}=await import("@stacksjs/database/model-sources");await overridesReady;const models=[];for(const model of resolveModelSources()?.models??[]){if(excludeModels.has(model.name.toLowerCase()))continue;const dashboard=await readModelDashboardConfig(model.file);models.push({name:model.name,id:modelNameToId(model.name),icon:dashboard?.icon??getModelIcon(model.name),category:categorizeModel(model.file,modelNameToId(model.name),model.origin==="framework"?void 0:"userland"),dashboard})}return models.sort((a,b)=>a.name.localeCompare(b.name))}export function buildManifest(models){return models.filter((model)=>model.dashboard?.access!==!1).map((m)=>{const row={id:m.id,name:m.name,icon:m.icon,hasDedicatedPage:dedicatedPages.has(m.id),category:m.category??"data"};if(m.dashboard)row.dashboard=m.dashboard;return row})}export function writeFileIfChanged(file,content){try{if(readFileSync(file,"utf8")===content)return!1}catch{}const temporary=`${file}.${process.pid}.${randomUUID()}.tmp`;try{writeFileSync(temporary,content,{flag:"wx"});renameSync(temporary,file)}finally{if(existsSync(temporary))unlinkSync(temporary)}return!0}export async function isPortAvailable(port){try{await Bun.serve({port,fetch:()=>new Response}).stop(!0);return!0}catch{return!1}}export async function findAvailablePort(preferred,maxAttempts=20){for(let i=0;i<maxAttempts;i++){const port=preferred+i;if(await isPortAvailable(port))return port}return preferred}function connectsWithin(port,timeoutMs){return new Promise((resolve)=>{const socket=connect({port,host:"127.0.0.1"}),finish=(connected)=>{clearTimeout(timer);try{socket.destroy()}catch{}resolve(connected)},timer=setTimeout(()=>finish(!1),timeoutMs);socket.once("connect",()=>finish(!0));socket.once("error",()=>finish(!1))})}export async function waitForServer(port,maxWait=500){const deadline=Date.now()+maxWait;while(!0){const remaining=deadline-Date.now();if(remaining<=0)return!1;if(await connectsWithin(port,Math.min(remaining,250)))return!0;if(Date.now()>=deadline)return!1;await new Promise((resolve)=>setTimeout(resolve,Math.min(25,Math.max(deadline-Date.now(),0))))}}function effectiveCategory(m){if(m.dashboard?.access===!1||m.dashboard?.enabled===!1)return;if(m.dashboard?.section)return m.dashboard.section;return m.category??"data"}function categoryRows(baseRoute,models,category,dedicated){return models.filter((m)=>effectiveCategory(m)===category).filter((m)=>!dedicatedPages.has(m.id)&&!dedicated.has(m.id)).map((m)=>({id:`model-${m.id}`,label:m.dashboard?.label??m.name,icon:m.icon,url:`${baseRoute}/models/${m.id}`,...m.dashboard?.roles&&m.dashboard.roles.length>0?{roles:m.dashboard.roles}:{}}))}export function buildSidebarConfig(baseRoute,discoveredModels,toggles={}){const enabled={library:toggles.library??!0,content:toggles.content??!0,commerce:toggles.commerce??!0,marketing:toggles.marketing??!0,analytics:toggles.analytics??!0,management:toggles.management??!0,utilities:toggles.utilities??!0},dataRow={dashboard:toggles.data?.dashboard??!0,activity:toggles.data?.activity??!0,users:toggles.data?.users??!0,teams:toggles.data?.teams??!0,subscribers:toggles.data?.subscribers??!0,allModels:toggles.data?.allModels??!0},sections=[],homeItems=[{id:"home",label:"Dashboard",icon:"house.fill",url:`${baseRoute}/`},{id:"dependencies",label:"Dependencies",icon:"shippingbox.fill",url:`${baseRoute}/dependencies`},{id:"health",label:"Health",icon:"heart.text.square.fill",url:`${baseRoute}/health`}];if(toggles.ci)homeItems.push({id:"ci",label:"CI",icon:"checkmark.seal.fill",url:`${baseRoute}/ci`});sections.push({id:"home",title:"Home",items:homeItems});if(enabled.library)sections.push({id:"library",title:"Library",items:[{id:"functions",label:"Functions",icon:"function",url:`${baseRoute}/functions`},{id:"packages",label:"Packages",icon:"shippingbox.fill",url:`${baseRoute}/packages`}]});if(enabled.content)sections.push({id:"content",title:"Content",items:[{id:"content-dashboard",label:"Dashboard",icon:"gauge.with.dots.needle.33percent",url:`${baseRoute}/content/dashboard`},{id:"files",label:"Files",icon:"folder.fill",url:`${baseRoute}/content/files`},{id:"pages",label:"Pages",icon:"doc.fill",url:`${baseRoute}/content/pages`},{id:"posts",label:"Posts",icon:"text.bubble.fill",url:`${baseRoute}/content/posts`},{id:"categories",label:"Categories",icon:"tag.fill",url:`${baseRoute}/content/categories`},{id:"tags",label:"Tags",icon:"tag",url:`${baseRoute}/content/tags`},{id:"comments",label:"Comments",icon:"bubble.left.fill",url:`${baseRoute}/content/comments`},{id:"authors",label:"Authors",icon:"person.text.rectangle.fill",url:`${baseRoute}/content/authors`},{id:"seo",label:"SEO",icon:"magnifyingglass",url:`${baseRoute}/content/seo`},...categoryRows(baseRoute,discoveredModels,"content",new Set(["page","post","category","tag","comment","author"]))]});sections.push({id:"app",title:"App",items:[{id:"deployments",label:"Deployments",icon:"rocket.fill",url:`${baseRoute}/deployments`},{id:"requests",label:"Requests",icon:"arrow.left.arrow.right",url:`${baseRoute}/requests`},{id:"realtime",label:"Realtime",icon:"link",url:`${baseRoute}/realtime`},{id:"actions",label:"Actions",icon:"bolt.fill",url:`${baseRoute}/actions`},{id:"commands",label:"Commands",icon:"terminal.fill",url:`${baseRoute}/commands`},{id:"search-engine",label:"Search Engine",icon:"magnifyingglass",url:`${baseRoute}/search-engine`},{id:"queue",label:"Queue",icon:"list.bullet.rectangle.fill",url:`${baseRoute}/queue`},{id:"jobs",label:"Jobs",icon:"briefcase.fill",url:`${baseRoute}/jobs`},{id:"inbox",label:"Inbox",icon:"tray.full.fill",url:`${baseRoute}/inbox`},{id:"queries",label:"Queries",icon:"magnifyingglass.circle.fill",url:`${baseRoute}/queries`},{id:"notifications",label:"Notifications",icon:"bell.fill",url:`${baseRoute}/notifications/dashboard`},...categoryRows(baseRoute,discoveredModels,"system",new Set)]});const dataItems=[];if(dataRow.dashboard)dataItems.push({id:"data-dashboard",label:"Dashboard",icon:"gauge.with.dots.needle.33percent",url:`${baseRoute}/data/dashboard`});if(dataRow.activity)dataItems.push({id:"activity",label:"Activity",icon:"waveform.path.ecg",url:`${baseRoute}/data/activity`});if(dataRow.users)dataItems.push({id:"users",label:"Users",icon:"person.crop.circle.fill",url:`${baseRoute}/data/users`});if(dataRow.teams)dataItems.push({id:"teams",label:"Teams",icon:"person.3.fill",url:`${baseRoute}/data/teams`});if(dataRow.subscribers)dataItems.push({id:"subscribers",label:"Subscribers",icon:"envelope.fill",url:`${baseRoute}/data/subscribers`});if(dataRow.allModels)dataItems.push({id:"data-models",label:"All Models",icon:"square.grid.2x2.fill",url:`${baseRoute}/models`});const dynamicRows=discoveredModels.filter((m)=>{const eff=effectiveCategory(m);return eff==="userland"||eff==="data"}).filter((m)=>!dedicatedPages.has(m.id)).map((model)=>({id:`model-${model.id}`,label:model.dashboard?.label??model.name,icon:model.icon,url:`${baseRoute}/models/${model.id}`,...model.dashboard?.roles&&model.dashboard.roles.length>0?{roles:model.dashboard.roles}:{}}));sections.push({id:"data",title:"Data",items:[...dataItems,...dynamicRows]});if(enabled.commerce)sections.push({id:"commerce",title:"Commerce",items:[{id:"commerce-dashboard",label:"Dashboard",icon:"gauge.with.dots.needle.33percent",url:`${baseRoute}/commerce/dashboard`},{id:"customers",label:"Customers",icon:"person.crop.circle.fill",url:`${baseRoute}/commerce/customers`},{id:"orders",label:"Orders",icon:"list.clipboard.fill",url:`${baseRoute}/commerce/orders`},{id:"products",label:"Products",icon:"cube.box.fill",url:`${baseRoute}/commerce/products`},{id:"coupons",label:"Coupons",icon:"ticket.fill",url:`${baseRoute}/commerce/coupons`},{id:"gift-cards",label:"Gift Cards",icon:"giftcard.fill",url:`${baseRoute}/commerce/gift-cards`},{id:"payments",label:"Payments",icon:"creditcard.fill",url:`${baseRoute}/commerce/payments`},{id:"delivery",label:"Delivery",icon:"truck.box.fill",url:`${baseRoute}/commerce/delivery`},{id:"taxes",label:"Taxes",icon:"percent",url:`${baseRoute}/commerce/taxes`},...categoryRows(baseRoute,discoveredModels,"commerce",new Set(["customer","order","product","coupon","gift-card","payment","review","category"]))]});if(enabled.marketing)sections.push({id:"marketing",title:"Marketing",items:[{id:"lists",label:"Lists",icon:"list.bullet",url:`${baseRoute}/marketing/lists`},{id:"social-posts",label:"Social Posts",icon:"clock.fill",url:`${baseRoute}/marketing/social-posts`},{id:"campaigns",label:"Campaigns",icon:"megaphone.fill",url:`${baseRoute}/marketing/campaigns`},{id:"marketing-reviews",label:"Reviews",icon:"star.fill",url:`${baseRoute}/marketing/reviews`},...categoryRows(baseRoute,discoveredModels,"marketing",new Set(["campaign"]))]});if(enabled.analytics)sections.push({id:"analytics",title:"Analytics",items:[{id:"analytics-web",label:"Web",icon:"globe",url:`${baseRoute}/analytics/web`},{id:"analytics-blog",label:"Blog",icon:"doc.text.fill",url:`${baseRoute}/analytics/blog`},{id:"analytics-commerce",label:"Commerce",icon:"cart.fill",url:`${baseRoute}/analytics/commerce/web`},{id:"analytics-marketing",label:"Marketing",icon:"megaphone.fill",url:`${baseRoute}/analytics/marketing`}]});if(enabled.management)sections.push({id:"management",title:"Management",items:[{id:"cloud",label:"Cloud",icon:"cloud.fill",url:`${baseRoute}/cloud`},{id:"servers",label:"Servers",icon:"server.rack",url:`${baseRoute}/servers`},{id:"serverless",label:"Serverless",icon:"bolt.horizontal.circle.fill",url:`${baseRoute}/serverless`},{id:"dns",label:"DNS",icon:"network",url:`${baseRoute}/dns`},{id:"mailboxes",label:"Mailboxes",icon:"tray.full.fill",url:`${baseRoute}/mailboxes`},{id:"logs",label:"Logs",icon:"list.bullet.rectangle.portrait.fill",url:`${baseRoute}/logs`},{id:"kanban",label:"Kanban",icon:"rectangle.stack.fill",url:`${baseRoute}/kanban`,roles:["admin","dev"]}]});if(enabled.utilities)sections.push({id:"utilities",title:"Utilities",items:[{id:"buddy",label:"AI Buddy",icon:"bubble.left.and.bubble.right.fill",url:`${baseRoute}/buddy`},{id:"environment",label:"Environment",icon:"key.fill",url:`${baseRoute}/environment`},{id:"access-tokens",label:"Access Tokens",icon:"key.horizontal.fill",url:`${baseRoute}/access-tokens`},{id:"settings",label:"Settings",icon:"gear",url:`${baseRoute}/settings/billing`}]});return{sections,minWidth:200,maxWidth:280}}
|
|
1
|
+
import{capitalCase,plural}from"@stacksjs/strings";import{Glob}from"bun";import{randomUUID}from"node:crypto";import{existsSync,readFileSync,renameSync,unlinkSync,writeFileSync}from"node:fs";import{connect}from"node:net";import path from"node:path";import{pathToFileURL}from"node:url";export const iconMap={user:"person.fill",team:"person.2.fill",subscriber:"envelope.open.fill",subscriberemail:"envelope.fill",post:"doc.text.fill",page:"doc.fill",product:"cube.box.fill",productvariant:"cube.fill",productunit:"scalemass.fill",order:"list.clipboard.fill",orderitem:"list.bullet.clipboard.fill",customer:"person.crop.circle.fill",payment:"creditcard.fill",paymentmethod:"creditcard.and.123",paymentproduct:"creditcard.fill",paymenttransaction:"creditcard.fill",category:"tag.fill",tag:"tag",comment:"bubble.left.fill",author:"person.text.rectangle.fill",notification:"bell.fill",job:"briefcase.fill",log:"list.bullet.rectangle.portrait.fill",campaign:"megaphone.fill",review:"star.fill",coupon:"ticket.fill",giftcard:"giftcard.fill",cart:"cart.fill",cartitem:"cart.badge.plus",taxrate:"percent",transaction:"arrow.left.arrow.right.circle.fill",subscription:"repeat.circle.fill",emaillist:"envelope.badge.person.crop",socialpost:"bubble.left.and.bubble.right.fill",manufacturer:"building.2.fill",shippingmethod:"shippingbox.fill",shippingzone:"map.fill",shippingrate:"dollarsign.circle.fill",deliveryroute:"map.fill",driver:"car.fill",digitaldelivery:"arrow.down.doc.fill",licensekey:"key.fill",loyaltypoint:"star.circle.fill",loyaltyreward:"gift.fill",printdevice:"printer.fill",receipt:"doc.text.fill",waitlistproduct:"clock.fill",waitlistrestaurant:"clock.badge.checkmark.fill",websocket:"antenna.radiowaves.left.and.right",default:"tablecells.fill"},excludeModels=new Set(["activity","request","error","failedjob"]),dedicatedPages=new Set(["user","team","subscriber","post","page","product","order","customer","payment","coupon","category","tag","comment","author","notification","job","campaign","review","gift-card"]);const ROOT_MODEL_CATEGORY={user:"data",team:"data",subscriber:"data",activity:"data",campaign:"marketing",emaillist:"marketing",socialpost:"marketing",subscriberemail:"marketing",comment:"content",tag:"content",paymentmethod:"commerce",paymentproduct:"commerce",paymenttransaction:"commerce",subscription:"commerce",deployment:"system",error:"system",failedjob:"system",job:"system",log:"system",notification:"system",release:"system",request:"system"};export function modelsWithEnabledFeatures(models,featureOf,enabled){return models.filter((model)=>{if(model.dashboard?.access===!1)return!1;if(model.category==="userland")return!0;const gate=featureOf(model.name);return gate===void 0||enabled(gate)})}export function modelNameToId(name){return name.replace(/([A-Z])/g,"-$1").toLowerCase().replace(/^-/,"")}export function getModelIcon(name){return iconMap[name.toLowerCase()]||iconMap.default||"database"}function categorizeModel(relativePath,modelId,defaultCategory){if(defaultCategory)return defaultCategory;const firstSeg=relativePath.includes("/")?(relativePath.split("/")[0]??"").toLowerCase():"";if(firstSeg==="commerce")return"commerce";if(firstSeg==="content")return"content";if(firstSeg==="realtime")return"system";return ROOT_MODEL_CATEGORY[modelId.replace(/-/g,"")]??"data"}async function readModelDashboardConfig(absolutePath){try{const mod=await import(pathToFileURL(absolutePath).href);return(mod.default??mod).dashboard}catch(error){throw Error(`Could not discover dashboard model ${absolutePath}: ${error instanceof Error?error.message:String(error)}`)}}export async function scanModelsDir(dir,seenNames,models,defaultCategory){if(!existsSync(dir))return;const glob=new Glob("**/*.ts");for await(const file of glob.scan({cwd:dir})){if(file.includes("README")||file.includes(".d.ts"))continue;const name=file.replace(/\.ts$/,"").split("/").pop()||"",nameLower=name.toLowerCase();if(name&&!seenNames.has(nameLower)&&!excludeModels.has(nameLower)){seenNames.add(nameLower);const id=modelNameToId(name),absolutePath=path.resolve(dir,file),dashboard=await readModelDashboardConfig(absolutePath);models.push({name,icon:dashboard?.icon??getModelIcon(name),id,category:categorizeModel(file,id,defaultCategory),dashboard})}}}export async function discoverModels(userModelsPath,defaultModelsPath){const models=[],seenNames=new Set;await scanModelsDir(userModelsPath,seenNames,models,"userland");await scanModelsDir(defaultModelsPath,seenNames,models);return models.sort((a,b)=>a.name.localeCompare(b.name))}export async function discoverProjectModels(){const{overridesReady}=await import("@stacksjs/config"),{resolveModelSources}=await import("@stacksjs/database/model-sources");await overridesReady;const models=[];for(const model of resolveModelSources()?.models??[]){if(excludeModels.has(model.name.toLowerCase()))continue;const dashboard=await readModelDashboardConfig(model.file);models.push({name:model.name,id:modelNameToId(model.name),icon:dashboard?.icon??getModelIcon(model.name),category:categorizeModel(model.file,modelNameToId(model.name),model.origin==="framework"?void 0:"userland"),dashboard})}return models.sort((a,b)=>a.name.localeCompare(b.name))}export function buildManifest(models){return models.filter((model)=>model.dashboard?.access!==!1).map((m)=>{const row={id:m.id,name:m.name,icon:m.icon,hasDedicatedPage:dedicatedPages.has(m.id),category:m.category??"data"};if(m.dashboard)row.dashboard=m.dashboard;return row})}export function writeFileIfChanged(file,content){try{if(readFileSync(file,"utf8")===content)return!1}catch{}const temporary=`${file}.${process.pid}.${randomUUID()}.tmp`;try{writeFileSync(temporary,content,{flag:"wx"});renameSync(temporary,file)}finally{if(existsSync(temporary))unlinkSync(temporary)}return!0}export async function isPortAvailable(port){try{await Bun.serve({port,fetch:()=>new Response}).stop(!0);return!0}catch{return!1}}export async function findAvailablePort(preferred,maxAttempts=20){for(let i=0;i<maxAttempts;i++){const port=preferred+i;if(await isPortAvailable(port))return port}return preferred}function connectsWithin(port,timeoutMs){return new Promise((resolve)=>{const socket=connect({port,host:"127.0.0.1"}),finish=(connected)=>{clearTimeout(timer);try{socket.destroy()}catch{}resolve(connected)},timer=setTimeout(()=>finish(!1),timeoutMs);socket.once("connect",()=>finish(!0));socket.once("error",()=>finish(!1))})}export async function waitForServer(port,maxWait=500){const deadline=Date.now()+maxWait;while(!0){const remaining=deadline-Date.now();if(remaining<=0)return!1;if(await connectsWithin(port,Math.min(remaining,250)))return!0;if(Date.now()>=deadline)return!1;await new Promise((resolve)=>setTimeout(resolve,Math.min(25,Math.max(deadline-Date.now(),0))))}}function effectiveCategory(m){if(m.dashboard?.access===!1||m.dashboard?.enabled===!1)return;if(m.dashboard?.section)return m.dashboard.section;return m.category??"data"}function categoryRows(baseRoute,models,category,dedicated){return models.filter((m)=>effectiveCategory(m)===category).filter((m)=>!dedicatedPages.has(m.id)&&!dedicated.has(m.id)).map((m)=>({id:`model-${m.id}`,label:m.dashboard?.label??capitalCase(plural(m.name)),icon:m.icon,url:`${baseRoute}/models/${m.id}`,...m.dashboard?.roles&&m.dashboard.roles.length>0?{roles:m.dashboard.roles}:{}}))}export function buildSidebarConfig(baseRoute,discoveredModels,toggles={}){const enabled={library:toggles.library??!0,content:toggles.content??!0,commerce:toggles.commerce??!0,marketing:toggles.marketing??!0,analytics:toggles.analytics??!0,management:toggles.management??!0,utilities:toggles.utilities??!0},dataRow={dashboard:toggles.data?.dashboard??!0,activity:toggles.data?.activity??!0,users:toggles.data?.users??!0,teams:toggles.data?.teams??!0,subscribers:toggles.data?.subscribers??!0,allModels:toggles.data?.allModels??!0},sections=[],homeItems=[{id:"home",label:"Dashboard",icon:"house.fill",url:`${baseRoute}/`},{id:"dependencies",label:"Dependencies",icon:"shippingbox.fill",url:`${baseRoute}/dependencies`},{id:"health",label:"Health",icon:"heart.text.square.fill",url:`${baseRoute}/health`}];if(toggles.ci)homeItems.push({id:"ci",label:"CI",icon:"checkmark.seal.fill",url:`${baseRoute}/ci`});sections.push({id:"home",title:"Home",items:homeItems});if(enabled.library)sections.push({id:"library",title:"Library",items:[{id:"functions",label:"Functions",icon:"function",url:`${baseRoute}/functions`},{id:"packages",label:"Packages",icon:"shippingbox.fill",url:`${baseRoute}/packages`}]});if(enabled.content)sections.push({id:"content",title:"Content",items:[{id:"content-dashboard",label:"Dashboard",icon:"gauge.with.dots.needle.33percent",url:`${baseRoute}/content/dashboard`},{id:"files",label:"Files",icon:"folder.fill",url:`${baseRoute}/content/files`},{id:"pages",label:"Pages",icon:"doc.fill",url:`${baseRoute}/content/pages`},{id:"posts",label:"Posts",icon:"text.bubble.fill",url:`${baseRoute}/content/posts`},{id:"categories",label:"Categories",icon:"tag.fill",url:`${baseRoute}/content/categories`},{id:"tags",label:"Tags",icon:"tag",url:`${baseRoute}/content/tags`},{id:"comments",label:"Comments",icon:"bubble.left.fill",url:`${baseRoute}/content/comments`},{id:"authors",label:"Authors",icon:"person.text.rectangle.fill",url:`${baseRoute}/content/authors`},{id:"seo",label:"SEO",icon:"magnifyingglass",url:`${baseRoute}/content/seo`},...categoryRows(baseRoute,discoveredModels,"content",new Set(["page","post","category","tag","comment","author"]))]});sections.push({id:"app",title:"App",items:[{id:"deployments",label:"Deployments",icon:"rocket.fill",url:`${baseRoute}/deployments`},{id:"requests",label:"Requests",icon:"arrow.left.arrow.right",url:`${baseRoute}/requests`},{id:"realtime",label:"Realtime",icon:"link",url:`${baseRoute}/realtime`},{id:"actions",label:"Actions",icon:"bolt.fill",url:`${baseRoute}/actions`},{id:"commands",label:"Commands",icon:"terminal.fill",url:`${baseRoute}/commands`},{id:"search-engine",label:"Search Engine",icon:"magnifyingglass",url:`${baseRoute}/search-engine`},{id:"queue",label:"Queue",icon:"list.bullet.rectangle.fill",url:`${baseRoute}/queue`},{id:"jobs",label:"Jobs",icon:"briefcase.fill",url:`${baseRoute}/jobs`},{id:"inbox",label:"Inbox",icon:"tray.full.fill",url:`${baseRoute}/inbox`},{id:"queries",label:"Queries",icon:"magnifyingglass.circle.fill",url:`${baseRoute}/queries`},{id:"notifications",label:"Notifications",icon:"bell.fill",url:`${baseRoute}/notifications/dashboard`},...categoryRows(baseRoute,discoveredModels,"system",new Set)]});const dataItems=[];if(dataRow.dashboard)dataItems.push({id:"data-dashboard",label:"Dashboard",icon:"gauge.with.dots.needle.33percent",url:`${baseRoute}/data/dashboard`});if(dataRow.activity)dataItems.push({id:"activity",label:"Activity",icon:"waveform.path.ecg",url:`${baseRoute}/data/activity`});if(dataRow.users)dataItems.push({id:"users",label:"Users",icon:"person.crop.circle.fill",url:`${baseRoute}/data/users`});if(dataRow.teams)dataItems.push({id:"teams",label:"Teams",icon:"person.3.fill",url:`${baseRoute}/data/teams`});if(dataRow.subscribers)dataItems.push({id:"subscribers",label:"Subscribers",icon:"envelope.fill",url:`${baseRoute}/data/subscribers`});if(dataRow.allModels)dataItems.push({id:"data-models",label:"All Models",icon:"square.grid.2x2.fill",url:`${baseRoute}/models`});const dynamicRows=discoveredModels.filter((m)=>{const eff=effectiveCategory(m);return eff==="userland"||eff==="data"}).filter((m)=>!dedicatedPages.has(m.id)).map((model)=>({id:`model-${model.id}`,label:model.dashboard?.label??capitalCase(plural(model.name)),icon:model.icon,url:`${baseRoute}/models/${model.id}`,...model.dashboard?.roles&&model.dashboard.roles.length>0?{roles:model.dashboard.roles}:{}}));sections.push({id:"data",title:"Data",items:[...dataItems,...dynamicRows]});if(enabled.commerce)sections.push({id:"commerce",title:"Commerce",items:[{id:"commerce-dashboard",label:"Dashboard",icon:"gauge.with.dots.needle.33percent",url:`${baseRoute}/commerce/dashboard`},{id:"customers",label:"Customers",icon:"person.crop.circle.fill",url:`${baseRoute}/commerce/customers`},{id:"orders",label:"Orders",icon:"list.clipboard.fill",url:`${baseRoute}/commerce/orders`},{id:"products",label:"Products",icon:"cube.box.fill",url:`${baseRoute}/commerce/products`},{id:"coupons",label:"Coupons",icon:"ticket.fill",url:`${baseRoute}/commerce/coupons`},{id:"gift-cards",label:"Gift Cards",icon:"giftcard.fill",url:`${baseRoute}/commerce/gift-cards`},{id:"payments",label:"Payments",icon:"creditcard.fill",url:`${baseRoute}/commerce/payments`},{id:"delivery",label:"Delivery",icon:"truck.box.fill",url:`${baseRoute}/commerce/delivery`},{id:"taxes",label:"Taxes",icon:"percent",url:`${baseRoute}/commerce/taxes`},...categoryRows(baseRoute,discoveredModels,"commerce",new Set(["customer","order","product","coupon","gift-card","payment","review","category"]))]});if(enabled.marketing)sections.push({id:"marketing",title:"Marketing",items:[{id:"lists",label:"Lists",icon:"list.bullet",url:`${baseRoute}/marketing/lists`},{id:"social-posts",label:"Social Posts",icon:"clock.fill",url:`${baseRoute}/marketing/social-posts`},{id:"campaigns",label:"Campaigns",icon:"megaphone.fill",url:`${baseRoute}/marketing/campaigns`},{id:"marketing-reviews",label:"Reviews",icon:"star.fill",url:`${baseRoute}/marketing/reviews`},...categoryRows(baseRoute,discoveredModels,"marketing",new Set(["campaign"]))]});if(enabled.analytics)sections.push({id:"analytics",title:"Analytics",items:[{id:"analytics-web",label:"Web",icon:"globe",url:`${baseRoute}/analytics/web`},{id:"analytics-blog",label:"Blog",icon:"doc.text.fill",url:`${baseRoute}/analytics/blog`},{id:"analytics-commerce",label:"Commerce",icon:"cart.fill",url:`${baseRoute}/analytics/commerce/web`},{id:"analytics-marketing",label:"Marketing",icon:"megaphone.fill",url:`${baseRoute}/analytics/marketing`}]});if(enabled.management)sections.push({id:"management",title:"Management",items:[{id:"cloud",label:"Cloud",icon:"cloud.fill",url:`${baseRoute}/cloud`},{id:"servers",label:"Servers",icon:"server.rack",url:`${baseRoute}/servers`},{id:"serverless",label:"Serverless",icon:"bolt.horizontal.circle.fill",url:`${baseRoute}/serverless`},{id:"dns",label:"DNS",icon:"network",url:`${baseRoute}/dns`},{id:"mailboxes",label:"Mailboxes",icon:"tray.full.fill",url:`${baseRoute}/mailboxes`},{id:"logs",label:"Logs",icon:"list.bullet.rectangle.portrait.fill",url:`${baseRoute}/logs`},{id:"kanban",label:"Kanban",icon:"rectangle.stack.fill",url:`${baseRoute}/kanban`,roles:["admin","dev"]}]});if(enabled.utilities)sections.push({id:"utilities",title:"Utilities",items:[{id:"buddy",label:"AI Buddy",icon:"bubble.left.and.bubble.right.fill",url:`${baseRoute}/buddy`},{id:"environment",label:"Environment",icon:"key.fill",url:`${baseRoute}/environment`},{id:"access-tokens",label:"Access Tokens",icon:"key.horizontal.fill",url:`${baseRoute}/access-tokens`},{id:"settings",label:"Settings",icon:"gear",url:`${baseRoute}/settings/billing`}]});return{sections,minWidth:200,maxWidth:280}}
|
package/dist/dev/dashboard.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import process from"node:process";import{existsSync,mkdirSync}from"node:fs";import{connect}from"node:net";import{bold,cyan,dim,green}from"@stacksjs/cli";import{defaultsPath,projectPath,publicPath,storagePath}from"@stacksjs/path";import{seedCsrfPageResponse,validateDevCsrfRequest}from"./csrf";import{resolveComponentsLibraryRoot}from"./defaults-resources";import{shouldDelegateDashboardRequest}from"./dashboard-request-routing";import{resolveDashboardCraftExecutable}from"./dashboard-native";import{resolveDashboardDomain,resolveDashboardProxyStrategy}from"./dashboard-proxy";import{buildManifest,discoverProjectModels,findAvailablePort,modelsWithEnabledFeatures,waitForServer,writeFileIfChanged}from"./dashboard-utils";import{runDashboardSupervisor}from"./dashboard-supervisor";import{ensureDiscoveredPackages}from"../discover-packages";import{resolveStxSource}from"../stx-source";if(process.env.STACKS_DASHBOARD_WORKER!=="1"){const exitCode=await runDashboardSupervisor(import.meta.path,process.argv.slice(2));process.exit(exitCode)}process.env.STX_DIR=storagePath("framework/runtime/dashboard-stx");const verboseIdx=process.argv.indexOf("--verbose"),verbose=verboseIdx!==-1&&process.argv[verboseIdx+1]!=="false",startTime=Bun.nanoseconds(),{log:originalConsoleLog,warn:originalConsoleWarn}=console,bufferedLogs=[];console.log=(...args)=>{bufferedLogs.push(args.map(String).join(" "))};console.warn=(...args)=>{bufferedLogs.push(args.map(String).join(" "))};const dashboardPath=defaultsPath("views/dashboard"),userDashboardPath=projectPath("resources/views/dashboard"),dashboardComponentsPath=defaultsPath("resources/components/Dashboard"),userDashboardComponentsPath=projectPath("resources/components/Dashboard"),preferredPort=Number(process.env.PORT_ADMIN)||3002,dashboardPort=await findAvailablePort(preferredPort),appUrl=process.env.APP_URL||"",dashboardDomain=resolveDashboardDomain(appUrl),sslBasePath=`${process.env.HOME}/.stacks/ssl`;function restoreConsole(){console.log=originalConsoleLog;console.warn=(...args)=>{const msg=args.map(String).join(" ");if(msg.includes("[STX] DOM API violation")||msg.includes("unsafe expression"))return;originalConsoleWarn(...args)}}async function startStxServer(){const{overridesReady}=await import("@stacksjs/config"),{autoImportsAreStale,generateAutoImportFiles,injectGlobalAutoImports}=await import("@stacksjs/server");await overridesReady;await ensureDiscoveredPackages();if(!existsSync(storagePath("framework/auto-imports/models.ts"))||autoImportsAreStale())await generateAutoImportFiles();await injectGlobalAutoImports();const serveSource=resolveStxSource({value:process.env.BUN_PLUGIN_STX_SRC});if(serveSource.kind==="missing")throw Error(`BUN_PLUGIN_STX_SRC points at ${serveSource.path}, which does not exist. Unset it to use the installed bun-plugin-stx.`);let serve;if(serveSource.kind==="override"){serve=(await import(serveSource.path)).serve;console.log(`[Dashboard] bun-plugin-stx from ${serveSource.path}`)}else serve=(await import("bun-plugin-stx/serve")).serve;const stxSource=resolveStxSource({value:process.env.STX_SRC});if(stxSource.kind==="missing")throw Error(`STX_SRC points at ${stxSource.path}, which does not exist. Unset it to use the installed @stacksjs/stx.`);let stxModule;if(stxSource.kind==="override"){stxModule=await import(stxSource.path);console.log(`[Dashboard] stx from ${stxSource.path}`)}const{listConfigFiles,readConfig,updateConfigKeys}=await import(defaultsPath("resources/functions/dashboard/config-io.ts")),localTsChartsRoot=process.env.TS_CHARTS_SRC,dependencyBundles=new Map;function resolveTsChartsSource(packageName){return[...localTsChartsRoot?[`${localTsChartsRoot}/packages/${packageName}/src/index.ts`]:[],projectPath(`node_modules/@ts-charts/${packageName}/src/index.ts`)].find(existsSync)||null}const tsChartsEntry=[...localTsChartsRoot?[`${localTsChartsRoot}/packages/ts-charts/src/index.ts`]:[],projectPath("node_modules/ts-charts/src/index.ts")].find(existsSync);async function buildDashboardDependency(entrypoint){const cached=dependencyBundles.get(entrypoint);if(cached)return cached;const build=(async()=>{const result=await Bun.build({entrypoints:[entrypoint],target:"browser",format:"esm",minify:!0,plugins:[{name:"dashboard-ts-charts-source",setup(builder){builder.onResolve({filter:/^@ts-charts\/[a-z0-9-]+$/},(args)=>{const packageName=args.path.slice(11),source=resolveTsChartsSource(packageName);if(source)return{path:source};return null})}}]});if(!result.success){const errors=result.logs.filter((log)=>log.level==="error").map((log)=>log.message).join(`
|
|
2
|
-
`);throw Error(errors||`Failed to bundle ${entrypoint}`)}const output=result.outputs.find((file)=>file.path.endsWith(".js"));if(!output)throw Error(`No JavaScript output produced for ${entrypoint}`);return output.text()})();dependencyBundles.set(entrypoint,build);return build}function browserDependencyRoute(entrypoint){return async()=>{try{return new Response(await buildDashboardDependency(entrypoint),{headers:{"content-type":"text/javascript; charset=utf-8","cache-control":"no-cache"}})}catch(error){dependencyBundles.delete(entrypoint);return new Response(`throw new Error(${JSON.stringify(error.message)})`,{status:500,headers:{"content-type":"text/javascript; charset=utf-8"}})}}}let dashboardIconCss=null;async function buildDashboardIconCss(){const{generateCss}=await import("@stacksjs/stx"),dirs=[dashboardPath,userDashboardPath,dashboardComponentsPath,userDashboardComponentsPath],icons=new Set;for(const dir of dirs){if(!existsSync(dir))continue;const glob=new Bun.Glob("**/*.{stx,ts}");for await(const file of glob.scan({cwd:dir,absolute:!0})){const text=await Bun.file(file).text();for(const match of text.matchAll(/\bi-[a-z][a-z0-9]*(?:-[a-z0-9]+)+/g))icons.add(match[0])}}if(icons.size===0)return"";return generateCss(`<div class="${[...icons].join(" ")}"></div>`,process.cwd())}const configRoutes={"/__deps/charts.js":browserDependencyRoute(storagePath("framework/core/charts/src/index.ts")),"/__deps/ts-charts.js":browserDependencyRoute(tsChartsEntry||`${localTsChartsRoot}/packages/ts-charts/src/index.ts`),"/__deps/dashboard-icons.css":async()=>{if(!dashboardIconCss)dashboardIconCss=buildDashboardIconCss();return new Response(await dashboardIconCss,{headers:{"content-type":"text/css; charset=utf-8","cache-control":"no-cache"}})},"/api/config/list":async()=>{try{return Response.json({ok:!0,files:listConfigFiles()})}catch(e){return Response.json({ok:!1,error:e?.message},{status:500})}},"/api/config/read":async(req)=>{try{const name=new URL(req.url).searchParams.get("name")||"";if(!/^[\w-]+$/.test(name))return Response.json({ok:!1,error:"Invalid config name"},{status:400});const result=await readConfig(name);if(!result)return Response.json({ok:!1,error:"Not found"},{status:404});return Response.json({ok:!0,name,fields:result.fields})}catch(e){return Response.json({ok:!1,error:e?.message},{status:500})}},"/api/config/source":async(req)=>{try{const name=new URL(req.url).searchParams.get("name")||"";if(!/^[\w-]+$/.test(name))return Response.json({ok:!1,error:"Invalid config name"},{status:400});const result=await readConfig(name);if(!result)return Response.json({ok:!1,error:"Not found"},{status:404});return new Response(result.source,{headers:{"content-type":"text/plain; charset=utf-8"}})}catch(e){return Response.json({ok:!1,error:e?.message},{status:500})}},"/api/config/update":async(req)=>{if(req.method!=="POST")return Response.json({ok:!1,error:"Method not allowed"},{status:405});try{await validateDevCsrfRequest(req);const body=await req.json(),file=body.file?.replace(/\.ts$/,"");if(!file||!/^[\w-]+$/.test(file))return Response.json({ok:!1,error:"Invalid file"},{status:400});const updates=[];if(Array.isArray(body.updates))for(const u of body.updates){const k=u.key??u.path;if(typeof k==="string")updates.push({key:k,value:u.value})}else if(body.key)updates.push({key:body.key,value:body.value});if(updates.length===0)return Response.json({ok:!1,error:"No updates supplied"},{status:400});const invalid=updates.find((update)=>!/^[A-Za-z_$][\w$]*$/.test(update.key)||typeof update.value!=="string"&&typeof update.value!=="number"&&typeof update.value!=="boolean"||typeof update.value==="number"&&!Number.isFinite(update.value));if(invalid)return Response.json({ok:!1,error:`Invalid value for configuration key "${invalid.key}"`},{status:400});const typedUpdates=updates;try{await updateConfigKeys(file,typedUpdates)}catch(err){const error=err?.message||"Configuration values could not be updated.",results=typedUpdates.map((update)=>({key:update.key,ok:!1,error}));return Response.json({ok:!1,file,results,error},{status:422})}const results=typedUpdates.map((update)=>({key:update.key,ok:!0,newValue:update.value}));return Response.json({ok:!0,file,results})}catch(e){if(e?.status===403)return Response.json({ok:!1,error:"Forbidden",message:"CSRF token mismatch"},{status:403});return Response.json({ok:!1,error:e?.message},{status:500})}}},router=await import("@stacksjs/router");await router.loadRoutes(await router.appRouteRegistry());await router.route.register(defaultsPath("routes/dashboard-api.ts"));const stacksRoute=router.route;serve({root:projectPath("resources"),patterns:[userDashboardPath,dashboardPath],port:dashboardPort,componentsDir:userDashboardComponentsPath,additionalComponentsDirs:[dashboardComponentsPath],fallbackComponentsDir:resolveComponentsLibraryRoot(),layoutsDir:projectPath("resources/views/dashboard/layouts"),fallbackLayoutsDir:defaultsPath("views/dashboard/layouts"),partialsDir:dashboardPath,publicDir:publicPath(),renderCache:!0,renderCacheVary:"source",prewarmRenderCache:!1,renderCachePersist:!0,watchDirs:[projectPath("resources/functions"),defaultsPath("resources/functions"),projectPath("config"),storagePath("framework/runtime/dashboard")],quiet:!0,routes:configRoutes,onRequest:async(req)=>{const pathname=new URL(req.url).pathname;if(shouldDelegateDashboardRequest(pathname,req.method))return stacksRoute.handleRequest(req);return null},onResponse:seedCsrfPageResponse,auth:!1,...stxModule&&{stxModule}}).catch((err)=>{restoreConsole();console.error(`
|
|
2
|
+
`);throw Error(errors||`Failed to bundle ${entrypoint}`)}const output=result.outputs.find((file)=>file.path.endsWith(".js"));if(!output)throw Error(`No JavaScript output produced for ${entrypoint}`);return output.text()})();dependencyBundles.set(entrypoint,build);return build}function browserDependencyRoute(entrypoint){return async()=>{try{return new Response(await buildDashboardDependency(entrypoint),{headers:{"content-type":"text/javascript; charset=utf-8","cache-control":"no-cache"}})}catch(error){dependencyBundles.delete(entrypoint);return new Response(`throw new Error(${JSON.stringify(error.message)})`,{status:500,headers:{"content-type":"text/javascript; charset=utf-8"}})}}}let dashboardIconCss=null;async function buildDashboardIconCss(){const{generateCss}=await import("@stacksjs/stx"),dirs=[dashboardPath,userDashboardPath,dashboardComponentsPath,userDashboardComponentsPath,projectPath("app/Models"),defaultsPath("app/Models")],icons=new Set;for(const dir of dirs){if(!existsSync(dir))continue;const glob=new Bun.Glob("**/*.{stx,ts}");for await(const file of glob.scan({cwd:dir,absolute:!0})){const text=await Bun.file(file).text();for(const match of text.matchAll(/\bi-[a-z][a-z0-9]*(?:-[a-z0-9]+)+/g))icons.add(match[0])}}if(icons.size===0)return"";return generateCss(`<div class="${[...icons].join(" ")}"></div>`,process.cwd())}const configRoutes={"/__deps/charts.js":browserDependencyRoute(storagePath("framework/core/charts/src/index.ts")),"/__deps/ts-charts.js":browserDependencyRoute(tsChartsEntry||`${localTsChartsRoot}/packages/ts-charts/src/index.ts`),"/__deps/dashboard-icons.css":async()=>{if(!dashboardIconCss)dashboardIconCss=buildDashboardIconCss();return new Response(await dashboardIconCss,{headers:{"content-type":"text/css; charset=utf-8","cache-control":"no-cache"}})},"/api/config/list":async()=>{try{return Response.json({ok:!0,files:listConfigFiles()})}catch(e){return Response.json({ok:!1,error:e?.message},{status:500})}},"/api/config/read":async(req)=>{try{const name=new URL(req.url).searchParams.get("name")||"";if(!/^[\w-]+$/.test(name))return Response.json({ok:!1,error:"Invalid config name"},{status:400});const result=await readConfig(name);if(!result)return Response.json({ok:!1,error:"Not found"},{status:404});return Response.json({ok:!0,name,fields:result.fields})}catch(e){return Response.json({ok:!1,error:e?.message},{status:500})}},"/api/config/source":async(req)=>{try{const name=new URL(req.url).searchParams.get("name")||"";if(!/^[\w-]+$/.test(name))return Response.json({ok:!1,error:"Invalid config name"},{status:400});const result=await readConfig(name);if(!result)return Response.json({ok:!1,error:"Not found"},{status:404});return new Response(result.source,{headers:{"content-type":"text/plain; charset=utf-8"}})}catch(e){return Response.json({ok:!1,error:e?.message},{status:500})}},"/api/config/update":async(req)=>{if(req.method!=="POST")return Response.json({ok:!1,error:"Method not allowed"},{status:405});try{await validateDevCsrfRequest(req);const body=await req.json(),file=body.file?.replace(/\.ts$/,"");if(!file||!/^[\w-]+$/.test(file))return Response.json({ok:!1,error:"Invalid file"},{status:400});const updates=[];if(Array.isArray(body.updates))for(const u of body.updates){const k=u.key??u.path;if(typeof k==="string")updates.push({key:k,value:u.value})}else if(body.key)updates.push({key:body.key,value:body.value});if(updates.length===0)return Response.json({ok:!1,error:"No updates supplied"},{status:400});const invalid=updates.find((update)=>!/^[A-Za-z_$][\w$]*$/.test(update.key)||typeof update.value!=="string"&&typeof update.value!=="number"&&typeof update.value!=="boolean"||typeof update.value==="number"&&!Number.isFinite(update.value));if(invalid)return Response.json({ok:!1,error:`Invalid value for configuration key "${invalid.key}"`},{status:400});const typedUpdates=updates;try{await updateConfigKeys(file,typedUpdates)}catch(err){const error=err?.message||"Configuration values could not be updated.",results=typedUpdates.map((update)=>({key:update.key,ok:!1,error}));return Response.json({ok:!1,file,results,error},{status:422})}const results=typedUpdates.map((update)=>({key:update.key,ok:!0,newValue:update.value}));return Response.json({ok:!0,file,results})}catch(e){if(e?.status===403)return Response.json({ok:!1,error:"Forbidden",message:"CSRF token mismatch"},{status:403});return Response.json({ok:!1,error:e?.message},{status:500})}}},router=await import("@stacksjs/router");await router.loadRoutes(await router.appRouteRegistry());await router.route.register(defaultsPath("routes/dashboard-api.ts"));const stacksRoute=router.route;serve({root:projectPath("resources"),patterns:[userDashboardPath,dashboardPath],port:dashboardPort,componentsDir:userDashboardComponentsPath,additionalComponentsDirs:[dashboardComponentsPath],fallbackComponentsDir:resolveComponentsLibraryRoot(),layoutsDir:projectPath("resources/views/dashboard/layouts"),fallbackLayoutsDir:defaultsPath("views/dashboard/layouts"),partialsDir:dashboardPath,publicDir:publicPath(),renderCache:!0,renderCacheVary:"source",prewarmRenderCache:!1,renderCachePersist:!0,watchDirs:[projectPath("resources/functions"),defaultsPath("resources/functions"),projectPath("config"),storagePath("framework/runtime/dashboard")],quiet:!0,routes:configRoutes,onRequest:async(req)=>{const pathname=new URL(req.url).pathname;if(shouldDelegateDashboardRequest(pathname,req.method))return stacksRoute.handleRequest(req);return null},onResponse:seedCsrfPageResponse,auth:!1,...stxModule&&{stxModule}}).catch((err)=>{restoreConsole();console.error(`
|
|
3
3
|
Failed to start dashboard server: ${err?.message||err}
|
|
4
4
|
`);process.exit(1)})}function portAnswers(port,timeoutMs=800){return new Promise((resolve)=>{const socket=connect({port,host:"127.0.0.1"}),finish=(answered)=>{try{socket.destroy()}catch{}resolve(answered)};socket.once("connect",()=>finish(!0));socket.once("error",()=>finish(!1));setTimeout(()=>finish(!1),timeoutMs).unref?.()})}async function registerWithRpxDaemon(domainToServe){const{writeEntry}=await import("@stacksjs/rpx");await writeEntry({id:`${domainToServe}-dashboard`,from:`localhost:${dashboardPort}`,to:domainToServe,cwd:process.cwd(),createdAt:new Date().toISOString(),pid:process.pid},void 0,verbose);return!0}async function startReverseProxy(){if(!dashboardDomain)return!1;try{let rpx;const loadRpx=async()=>rpx??=await import("@stacksjs/rpx"),strategy=await resolveDashboardProxyStrategy(dashboardDomain,{proxyManagedExternally:Boolean(process.env.STACKS_PROXY_MANAGED),isDaemonRunning:async()=>(await loadRpx()).isDaemonRunning(),httpsPortAnswers:()=>portAnswers(443)});if(strategy==="origin-only")return!1;if(strategy==="parent-managed")return!0;if(strategy==="daemon-route")return await registerWithRpxDaemon(dashboardDomain);await(await loadRpx()).startProxies({proxies:[{from:`localhost:${dashboardPort}`,to:dashboardDomain,cleanUrls:!1}],https:{basePath:sslBasePath,validityDays:825},regenerateUntrustedCerts:!1,verbose});return await portAnswers(443)}catch(error){if(verbose)originalConsoleLog(` ${dim(`Proxy: ${error}`)}`);return!1}}const[,allDiscoveredModels]=await Promise.all([startStxServer(),discoverProjectModels()]),{loadDashboardConfig}=await import(defaultsPath("resources/functions/dashboard/toggles.ts")),{feature:featureEnabled}=await import("@stacksjs/config"),{toggles:dashboardToggles,nav:dashboardNav}=await loadDashboardConfig(projectPath("config/dashboard.ts"),featureEnabled),{frameworkModelFeature}=await import("@stacksjs/orm"),discoveredModels=modelsWithEnabledFeatures(allDiscoveredModels,frameworkModelFeature,(name)=>featureEnabled(name)),manifestDir=storagePath("framework/runtime/dashboard"),manifestPath=storagePath("framework/runtime/dashboard/.discovered-models.json");mkdirSync(manifestDir,{recursive:!0});const{resolveModelSources}=await import("@stacksjs/database/model-sources"),manifestPayload={models:buildManifest(discoveredModels),schemaModels:(resolveModelSources()?.models??[]).map((model)=>model.name),sections:dashboardToggles,nav:dashboardNav};writeFileIfChanged(manifestPath,JSON.stringify(manifestPayload,null,2));const serverReady=await waitForServer(dashboardPort);restoreConsole();const proxyStarted=await startReverseProxy().catch((err)=>{if(verbose)console.warn("[Dashboard] Reverse proxy failed:",err);return!1}),dashboardHttpsUrl=dashboardDomain?`https://${dashboardDomain}`:null,dashboardLocalUrl=`http://localhost:${dashboardPort}`,initialUrl=dashboardHttpsUrl&&proxyStarted?`${dashboardHttpsUrl}/`:`${dashboardLocalUrl}/`,elapsedMs=(Bun.nanoseconds()-startTime)/1e6;console.log();console.log(` ${bold(cyan("stacks dashboard"))}`);console.log();if(dashboardHttpsUrl&&proxyStarted){console.log(` ${green("\u279C")} ${bold("Local")}: ${cyan(dashboardHttpsUrl)}`);console.log(` ${dim("\u279C")} ${dim("Origin")}: ${dim(dashboardLocalUrl)}`)}else{console.log(` ${green("\u279C")} ${bold("Local")}: ${cyan(dashboardLocalUrl)}`);if(dashboardHttpsUrl)console.log(` ${dim("\u279C")} ${dim("Pretty")}: ${dim(`${dashboardHttpsUrl} needs the rpx proxy - run \`buddy dev\``)}`)}console.log(` ${green("\u279C")} ${bold("Window")}: ${dim("Stacks Dashboard")} ${dim("1400\xD7900")}`);console.log(` ${green("\u279C")} ${bold("Models")}: ${dim(`${discoveredModels.length} discovered`)}`);if(dashboardPort!==preferredPort)console.log(` ${dim("\u279C")} ${dim(`Port ${preferredPort} in use, using ${dashboardPort}`)}`);if(!serverReady)console.log(` ${dim("\u26A0")} ${dim("Dev server may not be ready yet")}`);console.log();console.log(` ${dim(`ready in ${elapsedMs.toFixed(0)} ms`)}`);if(verbose){console.log();console.log(` ${dim("\u279C")} ${dim("URL")}: ${dim(initialUrl)}`);if(dashboardDomain){console.log(` ${dim("\u279C")} ${dim("SSL")}: ${dim(sslBasePath)}`);console.log(` ${dim("\u279C")} ${dim("Proxy")}: ${dim(`localhost:${dashboardPort} \u2192 ${dashboardDomain}`)}`)}if(bufferedLogs.length>0){console.log();for(const line of bufferedLogs)console.log(` ${dim(line)}`)}}console.log();let createApp,resolveCraftBinary;const nativeDisabled=process.env.STACKS_NO_NATIVE==="1",explicitCraftSdk=process.env.CRAFT_SDK_SRC;if(!nativeDisabled&&explicitCraftSdk){if(!existsSync(explicitCraftSdk))throw Error(`CRAFT_SDK_SRC not found: ${explicitCraftSdk}`);try{({createApp,resolveCraftBinary}=await import(explicitCraftSdk));if(!createApp||!resolveCraftBinary)throw Error("CRAFT_SDK_SRC must export createApp and resolveCraftBinary")}catch(error){throw Error(`Could not load CRAFT_SDK_SRC ${explicitCraftSdk}: ${error instanceof Error?error.message:String(error)}`)}}if(!nativeDisabled&&!explicitCraftSdk)try{({createApp,resolveCraftBinary}=await import("craft-native"))}catch{}const craftBinaryPath=createApp&&resolveCraftBinary?resolveDashboardCraftExecutable(resolveCraftBinary):void 0;if(createApp&&craftBinaryPath){const userIconPath=projectPath("resources/assets/images/app-icon.png"),defaultIconPath=defaultsPath("resources/assets/images/app-icon.png"),appIconPath=await Bun.file(userIconPath).exists()?userIconPath:await Bun.file(defaultIconPath).exists()?defaultIconPath:void 0,app=createApp({url:dashboardLocalUrl,quiet:!verbose,craftPath:craftBinaryPath,window:{title:"Stacks Dashboard",width:1400,height:900,titlebarHidden:!0,webSidebarMaterial:!0,webSidebarWidth:250,...appIconPath&&{icon:appIconPath}}});process.on("SIGINT",()=>{app.close();process.exit(0)});process.on("SIGTERM",()=>{app.close();process.exit(0)});try{await app.show();process.exit(0)}catch(error){const fallbackUrl=dashboardHttpsUrl||dashboardLocalUrl;console.log(` ${dim("Native Craft window failed:")} ${dim(error instanceof Error?error.message:String(error))}`);console.log(` ${dim("Dashboard available at:")} ${cyan(fallbackUrl)}
|
|
5
5
|
`);await new Promise(()=>{})}}else{console.log(` ${dim(nativeDisabled?"Native window disabled by STACKS_NO_NATIVE=1. Open the URL above in a browser.":"Native window unavailable. Run pantry install craft, set CRAFT_BIN, or open the URL above in a browser.")}
|
package/dist/pantry-lock.d.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
/** An SDK version bump must not re-resolve an unchanged native toolchain for the publisher's OS. */
|
|
2
|
+
export declare function preservePantrySystemPins(lock: string, baseline: string): string;
|
|
1
3
|
/**
|
|
2
4
|
* Why this lockfile must not be committed, or an empty list when it is sound.
|
|
3
5
|
*
|
package/dist/pantry-lock.js
CHANGED
|
@@ -1 +1,2 @@
|
|
|
1
|
-
const DEPENDENCY_FIELDS=["dependencies","devDependencies","peerDependencies","optionalDependencies"],UNCOMPARABLE_RANGE=/^(?:workspace|file|link|git|github|npm|catalog):/;function
|
|
1
|
+
const DEPENDENCY_FIELDS=["dependencies","devDependencies","peerDependencies","optionalDependencies"],UNCOMPARABLE_RANGE=/^(?:workspace|file|link|git|github|npm|catalog):/;export function preservePantrySystemPins(lock,baseline){const next=JSON.parse(lock),previous=JSON.parse(baseline),systems=(value)=>Object.entries(value.workspaces??{}).filter(([,workspace])=>workspace.system&&typeof workspace.system==="object").map(([path,workspace])=>[path,Object.entries(workspace.system).sort(([a],[b])=>a<b?-1:a>b?1:0)]).sort(([a],[b])=>String(a)<String(b)?-1:String(a)>String(b)?1:0),declared=systems(previous);if(!declared.length||JSON.stringify(declared)!==JSON.stringify(systems(next)))return lock;const native=(value)=>!!value&&typeof value==="object"&&value.source==="pantry",pinned=Object.entries(previous.packages??{}).filter(([,value])=>native(value));if(!pinned.length)return lock;const packages=Object.fromEntries(Object.entries(next.packages??{}).filter(([,value])=>!native(value)));for(const[name,value]of pinned)packages[name]=value;next.packages=Object.fromEntries(Object.entries(packages).sort(([a],[b])=>a<b?-1:a>b?1:0));return`${JSON.stringify(next,null,2)}
|
|
2
|
+
`}function splitPackageKey(key){const at=key.lastIndexOf("@");if(at<=0)return null;return{name:key.slice(0,at),version:key.slice(at+1)}}function resolvedVersions(packages){const resolved=new Map;for(const key of Object.keys(packages)){const parsed=splitPackageKey(key);if(!parsed)continue;const versions=resolved.get(parsed.name);if(versions)versions.push(parsed.version);else resolved.set(parsed.name,[parsed.version])}return resolved}function systemBlockProblems(root,baseline){if(!baseline)return[];let baselineSystem;try{baselineSystem=JSON.parse(baseline).workspaces?.[""]?.system}catch{return[]}if(!baselineSystem||typeof baselineSystem!=="object")return[];const expected=baselineSystem,system=root?.system;if(!system||typeof system!=="object")return[`the root "system" block was dropped (it pinned ${Object.keys(expected).join(", ")}), so CI would have no toolchain to provision`];const present=system;return Object.keys(expected).filter((pin)=>!(pin in present)).map((pin)=>`the root "system" block lost its "${pin}" pin`)}export function pantryLockViolations(lock,baseline,declarations){let parsed;try{parsed=JSON.parse(lock)}catch(error){return[`it is not valid JSON (${error instanceof Error?error.message:String(error)})`]}const problems=[],workspaces=parsed.workspaces??{},resolved=resolvedVersions(parsed.packages??{});if(declarations){for(const[workspacePath,current]of Object.entries(declarations)){const recorded=workspaces[workspacePath],label=workspacePath||"the workspace root";if(!recorded){problems.push(`${label}: current workspace is missing from pantry.lock`);continue}for(const field of["name","version"])if(current[field]!==recorded[field])problems.push(`${label}: ${field} is ${JSON.stringify(current[field])} but pantry.lock records ${JSON.stringify(recorded[field])}`);for(const field of["dependencies","devDependencies"]){const expected=current[field]??{},locked=recorded[field]??{};for(const[name,range]of Object.entries(expected))if(range!==locked[name])problems.push(`${label}: ${field}.${name} is ${JSON.stringify(range)} but pantry.lock records ${JSON.stringify(locked[name])}`);for(const name of Object.keys(locked))if(!(name in expected))problems.push(`${label}: pantry.lock records undeclared ${field}.${name}`)}}for(const workspacePath of Object.keys(workspaces))if(!(workspacePath in declarations))problems.push(`${workspacePath||"the workspace root"}: pantry.lock records a workspace absent from current declarations`)}for(const[workspacePath,workspace]of Object.entries(workspaces))for(const field of DEPENDENCY_FIELDS){const declared=workspace[field];if(!declared||typeof declared!=="object")continue;for(const[name,range]of Object.entries(declared)){if(typeof range!=="string"||UNCOMPARABLE_RANGE.test(range))continue;const versions=resolved.get(name);if(!versions)continue;if(!versions.some((version)=>Bun.semver.satisfies(version,range)))problems.push(`${name} is pinned at ${versions.join(", ")}, which does not satisfy "${range}" declared by ${workspacePath||"the workspace root"} (${field})`)}}problems.push(...systemBlockProblems(workspaces[""],baseline));return problems}
|
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.
|
|
5
|
+
"version": "0.75.497",
|
|
6
6
|
"description": "The Stacks actions.",
|
|
7
7
|
"author": "Chris Breuer",
|
|
8
8
|
"contributors": [
|
|
@@ -66,54 +66,54 @@
|
|
|
66
66
|
"prepublishOnly": "bun run build"
|
|
67
67
|
},
|
|
68
68
|
"dependencies": {
|
|
69
|
-
"@stacksjs/action-runner": "0.75.
|
|
70
|
-
"@stacksjs/ai": "0.75.
|
|
71
|
-
"@stacksjs/analytics": "0.75.
|
|
72
|
-
"@stacksjs/api": "0.75.
|
|
73
|
-
"@stacksjs/auth": "0.75.
|
|
74
|
-
"@stacksjs/build": "0.75.
|
|
69
|
+
"@stacksjs/action-runner": "0.75.497",
|
|
70
|
+
"@stacksjs/ai": "0.75.497",
|
|
71
|
+
"@stacksjs/analytics": "0.75.497",
|
|
72
|
+
"@stacksjs/api": "0.75.497",
|
|
73
|
+
"@stacksjs/auth": "0.75.497",
|
|
74
|
+
"@stacksjs/build": "0.75.497",
|
|
75
75
|
"@stacksjs/bumpx": "^0.2.26",
|
|
76
76
|
"@stacksjs/bunpress": "^0.2.15",
|
|
77
|
-
"@stacksjs/cli": "0.75.
|
|
78
|
-
"@stacksjs/cloud": "0.75.
|
|
79
|
-
"@stacksjs/cms": "0.75.
|
|
77
|
+
"@stacksjs/cli": "0.75.497",
|
|
78
|
+
"@stacksjs/cloud": "0.75.497",
|
|
79
|
+
"@stacksjs/cms": "0.75.497",
|
|
80
80
|
"@stacksjs/components": "0.2.807",
|
|
81
|
-
"@stacksjs/config": "0.75.
|
|
82
|
-
"@stacksjs/database": "0.75.
|
|
83
|
-
"@stacksjs/desktop-build": "0.75.
|
|
84
|
-
"@stacksjs/dns": "0.75.
|
|
85
|
-
"@stacksjs/enums": "0.75.
|
|
86
|
-
"@stacksjs/env": "0.75.
|
|
87
|
-
"@stacksjs/error-handling": "0.75.
|
|
88
|
-
"@stacksjs/github": "0.75.
|
|
81
|
+
"@stacksjs/config": "0.75.497",
|
|
82
|
+
"@stacksjs/database": "0.75.497",
|
|
83
|
+
"@stacksjs/desktop-build": "0.75.497",
|
|
84
|
+
"@stacksjs/dns": "0.75.497",
|
|
85
|
+
"@stacksjs/enums": "0.75.497",
|
|
86
|
+
"@stacksjs/env": "0.75.497",
|
|
87
|
+
"@stacksjs/error-handling": "0.75.497",
|
|
88
|
+
"@stacksjs/github": "0.75.497",
|
|
89
89
|
"@stacksjs/gitit": "^0.2.5",
|
|
90
|
-
"@stacksjs/i18n": "0.75.
|
|
91
|
-
"@stacksjs/image": "0.75.
|
|
92
|
-
"@stacksjs/logging": "0.75.
|
|
90
|
+
"@stacksjs/i18n": "0.75.497",
|
|
91
|
+
"@stacksjs/image": "0.75.497",
|
|
92
|
+
"@stacksjs/logging": "0.75.497",
|
|
93
93
|
"@stacksjs/logsmith": "^0.2.11",
|
|
94
|
-
"@stacksjs/mobile": "0.75.
|
|
95
|
-
"@stacksjs/orm": "0.75.
|
|
96
|
-
"@stacksjs/path": "0.75.
|
|
97
|
-
"@stacksjs/payments": "0.75.
|
|
98
|
-
"@stacksjs/queue": "0.75.
|
|
99
|
-
"@stacksjs/registry": "0.75.
|
|
100
|
-
"@stacksjs/router": "0.75.
|
|
94
|
+
"@stacksjs/mobile": "0.75.497",
|
|
95
|
+
"@stacksjs/orm": "0.75.497",
|
|
96
|
+
"@stacksjs/path": "0.75.497",
|
|
97
|
+
"@stacksjs/payments": "0.75.497",
|
|
98
|
+
"@stacksjs/queue": "0.75.497",
|
|
99
|
+
"@stacksjs/registry": "0.75.497",
|
|
100
|
+
"@stacksjs/router": "0.75.497",
|
|
101
101
|
"@stacksjs/rpx": "^0.11.54",
|
|
102
|
-
"@stacksjs/scheduler": "0.75.
|
|
103
|
-
"@stacksjs/search-engine": "0.75.
|
|
104
|
-
"@stacksjs/security": "0.75.
|
|
105
|
-
"@stacksjs/server": "0.75.
|
|
106
|
-
"@stacksjs/sites": "0.75.
|
|
107
|
-
"@stacksjs/storage": "0.75.
|
|
108
|
-
"@stacksjs/strings": "0.75.
|
|
102
|
+
"@stacksjs/scheduler": "0.75.497",
|
|
103
|
+
"@stacksjs/search-engine": "0.75.497",
|
|
104
|
+
"@stacksjs/security": "0.75.497",
|
|
105
|
+
"@stacksjs/server": "0.75.497",
|
|
106
|
+
"@stacksjs/sites": "0.75.497",
|
|
107
|
+
"@stacksjs/storage": "0.75.497",
|
|
108
|
+
"@stacksjs/strings": "0.75.497",
|
|
109
109
|
"@stacksjs/stx": "0.2.807",
|
|
110
110
|
"@stacksjs/tlsx": "^0.13.19",
|
|
111
111
|
"@stacksjs/ts-cloud": "^0.16.92",
|
|
112
112
|
"@stacksjs/ts-md": "^0.1.1",
|
|
113
|
-
"@stacksjs/tunnel": "0.75.
|
|
114
|
-
"@stacksjs/types": "0.75.
|
|
115
|
-
"@stacksjs/utils": "0.75.
|
|
116
|
-
"@stacksjs/whois": "0.75.
|
|
113
|
+
"@stacksjs/tunnel": "0.75.497",
|
|
114
|
+
"@stacksjs/types": "0.75.497",
|
|
115
|
+
"@stacksjs/utils": "0.75.497",
|
|
116
|
+
"@stacksjs/whois": "0.75.497",
|
|
117
117
|
"bun-plugin-stx": "0.2.807"
|
|
118
118
|
},
|
|
119
119
|
"peerDependencies": {
|
|
@@ -129,7 +129,7 @@
|
|
|
129
129
|
}
|
|
130
130
|
},
|
|
131
131
|
"devDependencies": {
|
|
132
|
-
"@stacksjs/validation": "0.75.
|
|
132
|
+
"@stacksjs/validation": "0.75.497",
|
|
133
133
|
"better-dx": "^0.2.24"
|
|
134
134
|
}
|
|
135
135
|
}
|