@stacksjs/actions 0.75.484 → 0.75.489
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.
|
@@ -17,6 +17,8 @@ export declare function getModelIcon(name: string): string;
|
|
|
17
17
|
export declare function scanModelsDir(dir: string, seenNames: Set<string>, models: DiscoveredModel[], defaultCategory?: ModelCategory): Promise<void>;
|
|
18
18
|
/** Discover models from both user and default directories */
|
|
19
19
|
export declare function discoverModels(userModelsPath: string, defaultModelsPath: string): Promise<DiscoveredModel[]>;
|
|
20
|
+
/** Discover the native application schema, including installed package models. */
|
|
21
|
+
export declare function discoverProjectModels(): Promise<DiscoveredModel[]>;
|
|
20
22
|
/** Build the manifest array for discovered models */
|
|
21
23
|
export declare function buildManifest(models: DiscoveredModel[]): DiscoveredModelManifestRow[];
|
|
22
24
|
/**
|
|
@@ -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.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 function buildManifest(models){return models.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?.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:"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{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}}
|
package/dist/dev/dashboard.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
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,
|
|
2
|
-
`);throw Error(errors||`Failed to bundle ${entrypoint}`)}const output=result.outputs.find((file)=>file.path.endsWith(".js"));if(!output)throw Error(`No JavaScript output produced for ${entrypoint}`);return output.text()})();dependencyBundles.set(entrypoint,build);return build}function browserDependencyRoute(entrypoint){return async()=>{try{return new Response(await buildDashboardDependency(entrypoint),{headers:{"content-type":"text/javascript; charset=utf-8","cache-control":"no-cache"}})}catch(error){dependencyBundles.delete(entrypoint);return new Response(`throw new Error(${JSON.stringify(error.message)})`,{status:500,headers:{"content-type":"text/javascript; charset=utf-8"}})}}}let dashboardIconCss=null;async function buildDashboardIconCss(){const{generateCss}=await import("@stacksjs/stx"),dirs=[dashboardPath,userDashboardPath,dashboardComponentsPath,userDashboardComponentsPath],icons=new Set;for(const dir of dirs){if(!existsSync(dir))continue;const glob=new Bun.Glob("**/*.{stx,ts}");for await(const file of glob.scan({cwd:dir,absolute:!0})){const text=await Bun.file(file).text();for(const match of text.matchAll(/\bi-[a-z][a-z0-9]*(?:-[a-z0-9]+)+/g))icons.add(match[0])}}if(icons.size===0)return"";return generateCss(`<div class="${[...icons].join(" ")}"></div>`,process.cwd())}const configRoutes={"/__deps/charts.js":browserDependencyRoute(storagePath("framework/core/charts/src/index.ts")),"/__deps/ts-charts.js":browserDependencyRoute(tsChartsEntry||`${localTsChartsRoot}/packages/ts-charts/src/index.ts`),"/__deps/dashboard-icons.css":async()=>{if(!dashboardIconCss)dashboardIconCss=buildDashboardIconCss();return new Response(await dashboardIconCss,{headers:{"content-type":"text/css; charset=utf-8","cache-control":"no-cache"}})},"/api/config/list":async()=>{try{return Response.json({ok:!0,files:listConfigFiles()})}catch(e){return Response.json({ok:!1,error:e?.message},{status:500})}},"/api/config/read":async(req)=>{try{const name=new URL(req.url).searchParams.get("name")||"";if(!/^[\w-]+$/.test(name))return Response.json({ok:!1,error:"Invalid config name"},{status:400});const result=await readConfig(name);if(!result)return Response.json({ok:!1,error:"Not found"},{status:404});return Response.json({ok:!0,name,fields:result.fields})}catch(e){return Response.json({ok:!1,error:e?.message},{status:500})}},"/api/config/source":async(req)=>{try{const name=new URL(req.url).searchParams.get("name")||"";if(!/^[\w-]+$/.test(name))return Response.json({ok:!1,error:"Invalid config name"},{status:400});const result=await readConfig(name);if(!result)return Response.json({ok:!1,error:"Not found"},{status:404});return new Response(result.source,{headers:{"content-type":"text/plain; charset=utf-8"}})}catch(e){return Response.json({ok:!1,error:e?.message},{status:500})}},"/api/config/update":async(req)=>{if(req.method!=="POST")return Response.json({ok:!1,error:"Method not allowed"},{status:405});try{await validateDevCsrfRequest(req);const body=await req.json(),file=body.file?.replace(/\.ts$/,"");if(!file||!/^[\w-]+$/.test(file))return Response.json({ok:!1,error:"Invalid file"},{status:400});const updates=[];if(Array.isArray(body.updates))for(const u of body.updates){const k=u.key??u.path;if(typeof k==="string")updates.push({key:k,value:u.value})}else if(body.key)updates.push({key:body.key,value:body.value});if(updates.length===0)return Response.json({ok:!1,error:"No updates supplied"},{status:400});const invalid=updates.find((update)=>!/^[A-Za-z_$][\w$]*$/.test(update.key)||typeof update.value!=="string"&&typeof update.value!=="number"&&typeof update.value!=="boolean"||typeof update.value==="number"&&!Number.isFinite(update.value));if(invalid)return Response.json({ok:!1,error:`Invalid value for configuration key "${invalid.key}"`},{status:400});const typedUpdates=updates;try{await updateConfigKeys(file,typedUpdates)}catch(err){const error=err?.message||"Configuration values could not be updated.",results=typedUpdates.map((update)=>({key:update.key,ok:!1,error}));return Response.json({ok:!1,file,results,error},{status:422})}const results=typedUpdates.map((update)=>({key:update.key,ok:!0,newValue:update.value}));return Response.json({ok:!0,file,results})}catch(e){if(e?.status===403)return Response.json({ok:!1,error:"Forbidden",message:"CSRF token mismatch"},{status:403});return Response.json({ok:!1,error:e?.message},{status:500})}}},router=await import("@stacksjs/router");await router.loadRoutes(await router.appRouteRegistry());const stacksRoute=router.route;serve({root:projectPath("resources"),patterns:[userDashboardPath,dashboardPath],port:dashboardPort,componentsDir:userDashboardComponentsPath,additionalComponentsDirs:[dashboardComponentsPath],fallbackComponentsDir:resolveComponentsLibraryRoot(),layoutsDir:projectPath("resources/views/dashboard/layouts"),fallbackLayoutsDir:defaultsPath("views/dashboard/layouts"),partialsDir:dashboardPath,publicDir:publicPath(),renderCache:!0,renderCacheVary:"source",prewarmRenderCache:!1,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(`
|
|
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(`
|
|
3
3
|
Failed to start dashboard server: ${err?.message||err}
|
|
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(),
|
|
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.")}
|
|
6
6
|
`);process.on("SIGINT",()=>process.exit(0));process.on("SIGTERM",()=>process.exit(0));await new Promise(()=>{})}
|
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.489",
|
|
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.489",
|
|
70
|
+
"@stacksjs/ai": "0.75.489",
|
|
71
|
+
"@stacksjs/analytics": "0.75.489",
|
|
72
|
+
"@stacksjs/api": "0.75.489",
|
|
73
|
+
"@stacksjs/auth": "0.75.489",
|
|
74
|
+
"@stacksjs/build": "0.75.489",
|
|
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.489",
|
|
78
|
+
"@stacksjs/cloud": "0.75.489",
|
|
79
|
+
"@stacksjs/cms": "0.75.489",
|
|
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.489",
|
|
82
|
+
"@stacksjs/database": "0.75.489",
|
|
83
|
+
"@stacksjs/desktop-build": "0.75.489",
|
|
84
|
+
"@stacksjs/dns": "0.75.489",
|
|
85
|
+
"@stacksjs/enums": "0.75.489",
|
|
86
|
+
"@stacksjs/env": "0.75.489",
|
|
87
|
+
"@stacksjs/error-handling": "0.75.489",
|
|
88
|
+
"@stacksjs/github": "0.75.489",
|
|
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.489",
|
|
91
|
+
"@stacksjs/image": "0.75.489",
|
|
92
|
+
"@stacksjs/logging": "0.75.489",
|
|
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.489",
|
|
95
|
+
"@stacksjs/orm": "0.75.489",
|
|
96
|
+
"@stacksjs/path": "0.75.489",
|
|
97
|
+
"@stacksjs/payments": "0.75.489",
|
|
98
|
+
"@stacksjs/queue": "0.75.489",
|
|
99
|
+
"@stacksjs/registry": "0.75.489",
|
|
100
|
+
"@stacksjs/router": "0.75.489",
|
|
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.489",
|
|
103
|
+
"@stacksjs/search-engine": "0.75.489",
|
|
104
|
+
"@stacksjs/security": "0.75.489",
|
|
105
|
+
"@stacksjs/server": "0.75.489",
|
|
106
|
+
"@stacksjs/sites": "0.75.489",
|
|
107
|
+
"@stacksjs/storage": "0.75.489",
|
|
108
|
+
"@stacksjs/strings": "0.75.489",
|
|
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.489",
|
|
114
|
+
"@stacksjs/types": "0.75.489",
|
|
115
|
+
"@stacksjs/utils": "0.75.489",
|
|
116
|
+
"@stacksjs/whois": "0.75.489",
|
|
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.489",
|
|
133
133
|
"better-dx": "^0.2.24"
|
|
134
134
|
}
|
|
135
135
|
}
|