@mistflow-ai/mcp 0.4.6 → 0.4.7
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/index.js +120 -161
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as
|
|
1
|
+
import{a as Nt,d as _t,e as Le}from"./chunk-UNFTM4B3.js";import{b as So,c as ds,d as ps,e as To}from"./chunk-2X3ZTRP7.js";import{A as ls,C as so,D as Ke,E as cs,F as oo,G as ro,H as no,I as io,J as ao,K as lo,L as co,M as po,N as uo,O as wt,P as mo,Q as ho,R as go,S as fo,T as Mt,U as yo,V as bo,W as wo,X as vo,Y as ko,_ as xo,b as Hs,c as Gs,d as yt,e as Ws,f as as,g as Dt,h as ye,i as Ee,j as Ye,k as bt,l as Vs,m as Se,n as Ys,o as Ks,s as Js,t as Qs,u as Xs,w as Zs,x as Oe,y as eo,z as to}from"./chunk-OIW7LXTF.js";import{Server as bc}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as wc}from"@modelcontextprotocol/sdk/server/stdio.js";import{CallToolRequestSchema as vc,ListToolsRequestSchema as kc}from"@modelcontextprotocol/sdk/types.js";import{zodToJsonSchema as xc}from"zod-to-json-schema";function d(o,s=!1){let e=o;try{let t=Gs();t&&(e=o+t)}catch{}return{content:[{type:"text",text:e}],isError:s}}function Ne(o){return d(`This is not a Mistflow project (no mistflow.json found at ${o}).
|
|
2
2
|
|
|
3
3
|
Mistflow creates new projects from scratch \u2014 it doesn't work inside existing codebases.
|
|
4
4
|
|
|
@@ -7,14 +7,14 @@ To get started:
|
|
|
7
7
|
2. Run mist_build (action: 'init') to create a new project in a subdirectory
|
|
8
8
|
3. Run mist_build (action: 'implement') to build each step
|
|
9
9
|
|
|
10
|
-
If you want to deploy an existing project, use your framework's deploy tools directly.`,!0)}async function Ue(s
|
|
10
|
+
If you want to deploy an existing project, use your framework's deploy tools directly.`,!0)}async function Ue(o,s){try{let{getPage:e,takeScreenshot:t}=await import("./browser-manager-QW3OYPFB.js"),n=await e();await n.goto(o,{waitUntil:"domcontentloaded",timeout:15e3}),await n.waitForLoadState("networkidle").catch(()=>{});let a=await t(n,!1);return{content:[{type:"text",text:s},{type:"image",data:a.toString("base64"),mimeType:"image/png"}]}}catch{return d(s)}}import{z as us}from"zod";import{platform as Dn}from"os";import{execFile as Co}from"child_process";var Mn=us.object({apiKey:us.string().optional().describe("API key (mist_...) for headless auth. Skips the device code flow entirely. Generate one at app.mistflow.ai/mcp-keys."),deviceCode:us.string().optional().describe("Resume polling for a pending device code. Returned by a previous mist_setup call with status 'pending'. Call mist_setup again with this value after ~15 seconds to check if the user approved.")});function $n(o){return"error"in o}function jn(o){return new Promise(s=>setTimeout(s,o))}function Ln(o){return new Promise(s=>{let e=Dn();e==="win32"?Co("cmd.exe",["/c","start","",o],t=>{t&&console.error("Could not open browser:",t.message),s(!t)}):Co(e==="darwin"?"open":"xdg-open",[o],n=>{n&&console.error("Could not open browser:",n.message),s(!n)}),setTimeout(()=>s(!1),5e3)})}var On={fetch:globalThis.fetch,openBrowser:Ln};async function Po(o,s,e,t){let n=e;for(let a=0;a<s;a++){await jn(n);let r;try{let l=await t.fetch(`${Ye()}/auth/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:o})});if(!l.ok)continue;r=await l.json()}catch{continue}if($n(r))switch(r.error){case"authorization_pending":continue;case"slow_down":n+=5e3;continue;case"expired_token":return d("The sign-in link expired. Run mist_setup again to get a new code.",!0);case"access_denied":return d("Sign-in was cancelled. Run mist_setup again to try again.",!0);case"already_exchanged":return d("This sign-in link was already used. Run mist_setup again to get a new code.",!0)}let i=r.email||r.org_name||r.org_slug;return as({apiKey:r.api_key,apiKeyId:r.api_key_id,apiKeyName:r.api_key_name,orgId:r.org_id,orgSlug:r.org_slug,email:r.email}),d(`Connected to Mistflow as ${i}. You are ready to build and deploy.`)}return null}async function Un(o,s=On){let e=o;if(e?.apiKey)try{let r=await s.fetch(`${Ye()}/api/org`,{headers:{Authorization:`ApiKey ${e.apiKey}`}});if(!r.ok)return d("Invalid API key. Check the key and try again.",!0);let i=await r.json();return as({apiKey:e.apiKey,orgId:i.id,orgSlug:i.slug}),d(`Connected to Mistflow as ${i.slug} via API key. You are ready to build and deploy.`)}catch{return d("Cannot reach Mistflow servers. Check your internet connection.",!0)}if(e?.deviceCode){let r=await Po(e.deviceCode,6,5e3,s);return r||d(JSON.stringify({status:"pending",deviceCode:e.deviceCode,instruction:"The user hasn't approved yet. Wait ~15 seconds and call mist_setup again with the same deviceCode."}))}let t;try{let r=await s.fetch(`${Ye()}/auth/device`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!r.ok)return d("Cannot reach Mistflow servers. Check your internet connection.",!0);t=await r.json()}catch{return d("Cannot reach Mistflow servers. Check your internet connection.",!0)}let n=`${t.verification_uri}?code=${t.user_code}`;console.error(`
|
|
11
11
|
Sign in at: ${n}
|
|
12
12
|
Your code: ${t.user_code}
|
|
13
|
-
`);try{await
|
|
13
|
+
`);try{await s.openBrowser(n)}catch{}let a=await Po(t.device_code,6,5e3,s);return a||d(JSON.stringify({status:"pending",deviceCode:t.device_code,signInUrl:n,userCode:t.user_code,instruction:"The user hasn't approved yet. Wait ~15 seconds, then call mist_setup again with deviceCode='"+t.device_code+"' to check if they approved."}))}var Ao={name:"mist_setup",description:"Connect the user's Mistflow account. Call this ONLY when: (a) the user has literally never signed in, or (b) a previous tool call returned error code 'auth_missing' or 'auth_revoked'. DO NOT call this tool in response to 500 errors, 404 errors, network errors, or any generic failure \u2014 those are backend issues, not auth issues. Running mist_setup when not needed wastes the user's time and creates login fatigue. Once signed in, the MCP persists a long-lived API key and never asks again. Two-phase device code flow: (1) Call without deviceCode \u2014 opens browser, returns status 'pending' with deviceCode and userCode. Tell the user the verification code and that they need to approve in the browser. (2) Call again with deviceCode after ~15 seconds \u2014 polls for approval. Also accepts an apiKey for headless auth (skips device code entirely).",inputSchema:Mn,handler:o=>Un(o)};import{z as O}from"zod";import{existsSync as vt,mkdirSync as jt,readFileSync as Uo,readdirSync as Qn,statSync as Xn,unlinkSync as Zn,writeFileSync as Lt}from"fs";import{dirname as ei,isAbsolute as ti,join as we}from"path";import{homedir as Fe}from"os";import{createHash as si,createHmac as Fo,randomBytes as oi,randomUUID as Oo,timingSafeEqual as ri}from"crypto";function Je(o,s,e,t=3e3){if(s===void 0)return{stop:()=>{}};let n=0,a=!1,i=setInterval(()=>{a||(n++,o.notification({method:"notifications/progress",params:{progressToken:s,progress:n,message:e()}}).catch(()=>{}))},t);return{stop:()=>{a||(a=!0,clearInterval(i))}}}var ms={},tt=[];function st(o){let s=tt.find(t=>t.id===o);if(s)return s;let e=o.toLowerCase().replace(/[^a-z0-9]/g,"");return tt.find(t=>{let n=t.title.toLowerCase().replace(/[^a-z0-9]/g,"");return n===e||n.includes(e)||e.includes(n)})}function Io(o){return ms[o]}function hs(o){return o?tt.filter(s=>s.category.toLowerCase()===o.toLowerCase()):tt}function Ro(o){let s=o??tt;if(s.length===0)return"Landing page presets have been replaced by the tone-based system. The landing page tone is now auto-selected based on your app's description during planning.";let e={};for(let n of s){e[n.category]||(e[n.category]=[]);let a=ms[n.id],r=a?` \u2014 ${a.description}`:"";e[n.category].push(`${n.id} \u2014 "${n.title}"${r}`)}let t=[];for(let[n,a]of Object.entries(e))t.push(`**${n}**:
|
|
14
14
|
${a.map(r=>` \u2022 ${r}`).join(`
|
|
15
15
|
`)}`);return t.join(`
|
|
16
16
|
|
|
17
|
-
`)}function
|
|
17
|
+
`)}function Fn(o){return o.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function Eo(o){return(o?hs(o):tt).map(e=>{let t=ms[e.id];return{id:e.id,slug:Fn(e.title),title:e.title,category:e.category,description:t?.description??"",tags:t?.tags??[],theme:t?.theme??"dark",colors:t?.colors??[],style:t?.style??""}})}function No(o,s){return[]}var gs={"resend-email":{description:"Transactional email with React Email templates and webhook handling.",tags:["email","transactional","welcome","notification","invite","alert"],envVars:[{key:"RESEND_API_KEY",description:"Resend API key for sending emails",setupUrl:"https://resend.com/api-keys"}],docsUrl:"https://resend.com/docs/send-with-nextjs",packages:["resend","@react-email/components"],difficulty:"easy"},"r2-storage":{description:"File uploads with drag-and-drop UI, stored in Mistflow Cloud.",tags:["storage","upload","file","image","media","attachment","avatar"],envVars:[],docsUrl:"https://developers.cloudflare.com/r2/",packages:[],difficulty:"easy"},"openai-ai":{description:"AI-powered features with OpenAI SDK, streaming chat, and content generation.",tags:["ai","openai","chatbot","gpt","llm","assistant","generation"],envVars:[{key:"OPENAI_API_KEY",description:"OpenAI API key for AI features",setupUrl:"https://platform.openai.com/api-keys"}],docsUrl:"https://platform.openai.com/docs/guides/text-generation",packages:["openai","ai"],difficulty:"medium"},"anthropic-ai":{description:"AI features with the Anthropic SDK, streaming Claude chat, and content generation.",tags:["ai","anthropic","claude","llm","assistant","generation"],envVars:[{key:"ANTHROPIC_API_KEY",description:"Anthropic API key for Claude",setupUrl:"https://console.anthropic.com/settings/keys"}],docsUrl:"https://docs.anthropic.com/en/docs/initial-setup",packages:["@anthropic-ai/sdk","ai"],difficulty:"medium"},"openrouter-ai":{description:"AI model router with access to 200+ models (GPT, Claude, Llama, Mistral, etc.) through one API.",tags:["ai","openrouter","llm","multi-model","claude","gpt","llama","mistral"],envVars:[{key:"OPENROUTER_API_KEY",description:"OpenRouter API key",setupUrl:"https://openrouter.ai/keys"}],docsUrl:"https://openrouter.ai/docs/quickstart",packages:["@openrouter/sdk"],difficulty:"easy"},"stripe-payments":{description:"Payment processing with Stripe Checkout, webhooks, and billing portal.",tags:["payments","stripe","billing","subscription","checkout","invoice"],envVars:[{key:"STRIPE_SECRET_KEY",description:"Stripe secret key",setupUrl:"https://dashboard.stripe.com/apikeys"},{key:"STRIPE_PUBLISHABLE_KEY",description:"Stripe publishable key (client-side)",setupUrl:"https://dashboard.stripe.com/apikeys"},{key:"STRIPE_WEBHOOK_SECRET",description:"Stripe webhook signing secret",setupUrl:"https://dashboard.stripe.com/webhooks"}],docsUrl:"https://docs.stripe.com/checkout/quickstart",packages:["stripe","@stripe/stripe-js"],difficulty:"advanced"},"elevenlabs-voice":{description:"Text-to-speech and voice generation with ElevenLabs API.",tags:["voice","tts","speech","audio","elevenlabs","narration","podcast"],envVars:[{key:"ELEVENLABS_API_KEY",description:"ElevenLabs API key for voice generation",setupUrl:"https://elevenlabs.io/app/settings/api-keys"}],docsUrl:"https://elevenlabs.io/docs/api-reference/text-to-speech",packages:["elevenlabs"],difficulty:"medium"},"google-maps":{description:"Google Maps embed, Places autocomplete, and geolocation features.",tags:["maps","location","google","places","geocoding","directions","nearby"],envVars:[{key:"NEXT_PUBLIC_GOOGLE_MAPS_API_KEY",description:"Google Maps API key (client-side)",setupUrl:"https://console.cloud.google.com/apis/credentials"}],docsUrl:"https://developers.google.com/maps/documentation/javascript",packages:["@googlemaps/js-api-loader"],difficulty:"medium"},"twilio-sms":{description:"SMS notifications, OTP verification, and phone number validation.",tags:["sms","twilio","otp","phone","verification","text-message"],envVars:[{key:"TWILIO_ACCOUNT_SID",description:"Twilio account SID",setupUrl:"https://console.twilio.com/"},{key:"TWILIO_AUTH_TOKEN",description:"Twilio auth token",setupUrl:"https://console.twilio.com/"},{key:"TWILIO_PHONE_NUMBER",description:"Twilio phone number for sending SMS",setupUrl:"https://console.twilio.com/us1/develop/phone-numbers/manage/incoming"}],docsUrl:"https://www.twilio.com/docs/messaging/quickstart/node",packages:["twilio"],difficulty:"medium"},"posthog-analytics":{description:"Product analytics with event tracking, feature flags, and session replay.",tags:["analytics","posthog","tracking","funnel","event","feature-flag"],envVars:[{key:"NEXT_PUBLIC_POSTHOG_KEY",description:"PostHog project API key",setupUrl:"https://app.posthog.com/project/settings"},{key:"NEXT_PUBLIC_POSTHOG_HOST",description:"PostHog instance URL (default: https://us.i.posthog.com)",setupUrl:"https://app.posthog.com/project/settings"}],docsUrl:"https://posthog.com/docs/libraries/next-js",packages:["posthog-js","posthog-node"],difficulty:"easy"},"firecrawl-scraping":{description:"Web scraping and crawling with markdown output, structured extraction, and async crawls.",tags:["scraping","crawl","firecrawl","web","extract","rag","markdown"],envVars:[{key:"FIRECRAWL_API_KEY",description:"Firecrawl API key",setupUrl:"https://firecrawl.dev"}],docsUrl:"https://docs.firecrawl.dev/sdks/node",packages:["@mendable/firecrawl-js"],difficulty:"easy"},"replicate-media":{description:"Image and video generation with 200+ AI models (Flux, Wan Video, Runway, SDXL, etc.) through one API.",tags:["image","video","replicate","flux","sdxl","generation","media","avatar","thumbnail"],envVars:[{key:"REPLICATE_API_TOKEN",description:"Replicate API token",setupUrl:"https://replicate.com/account/api-tokens"}],docsUrl:"https://replicate.com/docs/get-started/nodejs",packages:["replicate"],difficulty:"medium"}},ot=[{id:"resend-email",name:"Resend Email",category:"communication",prompt:`## Resend Email Integration
|
|
18
18
|
|
|
19
19
|
### File Structure
|
|
20
20
|
\`\`\`
|
|
@@ -1434,12 +1434,12 @@ export function ImageGenerator() {
|
|
|
1434
1434
|
5. **Replicate charges per prediction.** Flux Schnell is ~$0.003/image. Flux Pro is ~$0.05/image. Video models are $0.05-$0.50/generation. Show generation cost to users.
|
|
1435
1435
|
6. **Cache generated images.** Store output URLs in your database. Replicate URLs expire after a few hours. Download and re-host on R2 for permanent storage.
|
|
1436
1436
|
7. **Network I/O does NOT count as CPU time on Workers.** Image generation wait time is all network I/O.
|
|
1437
|
-
8. **Never ask the user to paste REPLICATE_API_TOKEN in chat.** Direct them to set it in the Mistflow dashboard (Project Settings > Environment Variables).`}];function
|
|
1437
|
+
8. **Never ask the user to paste REPLICATE_API_TOKEN in chat.** Direct them to set it in the Mistflow dashboard (Project Settings > Environment Variables).`}];function Bn(o){return o.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function rt(o){let s=ot.find(t=>t.id===o);if(s)return s;let e=o.toLowerCase().replace(/[^a-z0-9]/g,"");return ot.find(t=>{let n=t.name.toLowerCase().replace(/[^a-z0-9]/g,"");return n===e||n.includes(e)||e.includes(n)})}function nt(o){return gs[o]}function fs(o){return o?ot.filter(s=>s.category.toLowerCase()===o.toLowerCase()):ot}function _o(o){let s=o??ot,e={};for(let n of s){e[n.category]||(e[n.category]=[]);let a=gs[n.id],r=a?` \u2014 ${a.description}`:"",i=a?.packages.length?` (${a.packages.join(", ")})`:"";e[n.category].push(`${n.id} \u2014 "${n.name}"${r}${i}`)}let t=[];for(let[n,a]of Object.entries(e))t.push(`**${n}**:
|
|
1438
1438
|
${a.map(r=>` - ${r}`).join(`
|
|
1439
1439
|
`)}`);return t.join(`
|
|
1440
1440
|
|
|
1441
|
-
`)}function
|
|
1442
|
-
`)}function
|
|
1441
|
+
`)}function Do(o){return(o?fs(o):ot).map(e=>{let t=gs[e.id];return{id:e.id,slug:Bn(e.name),name:e.name,category:e.category,description:t?.description??"",tags:t?.tags??[],envVars:t?.envVars??[],docsUrl:t?.docsUrl??"",packages:t?.packages??[],difficulty:t?.difficulty??"medium"}})}var qn=[{name:"Dashboard",description:"Overview with key stats and today's activity",condition:o=>o.surfaceType==="internal-tool"||o.surfaceType==="customer-app",keywords:/\b(dashboard|overview|home.?page|stats)\b/i},{name:"Landing Page",description:"Public page explaining what this does",condition:o=>o.publicLanding===!0,keywords:/\b(landing|marketing|hero|homepage)\b/i},{name:"Scheduling / Booking",description:"Calendar, time slots, reservations",condition:o=>o.scheduling===!0,keywords:/\b(schedul|book|reserv|appointment|calendar|slot)\b/i},{name:"Payments / Billing",description:"Charge users, invoices, subscriptions (experimental \u2014 Stripe integration is early-stage)",condition:()=>!1,keywords:/\b(payment|billing|invoice|subscription|checkout|stripe)\b/i},{name:"Admin Panel",description:"Manage users, roles, and content",condition:o=>o.multiRole===!0||o.primaryActor==="both",keywords:/\b(admin|panel|manage.?user|moderat)\b/i},{name:"User Profiles",description:"Account pages, settings, preferences",condition:o=>o.primaryActor==="customers"||o.primaryActor==="both",keywords:/\b(profile|account|settings|preferences)\b/i},{name:"Search / Browse",description:"Find and filter content or listings",condition:o=>o.surfaceType==="marketplace",keywords:/\b(search|browse|filter|discover|explore)\b/i},{name:"Email Notifications",description:"Welcome emails, alerts, reminders",condition:o=>o.integrations?.includes("email")===!0,keywords:/\b(notification|alert|reminder|email.?notif|sms|welcome.?email)\b/i},{name:"Analytics / Reports",description:"Usage stats, trends, data exports",condition:()=>!1,keywords:/\b(analytics|report|chart|trend|insight|metric)\b/i},{name:"File Uploads",description:"Images, documents, attachments",condition:o=>o.integrations?.includes("file-uploads")===!0,keywords:/\b(upload|image|photo|attachment|document|gallery|file)\b/i},{name:"AI Features",description:"Chatbot, content generation, AI assistant",condition:o=>o.integrations?.includes("ai")===!0,keywords:/\b(ai|chatbot|gpt|llm|generat|assistant)\b/i},{name:"Maps / Location",description:"Google Maps, location search, geolocation",condition:o=>o.integrations?.includes("maps")===!0,keywords:/\b(map|location|address|geo|places)\b/i},{name:"Voice / TTS",description:"Text-to-speech, voice notes, audio generation",condition:()=>!1,keywords:/\b(voice|tts|text.?to.?speech|audio|speak|narrat|podcast|elevenlabs)\b/i},{name:"SMS / Text Messages",description:"Send SMS notifications, OTP verification",condition:o=>o.integrations?.includes("sms")===!0,keywords:/\b(sms|text.?message|twilio|otp|verification.?code|phone.?verif)\b/i},{name:"Web Scraping",description:"Scrape URLs, crawl websites, extract structured data",condition:()=>!1,keywords:/\b(scrape|crawl|web.?scrap|extract.?from.?url|read.?url|ingest.?web|firecrawl)\b/i},{name:"Chat / Messaging",description:"Real-time messaging between users",condition:()=>!1,keywords:/\b(chat|messag|inbox|conversation|dm)\b/i},{name:"Events / Tournaments",description:"Create and manage events, registrations",condition:()=>!1,keywords:/\b(event|tournament|competition|league|registration)\b/i},{name:"High Scores",description:"Track and display top scores with a leaderboard",condition:o=>o.surfaceType==="game",keywords:/\b(high.?score|leaderboard|top.?score|ranking|scoreboard)\b/i},{name:"Save Progress",description:"Save and resume game state between sessions",condition:o=>o.surfaceType==="game",keywords:/\b(save|progress|resume|checkpoint|continue)\b/i},{name:"Guest Play",description:"Play immediately without signing up, optionally link account later",condition:o=>o.surfaceType==="game",keywords:/\b(guest|anonymous|no.?login|play.?now|instant.?play)\b/i},{name:"Levels / Stages",description:"Progressive difficulty with unlockable stages",condition:()=>!1,keywords:/\b(level|stage|unlock|difficult|progress|world)\b/i},{name:"Achievements",description:"Badges, trophies, and milestones for player accomplishments",condition:()=>!1,keywords:/\b(achieve|badge|trophy|milestone|reward|unlock)\b/i},{name:"Daily Challenge",description:"New puzzle or challenge every day to keep players coming back",condition:()=>!1,keywords:/\b(daily|challenge|streak|word.?of.?the.?day|puzzle.?of)\b/i}];function Mo(o,s,e){let t=e?.suggestedName||zn(o),n=s.primaryActor==="both"?"Staff + Customers":s.primaryActor==="staff"?"Staff / Admin":s.primaryActor==="customers"?"End Users":"Users",a=s.audienceType??(s.surfaceType==="internal-tool"?"internal":(s.primaryActor==="customers"||s.primaryActor==="both","b2c")),r=s.surfaceType==="internal-tool"?"Internal tool":s.surfaceType==="marketplace"?"Marketplace":s.surfaceType==="content-site"?"Content site":s.surfaceType==="game"?"Game":"App",i;if(e?.suggestedFeatures&&e.suggestedFeatures.length>0)i=e.suggestedFeatures.map(l=>({name:l.name,description:l.description,checked:l.recommended,source:l.recommended?"explicit":"suggested"}));else{let l=`${o} ${s.primaryAction||""}`;i=[];for(let c of qn){let u=c.keywords.test(l),m=c.condition(s);(u||m)&&i.push({name:c.name,description:c.description,checked:u,source:u?"explicit":"suggested"})}}return{name:t,audience:n,audienceType:a,surfaceType:r,primaryAction:s.primaryAction||"manage items",features:i,publicLanding:s.publicLanding??!0,authModel:s.authModel??"email",dbProvider:s.dbProvider??"neon",integrations:s.integrations??[],language:e?.language||"English"}}function $o(o){let s=o.features.filter(i=>i.checked),e=o.features.filter(i=>!i.checked),t={email:"Email sign-up",none:"No login (public)",social:"Social login","invite-only":"Invite-only"},n={neon:"Postgres",turso:"SQLite (legacy)"},a={b2c:"Your customers use this app (business-to-customer)",b2b:"Other businesses sign up for this (SaaS platform)",internal:"Internal team tool (staff only)"},r=[`**${o.name}** \u2014 ${o.surfaceType} for ${o.audience}`,`Audience: ${a[o.audienceType]??o.audienceType}`,`Primary action: ${o.primaryAction}`,`Access: ${t[o.authModel]??o.authModel} | Database: ${n[o.dbProvider]??o.dbProvider}${o.publicLanding?" | Landing page: Yes":""}${o.language&&o.language!=="English"?` | Language: ${o.language}`:""}`,""];if(s.length>0){r.push("**Included:**");for(let i of s)r.push(` \u2713 ${i.name} \u2014 ${i.description}`)}if(o.integrations.length>0&&(r.push(""),r.push(`**Integrations:** ${o.integrations.join(", ")}`)),e.length>0){r.push(""),r.push("**Available to add:**");for(let i of e)r.push(` \u25CB ${i.name} \u2014 ${i.description}`)}return r.join(`
|
|
1442
|
+
`)}function zn(o){let s=o.match(/\b(?:called|named)\s+["']?([A-Za-z][A-Za-z0-9 ]{1,30})["']?/i);if(s)return ys(s[1]);let e=new Set(["build","create","make","a","an","the","for","me","my","app","application","website","web","tool","system","platform","using","with","and","that","this","want","need","please","can","you","i","mist","mistflow"]),n=o.toLowerCase().replace(/[^a-z0-9\s]/g,"").split(/\s+/).filter(a=>a.length>2&&!e.has(a)).slice(0,3);return n.length===0?"my-app":n.join("-")}function ys(o){return o.toLowerCase().replace(/[^a-z0-9\s]/g,"").trim().replace(/\s+/g,"-")}var Hn=["typographic","split-panel","terminal","full-bleed-photo","magazine-hero"],Gn=["sharp","soft","pill","organic"],Wn=["flat","paper-grain","film-grain","scanlines","gradient-mesh","noise","glassmorphic"];function bs(o,s,e){return s.includes(o)?o:e}function be(o){return String(o??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function it(o,s){return typeof o!="string"?s:/^#[0-9a-fA-F]{3}([0-9a-fA-F]{3})?$/.test(o.trim())?o.trim():s}function Vn(o){let s=new Set;for(let t of o)t.fonts?.display&&s.add(t.fonts.display),t.fonts?.body&&s.add(t.fonts.body);return s.size===0?"":`https://fonts.googleapis.com/css2?${[...s].map(t=>`family=${t.trim().replace(/\s+/g,"+").replace(/[^A-Za-z0-9+]/g,"")}:wght@400;700`).join("&")}&display=swap`}function jo(o){let s=(o||"").trim(),e=s.toLowerCase(),t=/mono|courier|code/.test(e)?"ui-monospace, monospace":/serif|garamond|bodoni|fraunces|playfair|lora|sentient|migra|sectra|cormorant|abril|crimson/.test(e)?"Georgia, serif":"system-ui, sans-serif";return s?`"${s.replace(/"/g,"")}", ${t}`:t}function Yn(o){switch(o){case"sharp":return{card:"0px",button:"0px",chip:"0px"};case"pill":return{card:"20px",button:"999px",chip:"999px"};case"organic":return{card:"4px 24px 4px 24px",button:"24px 4px 24px 4px",chip:"12px 2px 12px 2px"};default:return{card:"10px",button:"8px",chip:"6px"}}}function Kn(){let o=`url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='180' height='180'><filter id='n'><feTurbulence type='fractalNoise' baseFrequency='0.85' numOctaves='2' stitchTiles='stitch'/><feColorMatrix values='0 0 0 0 0.3 0 0 0 0 0.3 0 0 0 0 0.3 0 0 0 0.55 0'/></filter><rect width='100%25' height='100%25' filter='url(%23n)'/></svg>")`;return`
|
|
1443
1443
|
.card-hero { position: relative; overflow: hidden; isolation: isolate; }
|
|
1444
1444
|
.card-hero::before {
|
|
1445
1445
|
content: "";
|
|
@@ -1456,17 +1456,17 @@ ${a.map(r=>` - ${r}`).join(`
|
|
|
1456
1456
|
|
|
1457
1457
|
.card-hero.texture-paper-grain::before {
|
|
1458
1458
|
opacity: 0.35;
|
|
1459
|
-
background-image: ${
|
|
1459
|
+
background-image: ${o};
|
|
1460
1460
|
mix-blend-mode: multiply;
|
|
1461
1461
|
}
|
|
1462
1462
|
.card-hero.texture-film-grain::before {
|
|
1463
1463
|
opacity: 0.5;
|
|
1464
|
-
background-image: ${
|
|
1464
|
+
background-image: ${o};
|
|
1465
1465
|
mix-blend-mode: overlay;
|
|
1466
1466
|
}
|
|
1467
1467
|
.card-hero.texture-noise::before {
|
|
1468
1468
|
opacity: 0.25;
|
|
1469
|
-
background-image: ${
|
|
1469
|
+
background-image: ${o};
|
|
1470
1470
|
mix-blend-mode: overlay;
|
|
1471
1471
|
}
|
|
1472
1472
|
.card-hero.texture-scanlines::before {
|
|
@@ -1497,7 +1497,7 @@ ${a.map(r=>` - ${r}`).join(`
|
|
|
1497
1497
|
backdrop-filter: blur(14px);
|
|
1498
1498
|
mix-blend-mode: normal;
|
|
1499
1499
|
}
|
|
1500
|
-
`}function
|
|
1500
|
+
`}function Jn(o,s,e,t){let n=it(o.colors?.bg??"","#0f0f0f"),a=it(o.colors?.fg??"","#f5f5f5"),r=it(o.colors?.accent??"","#7c9cff"),i=be(o.name),l=be(o.hero_headline||o.name),c=be(o.body_sample||o.summary||""),u=be(o.cta_text||"Continue"),m=`<div class="hero-eyebrow" style="font-family:${e}">${i.toUpperCase()}</div>`,p=`<h2 class="hero-headline" style="font-family:${s}">${l}</h2>`,f=`<p class="hero-body" style="font-family:${e}">${c}</p>`,w=`<button class="hero-cta" style="background:${r};color:${n};font-family:${e};border-radius:${t.button}">${u}</button>`,g=bs(o.hero_treatment,Hn,"typographic");if(g==="terminal"){let h=`"${(o.fonts?.display??"JetBrains Mono").replace(/"/g,"")}", ui-monospace, monospace`;return`
|
|
1501
1501
|
${m}
|
|
1502
1502
|
<div class="hero-terminal-lines" style="font-family:${h};color:${a}">
|
|
1503
1503
|
<div>$ status --all</div>
|
|
@@ -1506,31 +1506,31 @@ ${a.map(r=>` - ${r}`).join(`
|
|
|
1506
1506
|
<div>db.primary.......<span style="color:${r}">OK</span></div>
|
|
1507
1507
|
</div>
|
|
1508
1508
|
${p}
|
|
1509
|
-
${
|
|
1509
|
+
${f}
|
|
1510
1510
|
<div class="hero-cta-row">${w}</div>
|
|
1511
|
-
`}return
|
|
1511
|
+
`}return g==="split-panel"?`
|
|
1512
1512
|
<div class="hero-split">
|
|
1513
|
-
<div class="hero-split-left" style="background:${r};color:${n};font-family:${
|
|
1513
|
+
<div class="hero-split-left" style="background:${r};color:${n};font-family:${s}">
|
|
1514
1514
|
<div class="hero-split-mark" style="font-family:${e};color:${n}">${i[0]??"\xB7"}</div>
|
|
1515
1515
|
</div>
|
|
1516
1516
|
<div class="hero-split-right">
|
|
1517
1517
|
${m}
|
|
1518
1518
|
${p}
|
|
1519
|
-
${
|
|
1519
|
+
${f}
|
|
1520
1520
|
<div class="hero-cta-row">${w}</div>
|
|
1521
1521
|
</div>
|
|
1522
1522
|
</div>
|
|
1523
|
-
`:
|
|
1523
|
+
`:g==="full-bleed-photo"?`
|
|
1524
1524
|
<div class="hero-photo" style="background: linear-gradient(160deg, ${r}30 0%, ${a}08 35%, ${n} 100%), ${n}">
|
|
1525
1525
|
<span class="hero-photo-label" style="font-family:${e};color:${a}">photo slot</span>
|
|
1526
1526
|
</div>
|
|
1527
1527
|
${m}
|
|
1528
1528
|
${p}
|
|
1529
|
-
${
|
|
1529
|
+
${f}
|
|
1530
1530
|
<div class="hero-cta-row">${w}</div>
|
|
1531
|
-
`:
|
|
1531
|
+
`:g==="magazine-hero"?`
|
|
1532
1532
|
${m}
|
|
1533
|
-
<h2 class="hero-headline hero-headline-mag" style="font-family:${
|
|
1533
|
+
<h2 class="hero-headline hero-headline-mag" style="font-family:${s}">${l}</h2>
|
|
1534
1534
|
<div class="hero-rule" style="background:${a}"></div>
|
|
1535
1535
|
<p class="hero-body hero-body-mag" style="font-family:${e}">${c}</p>
|
|
1536
1536
|
<div class="hero-byline" style="font-family:${e};color:${a}">\u2014 Volume 01 \xB7 Issue 01</div>
|
|
@@ -1538,10 +1538,10 @@ ${a.map(r=>` - ${r}`).join(`
|
|
|
1538
1538
|
`:`
|
|
1539
1539
|
${m}
|
|
1540
1540
|
${p}
|
|
1541
|
-
${
|
|
1541
|
+
${f}
|
|
1542
1542
|
<div class="hero-cta-row">${w}</div>
|
|
1543
|
-
`}function
|
|
1544
|
-
<div class="card-hero texture-${m}" style="background:${a};color:${r}">${
|
|
1543
|
+
`}function Lo(o,s){let e=Vn(s),t=s.map(n=>{let a=it(n.colors?.bg??"","#0f0f0f"),r=it(n.colors?.fg??"","#f5f5f5"),i=it(n.colors?.accent??"","#7c9cff"),l=jo(n.fonts?.display??""),c=jo(n.fonts?.body??""),u=bs(n.shape_lang,Gn,"soft"),m=bs(n.texture,Wn,"flat"),p=Yn(u),f=Jn(n,l,c,p),w=be(n.name),g=be(n.id),h=be(n.fonts?.display??""),v=be(n.fonts?.body??""),E=be(n.summary||""),R=be(n.decoration_hint||""),C=(P,j)=>`<div class="card-meta-row"><span class="card-meta-label">${P}</span><span class="card-meta-value">${j}</span></div>`;return` <article class="card" data-direction-id="${g}" style="border-radius:${p.card}">
|
|
1544
|
+
<div class="card-hero texture-${m}" style="background:${a};color:${r}">${f}
|
|
1545
1545
|
</div>
|
|
1546
1546
|
<div class="card-meta" style="border-top-color:${r}14">
|
|
1547
1547
|
<div class="card-meta-title">${w}</div>
|
|
@@ -1565,7 +1565,7 @@ ${a.map(r=>` - ${r}`).join(`
|
|
|
1565
1565
|
<head>
|
|
1566
1566
|
<meta charset="UTF-8" />
|
|
1567
1567
|
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
|
1568
|
-
<title>Design directions \u2014 ${be(
|
|
1568
|
+
<title>Design directions \u2014 ${be(o)}</title>
|
|
1569
1569
|
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
|
1570
1570
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
|
1571
1571
|
${e?`<link rel="stylesheet" href="${e}" />`:""}
|
|
@@ -1752,7 +1752,7 @@ ${a.map(r=>` - ${r}`).join(`
|
|
|
1752
1752
|
margin-top: 4px;
|
|
1753
1753
|
}
|
|
1754
1754
|
|
|
1755
|
-
${
|
|
1755
|
+
${Kn()}
|
|
1756
1756
|
|
|
1757
1757
|
/* \u2500\u2500 Card meta footer \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
|
|
1758
1758
|
.card-meta {
|
|
@@ -1861,7 +1861,7 @@ ${a.map(r=>` - ${r}`).join(`
|
|
|
1861
1861
|
<div class="page">
|
|
1862
1862
|
<header class="page-header">
|
|
1863
1863
|
<div class="eyebrow"><span class="eyebrow-dot"></span>Mistflow \xB7 design direction</div>
|
|
1864
|
-
<h1 class="page-title">How should <strong>${be(
|
|
1864
|
+
<h1 class="page-title">How should <strong>${be(o)}</strong> feel?</h1>
|
|
1865
1865
|
<p class="page-sub">Each card commits to a different extreme \u2014 different fonts, colors, hero layout, corner radius, texture, and voice. Pick one by telling your coding assistant its name, or describe your own.</p>
|
|
1866
1866
|
</header>
|
|
1867
1867
|
|
|
@@ -1881,28 +1881,28 @@ ${t}
|
|
|
1881
1881
|
</div>
|
|
1882
1882
|
</body>
|
|
1883
1883
|
</html>
|
|
1884
|
-
`}var
|
|
1885
|
-
`)}),!0);if(b==="foreign"&&!w){if(!(
|
|
1886
|
-
`)}))}P="Note: You're inside an existing project. Mistflow will create the new app in a subdirectory. It won't modify this codebase."}else b==="foreign"&&w&&(P="Note: You're inside an existing project. Mistflow will create the new app in a subdirectory. It won't modify this codebase.")}if(l)try{if(!(await
|
|
1884
|
+
`}var $t="__mistflow_url_choice__",ni=600*1e3;function Bo(){let o=we(Fe(),".mistflow","confirm-secret");if(vt(o))try{return Buffer.from(Uo(o,"utf-8").trim(),"hex")}catch{}let s=oi(32);return jt(we(Fe(),".mistflow"),{recursive:!0}),Lt(o,s.toString("hex"),{mode:384}),s}function qo(o){return si("sha256").update(o.trim().toLowerCase()).digest("hex").slice(0,16)}function ii(o,s){let e={cwd:o,d:qo(s),exp:Date.now()+ni},t=Buffer.from(JSON.stringify(e)).toString("base64url"),n=Fo("sha256",Bo()).update(t).digest("base64url");return`${t}.${n}`}function ai(o,s,e){let t=o.split(".");if(t.length!==2)return!1;let[n,a]=t,r=Fo("sha256",Bo()).update(n).digest("base64url"),i=Buffer.from(a),l=Buffer.from(r);if(i.length!==l.length||!ri(i,l))return!1;try{let c=JSON.parse(Buffer.from(n,"base64url").toString("utf-8"));return!(typeof c.exp!="number"||Date.now()>c.exp||c.cwd!==s||c.d!==qo(e))}catch{return!1}}function li(o){let s=o,e=Fe(),t=!1;for(let n=0;n<64;n++){if(vt(we(s,"mistflow.json")))return"mistflow";if(!t&&vt(we(s,"package.json"))&&(t=!0),s===e)break;let a=ei(s);if(a===s)break;s=a}return t?"foreign":"none"}function ci(o){let s=Fe(),e=o.replace(/\/+$/,"");if(e===s||e==="/"||e===""||e==="/tmp"||e==="/private/tmp")return!0;let t=["Desktop","Documents","Downloads"];for(let n of t)if(e===we(s,n))return!0;return!1}var di=O.object({description:O.string().min(1,"App description or modification request"),projectPath:O.string().min(1).describe("REQUIRED. Absolute path to the user's current working directory \u2014 where the Mistflow app will be scaffolded. Pass the directory the user is actually working in (e.g. /Users/alice/projects). Do NOT pass '/', '~', $HOME, Desktop, Documents, Downloads, or /tmp \u2014 the tool will refuse to scaffold at those locations. If you are unsure of the user's working directory, ask them before calling this tool."),conversationId:O.string().optional().describe("Returned by a previous mist_plan call with status 'clarify'. Pass it back to continue the conversation."),answers:O.record(O.string()).optional().describe("User's answers to the clarifying questions from the previous round. Keys are the questions, values are the answers."),existingPlan:O.record(O.unknown()).optional().describe("If provided, modifies this existing plan instead of creating a new one. Pass the current plan object from mistflow.json."),existingPlanId:O.string().optional().describe("Alternative to existingPlan \u2014 pass the planId from a previous mist_plan call to modify that plan."),templateToken:O.string().optional().describe("Fork from a shared template. Pass the share token (from a mistflow.ai/t/... URL) to clone that project's plan into your workspace."),remixDescription:O.string().optional().describe("Optional remix request when forking a template. Describes how you want the template to be different. E.g. 'Make it for tracking books instead of habits, add a search feature.' Only used with templateToken."),autonomous:O.boolean().optional().describe("Skip clarifying questions and generate the plan immediately"),landingDesign:O.string().optional().describe("ID of a curated landing page design for the hero section. When set, the design's detailed blueprint (colors, fonts, layout, animations) is injected during the landing page implementation step. Use mist_project with action='landing-designs' to browse available landing designs."),appStyle:O.string().optional().describe("ID of a full-app style (e.g. 'stripe', 'linear', 'vercel', 'notion'). When set, the style's color palette, typography, component specs, shadows, and layout rules are injected during ALL implementation steps for consistent brand-quality design across every page. Use mist_project with action='app-styles' to browse available app styles."),language:O.string().optional().describe("UI language for the app. All user-facing text, labels, buttons, and content will be generated in this language. Use the language name in English (e.g. 'Spanish', 'French', 'Arabic', 'Japanese'). Defaults to English if not specified."),brandMentioned:O.boolean().optional().describe("Set to true ONLY when the user's original request explicitly invoked Mistflow by name (e.g. 'build me a CRM using mist', 'make a todo app with mistflow'). Skips the existing-project confirmation gate because the user clearly wants Mistflow. Do NOT set this for generic 'build me X' requests. Do NOT infer this \u2014 only set it when the user literally typed 'mist' or 'mistflow'."),confirmToken:O.string().optional().describe("The token returned in a previous mist_plan response with status 'confirm_new_project'. Only pass this AFTER asking the user via AskUserQuestion and they chose to scaffold a new Mistflow app in an existing-project directory. The token is bound to the projectPath and description \u2014 you must pass the SAME description AND projectPath on the retry."),urlChoice:O.string().optional().describe("The user's answer to the 'Your app URL' question from a previous mist_plan response. Pass JUST the subdomain (e.g. 'nutrition-tracker'), not the full URL or the option label. If the user kept the default suggestion, pass the suggested subdomain verbatim. If they typed a custom URL like 'myapp.mistflow.app', pass just 'myapp'. Pass this as a top-level parameter \u2014 do NOT nest it inside answers. The answers-dict magic key is deprecated and unreliable."),designConversationId:O.string().optional().describe("Returned by a previous mist_plan call with status 'design_clarify'. Pass it back on the follow-up call together with designDirection to finalize the plan's DESIGN.md."),designDirection:O.object({id:O.string().optional(),name:O.string().optional(),summary:O.string().optional(),heroHeadline:O.string().optional(),ctaText:O.string().optional(),bodySample:O.string().optional(),fontsHint:O.string().optional(),fonts:O.object({display:O.string(),body:O.string()}).partial().optional(),colorMood:O.string().optional(),colors:O.object({bg:O.string(),fg:O.string(),accent:O.string()}).partial().optional(),heroTreatment:O.string().optional(),shapeLang:O.string().optional(),texture:O.string().optional(),decorationHint:O.string().optional(),custom:O.string().optional()}).passthrough().optional().describe("The creative direction the user picked from a previous 'design_clarify' response. Pass the FULL direction object the user chose (all fields from the 'directions' array). If the user wrote their own description instead of picking one, pass { custom: '<their description>' } and omit the other fields.")});function pi(o){let s=[[/payment/i,"Payments"],[/database/i,"Database"],[/auth|sign.?up|login|access/i,"Access"],[/landing.?page/i,"Landing page"],[/who.*using|user|role/i,"Users"],[/design|theme|style/i,"Design"],[/deploy/i,"Deploy"],[/domain/i,"Domain"],[/notification/i,"Notify"],[/email/i,"Email"],[/mobile|responsive/i,"Mobile"],[/integrat/i,"Integration"],[/field|info|propert|detail|contain/i,"Item shape"],[/view|layout|board|grid|list|timeline/i,"View"],[/scope|how many|one.*or.*many|multi/i,"Scope"],[/share|read.?only|viewer|stakeholder/i,"Sharing"],[/workflow|status|state|move|stage|pipeline/i,"Workflow"],[/avoid|bloat|simple|complex|minimal/i,"Constraints"],[/time.*period|quarter|month|sprint/i,"Time periods"],[/swimlane|column|group|categor/i,"Structure"]];for(let[t,n]of s)if(t.test(o))return n;return o.replace(/[?.,!]/g,"").split(/\s+/).filter(t=>!["what","how","do","does","is","are","the","a","an","would","should","you","your","for","this","that","to","of","or","and","want","like","prefer"].includes(t.toLowerCase())).slice(0,2).join(" ").slice(0,12)||"Option"}function ui(o){let s=we(Fe(),".mistflow","plans",`${o}.json`);if(!vt(s))return null;try{return JSON.parse(Uo(s,"utf-8")).plan??null}catch{return null}}async function mi(o){for(let t=0;t<60;t++){try{let n=await eo(o.design_conversation_id);if(n.status==="ready")return{status:"design_clarify",design_conversation_id:o.design_conversation_id,directions:n.directions,plan:n.plan,methodology:n.methodology};if(n.status==="failed")return{status:"ready",plan:n.plan,methodology:n.methodology}}catch(n){let a=n instanceof Error?n.message:String(n);if(a.toLowerCase().includes("not found"))return{status:"ready",plan:o.plan,methodology:o.methodology};console.error(`[plan] directions poll attempt ${t+1} failed: ${a}`)}await new Promise(n=>setTimeout(n,2e3))}return console.error("[plan] directions poll exhausted, falling back to ready"),{status:"ready",plan:o.plan,methodology:o.methodology}}async function hi(o,s){let{description:e,projectPath:t,conversationId:n,answers:a,existingPlan:r,existingPlanId:i,templateToken:l,remixDescription:c,autonomous:u,language:m,landingDesign:p,appStyle:f,brandMentioned:w,confirmToken:g,urlChoice:h,designConversationId:v,designDirection:E}=o,R=r;if(!R&&i&&(R=ui(i)??void 0,!R))return d("Your previous plan is no longer available. Please describe your app again to generate a new plan.",!0);let C=n;if(!ye())return d("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let P;if(!C&&!R&&!l){if(!ti(t))return d(`projectPath must be an absolute path \u2014 received '${t}'. Pass the full absolute path to the user's project directory (e.g. /Users/alice/projects/my-app).`,!0);let b=li(t);if(b!=="mistflow"&&ci(t))return d(JSON.stringify({status:"unsafe_cwd",projectPath:t,instruction:[`The projectPath you passed (${t}) is a system-level directory (home root, Desktop, Documents, Downloads, or /tmp).`,"Scaffolding here would drop node_modules and a git repo directly at that location, which is messy and hard to clean up.","MANDATORY: Before calling mist_plan again:"," 1. Pick a subfolder name based on the app description (e.g. 'nutrition-tracker', 'habit-app').",` 2. Create the subfolder at ${t}/<subfolder-name>.`," 3. Call mist_plan again with the SAME description and projectPath set to the new subfolder.","Do NOT ask the user where to put the project \u2014 just pick a sensible subfolder name from their description."].join(`
|
|
1885
|
+
`)}),!0);if(b==="foreign"&&!w){if(!(g?ai(g,t,e):!1)){let $=ii(t,e);return d(JSON.stringify({status:"confirm_new_project",projectPath:t,description:e,confirmToken:$,askUserQuestion:{question:"You're inside an existing project directory. Do you want to scaffold a new Mistflow app here, or edit the existing codebase directly?",header:"Scope",options:[{label:"Scaffold a new Mistflow app in a subdirectory",description:"Creates a fresh project in this folder without touching the existing code."},{label:"Edit this existing codebase directly",description:"Cancel Mistflow. Handle the request by editing the current project's files."}],multiSelect:!1},instruction:["The user is inside an existing project (package.json found up the directory tree, no mistflow.json) and did NOT explicitly invoke Mistflow by name.","MANDATORY: Use the AskUserQuestion tool with the provided askUserQuestion to confirm their intent before calling mist_plan again.","If they pick 'Scaffold a new Mistflow app in a subdirectory', call mist_plan again with the SAME description and confirmToken set to the token returned above.","If they pick 'Edit this existing codebase directly', DO NOT call mist_plan again. Fulfill their request by editing files directly in the current project.",g?"The previous confirmToken was invalid, expired, or did not match the current directory/description. Use the fresh token above.":""].filter(Boolean).join(`
|
|
1886
|
+
`)}))}P="Note: You're inside an existing project. Mistflow will create the new app in a subdirectory. It won't modify this codebase."}else b==="foreign"&&w&&(P="Note: You're inside an existing project. Mistflow will create the new app in a subdirectory. It won't modify this codebase.")}if(l)try{if(!(await wo(l)).plan)return d("This template has no plan to fork. Try a different template.",!0);let k=await vo(l),$=k.plan,L="";if(c&&k.has_source)try{let fe=await ls(k.plan,c),X=fe.plan??fe,Et=fe.diff,ne=X?.steps??[],is=new Set([...(Et?.added??[]).map(Re=>Re.number),...(Et?.modified??[]).map(Re=>Re.number)]),je=ne.map(Re=>{let _n=Re.number;return is.has(_n)?{...Re,status:"pending"}:{...Re,status:"completed",source:"forked"}});X.steps=je,$=X;let Ve=je.filter(Re=>Re.status==="pending").length;L=` Remixed: ${je.filter(Re=>Re.status==="completed").length} steps unchanged, ${Ve} steps need re-implementation.`}catch(fe){console.error("[plan] Remix failed, using original plan:",fe),L=" (Remix failed \u2014 using original plan. You can modify it later.)"}let ce=Oo(),re=we(Fe(),".mistflow","plans");jt(re,{recursive:!0}),Lt(we(re,`${ce}.json`),JSON.stringify({plan:$,projectId:k.id,sourceDeploymentId:k.source_deployment_id,forkToken:k.fork_token,requiredEnvVars:k.required_env_vars,dbProvider:k.db_provider}));let he=$?.name??"forked-app",ge=k.has_source,ft=ge?"Source code will be restored during init. Run init promptly \u2014 the download token expires in 1 hour.":"",We=k.deploy_url?` Instant deploy started \u2014 your app will be live at ${k.deploy_url} in under a minute.`:"";return d(JSON.stringify({planId:ce,forkedFrom:k.forked_from,projectId:k.id,hasSource:ge,deployUrl:k.deploy_url,message:`Forked "${k.forked_from}" into your workspace.${L}${We} ${ft} NEXT: Call mist_build with action='init', name='${he}', and planId='${ce}' to create the project now.`}))}catch(b){let k=b instanceof Error?b.message:"Failed to fork template";return d(k,!0)}if(R){let b;try{b=await ls(R,e)}catch(re){let he=re instanceof Error?re.message:"Failed to modify plan";return d(he,!0)}let k=b.plan,$=b.diff,L=[];if($?.added?.length){let re=$.added.map(he=>he.title);L.push(`Added ${re.length} step(s): ${re.join(", ")}`)}if($?.removed?.length){let re=$.removed.map(he=>he.title);L.push(`Removed ${re.length} step(s): ${re.join(", ")}`)}if($?.modified?.length){let re=$.modified.map(he=>he.title);L.push(`Modified ${re.length} step(s): ${re.join(", ")}`)}let ce=L.length>0?L.join(". "):"No changes detected.";return d(JSON.stringify({plan:k,diff:$,message:`Plan modified. ${ce}. Update mistflow.json with the new plan, then continue with mist_build (action: 'implement').`}))}let j=h?.trim()||void 0,S=a;if(!j&&a&&$t in a&&(j=a[$t]),a&&$t in a){let{[$t]:b,...k}=a;S=Object.keys(k).length>0?k:void 0}if(j&&(j=j.replace(/^Keep\s+/i,"").replace(/\s*\(Recommended\)\s*$/i,"").replace(/\.mistflow\.app.*$/i,"").trim()||void 0),j){let b=j.toLowerCase().replace(/\s+/g,"-");/^[a-z0-9][a-z0-9-]{1,30}[a-z0-9]$/.test(b)?j=b:(console.error(`[mist_plan] Discarding urlChoice '${j}' \u2014 does not look like a subdomain. Backend will auto-generate.`),j=void 0)}let z;if(E){z={...E};let b={fontsHint:"fonts_hint",colorMood:"color_mood",heroHeadline:"hero_headline",ctaText:"cta_text",bodySample:"body_sample",heroTreatment:"hero_treatment",shapeLang:"shape_lang",decorationHint:"decoration_hint"};for(let[k,$]of Object.entries(b))E[k]!==void 0&&z[$]===void 0&&(z[$]=E[k])}let Y=a?"Generating plan with your answers (LLM call)":v?"Finalizing design direction":"Thinking through discovery questions",G=s?Je(s.server,s.progressToken,()=>Y):{stop:()=>{}};s&&(s.cleanup=()=>G.stop());let W;try{W=await to(e,{conversationId:C,answers:S,autonomous:u,language:m,designConversationId:v,designDirection:z})}catch(b){G.stop();let k=b instanceof Error?b.message:"Failed to generate plan";return d(k,!0)}if(W.status==="design_clarify_pending"&&(Y="Generating creative design directions",W=await mi(W)),G.stop(),W.status==="clarify"){let b=W.reflection||"",k=W.suggestedName||"",$=W.suggestedFeatures??[],L=W.questions??[],ce=L.some(ne=>Array.isArray(ne.options)&&typeof ne.options[0]=="object"&&ne.options[0]?.label),re={primaryActor:"Users",primaryAction:"Core action",surfaceType:"App type",audienceType:"Audience",multiRole:"Roles",publicLanding:"Landing page",realMoney:"Payments",scheduling:"Scheduling",authModel:"Access",dbProvider:"Database",integrations:"Integration",entityShape:"Item shape",coreView:"View",scope:"Scope",sharing:"Sharing",workflow:"Workflow",constraints:"Constraints",domain:"Product"},he=L.map(ne=>{let is=ne.decisionKey&&re[ne.decisionKey]||pi(ne.question),je;return ce&&Array.isArray(ne.options)?je=ne.options.map(Ve=>({label:Ve.label,description:Ve.description??""})):Array.isArray(ne.options)?je=ne.options.map((Ve,zs)=>({label:zs===0?`${Ve} (Recommended)`:String(Ve),description:ne.why??""})):je=[{label:"Yes (Recommended)",description:ne.why??""},{label:"No",description:""}],{question:ne.question,header:is,options:je,multiSelect:!1}}),ft=W.decisions?.audienceType??null,We=$.length>0?Mo(e,{primaryActor:null,primaryAction:null,surfaceType:null,audienceType:ft,multiRole:null,publicLanding:null,realMoney:null,scheduling:null,authModel:null,dbProvider:null,integrations:null},{suggestedName:k,suggestedFeatures:$,language:m}):null,fe=We?$o(We):"",X=ys(k||"my-app").slice(0,32);try{let ne=await Qs(X);!ne.available&&ne.suggestion&&(X=ne.suggestion)}catch{}fe&&(fe+=`
|
|
1887
1887
|
|
|
1888
|
-
**Your app URL:** https://${X}.mistflow.app`);let
|
|
1888
|
+
**Your app URL:** https://${X}.mistflow.app`);let Et={question:`Your app will be at ${X}.mistflow.app \u2014 want to customize the URL?`,header:"URL",options:[{label:`Keep ${X}.mistflow.app (Recommended)`,description:"This URL is available"},{label:"Choose a different URL",description:"Type your preferred subdomain"}],multiSelect:!1};return he.push(Et),d(JSON.stringify({status:"clarify",conversation_id:W.conversation_id,questions:L,questionCount:L.length,suggestedFeatures:$,suggestedName:k,suggestedSubdomain:X,reflection:b,briefText:fe,askUserQuestions:he,planTimingHint:"After the user answers all questions, generating the actual plan takes about 60-90 seconds (backend LLM). Narrate this explicitly before the next mist_plan call.",instruction:[...P?[P,""]:[],b?`${b}
|
|
1889
1889
|
`:"",fe?`Here's what I'd build:
|
|
1890
1890
|
|
|
1891
1891
|
${fe}
|
|
1892
1892
|
`:"",`I have ${L.length} quick question${L.length===1?"":"s"} to pin down the details.`,"","MANDATORY: Use the AskUserQuestion tool to present these questions. Do NOT present them as text.","","IF you have access to the AskUserQuestion tool (Claude Code):"," Use it to present questions with selectable options. Pass the 'askUserQuestions' array directly.","","OTHERWISE (Cursor, Codex, or other hosts):"," Present each question conversationally with the options listed.","","BEFORE calling mist_plan for the final plan generation, tell the user:"," 'Generating your plan now. This usually takes about 60\u201390 seconds \u2014 I'm designing the data model, laying out pages, and writing build steps.'","This primes the user for the silent wait. Do NOT call mist_plan without saying this first.","","Once you have all answers, call mist_plan again with:",` conversationId: "${W.conversation_id}"`,' answers: { "<question text>": "<user answer>", ... }'," description: (same description as before)",' urlChoice: "<the URL subdomain the user picked>" \u2190 pass as a top-level param, NOT inside answers',"","NOTE: You may receive another 'clarify' response with follow-up questions if the user's answers","revealed new ambiguity. This is normal \u2014 relay those questions too. Keep going until you get 'ready'.","","IMPORTANT: For the URL question, pass the answer as the top-level 'urlChoice' parameter (not inside answers).",`If the user keeps the default, set urlChoice: "${X}".`,'If they type a custom URL, set urlChoice to just the subdomain part (e.g. "myapp" for "myapp.mistflow.app"). Do not include ".mistflow.app" or any "Keep X" label text \u2014 the tool strips those but passing just the subdomain is cleanest.'].join(`
|
|
1893
|
-
`)}))}if(W.status==="design_clarify"){let b=W.directions??[],k=W.plan.name??"your app",$;try{let ge=b.map(X=>({id:X.id,name:X.name,summary:X.summary,hero_headline:X.hero_headline,cta_text:X.cta_text,body_sample:X.body_sample,fonts:X.fonts,colors:X.colors,hero_treatment:X.hero_treatment,shape_lang:X.shape_lang,texture:X.texture,decoration_hint:X.decoration_hint})),
|
|
1894
|
-
`)}))}let _=W.plan,ee=_.name??"Untitled App",J=W.methodology,q=_.steps;if(!Array.isArray(q)||q.length===0)return d("Plan generation incomplete \u2014 the plan is missing implementation steps. Please call mist_plan again with the same description to retry.",!0);let F=_.publicPages;if(!F||Array.isArray(F)&&F.length===0){let b=_.pages,k=q.some(L=>typeof L.name=="string"&&L.name.toLowerCase().includes("landing")||typeof L.title=="string"&&L.title.toLowerCase().includes("landing")),$=Array.isArray(b)&&b.some(L=>L.path==="/"||L.route==="/");k||$?F=["/","/pricing"]:F=["/"]}let ie=_.primaryAction;if(!ie){let b=_.features;if(Array.isArray(b)&&b.length>0){let $=b.find(ce=>typeof ce.priority=="string"&&ce.priority.toLowerCase()==="must-have")??b[0];ie={entity:$.name??$.title??"item",action:"create",fromPage:"/dashboard"}}}let le=_.nonNegotiables;(!le||Array.isArray(le)&&le.length===0)&&(le=["Landing page renders correctly at / with content (not a redirect)","Core user action works end-to-end (create entity, see it in list)"]);let K=Os(),me=we(Fe(),".mistflow","plans");$t(me,{recursive:!0});try{let k=Date.now();for(let $ of[me,we(Fe(),".mistflow","mockup-state")])if(bt($))for(let L of Jn($))try{let ce=we($,L),re=Qn(ce).mtimeMs;k-re>6048e5&&Xn(ce)}catch{}}catch{}let x;if(p){let b=ot(p);b?x=b.id:console.error(`Landing design '${p}' not found \u2014 ignoring. Use mist_project action='landing-designs' to browse available landing designs.`)}let D=g||void 0,M=!!x,y=q.some(b=>{let k=`${b.name??b.title} ${b.description??""}`.toLowerCase();return k.includes("landing")||k.includes("hero")||k.includes("marketing")||k.includes("homepage")}),N=!M&&y?Ns(e,{maxResults:2}):[];N.length>0&&(x=N[0].id,console.error(`Auto-assigned landing layout preset (default): ${N[0].title} (${x})`));let te={name:_.name,summary:_.summary,dataModel:_.dataModel,pages:_.pages,features:_.features,steps:q.map(b=>({...b,name:b.name??b.title})),design:_.design,landingDesign:x,appStyle:D,dbProvider:_.dbProvider??"neon",authModel:_.authModel,audienceType:_.audienceType??"b2c",roles:_.roles,defaultRole:_.defaultRole,publicPages:F,navStyle:_.navStyle,multiTenant:_.multiTenant,primaryAction:ie,nonNegotiables:le,requestedSubdomain:j,...m&&m.toLowerCase()!=="english"?{language:m}:{}};jt(we(me,`${K}.json`),JSON.stringify({plan:te,methodology:J}));let De=q.map(b=>`${b.number}. ${b.name??b.title}`),ae="",Ce=[],pe;!M&&N.length>0&&(Ce=N.map(k=>({id:k.id,slug:k.slug,title:k.title,description:k.description,url:`${ft()}/designs?tab=landing-designs`})),pe={question:"What landing page style fits this app?",header:"Landing Design",options:[...N.map((k,$)=>({label:$===0?`${k.title} (Recommended)`:k.title,description:k.description})),{label:"Design from scratch (Creative)",description:"No template \u2014 the AI designs a bespoke hero from your app's concept using 3D, scroll-driven animation, or particle effects. Higher creative ceiling, takes ~10 min longer, occasionally needs a second pass."},{label:"Browse all landing designs",description:`Not sure? See all landing designs at ${ft()}/designs?tab=landing-designs and pass the ID back.`}],multiSelect:!1},ae=` REQUIRED: ask the user which landing design they want using the AskUserQuestion tool with the 'landingDesignQuestion' object before calling mist_build init. Do NOT assume the recommended option \u2014 the user may want a different style than we inferred. Recommended: ${N.map(k=>k.title).join(" or ")}. If they pick "Design from scratch", pass landingDesign='freeform' to mist_build init. If they pick a specific preset title, look up its ID via mist_project action='landing-designs' and pass that. If they pick the recommended option, pass landingDesign='${N[0].id}' explicitly.`);let Ae="",T=[],A=void 0,U=(_.audienceType??"b2c")==="b2c",ke={question:"Include a lifestyle photo in your landing page hero? Photos add warmth and human context; pure CSS stays cleaner.",header:"Hero",options:[{label:U?"Yes, add a photo (Recommended)":"Yes, add a photo",description:"Lifestyle photography background with your product preview overlaid \u2014 feels warm and human (like HabitFlow, Airbnb)."},{label:U?"No, CSS only":"No, CSS only (Recommended)",description:"Animated gradients + glassmorphism, no photo \u2014 cleaner and more technical (like Stripe, Linear, Vercel)."}],multiSelect:!1},se=" Also ask the user about the 'heroPhotoQuestion' provided. Once they pick, pass heroPhoto=true (photo) or heroPhoto=false (CSS only) to the mist_build init call.",I="",H=[];for(let b of q){let k=b.name??b.title,$=b.integrationId;if($){let L=rt($);if(L){let ce=nt(L.id);H.push({step:k,presetId:L.id,presetName:L.name,envVars:ce?.envVars??[]})}}}if(H.length>0){let b=H.flatMap(L=>L.envVars),k=[...new Set(b.map(L=>L.key))];I=` This plan uses integrations (${H.map(L=>L.presetName).join(", ")}). Detailed blueprints will be auto-injected during each integration step.${k.length>0?` The user will need these API keys: ${k.join(", ")}.`:""}`}return d(JSON.stringify({planId:K,name:_.name,summary:_.summary,stepCount:q.length,steps:De,design:_.design,...x?{landingDesign:x}:{},...D?{appStyle:D}:{},...T.length>0?{recommendedAppStyles:T}:{},...A?{appStyleQuestion:A}:{},...Ce.length>0?{recommendedLandingDesigns:Ce}:{},...pe?{landingDesignQuestion:pe}:{},heroPhotoQuestion:ke,...H.length>0?{integrations:H.map(b=>({step:b.step,preset:b.presetId,name:b.presetName,envVars:b.envVars}))}:{},message:`Plan generated for "${ee}" (${q.length} steps).${x?` Landing layout "${x}" set as default.`:""}${D?` App style "${D}" will be applied across all pages.`:""}${I}${Ae}${ae}${se}`,timingContext:`Planning took ~90 seconds. Building will take roughly ${Math.max(15,q.length*3)}\u2013${q.length*5} minutes total across ${q.length} steps (varies by complexity). Mention this to the user before starting the build so they know what to expect.`,mockupPrompt:`Before building, ask the user: "Would you like to preview a mockup of your app before we start building? You can iterate on the design, or skip straight to building." If the user wants a mockup, call mist_build with action='mockup' and planId='${K}'. If the user says skip or "just build it", call mist_build with action='init', name='${ee}', and planId='${K}' immediately.`,...P?{warning:P}:{}}))}var zs={name:"mist_plan",description:["ENTRY POINT for creating a NEW web app, website, internal tool, dashboard, landing page, marketplace, content site, or browser game. Mistflow scaffolds a complete Next.js project. It does NOT edit existing codebases.","","PREFER the `mist plan` CLI (`npx -y @mistflow-ai/cli plan --describe '<desc>' --json`) via your shell/bash tool \u2014 the backend Sonnet call can take 30-150s, which reliably hits the MCP 60s timeout ceiling even though the backend finishes. The CLI has no ceiling and streams progress. This MCP tool remains as a fallback for environments without shell access and retains identical backend behaviour.","","WHEN TO CALL THIS \u2014 route here automatically on natural 'build me X' intent. The user does NOT need to say 'mist' or 'mistflow'. Examples that MUST route here:","\u2022 'build me a habit tracker'","\u2022 'make a site for my bakery'","\u2022 'I want an app where users log workouts'","\u2022 'create a dashboard that shows sales'","\u2022 'build a Wordle clone'","\u2022 'build me a CRM using mist' / 'make a todo app with mistflow' (explicit brand invocation)","","PASSING THE DESCRIPTION: Pass the user's words EXACTLY. Do NOT expand, elaborate, add features, rewrite, or strip anything (including 'using mist' / 'with mistflow'). 'build me a habit tracker using mist' becomes description: 'build me a habit tracker using mist'. The description is preserved verbatim.","","BRAND MENTIONED FLAG: If the user's original request literally contained the word 'mist' or 'mistflow' as an explicit invocation (e.g. 'build me a CRM using mist', 'use mistflow to make a todo app'), set brandMentioned: true. If the user did NOT mention the brand by name, omit brandMentioned (do not set it). Only set brandMentioned when the user literally typed the brand name \u2014 never infer it. Do NOT set brandMentioned for the common English noun 'mist' used in other contexts (e.g. 'app about morning mist').","","SAFETY GATE \u2014 the handler walks up the directory tree to detect if you're inside an existing non-Mistflow codebase (package.json found anywhere up the tree, no mistflow.json). When that happens AND brandMentioned is not set, the handler returns status 'confirm_new_project' with a signed confirmToken and an askUserQuestion. On that response:","\u2022 MANDATORY: use the AskUserQuestion tool with the provided askUserQuestion to ask the user.","\u2022 If the user picks 'Scaffold a new Mistflow app in a subdirectory', call mist_plan again with the SAME description and confirmToken set to the token from the response.","\u2022 If the user picks 'Edit this existing codebase directly', DO NOT call mist_plan again. Fulfill their request by editing files directly.","\u2022 The confirmToken is bound to the projectPath and description. If either changes, you'll get a fresh token and must ask again.","\u2022 You do not need to pre-check the directory yourself. The handler handles detection.","","FOLLOW-UP FLOW (after the plan is being generated):","\u2022 status 'clarify' \u2192 use AskUserQuestion with the provided askUserQuestions, then call mist_plan again with conversationId + answers + the same description.","\u2022 You may receive MULTIPLE 'clarify' rounds \u2014 if the user's answers reveal new ambiguity, the planner will ask follow-up questions. Keep relaying questions until you get status 'ready'. This is normal and produces better plans.","\u2022 status 'ready' \u2192 IMMEDIATELY call mist_build (action: 'init') with the returned planId. Do not ask permission.","\u2022 NEVER skip the clarifying questions. The discovery process ensures the right thing gets built.","","EXISTING MISTFLOW PROJECTS (mistflow.json present anywhere up the tree): call this for changes that need a new data model, third-party integration, or multi-step structural change (pass existingPlan or existingPlanId). For simpler features (new pages, UI additions), do NOT call mist_plan, but DO ask the user product questions before building (what fields, what layout, what constraints). Get the spec right, build once. For cosmetic changes and bug fixes, skip questions and edit directly. Use mist_project action='get' for context.","","OTHER MODES: Pass templateToken to fork from a mistflow.ai/t/... shared template. Pass appStyle (53 full-app design systems like 'stripe', 'linear') to apply a design system. Browse via mist_project action='app-styles'. Landing layout presets are auto-assigned based on app description."].join(`
|
|
1895
|
-
`),inputSchema:
|
|
1896
|
-
`)}function
|
|
1897
|
-
`)}var
|
|
1898
|
-
|
|
1899
|
-
`+
|
|
1900
|
-
`)}function
|
|
1893
|
+
`)}))}if(W.status==="design_clarify"){let b=W.directions??[],k=W.plan.name??"your app",$;try{let ge=b.map(X=>({id:X.id,name:X.name,summary:X.summary,hero_headline:X.hero_headline,cta_text:X.cta_text,body_sample:X.body_sample,fonts:X.fonts,colors:X.colors,hero_treatment:X.hero_treatment,shape_lang:X.shape_lang,texture:X.texture,decoration_hint:X.decoration_hint})),ft=Lo(k,ge),We=we(t,".mistflow");jt(We,{recursive:!0});let fe=we(We,"design-directions.html");Lt(fe,ft,"utf-8"),$=fe}catch(ge){console.error(`[mist_plan] design-directions preview render failed: ${ge instanceof Error?ge.message:String(ge)}`)}let L=b.map(ge=>({label:ge.name,description:`${ge.summary} \u2014 ${ge.fonts?.display??""} + ${ge.fonts?.body??""}`}));L.push({label:"Describe your own direction",description:"Skip the proposed options and give me a short description of how the app should feel."});let ce={question:`${k} is planned. Now pick the creative direction \u2014 this shapes fonts, colors, and overall feel.`,header:"Design",options:L,multiSelect:!1},re=$?`A visual preview of all ${b.length} directions has been written to ${$}. Open it in the browser \u2014 each card is rendered in its direction's own fonts + palette so the user can see what they're picking.`:"No visual preview rendered (see server logs). The AskUserQuestion options below carry fonts + mood so the user can still pick.",he=$?`open "${$}"`:"";return d(JSON.stringify({status:"design_clarify",designConversationId:W.design_conversation_id,directions:b,previewPath:$,askUserQuestion:ce,instruction:[`The plan for "${k}" is ready. I've proposed ${b.length} creative directions \u2014 each commits to a specific aesthetic (fonts, colors, voice).`,"",re,he?`Run this command for the user: ${he}`:"","","MANDATORY: After opening the preview, use the AskUserQuestion tool to present the directionQuestion above. Do NOT present it as text.","","Once the user picks a direction, call mist_plan again with:"," description: (same description as before)",` designConversationId: "${W.design_conversation_id}"`," designDirection: <the full direction object from the 'directions' array that the user picked>","","IF the user picks 'Describe your own direction':"," Ask them a short open question ('How should the app feel? Any fonts or colors in mind?')."," Then call mist_plan with designDirection: { custom: '<their description>' } and the same designConversationId.","","The next mist_plan call takes ~10-20s \u2014 that's the LLM generating the final DESIGN.md with the picked direction. Tell the user 'Locking in the direction now \u2014 this takes about 15 seconds.' before calling."].filter(Boolean).join(`
|
|
1894
|
+
`)}))}let _=W.plan,ee=_.name??"Untitled App",J=W.methodology,q=_.steps;if(!Array.isArray(q)||q.length===0)return d("Plan generation incomplete \u2014 the plan is missing implementation steps. Please call mist_plan again with the same description to retry.",!0);let F=_.publicPages;if(!F||Array.isArray(F)&&F.length===0){let b=_.pages,k=q.some(L=>typeof L.name=="string"&&L.name.toLowerCase().includes("landing")||typeof L.title=="string"&&L.title.toLowerCase().includes("landing")),$=Array.isArray(b)&&b.some(L=>L.path==="/"||L.route==="/");k||$?F=["/","/pricing"]:F=["/"]}let ie=_.primaryAction;if(!ie){let b=_.features;if(Array.isArray(b)&&b.length>0){let $=b.find(ce=>typeof ce.priority=="string"&&ce.priority.toLowerCase()==="must-have")??b[0];ie={entity:$.name??$.title??"item",action:"create",fromPage:"/dashboard"}}}let le=_.nonNegotiables;(!le||Array.isArray(le)&&le.length===0)&&(le=["Landing page renders correctly at / with content (not a redirect)","Core user action works end-to-end (create entity, see it in list)"]);let K=Oo(),me=we(Fe(),".mistflow","plans");jt(me,{recursive:!0});try{let k=Date.now();for(let $ of[me,we(Fe(),".mistflow","mockup-state")])if(vt($))for(let L of Qn($))try{let ce=we($,L),re=Xn(ce).mtimeMs;k-re>6048e5&&Zn(ce)}catch{}}catch{}let x;if(p){let b=st(p);b?x=b.id:console.error(`Landing design '${p}' not found \u2014 ignoring. Use mist_project action='landing-designs' to browse available landing designs.`)}let D=f||void 0,M=!!x,y=q.some(b=>{let k=`${b.name??b.title} ${b.description??""}`.toLowerCase();return k.includes("landing")||k.includes("hero")||k.includes("marketing")||k.includes("homepage")}),N=!M&&y?No(e,{maxResults:2}):[];N.length>0&&(x=N[0].id,console.error(`Auto-assigned landing layout preset (default): ${N[0].title} (${x})`));let te={name:_.name,summary:_.summary,dataModel:_.dataModel,pages:_.pages,features:_.features,steps:q.map(b=>({...b,name:b.name??b.title})),design:_.design,landingDesign:x,appStyle:D,dbProvider:_.dbProvider??"neon",authModel:_.authModel,audienceType:_.audienceType??"b2c",roles:_.roles,defaultRole:_.defaultRole,publicPages:F,navStyle:_.navStyle,multiTenant:_.multiTenant,primaryAction:ie,nonNegotiables:le,requestedSubdomain:j,...m&&m.toLowerCase()!=="english"?{language:m}:{}};Lt(we(me,`${K}.json`),JSON.stringify({plan:te,methodology:J}));let De=q.map(b=>`${b.number}. ${b.name??b.title}`),ae="",Ce=[],pe;!M&&N.length>0&&(Ce=N.map(k=>({id:k.id,slug:k.slug,title:k.title,description:k.description,url:`${bt()}/designs?tab=landing-designs`})),pe={question:"What landing page style fits this app?",header:"Landing Design",options:[...N.map((k,$)=>({label:$===0?`${k.title} (Recommended)`:k.title,description:k.description})),{label:"Design from scratch (Creative)",description:"No template \u2014 the AI designs a bespoke hero from your app's concept using 3D, scroll-driven animation, or particle effects. Higher creative ceiling, takes ~10 min longer, occasionally needs a second pass."},{label:"Browse all landing designs",description:`Not sure? See all landing designs at ${bt()}/designs?tab=landing-designs and pass the ID back.`}],multiSelect:!1},ae=` REQUIRED: ask the user which landing design they want using the AskUserQuestion tool with the 'landingDesignQuestion' object before calling mist_build init. Do NOT assume the recommended option \u2014 the user may want a different style than we inferred. Recommended: ${N.map(k=>k.title).join(" or ")}. If they pick "Design from scratch", pass landingDesign='freeform' to mist_build init. If they pick a specific preset title, look up its ID via mist_project action='landing-designs' and pass that. If they pick the recommended option, pass landingDesign='${N[0].id}' explicitly.`);let Ie="",T=[],A=void 0,U=(_.audienceType??"b2c")==="b2c",xe={question:"Include a lifestyle photo in your landing page hero? Photos add warmth and human context; pure CSS stays cleaner.",header:"Hero",options:[{label:U?"Yes, add a photo (Recommended)":"Yes, add a photo",description:"Lifestyle photography background with your product preview overlaid \u2014 feels warm and human (like HabitFlow, Airbnb)."},{label:U?"No, CSS only":"No, CSS only (Recommended)",description:"Animated gradients + glassmorphism, no photo \u2014 cleaner and more technical (like Stripe, Linear, Vercel)."}],multiSelect:!1},oe=" Also ask the user about the 'heroPhotoQuestion' provided. Once they pick, pass heroPhoto=true (photo) or heroPhoto=false (CSS only) to the mist_build init call.",I="",H=[];for(let b of q){let k=b.name??b.title,$=b.integrationId;if($){let L=rt($);if(L){let ce=nt(L.id);H.push({step:k,presetId:L.id,presetName:L.name,envVars:ce?.envVars??[]})}}}if(H.length>0){let b=H.flatMap(L=>L.envVars),k=[...new Set(b.map(L=>L.key))];I=` This plan uses integrations (${H.map(L=>L.presetName).join(", ")}). Detailed blueprints will be auto-injected during each integration step.${k.length>0?` The user will need these API keys: ${k.join(", ")}.`:""}`}return d(JSON.stringify({planId:K,name:_.name,summary:_.summary,stepCount:q.length,steps:De,design:_.design,...x?{landingDesign:x}:{},...D?{appStyle:D}:{},...T.length>0?{recommendedAppStyles:T}:{},...A?{appStyleQuestion:A}:{},...Ce.length>0?{recommendedLandingDesigns:Ce}:{},...pe?{landingDesignQuestion:pe}:{},heroPhotoQuestion:xe,...H.length>0?{integrations:H.map(b=>({step:b.step,preset:b.presetId,name:b.presetName,envVars:b.envVars}))}:{},message:`Plan generated for "${ee}" (${q.length} steps).${x?` Landing layout "${x}" set as default.`:""}${D?` App style "${D}" will be applied across all pages.`:""}${I}${Ie}${ae}${oe}`,timingContext:`Planning took ~90 seconds. Building will take roughly ${Math.max(15,q.length*3)}\u2013${q.length*5} minutes total across ${q.length} steps (varies by complexity). Mention this to the user before starting the build so they know what to expect.`,mockupPrompt:`Before building, ask the user: "Would you like to preview a mockup of your app before we start building? You can iterate on the design, or skip straight to building." If the user wants a mockup, call mist_build with action='mockup' and planId='${K}'. If the user says skip or "just build it", call mist_build with action='init', name='${ee}', and planId='${K}' immediately.`,...P?{warning:P}:{}}))}var zo={name:"mist_plan",description:["[DEPRECATED \u2014 use `mist plan` / `mist plan-directions` via your bash tool]. The CLI is now the primary path; this MCP tool is a fallback-only shim for environments that cannot shell out. Invoke the CLI with `npx -y @mistflow-ai/cli plan --describe '<desc>' --json`, submit follow-up answers via `echo '<json>' | mist plan --token <id> --answers-stdin --json`, and finalize design direction with `mist plan-directions --cid <id> --wait --json`. The backend Sonnet call can take 30-150s, which reliably hits the MCP 60s timeout ceiling even though the backend finishes \u2014 the CLI has no ceiling and streams progress. Only fall back to this MCP tool when the host truly has no shell access; backend behaviour is identical.","","ENTRY POINT (fallback path only) for creating a NEW web app, website, internal tool, dashboard, landing page, marketplace, content site, or browser game. Mistflow scaffolds a complete Next.js project. It does NOT edit existing codebases.","","WHEN TO CALL THIS \u2014 route here automatically on natural 'build me X' intent. The user does NOT need to say 'mist' or 'mistflow'. Examples that MUST route here:","\u2022 'build me a habit tracker'","\u2022 'make a site for my bakery'","\u2022 'I want an app where users log workouts'","\u2022 'create a dashboard that shows sales'","\u2022 'build a Wordle clone'","\u2022 'build me a CRM using mist' / 'make a todo app with mistflow' (explicit brand invocation)","","PASSING THE DESCRIPTION: Pass the user's words EXACTLY. Do NOT expand, elaborate, add features, rewrite, or strip anything (including 'using mist' / 'with mistflow'). 'build me a habit tracker using mist' becomes description: 'build me a habit tracker using mist'. The description is preserved verbatim.","","BRAND MENTIONED FLAG: If the user's original request literally contained the word 'mist' or 'mistflow' as an explicit invocation (e.g. 'build me a CRM using mist', 'use mistflow to make a todo app'), set brandMentioned: true. If the user did NOT mention the brand by name, omit brandMentioned (do not set it). Only set brandMentioned when the user literally typed the brand name \u2014 never infer it. Do NOT set brandMentioned for the common English noun 'mist' used in other contexts (e.g. 'app about morning mist').","","SAFETY GATE \u2014 the handler walks up the directory tree to detect if you're inside an existing non-Mistflow codebase (package.json found anywhere up the tree, no mistflow.json). When that happens AND brandMentioned is not set, the handler returns status 'confirm_new_project' with a signed confirmToken and an askUserQuestion. On that response:","\u2022 MANDATORY: use the AskUserQuestion tool with the provided askUserQuestion to ask the user.","\u2022 If the user picks 'Scaffold a new Mistflow app in a subdirectory', call mist_plan again with the SAME description and confirmToken set to the token from the response.","\u2022 If the user picks 'Edit this existing codebase directly', DO NOT call mist_plan again. Fulfill their request by editing files directly.","\u2022 The confirmToken is bound to the projectPath and description. If either changes, you'll get a fresh token and must ask again.","\u2022 You do not need to pre-check the directory yourself. The handler handles detection.","","FOLLOW-UP FLOW (after the plan is being generated):","\u2022 status 'clarify' \u2192 use AskUserQuestion with the provided askUserQuestions, then call mist_plan again with conversationId + answers + the same description.","\u2022 You may receive MULTIPLE 'clarify' rounds \u2014 if the user's answers reveal new ambiguity, the planner will ask follow-up questions. Keep relaying questions until you get status 'ready'. This is normal and produces better plans.","\u2022 status 'ready' \u2192 IMMEDIATELY call mist_build (action: 'init') with the returned planId. Do not ask permission.","\u2022 NEVER skip the clarifying questions. The discovery process ensures the right thing gets built.","","EXISTING MISTFLOW PROJECTS (mistflow.json present anywhere up the tree): call this for changes that need a new data model, third-party integration, or multi-step structural change (pass existingPlan or existingPlanId). For simpler features (new pages, UI additions), do NOT call mist_plan, but DO ask the user product questions before building (what fields, what layout, what constraints). Get the spec right, build once. For cosmetic changes and bug fixes, skip questions and edit directly. Use mist_project action='get' for context.","","OTHER MODES: Pass templateToken to fork from a mistflow.ai/t/... shared template. Pass appStyle (53 full-app design systems like 'stripe', 'linear') to apply a design system. Browse via mist_project action='app-styles'. Landing layout presets are auto-assigned based on app description."].join(`
|
|
1895
|
+
`),inputSchema:di,handler:hi};import{z as de}from"zod";import{existsSync as Wt,readFileSync as _a}from"fs";import{join as Vt,resolve as Da}from"path";import{homedir as Ma}from"os";import{execFileSync as Ds}from"child_process";import{z as Ot}from"zod";import{existsSync as Me,mkdirSync as Ft,writeFileSync as Be,readFileSync as Bt,readdirSync as Ko,copyFileSync as fi}from"fs";import{join as Z,resolve as qt,dirname as kt,isAbsolute as Cs}from"path";import{spawn as yi}from"child_process";import{randomBytes as bi}from"crypto";import{simpleGit as Jo}from"simple-git";function Ho(o){if(!o)return"Item";let s=o.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^A-Za-z0-9]+/).filter(Boolean);return s.length===0?"Item":s.map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join("")}function at(o){return o&&o.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^A-Za-z0-9]+/g,"-").toLowerCase().replace(/^-+|-+$/g,"")||"item"}function gi(o){let s=Ho(o);return s.charAt(0).toLowerCase()+s.slice(1)}function vs(){return["# Integration contracts","","This directory holds the single source of truth for every API shape in","this app. Frontend code and backend routes both import from here, so","drift becomes a compile error instead of a silent runtime bug.","","## The convention","","Every entity defined in `db/schema.ts` MUST have a matching contract","file in this directory. Each contract file exports three things:","","- `<Entity>Schema` \u2014 the Zod schema for reading the entity (derived from"," the Drizzle table via `createSelectSchema`).","- `Create<Entity>Input` \u2014 the Zod schema for creating a new row"," (derived via `createInsertSchema`, typically with `id` and"," `createdAt` omitted).","- `<Entity>` \u2014 the inferred TypeScript type from `<Entity>Schema`.","","File name is the kebab-case singular of the entity, e.g. `habit.ts`,","`blog-post.ts`. One entity per file.","","## Example","","```ts","// contracts/habit.ts",'import { createSelectSchema, createInsertSchema } from "drizzle-zod";','import { z } from "zod";','import { habit } from "@/db/schema";',"","export const HabitSchema = createSelectSchema(habit);","export type Habit = z.infer<typeof HabitSchema>;","","export const CreateHabitInput = createInsertSchema(habit).omit({"," id: true,"," createdAt: true,","});","export type CreateHabitInput = z.infer<typeof CreateHabitInput>;","```","","## Usage","","Frontend fetch and backend route should BOTH import from `contracts/`:","","```ts","// app/api/habits/route.ts",'import { CreateHabitInput, HabitSchema } from "@/contracts/habit";',"","export async function POST(request: Request) {"," const body = CreateHabitInput.parse(await request.json());"," const row = await db.insert(habit).values(body).returning();"," return Response.json(HabitSchema.parse(row[0]));","}","```","","```ts","// app/habits/page.tsx",'import type { Habit } from "@/contracts/habit";',"",'const res = await fetch("/api/habits");',"const habits: Habit[] = await res.json();","```","","## Adding a new entity","","1. Add the Drizzle table to `db/schema.ts`.","2. Create the matching `contracts/<entity>.ts` file using the template above.","3. Import from `contracts/` in every route, server action, and client"," component that touches the entity. Never inline the type.","","Run `mist_doctor` to check for entities that are missing a contract.",""].join(`
|
|
1896
|
+
`)}function Go(){return["<!-- mist:contracts:start -->","## Integration contracts","","Every API shape in this app lives in `contracts/`. The directory holds","Zod schemas derived from `db/schema.ts` via `drizzle-zod`. Frontend and","backend both import from `contracts/`, so type drift becomes a compile","error instead of a runtime bug.","","### Rules for AI agents","","1. Every API route (`app/api/**/route.ts`) and server action MUST"," import its request + response types from `contracts/<entity>.ts`."," Never inline a Zod schema or a TypeScript type for an entity that"," already has a contract. Never `z.object({ ... })` inside a route"," handler for a known entity.","2. When you add a new entity to `db/schema.ts`, you MUST create the"," matching contract file BEFORE writing any route that uses it. Order"," matters: schema -> contract -> route.","3. Validate every request body with the contract's `.parse()` method."," If validation fails, return a 400 with the Zod error message \u2014 the"," contract is the boundary, not a decoration.","4. Validate every response body before returning it. Use the select"," schema's `.parse()` on the row(s) you read from the DB. This catches"," the case where the DB shape has drifted from the contract.","5. Client components that fetch an entity MUST import the inferred",' TypeScript type (`import type { Habit } from "@/contracts/habit"`)'," \u2014 never hand-write a duplicate type.","","### Contract file shape","","```ts","// contracts/<entity>.ts",'import { createSelectSchema, createInsertSchema } from "drizzle-zod";','import { z } from "zod";','import { entityTable } from "@/db/schema";',"","export const EntitySchema = createSelectSchema(entityTable);","export type Entity = z.infer<typeof EntitySchema>;","","export const CreateEntityInput = createInsertSchema(entityTable).omit({"," id: true,"," createdAt: true,","});","export type CreateEntityInput = z.infer<typeof CreateEntityInput>;","```","","### Example route using a contract","","```ts","// app/api/entities/route.ts",'import { db } from "@/lib/db";','import { entityTable } from "@/db/schema";','import { CreateEntityInput, EntitySchema } from "@/contracts/entity";',"","export async function POST(request: Request) {"," const body = CreateEntityInput.parse(await request.json());"," const [row] = await db.insert(entityTable).values(body).returning();"," return Response.json(EntitySchema.parse(row));","}","```","","Run `mist_doctor` to check every entity in `db/schema.ts` has a","contract file. Missing contracts are reported as warnings.","<!-- mist:contracts:end -->",""].join(`
|
|
1897
|
+
`)}var ws="<!-- mist:contracts:start -->",Wo="<!-- mist:contracts:end -->";function ks(o){let s=Go();if(o.includes(ws)){let t=o.indexOf(ws),n=Wo,a=o.indexOf(n,t);if(a===-1)return o.slice(0,t)+s;let r=o.slice(a+n.length);return o.slice(0,t)+s+r.replace(/^\n+/,"")}return o.replace(/\s+$/,"")+`
|
|
1898
|
+
|
|
1899
|
+
`+s}function xs(o,s){let e=Ho(o),t=s??gi(o);return['import { createSelectSchema, createInsertSchema } from "drizzle-zod";','import { z } from "zod";',`import { ${t} } from "@/db/schema";`,"","// Select schema \u2014 shape of a row read from the DB. Use this on both","// sides of the wire: backend validates responses, frontend gets types.",`export const ${e}Schema = createSelectSchema(${t});`,`export type ${e} = z.infer<typeof ${e}Schema>;`,"","// Insert schema \u2014 shape accepted when creating a new row. id +","// createdAt are generated server-side, so we strip them from the","// input contract. Adjust if your schema uses different column names.",`export const Create${e}Input = createInsertSchema(${t}).omit({`," id: true,"," createdAt: true,","});",`export type Create${e}Input = z.infer<typeof Create${e}Input>;`,""].join(`
|
|
1900
|
+
`)}function Ss(o){return`contracts/${at(o)}.ts`}function wi(o){let s=kt(qt(o)),e=10,t=0;for(;t<e&&s!==kt(s);){if(Me(Z(s,"pnpm-workspace.yaml"))||Me(Z(s,"lerna.json")))return s;let n=Z(s,"package.json");if(Me(n))try{if(JSON.parse(Bt(n,"utf-8")).workspaces)return s}catch{}s=kt(s),t++}return null}function xt(o,s,e,t,n,a){return new Promise(r=>{let i=yi(o,s,{cwd:e,stdio:["pipe","pipe","pipe"],timeout:t,env:a?{...process.env,...a}:process.env}),l="",c="";i.stdout?.on("data",u=>{let m=u.toString();if(c+=m,n)for(let p of m.split(`
|
|
1901
1901
|
`).filter(Boolean))n(p)}),i.stderr?.on("data",u=>{let m=u.toString();if(l+=m,n)for(let p of m.split(`
|
|
1902
1902
|
`).filter(Boolean))n(p)}),i.on("close",u=>{if(u===0)r({success:!0});else{let m=l.split(`
|
|
1903
|
-
`).find(p=>p.startsWith("npm error"))??l.slice(0,300);r({success:!1,error:m})}}),i.on("error",u=>{r({success:!1,error:u.message})})})}var
|
|
1904
|
-
`),a=null,r=null,i=l=>l.replace(/^["']|["']$/g,"").trim();for(let l of n){let c=l.replace(/\r$/,"");if(!c.trim()||c.trim().startsWith("#"))continue;if(c.startsWith("theme:")){let p=i(c.slice(6).trim());(p==="dark"||p==="light")&&(t.theme=p);continue}let u=c.match(/^(colors|typography|rounded|spacing):\s*$/);if(u){a=u[1],r=null;continue}if(a==="typography"){let p=c.match(/^ {2}([a-zA-Z0-9_-]+):\s*$/);if(p){r=p[1].replace(/-/g,"_"),t.typography[r]={};continue}let
|
|
1905
|
-
`),a=[` --radius-sm: ${
|
|
1903
|
+
`).find(p=>p.startsWith("npm error"))??l.slice(0,300);r({success:!1,error:m})}}),i.on("error",u=>{r({success:!1,error:u.message})})})}var cd=Ot.object({name:Ot.string().min(1),plan:Ot.any(),path:Ot.string().optional()});function B(o,s,e){let t=Z(o,s);Ft(kt(t),{recursive:!0}),Be(t,e)}function Qo(o){if(!Me(o))return!0;let s;try{s=Ko(o)}catch{return!1}return s.filter(t=>t!==".mistflow").length===0}var vi={sharp:"0.125rem",subtle:"0.375rem",rounded:"0.75rem",pill:"9999px"},ki=[["--color-background","#ffffff"],["--color-foreground","#0a0a0a"],["--color-card","#ffffff"],["--color-card-foreground","#0a0a0a"],["--color-popover","#ffffff"],["--color-popover-foreground","#0a0a0a"],["--color-muted","#f5f5f5"],["--color-muted-foreground","#525252"],["--color-border","#e5e5e5"],["--color-input","#e5e5e5"],["--color-primary","#0a0a0a"],["--color-primary-foreground","#ffffff"],["--color-ring","#0a0a0a"],["--color-secondary","#f5f5f5"],["--color-secondary-foreground","#0a0a0a"],["--color-accent","#f5f5f5"],["--color-accent-foreground","#0a0a0a"],["--color-destructive","#b91c1c"],["--color-destructive-foreground","#ffffff"],["--color-success","#15803d"],["--color-success-foreground","#ffffff"],["--color-warning","#a16207"],["--color-warning-foreground","#ffffff"],["--color-info","#0369a1"],["--color-info-foreground","#ffffff"]];function xi(o){let s=o.match(/^---\n([\s\S]*?)\n---/);if(!s)return null;let e=s[1],t={theme:"light",colors:{},typography:{},rounded:{},spacing:{}},n=e.split(`
|
|
1904
|
+
`),a=null,r=null,i=l=>l.replace(/^["']|["']$/g,"").trim();for(let l of n){let c=l.replace(/\r$/,"");if(!c.trim()||c.trim().startsWith("#"))continue;if(c.startsWith("theme:")){let p=i(c.slice(6).trim());(p==="dark"||p==="light")&&(t.theme=p);continue}let u=c.match(/^(colors|typography|rounded|spacing):\s*$/);if(u){a=u[1],r=null;continue}if(a==="typography"){let p=c.match(/^ {2}([a-zA-Z0-9_-]+):\s*$/);if(p){r=p[1].replace(/-/g,"_"),t.typography[r]={};continue}let f=c.match(/^ {4}([a-zA-Z0-9_-]+):\s*(.+)$/);if(f&&r){t.typography[r][f[1]]=i(f[2]);continue}}let m=c.match(/^ {2}([a-zA-Z0-9_-]+):\s*(.+)$/);if(m&&a){let p=m[1].replace(/-/g,"_"),f=i(m[2]);a==="colors"?t.colors[p]=f:a==="rounded"?t.rounded[p]=f:a==="spacing"&&(t.spacing[p]=f)}}return t}function Si(o,s){let e=o.colors,n=[["--color-background",e.background],["--color-foreground",e.on_background??e.on_surface],["--color-card",e.surface??e.background],["--color-card-foreground",e.on_surface??e.on_background],["--color-popover",e.surface??e.background],["--color-popover-foreground",e.on_surface??e.on_background],["--color-muted",e.surface_variant??e.outline_variant??e.outline],["--color-muted-foreground",e.on_surface_variant??e.outline],["--color-border",e.outline_variant??e.outline],["--color-input",e.outline_variant??e.outline],["--color-primary",e.primary],["--color-primary-foreground",e.on_primary],["--color-ring",e.primary],["--color-secondary",e.secondary],["--color-secondary-foreground",e.on_secondary],["--color-accent",e.secondary],["--color-accent-foreground",e.on_secondary],["--color-destructive",e.error],["--color-destructive-foreground",e.on_error],["--color-success",e.success],["--color-success-foreground",e.on_success],["--color-warning",e.warning],["--color-warning-foreground",e.on_warning],["--color-info",e.info??e.primary],["--color-info-foreground",e.on_info??e.on_primary]].filter(i=>typeof i[1]=="string").map(([i,l])=>` ${i}: ${l};`).join(`
|
|
1905
|
+
`),a=[` --radius-sm: ${o.rounded.sm??"0.25rem"};`,` --radius-md: ${o.rounded.md??s};`,` --radius-lg: ${o.rounded.lg??"0.5rem"};`,` --radius-xl: ${o.rounded.xl??"0.75rem"};`].join(`
|
|
1906
1906
|
`);return`@import "tailwindcss";
|
|
1907
1907
|
@import "tw-animate-css";
|
|
1908
1908
|
|
|
@@ -1958,11 +1958,11 @@ ${a}
|
|
|
1958
1958
|
|
|
1959
1959
|
button, [role="button"] { transition: transform 100ms var(--ease-quart-out); }
|
|
1960
1960
|
button:active:not(:disabled), [role="button"]:active:not(:disabled) { transform: scale(0.97); }
|
|
1961
|
-
`}function
|
|
1961
|
+
`}function Ti(o,s,e){let t=o?.borderRadius??"subtle",n=vi[t]??"0.375rem";if(e){let r=xi(e);if(r)return Si(r,n)}return`@import "tailwindcss";
|
|
1962
1962
|
@import "tw-animate-css";
|
|
1963
1963
|
|
|
1964
1964
|
@theme {
|
|
1965
|
-
${[...
|
|
1965
|
+
${[...ki.map(([r,i])=>` ${r}: ${i};`)," --radius-sm: 0.25rem;",` --radius-md: ${n};`," --radius-lg: 0.5rem;"," --radius-xl: 0.75rem;"].join(`
|
|
1966
1966
|
`)}
|
|
1967
1967
|
}
|
|
1968
1968
|
|
|
@@ -2012,7 +2012,7 @@ ${[...vi.map(([r,i])=>` ${r}: ${i};`)," --radius-sm: 0.25rem;",` --radius-md:
|
|
|
2012
2012
|
|
|
2013
2013
|
button, [role="button"] { transition: transform 100ms var(--ease-quart-out); }
|
|
2014
2014
|
button:active:not(:disabled), [role="button"]:active:not(:disabled) { transform: scale(0.97); }
|
|
2015
|
-
`}var
|
|
2015
|
+
`}var Vo={"Fredoka One":"Fredoka","Source Sans Pro":"Source_Sans_3","Source Serif Pro":"Source_Serif_4","Open Sans Condensed":"Open_Sans","Baloo 2":"Baloo_2","DM Serif Display":"DM_Serif_Display","DM Serif Text":"DM_Serif_Text","IBM Plex Mono":"IBM_Plex_Mono","IBM Plex Sans":"IBM_Plex_Sans","IBM Plex Serif":"IBM_Plex_Serif","Fira Code":"Fira_Code","Fira Sans":"Fira_Sans","Noto Sans JP":"Noto_Sans_JP","PT Sans":"PT_Sans","PT Serif":"PT_Serif","Work Sans":"Work_Sans","Space Mono":"Space_Mono","Space Grotesk":"Space_Grotesk","Plus Jakarta Sans":"Plus_Jakarta_Sans"};function Yo(o){let s=o.replace(/[^A-Za-z0-9_ -]/g,"");return Vo[s]?Vo[s]:s.replace(/\s+/g,"_")}function Ci(o){return o?{english:"en",spanish:"es",french:"fr",german:"de",italian:"it",portuguese:"pt",dutch:"nl",russian:"ru",japanese:"ja",chinese:"zh",korean:"ko",arabic:"ar",hebrew:"he",hindi:"hi",turkish:"tr",polish:"pl",swedish:"sv",norwegian:"no",danish:"da",finnish:"fi",thai:"th",vietnamese:"vi",indonesian:"id",malay:"ms",farsi:"fa",persian:"fa",czech:"cs",greek:"el",romanian:"ro",hungarian:"hu",ukrainian:"uk",bengali:"bn",tamil:"ta",telugu:"te",urdu:"ur"}[o.toLowerCase()]??"en":"en"}var Pi=new Set(["ar","he","fa","ur"]);function Ai(o,s,e){let t=o.replace(/[\\"`$]/g,""),n=Ci(e),r=Pi.has(n)?`lang="${n}" dir="rtl"`:`lang="${n}"`,i=s?.fonts?.heading,l=s?.fonts?.body;if(!i&&!l)return`import type { Metadata } from "next";
|
|
2016
2016
|
import { DM_Sans } from "next/font/google";
|
|
2017
2017
|
import { Toaster } from "sonner";
|
|
2018
2018
|
import "./globals.css";
|
|
@@ -2028,7 +2028,7 @@ export default function RootLayout({ children }: { children: React.ReactNode })
|
|
|
2028
2028
|
</html>
|
|
2029
2029
|
);
|
|
2030
2030
|
}
|
|
2031
|
-
`;let c=
|
|
2031
|
+
`;let c=Yo(i??l),u=Yo(l??i);return c===u?`import type { Metadata } from "next";
|
|
2032
2032
|
import { ${c} } from "next/font/google";
|
|
2033
2033
|
import { Toaster } from "sonner";
|
|
2034
2034
|
import "./globals.css";
|
|
@@ -2061,38 +2061,38 @@ export default function RootLayout({ children }: { children: React.ReactNode })
|
|
|
2061
2061
|
</html>
|
|
2062
2062
|
);
|
|
2063
2063
|
}
|
|
2064
|
-
`}function
|
|
2065
|
-
`)}function
|
|
2064
|
+
`}function Ut(o,...s){let e=JSON.stringify(o).toLowerCase();return s.some(t=>e.includes(t.toLowerCase()))}var Ii={dashboard:"Home",home:"Home",overview:"Home",patient:"Users",member:"Users",user:"Users",people:"Users",team:"Users",client:"Users",contact:"Users",customer:"Users",appointment:"Calendar",schedule:"Calendar",booking:"Calendar",event:"Calendar",billing:"CreditCard",invoice:"CreditCard",payment:"CreditCard",pricing:"CreditCard",treatment:"ClipboardList",plan:"ClipboardList",task:"CheckSquare",exercise:"Dumbbell",workout:"Dumbbell",report:"BarChart3",analytics:"BarChart3",stats:"BarChart3",setting:"Settings",config:"Settings",profile:"User",account:"User",message:"MessageSquare",chat:"MessageSquare",inbox:"MessageSquare",product:"Package",item:"Package",catalog:"Package",order:"ShoppingCart",cart:"ShoppingCart",file:"FileText",document:"FileText",upload:"Upload",notification:"Bell",alert:"Bell",project:"FolderKanban",board:"FolderKanban",post:"PenSquare",blog:"PenSquare",article:"PenSquare",course:"GraduationCap",lesson:"GraduationCap",class:"GraduationCap",habit:"Target",goal:"Target",streak:"Flame",progress:"TrendingUp",feature:"Sparkles",subscription:"CreditCard",price:"CreditCard",recipe:"ChefHat",food:"UtensilsCrossed",meal:"UtensilsCrossed",pet:"PawPrint",animal:"PawPrint",music:"Music",playlist:"ListMusic",song:"Music",photo:"Image",image:"Image",gallery:"Images",video:"Video",movie:"Film",map:"MapPin",location:"MapPin",place:"MapPin",search:"Search",explore:"Compass",inventory:"Boxes",stock:"Boxes",warehouse:"Warehouse",review:"Star",rating:"Star",feedback:"Star",log:"ScrollText",history:"Clock",activity:"Activity"};function Ts(o){let s=o.toLowerCase().replace(/[^a-z]/g,"");for(let[e,t]of Object.entries(Ii))if(s.includes(e))return t;return"Circle"}function St(o){return o.split("-").map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" ")}function Ri(o){if(o.authModel==="none")return null;let s=["/login","/register","/forgot-password","/reset-password","/api/auth","/api/health","/api/webhooks","/api/admin/seed"];if(o.publicPages&&Array.isArray(o.publicPages))for(let a of o.publicPages){if(typeof a!="string"||a.length<1)continue;let r=a.replace(/[\u201C\u201D\u201E\u201F\u2018\u2019\u2033\u2036]/g,"").trim();if(!r)continue;let i=r.startsWith("/")?r:"/"+r;s.includes(i)||s.push(i)}let e=s.filter(a=>a==="/"),t=s.filter(a=>a!=="/"),n=[];n.push('import { NextRequest, NextResponse } from "next/server";'),n.push(""),n.push("const PUBLIC_PREFIXES = [");for(let a of t)n.push(' "'+a+'",');return n.push("];"),n.push(""),e.length>0&&(n.push('const PUBLIC_EXACT = ["'+e.join('", "')+'"];'),n.push("")),n.push("export function middleware(req: NextRequest) {"),n.push(" const { pathname, search } = req.nextUrl;"),n.push(""),e.length>0&&n.push(" if (PUBLIC_EXACT.includes(pathname)) return NextResponse.next();"),n.push(" if (PUBLIC_PREFIXES.some((p) => pathname.startsWith(p))) return NextResponse.next();"),n.push(""),n.push(' const token = req.cookies.get("better-auth.session_token")?.value || req.cookies.get("__Secure-better-auth.session_token")?.value;'),n.push(" if (!token) {"),n.push(' const loginUrl = new URL("/login", req.url);'),n.push(" const params = new URLSearchParams(search);"),n.push(' for (const key of ["verified", "error"]) {'),n.push(" const v = params.get(key);"),n.push(" if (v) loginUrl.searchParams.set(key, v);"),n.push(" }"),n.push(" return NextResponse.redirect(loginUrl);"),n.push(" }"),n.push(""),n.push(" return NextResponse.next();"),n.push("}"),n.push(""),n.push("export const config = {"),n.push(' matcher: ["/((?!_next|static|favicon\\\\.ico).*)"],'),n.push("};"),n.push(""),n.join(`
|
|
2065
|
+
`)}function Ei(o){if(o.navStyle==="none")return null;let s=["/api","/login","/register","/sign-in","/sign-up","/admin","/pricing","/about","/contact","/terms","/privacy","/onboarding","/join","/forgot-password","/reset-password"],t=(o.pages??[]).filter(l=>{let c=l.path??l.route??"";return c==="/"||c===""||c.includes("[")||c.replace(/^\//,"").split("/").length>1?!1:!s.some(m=>c.startsWith(m))}).map(l=>{let c=l.path??l.route??"",u=c.startsWith("/")?c:"/"+c,m=l.name??St(c.replace(/^\//,"")),p=Ts(m);return{label:m,href:u,icon:p}});t.some(l=>l.href==="/dashboard")||t.unshift({label:"Dashboard",href:"/dashboard",icon:"Home"});let n=o.authModel==="none",a=[...new Set(t.map(l=>l.icon))];n||a.push("LogOut");let r=St(o.name);if(o.navStyle==="topbar"){let l=[];l.push('"use client";'),l.push(""),l.push('import Link from "next/link";'),l.push('import { usePathname } from "next/navigation";'),n||l.push('import { authClient } from "@/lib/auth-client";'),l.push('import { Button } from "@/components/ui/button";'),l.push('import { cn } from "@/lib/utils";'),l.push("import { "+a.join(", ")+' } from "lucide-react";'),l.push(""),l.push("interface TopNavProps {"),l.push(" user: { name: string | null; email: string; role?: string | undefined };"),l.push("}"),l.push(""),l.push("const NAV_ITEMS = [");for(let c of t)l.push(' { label: "'+c.label+'", href: "'+c.href+'", icon: '+c.icon+" },");return l.push("];"),l.push(""),l.push("export default function TopNav({ user }: TopNavProps) {"),l.push(" const pathname = usePathname();"),l.push(""),l.push(" return ("),l.push(' <nav className="border-b bg-card">'),l.push(' <div className="mx-auto flex h-14 max-w-7xl items-center justify-between px-4">'),l.push(' <div className="flex items-center gap-6">'),l.push(' <span className="text-lg font-semibold">'+r+"</span>"),l.push(' <div className="flex items-center gap-1">'),l.push(" {NAV_ITEMS.map((item) => ("),l.push(" <Link"),l.push(" key={item.href}"),l.push(" href={item.href}"),l.push(' aria-current={pathname === item.href ? "page" : undefined}'),l.push(" className={cn("),l.push(' "flex items-center gap-1.5 rounded-md px-3 py-1.5 text-sm font-medium transition-colors",'),l.push(' pathname === item.href ? "bg-primary/10 text-primary" : "text-muted-foreground hover:text-foreground"'),l.push(" )}"),l.push(" >"),l.push(' <item.icon className="h-4 w-4" />'),l.push(" {item.label}"),l.push(" </Link>"),l.push(" ))}"),l.push(" </div>"),l.push(" </div>"),n?l.push(' <span className="text-sm text-muted-foreground">{user.name}</span>'):(l.push(' <div className="flex items-center gap-2">'),l.push(' <span className="text-sm text-muted-foreground">{user.email}</span>'),l.push(" <Button"),l.push(' variant="ghost"'),l.push(' size="sm"'),l.push(' onClick={() => authClient.signOut({ fetchOptions: { onSuccess: () => { window.location.href = "/login"; } } })}'),l.push(" >"),l.push(' <LogOut className="h-4 w-4" />'),l.push(" </Button>"),l.push(" </div>")),l.push(" </div>"),l.push(" </nav>"),l.push(" );"),l.push("}"),l.push(""),{path:"components/topnav.tsx",content:l.join(`
|
|
2066
2066
|
`)}}let i=[];i.push('"use client";'),i.push(""),i.push('import { useState } from "react";'),i.push('import Link from "next/link";'),i.push('import { usePathname } from "next/navigation";'),n||i.push('import { authClient } from "@/lib/auth-client";'),i.push('import { Button } from "@/components/ui/button";'),i.push('import { Sheet, SheetContent, SheetTrigger, SheetTitle } from "@/components/ui/sheet";'),i.push('import { cn } from "@/lib/utils";'),i.push("import { Menu, "+a.join(", ")+' } from "lucide-react";'),i.push(""),i.push("interface SidebarProps {"),i.push(" user: { name: string | null; email: string; role?: string | undefined };"),i.push("}"),i.push(""),i.push("const NAV_ITEMS = [");for(let l of t)i.push(' { label: "'+l.label+'", href: "'+l.href+'", icon: '+l.icon+" },");return i.push("];"),i.push(""),i.push('function NavContent({ pathname, user, onNavigate }: { pathname: string; user: SidebarProps["user"]; onNavigate?: () => void }) {'),i.push(" return ("),i.push(" <>"),i.push(' <div className="flex h-14 items-center border-b px-4">'),i.push(' <span className="text-lg font-semibold">'+r+"</span>"),i.push(" </div>"),i.push(' <nav className="flex-1 space-y-1 p-2">'),i.push(" {NAV_ITEMS.map((item) => ("),i.push(" <Link"),i.push(" key={item.href}"),i.push(" href={item.href}"),i.push(" onClick={onNavigate}"),i.push(' aria-current={pathname === item.href ? "page" : undefined}'),i.push(" className={cn("),i.push(' "flex items-center gap-3 rounded-md px-3 py-2.5 text-sm font-medium transition-colors",'),i.push(' pathname === item.href ? "bg-primary/10 text-primary" : "text-muted-foreground hover:bg-muted hover:text-foreground"'),i.push(" )}"),i.push(" >"),i.push(' <item.icon className="h-4 w-4" />'),i.push(" {item.label}"),i.push(" </Link>"),i.push(" ))}"),i.push(" </nav>"),i.push(' <div className="border-t p-4">'),i.push(' <div className="flex items-center gap-3">'),i.push(' <div className="flex-1 truncate">'),i.push(' <p className="truncate text-sm font-medium">{user.name ?? "User"}</p>'),i.push(' <p className="truncate text-xs text-muted-foreground">{user.email}</p>'),i.push(" </div>"),n||(i.push(" <Button"),i.push(' variant="ghost"'),i.push(' size="icon"'),i.push(' onClick={() => authClient.signOut({ fetchOptions: { onSuccess: () => { window.location.href = "/login"; } } })}'),i.push(" >"),i.push(' <LogOut className="h-4 w-4" />'),i.push(" </Button>")),i.push(" </div>"),i.push(" </div>"),i.push(" </>"),i.push(" );"),i.push("}"),i.push(""),i.push("export default function Sidebar({ user }: SidebarProps) {"),i.push(" const pathname = usePathname();"),i.push(" const [open, setOpen] = useState(false);"),i.push(""),i.push(" return ("),i.push(" <>"),i.push(' <aside className="hidden md:flex h-screen w-64 flex-col border-r bg-card">'),i.push(" <NavContent pathname={pathname} user={user} />"),i.push(" </aside>"),i.push(' <div className="sticky top-0 z-[var(--z-sticky)] flex h-14 items-center gap-3 border-b bg-card px-4 md:hidden">'),i.push(" <Sheet open={open} onOpenChange={setOpen}>"),i.push(" <SheetTrigger asChild>"),i.push(' <Button variant="ghost" size="icon" className="-ml-2">'),i.push(' <Menu className="h-5 w-5" />'),i.push(" </Button>"),i.push(" </SheetTrigger>"),i.push(' <SheetContent side="left" className="w-64 p-0">'),i.push(' <SheetTitle className="sr-only">Navigation</SheetTitle>'),i.push(' <div className="flex h-full flex-col">'),i.push(" <NavContent pathname={pathname} user={user} onNavigate={() => setOpen(false)} />"),i.push(" </div>"),i.push(" </SheetContent>"),i.push(" </Sheet>"),i.push(' <span className="text-lg font-semibold">'+r+"</span>"),i.push(" </div>"),i.push(" </>"),i.push(" );"),i.push("}"),i.push(""),{path:"components/sidebar.tsx",content:i.join(`
|
|
2067
|
-
`)}}function
|
|
2068
|
-
`)}function
|
|
2069
|
-
`)}let e=
|
|
2070
|
-
`)}if(e){let a=[];return a.push('import Link from "next/link";'),a.push(""),a.push("export default function HomePage() {"),a.push(" return ("),a.push(' <main className="flex min-h-screen flex-col items-center justify-center gap-6 p-8 text-center">'),a.push(' <h1 className="text-4xl font-bold">'+
|
|
2067
|
+
`)}}function Ni(o){if(!o.roles||o.roles.length===0)return null;let s=o.roles,e=o.defaultRole??s[0],t=[];t.push("export type Role = "+s.map(n=>'"'+n+'"').join(" | ")+";"),t.push(""),t.push("export const ROLES = ["+s.map(n=>'"'+n+'"').join(", ")+"] as const;"),t.push(""),t.push('export const DEFAULT_ROLE: Role = "'+e+'";'),t.push(""),t.push("export const ROLE_LABELS: Record<Role, string> = {");for(let n of s){let a=n.charAt(0).toUpperCase()+n.slice(1);t.push(' "'+n+'": "'+a+'",')}return t.push("};"),t.push(""),t.push("export function getUserRole(user: Record<string, unknown>): Role {"),t.push(" const role = (user.role as string) ?? DEFAULT_ROLE;"),t.push(" if (ROLES.includes(role as Role)) return role as Role;"),t.push(" return DEFAULT_ROLE;"),t.push("}"),t.push(""),t.push("export function hasRole(userRole: string | undefined, required: Role | Role[]): boolean {"),t.push(" if (!userRole) return false;"),t.push(" const allowed = Array.isArray(required) ? required : [required];"),t.push(" return allowed.includes(userRole as Role);"),t.push("}"),t.push(""),t.join(`
|
|
2068
|
+
`)}function _i(o){let s=St(o.name);if(o.authModel==="none"){let a=[];return a.push("export default function HomePage() {"),a.push(" return ("),a.push(' <main className="flex min-h-screen flex-col items-center justify-center p-8">'),a.push(' <h1 className="text-4xl font-bold">'+s+"</h1>"),o.summary&&a.push(' <p className="mt-4 text-lg text-muted-foreground">'+o.summary+"</p>"),a.push(" </main>"),a.push(" );"),a.push("}"),a.push(""),a.join(`
|
|
2069
|
+
`)}let e=o.publicPages?.includes("/"),t=o.design?.landingTone;if(e&&t){let a=[];return a.push('import Link from "next/link";'),a.push(""),a.push("export default function HomePage() {"),a.push(" return ("),a.push(' <main className="flex min-h-screen flex-col">'),a.push(' <section className="flex flex-1 flex-col items-center justify-center gap-6 px-4 py-24 text-center">'),a.push(' <h1 className="text-5xl font-bold tracking-tight">'+s+"</h1>"),o.summary&&a.push(' <p className="max-w-2xl text-xl text-muted-foreground">'+o.summary+"</p>"),a.push(' <div className="flex gap-4">'),a.push(' <Link href="/register" className="inline-flex h-11 items-center rounded-md bg-primary px-8 text-sm font-medium text-primary-foreground hover:bg-primary/90">'),a.push(" Get Started"),a.push(" </Link>"),a.push(' <Link href="/login" className="inline-flex h-11 items-center rounded-md border px-8 text-sm font-medium hover:bg-muted">'),a.push(" Sign In"),a.push(" </Link>"),a.push(" </div>"),a.push(" </section>"),a.push(" </main>"),a.push(" );"),a.push("}"),a.push(""),a.join(`
|
|
2070
|
+
`)}if(e){let a=[];return a.push('import Link from "next/link";'),a.push(""),a.push("export default function HomePage() {"),a.push(" return ("),a.push(' <main className="flex min-h-screen flex-col items-center justify-center gap-6 p-8 text-center">'),a.push(' <h1 className="text-4xl font-bold">'+s+"</h1>"),o.summary&&a.push(' <p className="text-lg text-muted-foreground">'+o.summary+"</p>"),a.push(' <Link href="/login" className="inline-flex h-10 items-center rounded-md bg-primary px-6 text-sm font-medium text-primary-foreground hover:bg-primary/90">'),a.push(" Sign In"),a.push(" </Link>"),a.push(" </main>"),a.push(" );"),a.push("}"),a.push(""),a.join(`
|
|
2071
2071
|
`)}let n=[];return n.push('import { headers } from "next/headers";'),n.push('import { redirect } from "next/navigation";'),n.push('import { auth } from "@/lib/auth";'),n.push(""),n.push("export default async function HomePage() {"),n.push(" const session = await auth.api.getSession({ headers: await headers() });"),n.push(' if (session) redirect("/dashboard");'),n.push(' redirect("/login");'),n.push("}"),n.push(""),n.join(`
|
|
2072
|
-
`)}function
|
|
2073
|
-
`)}function
|
|
2074
|
-
`)}function
|
|
2075
|
-
`)}function
|
|
2076
|
-
`)}function
|
|
2077
|
-
`)}function
|
|
2078
|
-
`)}async function
|
|
2072
|
+
`)}function Di(o,s){let e=o.authModel==="none",t=[];e||(t.push('import { Suspense } from "react";'),t.push('import { headers } from "next/headers";'),t.push('import { redirect } from "next/navigation";'),t.push('import { auth } from "@/lib/auth";'),t.push('import { VerifiedBanner } from "@/components/auth/verified-banner";')),o.navStyle==="topbar"?t.push('import TopNav from "@/components/topnav";'):o.navStyle!=="none"&&t.push('import Sidebar from "@/components/sidebar";'),!e&&o.roles&&o.roles.length>0&&t.push('import { getUserRole } from "@/lib/roles";'),t.push(""),t.push("export default async function DashboardLayout({ children }: { children: React.ReactNode }) {"),e?t.push(' const user = { name: "Guest", email: "" };'):(t.push(" const session = await auth.api.getSession({ headers: await headers() });"),t.push(' if (!session) redirect("/login");'),t.push(""),o.roles&&o.roles.length>0?(t.push(" const role = getUserRole(session.user as Record<string, unknown>);"),t.push(" const user = { name: session.user.name, email: session.user.email, role };")):(t.push(" const user = {"),t.push(" name: session.user.name,"),t.push(" email: session.user.email,"),t.push(" role: (session.user as Record<string, unknown>).role as string | undefined,"),t.push(" };"))),t.push("");let n=e?"":"<Suspense fallback={null}><VerifiedBanner /></Suspense>";return o.navStyle==="topbar"?(t.push(" return ("),t.push(' <div className="min-h-screen">'),t.push(" <TopNav user={user} />"),t.push(' <main className="mx-auto max-w-7xl p-6">'+n+"{children}</main>"),t.push(" </div>"),t.push(" );")):o.navStyle==="none"?(t.push(" return ("),t.push(' <div className="min-h-screen">'),t.push(' <main className="mx-auto max-w-5xl p-6">'+n+"{children}</main>"),t.push(" </div>"),t.push(" );")):(t.push(" return ("),t.push(' <div className="flex flex-col md:flex-row min-h-screen">'),t.push(" <Sidebar user={user} />"),t.push(' <main className="flex-1 overflow-x-hidden p-4 md:p-6">'+n+"{children}</main>"),t.push(" </div>"),t.push(" );")),t.push("}"),t.push(""),t.join(`
|
|
2073
|
+
`)}function Mi(o){let s=St(o.name),e=o.dataModel??[],t=[];if(e.length>0){let n=e.map(r=>Ts(r.entity??r.name??"item")),a=[...new Set(n)];t.push('import { Card, CardContent } from "@/components/ui/card";'),t.push("import { "+a.join(", ")+' } from "lucide-react";'),t.push("")}if(t.push("export default function DashboardPage() {"),t.push(" return ("),t.push(' <div className="space-y-6">'),t.push(" <div>"),t.push(' <h1 className="text-3xl font-bold">'+s+"</h1>"),o.summary&&t.push(' <p className="mt-1 text-muted-foreground">'+o.summary+"</p>"),t.push(" </div>"),e.length>0){t.push(' <div className="rounded-lg border p-8 text-center">'),t.push(' <h2 className="text-lg font-semibold">Get started</h2>'),t.push(` <p className="mt-1 text-sm text-muted-foreground">Here's what you can do</p>`),t.push(' <div className="mt-6 grid gap-3 sm:grid-cols-2 text-left">');for(let n of e){let a=n.entity??n.name??"Item",r=Ts(a),i=St(a.replace(/_/g,"-"));t.push(' <div className="flex items-center gap-3 rounded-md border p-3">'),t.push(" <"+r+' className="h-5 w-5 text-muted-foreground" />'),t.push(' <span className="text-sm font-medium">Add your first '+i+"</span>"),t.push(" </div>")}t.push(" </div>"),t.push(" </div>")}return t.push(" </div>"),t.push(" );"),t.push("}"),t.push(""),t.join(`
|
|
2074
|
+
`)}function $i(o,s=!1){if(!o.multiTenant)return null;let e=[];return s?(e.push('import { pgTable, text, timestamp, index } from "drizzle-orm/pg-core";'),e.push('import { user } from "./auth";'),e.push(""),e.push('export const organization = pgTable("organization", {'),e.push(' id: text("id").primaryKey(),'),e.push(' name: text("name").notNull(),'),e.push(' slug: text("slug").unique().notNull(),'),e.push(' createdAt: timestamp("created_at").defaultNow().notNull(),'),e.push(' updatedAt: timestamp("updated_at").defaultNow().notNull(),'),e.push("});"),e.push(""),e.push("export const orgMember = pgTable(")):(e.push('import { sqliteTable, text, index } from "drizzle-orm/sqlite-core";'),e.push('import { sql } from "drizzle-orm";'),e.push('import { user } from "./auth";'),e.push(""),e.push('export const organization = sqliteTable("organization", {'),e.push(' id: text("id").primaryKey(),'),e.push(' name: text("name").notNull(),'),e.push(' slug: text("slug").unique().notNull(),'),e.push(' createdAt: text("created_at").default(sql`CURRENT_TIMESTAMP`).notNull(),'),e.push(' updatedAt: text("updated_at").default(sql`CURRENT_TIMESTAMP`).notNull(),'),e.push("});"),e.push(""),e.push("export const orgMember = sqliteTable(")),e.push(' "org_member",'),e.push(" {"),e.push(' id: text("id").primaryKey(),'),e.push(' orgId: text("org_id").notNull().references(() => organization.id),'),e.push(' userId: text("user_id").notNull().references(() => user.id),'),e.push(' role: text("role").notNull(),'),s?e.push(' joinedAt: timestamp("joined_at").defaultNow().notNull(),'):e.push(' joinedAt: text("joined_at").default(sql`CURRENT_TIMESTAMP`).notNull(),'),e.push(" },"),e.push(" (table) => ({"),e.push(' orgIdx: index("org_member_org_idx").on(table.orgId),'),e.push(' userIdx: index("org_member_user_idx").on(table.userId),'),e.push(" }),"),e.push(");"),e.push(""),e.join(`
|
|
2075
|
+
`)}function ji(o){if(!o.multiTenant)return null;let s=[];return s.push('import { db } from "./db";'),s.push('import { organization, orgMember } from "@/db/schema/organization";'),s.push('import { eq } from "drizzle-orm";'),s.push(""),s.push("export async function getCurrentOrg(userId: string) {"),s.push(" const membership = await db"),s.push(" .select()"),s.push(" .from(orgMember)"),s.push(" .where(eq(orgMember.userId, userId))"),s.push(" .limit(1);"),s.push(" if (membership.length === 0) return null;"),s.push(" const org = await db"),s.push(" .select()"),s.push(" .from(organization)"),s.push(" .where(eq(organization.id, membership[0].orgId))"),s.push(" .limit(1);"),s.push(" return org[0] ?? null;"),s.push("}"),s.push(""),s.push("export async function getOrgMembers(orgId: string) {"),s.push(" return db"),s.push(" .select()"),s.push(" .from(orgMember)"),s.push(" .where(eq(orgMember.orgId, orgId));"),s.push("}"),s.push(""),s.push("export async function inviteToOrg(orgId: string, email: string, role: string) {"),s.push(" const id = crypto.randomUUID();"),s.push(" await db.insert(orgMember).values({"),s.push(" id,"),s.push(" orgId,"),s.push(" userId: email,"),s.push(" role,"),s.push(" });"),s.push(" return { id, orgId, email, role };"),s.push("}"),s.push(""),s.join(`
|
|
2076
|
+
`)}function Li(o){if(!o.multiTenant)return null;let s=[];return s.push('"use client";'),s.push(""),s.push("import {"),s.push(" DropdownMenu,"),s.push(" DropdownMenuContent,"),s.push(" DropdownMenuItem,"),s.push(" DropdownMenuTrigger,"),s.push('} from "@/components/ui/dropdown-menu";'),s.push('import { Button } from "@/components/ui/button";'),s.push('import { ChevronsUpDown } from "lucide-react";'),s.push(""),s.push("interface OrgSwitcherProps {"),s.push(" orgs: Array<{ id: string; name: string }>;"),s.push(" currentOrgId: string;"),s.push("}"),s.push(""),s.push("export default function OrgSwitcher({ orgs, currentOrgId }: OrgSwitcherProps) {"),s.push(" const currentOrg = orgs.find((o) => o.id === currentOrgId);"),s.push(""),s.push(" return ("),s.push(" <DropdownMenu>"),s.push(" <DropdownMenuTrigger asChild>"),s.push(' <Button variant="outline" className="w-full justify-between">'),s.push(' <span className="truncate">{currentOrg?.name ?? "Select org"}</span>'),s.push(' <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />'),s.push(" </Button>"),s.push(" </DropdownMenuTrigger>"),s.push(' <DropdownMenuContent className="w-56">'),s.push(" {orgs.map((org) => ("),s.push(" <DropdownMenuItem key={org.id}>"),s.push(" {org.name}"),s.push(" </DropdownMenuItem>"),s.push(" ))}"),s.push(" </DropdownMenuContent>"),s.push(" </DropdownMenu>"),s.push(" );"),s.push("}"),s.push(""),s.join(`
|
|
2077
|
+
`)}function Oi(o,s,e){let t=[],n=o.split("-").map(l=>l.charAt(0).toUpperCase()+l.slice(1)).join(" ");t.push(`# ${n}`),t.push(""),s?.summary&&(t.push(s.summary),t.push(""));let a=s?.features??[];if(a.length>0){t.push("## Features"),t.push("");for(let l of a){let c=l.description?` \u2014 ${l.description}`:"";t.push(`- **${l.name}**${c}`)}t.push("")}t.push("## Tech Stack"),t.push(""),t.push("| Layer | Technology |"),t.push("|-------|------------|"),t.push("| Framework | Next.js 15 (App Router) |"),t.push("| Database | Mistflow Cloud (Postgres) + Drizzle ORM |"),t.push("| Auth | Better Auth (email/password, social login) |"),t.push("| Styling | Tailwind CSS + shadcn/ui |"),t.push("| Deployment | Mistflow Cloud |"),e.hasStripe&&t.push("| Payments | Stripe |"),e.hasResend&&t.push("| Email | Resend + React Email |"),e.hasStorage&&t.push("| File Storage | Mistflow Cloud (managed blob storage) |"),e.hasAdmin&&t.push("| Admin | Better Auth admin plugin |"),e.hasAI&&t.push("| AI | Vercel AI SDK + OpenAI |"),t.push("");let r=s?.pages??[];if(r.length>0){t.push("## Pages"),t.push(""),t.push("| Route | Description |"),t.push("|-------|-------------|");for(let l of r){let c=l.path??l.route??l.name??"",u=l.description??"";t.push(`| \`${c.startsWith("/")?c:"/"+c}\` | ${u} |`)}t.push("")}let i=s?.dataModel??[];if(i.length>0){t.push("## Data Model"),t.push("");for(let l of i){let c=l.entity??l.name??"Unknown";if(t.push(`### ${c}`),t.push(""),l.fields.length>0){if(typeof l.fields[0]=="string")t.push(`Fields: ${l.fields.join(", ")}`);else{t.push("| Field | Type |"),t.push("|-------|------|");for(let u of l.fields)t.push(`| ${u.name} | ${u.type} |`)}t.push("")}}}return t.push("## Getting Started"),t.push(""),t.push("### Prerequisites"),t.push(""),t.push("- Node.js 20+"),t.push("- npm"),t.push(""),t.push("### Install"),t.push(""),t.push("Use the Mistflow CLI (recommended \u2014 streams output live and has no 60s tool-call timeout):"),t.push(""),t.push("```bash"),t.push("npx -y @mistflow-ai/cli install"),t.push("```"),t.push(""),t.push("Or plain npm if you prefer:"),t.push(""),t.push("```bash"),t.push("npm install"),t.push("```"),t.push(""),t.push("### Set up environment"),t.push(""),t.push("Copy `.env.example` to `.env.local` and fill in the values:"),t.push(""),t.push("```bash"),t.push("cp .env.example .env.local"),t.push("```"),t.push(""),t.push("| Variable | Description | Required |"),t.push("|----------|-------------|----------|"),e.isNeon?t.push("| `DATABASE_URL` | Postgres connection URL | Yes |"):(t.push("| `TURSO_URL` | Database connection URL | Yes |"),t.push("| `TURSO_AUTH_TOKEN` | Database auth token | Yes |")),t.push("| `AUTH_SECRET` | Auth encryption secret (auto-generated) | Yes |"),e.hasStripe&&(t.push("| `STRIPE_SECRET_KEY` | Stripe secret key | Yes |"),t.push("| `STRIPE_WEBHOOK_SECRET` | Stripe webhook signing secret | Yes |"),t.push("| `NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY` | Stripe publishable key | Yes |")),e.hasResend&&(t.push("| `RESEND_API_KEY` | Resend API key | Yes |"),t.push("| `EMAIL_FROM` | Sender email address | Yes (production) |")),e.hasStorage&&(t.push("| `MISTFLOW_API_KEY` | Mistflow API key for file storage | Yes |"),t.push("| `MISTFLOW_PROJECT_ID` | Mistflow project ID | Yes |")),e.hasAI&&t.push("| `OPENAI_API_KEY` | OpenAI API key | Yes |"),t.push(""),t.push("### Local database"),t.push(""),e.isNeon?(t.push("For local development, start a local Postgres server:"),t.push(""),t.push("```bash"),t.push("# Using Docker:"),t.push("docker run -d --name postgres -e POSTGRES_PASSWORD=postgres -p 5432:5432 postgres:17"),t.push("# Or install via Homebrew: brew install postgresql@17 && brew services start postgresql@17"),t.push("```")):(t.push("For local development, start a local Turso server:"),t.push(""),t.push("```bash"),t.push("npx turso dev"),t.push("```")),t.push(""),t.push("Then set up the database:"),t.push(""),t.push("```bash"),t.push("npm run db:push"),t.push("```"),t.push(""),t.push("### Run"),t.push(""),t.push("```bash"),t.push("npm run dev"),t.push("```"),t.push(""),t.push("Open [http://localhost:3000](http://localhost:3000)."),t.push(""),t.push("## Project Structure"),t.push(""),t.push("```"),t.push("app/"),t.push(" (auth)/ Login and registration pages"),t.push(" (dashboard)/ Authenticated app pages"),e.hasAdmin&&t.push(" (admin)/ Admin panel pages"),t.push(" api/ API routes (auth, health, webhooks)"),t.push(" layout.tsx Root layout with fonts and providers"),t.push(" globals.css Design tokens and Tailwind config"),t.push("components/ Reusable UI components"),t.push("db/"),t.push(" schema/ Database table definitions"),t.push(" index.ts Schema exports"),t.push("lib/"),t.push(" auth.ts Better Auth server config"),t.push(" auth-client.ts Better Auth client config"),t.push(` db.ts ${e.isNeon?"Postgres":"SQLite"} database connection`),e.hasStripe&&t.push(" stripe.ts Stripe client"),e.hasResend&&(t.push(" resend.ts Resend client"),t.push(" email.ts Email send helpers")),e.hasStorage&&t.push(" storage.ts File upload/download helpers"),e.hasAI&&t.push(" ai.ts AI client (Vercel AI SDK + OpenAI)"),e.hasResend&&t.push("emails/ React Email templates"),t.push("```"),t.push(""),t.push("## Deploy"),t.push(""),t.push("Deploy to production with Mistflow:"),t.push(""),t.push("```"),t.push("# In your AI editor (Claude Code, Cursor, etc.):"),t.push("mist_deploy action='deploy'"),t.push("```"),t.push(""),t.push("Your app will be live at `https://<app-name>.mistflow.app`."),t.push(""),s?.design&&(t.push("## Design"),t.push(""),s.design.tone&&t.push(`- **Tone**: ${s.design.tone}`),s.design.fonts&&(t.push(`- **Heading font**: ${s.design.fonts.heading}`),t.push(`- **Body font**: ${s.design.fonts.body}`)),s.design.accentColor&&t.push(`- **Accent color**: ${s.design.accentColor}`),s.design.borderRadius&&t.push(`- **Border radius**: ${s.design.borderRadius}`),t.push("")),t.push("---"),t.push(""),t.push("Built with [Mistflow](https://mistflow.ai)"),t.push(""),t.join(`
|
|
2078
|
+
`)}async function Xo(o,s){let{name:e,plan:t,path:n,planId:a}=o;if(!n)return d("mist_build init requires an explicit 'path' \u2014 the absolute directory where the project should be scaffolded. Pass the user's project directory (e.g. /Users/alice/projects/my-app). Do not rely on a default.",!0);if(!Cs(n))return d(`mist_build init 'path' must be an absolute path \u2014 received '${n}'. Pass the full absolute path to the target directory.`,!0);let r=qt(n),i=t?.design,l=t?.appStyle,c=t?Ut(t,"stripe","payment","billing","subscription","checkout","pricing"):!1,u=!0,m=t?Ut(t,"upload","file storage","image upload","profile picture","attachment","gallery","media","blob"):!1,p=t?Ut(t,"admin panel","admin dashboard","admin management"):!1,f=t?Ut(t,"ai integration","openai","llm","ai chat","chatbot","gpt"):!1,w=t,g=!0;if(!Qo(r))return d(`A project already exists at this location (${r}). Choose a different name, or delete the existing folder first. (A .mistflow/ folder left over from planning is fine \u2014 init will preserve it.)`,!0);Ft(r,{recursive:!0});try{let T=Z(kt(r),".mistflow","mockups");if(Me(T)){let A=Ko(T).filter(V=>V.endsWith(".html"));if(A.length>0){let V=Z(r,".mistflow","mockups");Ft(V,{recursive:!0});for(let U of A)fi(Z(T,U),Z(V,U));console.error(`Copied ${A.length} mockup file(s) into project`)}}}catch(T){console.error("Could not copy mockup files:",T instanceof Error?T.message:T)}let h=null;try{h=await Mt("nextjs")}catch(T){console.error("Could not fetch scaffold from API, using minimal scaffold:",T instanceof Error?T.message:T)}if(h){let T=e.toLowerCase().replace(/[^a-z0-9-]/g,"-");for(let I of h.files){if(I.path==="package.json"||I.path==="middleware.ts"||I.path==="components/sidebar.tsx"||I.path==="components/topnav.tsx"||I.path==="app/(dashboard)/layout.tsx"||I.path==="app/(dashboard)/page.tsx"||I.path==="app/(dashboard)/dashboard/page.tsx"||!c&&(I.path.includes("stripe")||I.path.includes("webhook/stripe"))||!u&&(I.path.includes("resend")||I.path.includes("emails/"))||!p&&(I.path.includes("(admin)")||I.path.includes("admin-sidebar"))||g&&(I.path==="lib/db.ts"||I.path==="lib/auth.ts"||I.path==="drizzle.config.ts"||I.path==="db/schema/auth.ts"))continue;let H=I.content.replace(/\{\{APP_NAME\}\}/g,e).replace(/\{\{WORKER_NAME\}\}/g,T);if(g&&I.path==="next.config.ts"&&(H=H.replace(/serverExternalPackages:\s*\[[^\]]*\],?/g,'serverExternalPackages: ["@electric-sql/pglite"],')),I.path==="next.config.ts"){let b=wi(r);b&&(console.error(`[init] Project is inside monorepo at ${b} \u2014 adding outputFileTracingRoot`),H.includes("outputFileTracingRoot")||(H=H.replace('import type { NextConfig } from "next";',`import type { NextConfig } from "next";
|
|
2079
2079
|
import { dirname } from "path";
|
|
2080
2080
|
import { fileURLToPath } from "url";
|
|
2081
2081
|
|
|
2082
2082
|
const __dirname = dirname(fileURLToPath(import.meta.url));`),H=H.replace("images: {",`outputFileTracingRoot: __dirname,
|
|
2083
|
-
images: {`)))}!p&&I.path.includes("sidebar")&&(H=H.replace(/\{user\.role === "admin"[\s\S]*?<\/Link>\s*\)\}/m,""),H=H.replace(/, Shield/g,"")),B(r,I.path,H)}let A={...h.dependencies},V={...h.devDependencies};if(A["drizzle-zod"]||(A["drizzle-zod"]="^0.5.1"),
|
|
2083
|
+
images: {`)))}!p&&I.path.includes("sidebar")&&(H=H.replace(/\{user\.role === "admin"[\s\S]*?<\/Link>\s*\)\}/m,""),H=H.replace(/, Shield/g,"")),B(r,I.path,H)}let A={...h.dependencies},V={...h.devDependencies};if(A["drizzle-zod"]||(A["drizzle-zod"]="^0.5.1"),g&&(delete A["@libsql/client"],A["@neondatabase/serverless"]="^0.10.0",V["@electric-sql/pglite"]="^0.2.0"),c&&(A.stripe="^17.0.0"),u&&(A.resend="^4.0.0",A["@react-email/components"]="^0.0.31"),f&&(A.ai="^4.0.0",A["@ai-sdk/openai"]="^1.0.0",A.openai="^4.0.0"),B(r,"package.json",JSON.stringify({name:e,version:"0.1.0",private:!0,scripts:{dev:"next dev",build:"next build",start:"next start",lint:"next lint","db:push":"drizzle-kit push","db:studio":"drizzle-kit studio"},dependencies:A,devDependencies:V,optionalDependencies:{"@noble/ciphers":"^1.3.0"},overrides:{react:"19.1.0","react-dom":"19.1.0",punycode:"^2.3.1"}},null,2)),h.methodology){let I=h.methodology;g&&(I=I.replace(/sqliteTable/g,"pgTable").replace(/drizzle-orm\/sqlite-core/g,"drizzle-orm/pg-core").replace(/Use `text` for dates \(SQLite stores dates as text\)/g,"Use `timestamp` for dates and `boolean` for booleans (native Postgres types)").replace(/text\("created_at"\)\.notNull\(\)\.default\(sql`\(CURRENT_TIMESTAMP\)`\)/g,'timestamp("created_at").notNull().defaultNow()').replace(/text\("updated_at"\)\.notNull\(\)\.default\(sql`\(CURRENT_TIMESTAMP\)`\)/g,'timestamp("updated_at").notNull().defaultNow()').replace(/import { sqliteTable, text, integer } from "drizzle-orm\/sqlite-core";\nimport { sql } from "drizzle-orm";/g,'import { pgTable, text, timestamp, boolean } from "drizzle-orm/pg-core";').replace(/`drizzle-kit push` for SQLite\/Turso/g,"`drizzle-kit push` for Postgres")),I=ks(I),B(r,"AGENTS.md",I),B(r,"CLAUDE.md",I)}let oe=t?.designMd;oe&&B(r,"DESIGN.md",oe),g&&(B(r,"lib/db.ts",['import { neon } from "@neondatabase/serverless";','import { drizzle as drizzleNeon } from "drizzle-orm/neon-http";',"","// eslint-disable-next-line @typescript-eslint/no-explicit-any","let _db: any = null;","","function getDb() {"," if (!_db) {",' if (process.env.DATABASE_URL && process.env.DATABASE_URL !== "pglite") {'," // Production / remote Postgres"," const sql = neon(process.env.DATABASE_URL);"," _db = drizzleNeon(sql);"," } else {"," // Local dev \u2014 PGlite (zero-install embedded Postgres). Lives in"," // lib/db-local.ts and is loaded through a runtime-only require"," // whose path is built from a variable, so esbuild's static"," // analysis can't follow it. Keeps pglite + its 30MB WASM out of"," // the Worker bundle.",' const localPath: string = "./" + "db-local";'," // eslint-disable-next-line @typescript-eslint/no-require-imports"," const { createLocalDb } = require(localPath);"," _db = createLocalDb();"," }"," }"," return _db;","}","","// Lazy proxy \u2014 DB isn't initialized at import/build time","// eslint-disable-next-line @typescript-eslint/no-explicit-any","export const db: any = new Proxy({} as any, {"," get(_target, prop, receiver) {"," const realDb = getDb();"," const value = Reflect.get(realDb, prop, receiver);",' if (typeof value === "function") {'," return value.bind(realDb);"," }"," return value;"," },","});",""].join(`
|
|
2084
2084
|
`)),B(r,"lib/db-local.ts",["// Local-dev-only DB factory. Isolated from lib/db.ts so the production","// Cloudflare Worker bundle never loads drizzle-orm/pglite or its","// transitive 30MB WASM binary. Loaded via runtime-only require() from","// db.ts, where the path is built from a variable to defeat static analysis.","",'const pglitePkg: string = ["@electric-sql", "pglite"].join("/");',"// eslint-disable-next-line @typescript-eslint/no-require-imports","const { PGlite } = require(pglitePkg);","",'const drizzlePath: string = "drizzle-orm/" + "pglite";',"// eslint-disable-next-line @typescript-eslint/no-require-imports","const { drizzle } = require(drizzlePath);","","// eslint-disable-next-line @typescript-eslint/no-explicit-any","export function createLocalDb(): any {",' const client = new PGlite("./local.pg");'," return drizzle(client);","}",""].join(`
|
|
2085
2085
|
`)),B(r,"drizzle.config.ts",['import { defineConfig } from "drizzle-kit";',"","// PGlite for local dev (no Postgres install needed), Mistflow Cloud for production",'const isPglite = !process.env.DATABASE_URL || process.env.DATABASE_URL === "pglite";',"","export default defineConfig({",' schema: "./db/schema",',' out: "./db/migrations",',' dialect: "postgresql",',' ...(isPglite ? { driver: "pglite", dbCredentials: { url: "./local.pg" } } : { dbCredentials: { url: process.env.DATABASE_URL! } }),',"});",""].join(`
|
|
2086
2086
|
`)),B(r,"db/schema/auth.ts",['import { pgTable, text, boolean, timestamp } from "drizzle-orm/pg-core";',"",'export const user = pgTable("user", {',' id: text("id").primaryKey(),',' name: text("name").notNull(),',' email: text("email").notNull().unique(),',' emailVerified: boolean("email_verified").notNull().default(false),',' image: text("image"),',' role: text("role").default("user"),',' banned: boolean("banned").default(false),',' banReason: text("ban_reason"),',' banExpires: timestamp("ban_expires"),',' createdAt: timestamp("created_at").notNull(),',' updatedAt: timestamp("updated_at").notNull(),',"});","",'export const session = pgTable("session", {',' id: text("id").primaryKey(),',' expiresAt: timestamp("expires_at").notNull(),',' token: text("token").notNull().unique(),',' createdAt: timestamp("created_at").notNull(),',' updatedAt: timestamp("updated_at").notNull(),',' ipAddress: text("ip_address"),',' userAgent: text("user_agent"),',' userId: text("user_id").notNull().references(() => user.id, { onDelete: "cascade" }),',' impersonatedBy: text("impersonated_by"),',"});","",'export const account = pgTable("account", {',' id: text("id").primaryKey(),',' accountId: text("account_id").notNull(),',' providerId: text("provider_id").notNull(),',' userId: text("user_id").notNull().references(() => user.id, { onDelete: "cascade" }),',' accessToken: text("access_token"),',' refreshToken: text("refresh_token"),',' idToken: text("id_token"),',' accessTokenExpiresAt: timestamp("access_token_expires_at"),',' refreshTokenExpiresAt: timestamp("refresh_token_expires_at"),',' scope: text("scope"),',' password: text("password"),',' createdAt: timestamp("created_at").notNull(),',' updatedAt: timestamp("updated_at").notNull(),',"});","",'export const verification = pgTable("verification", {',' id: text("id").primaryKey(),',' identifier: text("identifier").notNull(),',' value: text("value").notNull(),',' expiresAt: timestamp("expires_at").notNull(),',' createdAt: timestamp("created_at"),',' updatedAt: timestamp("updated_at"),',"});",""].join(`
|
|
2087
2087
|
`)),B(r,"lib/auth.ts",['import { betterAuth } from "better-auth";','import { drizzleAdapter } from "better-auth/adapters/drizzle";','import { admin } from "better-auth/plugins/admin";','import { nextCookies } from "better-auth/next-js";','import { db } from "./db";','import * as schema from "@/db";',"","async function sendEmail({ to, subject, html, fallbackUrl }: { to: string; subject: string; html: string; fallbackUrl?: string }) {"," const apiKey = process.env.RESEND_API_KEY;"," if (!apiKey) {"," if (fallbackUrl) {"," console.error(`\\n[auth] No RESEND_API_KEY set. Email to ${to} was not sent.`);"," console.error(`[auth] Dev fallback \u2014 use this link directly:\\n ${fallbackUrl}\\n`);"," } else {"," console.error(`[auth] RESEND_API_KEY not set \u2014 skipping email send to ${to}`);"," }"," return;"," }",' const from = process.env.EMAIL_FROM || "noreply@mail.mistflow.app";',' const res = await fetch("https://api.resend.com/emails", {',' method: "POST",',' headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },'," body: JSON.stringify({ from, to, subject, html }),"," });"," if (!res.ok) {",' const body = await res.text().catch(() => "unknown");'," console.error(`[auth] Email send failed (${res.status}): ${body}`);"," throw new Error(`Email send failed: ${res.status}`);"," }","}","","function createAuth() {",' const baseURL = process.env.BETTER_AUTH_URL || process.env.NEXT_PUBLIC_APP_URL || "http://localhost:3000";',' const isLocal = baseURL.includes("localhost") || baseURL.includes("127.0.0.1");'," const canSendEmail = Boolean(process.env.RESEND_API_KEY);"," // Refuse to boot a production app with email auth but no mail sender. Mistflow's"," // deploy pipeline injects a managed Resend key automatically; if it's missing,"," // that's a real misconfig and silent fallbacks let unverified users sign up."," if (!isLocal && !canSendEmail) {",` throw new Error("[auth] RESEND_API_KEY is required in production. The Mistflow deploy pipeline injects one automatically \u2014 if you're seeing this, check the project's env vars in the dashboard, or set your own RESEND_API_KEY.");`," }"," return betterAuth({"," baseURL,"," trustedOrigins: [baseURL],",' database: drizzleAdapter(db, { provider: "pg", schema }),'," emailAndPassword: {"," enabled: true,"," requireEmailVerification: !isLocal && canSendEmail,"," sendResetPassword: async ({ user, token }: { user: { email: string; name: string }; url: string; token: string }) => {"," // Better Auth's default reset URL points at /reset-password/:token (path),"," // which our frontend doesn't route. We build our own pointing at our"," // /reset-password?token=xxx page which reads the token from the query."," const resetUrl = `${baseURL}/reset-password?token=${token}`;"," await sendEmail({"," to: user.email,",' subject: "Reset your password",',' html: `<p>Hi ${user.name},</p><p>Click the link below to reset your password:</p><p><a href="${resetUrl}">${resetUrl}</a></p>`,'," fallbackUrl: isLocal ? resetUrl : undefined,"," });"," },"," },"," emailVerification: {"," sendOnSignUp: canSendEmail,"," autoSignInAfterVerification: true,"," sendVerificationEmail: async ({ user, url }: { user: { email: string; name: string }; url: string }) => {"," await sendEmail({"," to: user.email,",' subject: "Verify your email address",',' html: `<p>Hi ${user.name},</p><p>Click the link below to verify your email:</p><p><a href="${url}">${url}</a></p>`,'," fallbackUrl: isLocal ? url : undefined,"," });"," },"," },"," secret: process.env.AUTH_SECRET,",' plugins: [admin({ defaultRole: "user" }), nextCookies()],'," databaseHooks: {"," user: {"," create: {"," // Auto-promote the app owner to admin on first signup. ADMIN_EMAIL"," // is injected by the Mistflow deploy pipeline (the email of the"," // account that ran mist_deploy). Email verification still gates"," // login when Resend is configured, so a collision attempt can't"," // actually sign in without clicking a link delivered to the"," // owner's inbox."," before: async (user: { email?: string; [k: string]: unknown }) => {"," const adminEmail = process.env.ADMIN_EMAIL;"," if (adminEmail && user.email?.toLowerCase() === adminEmail.toLowerCase()) {",' return { data: { ...user, role: "admin" } };'," }"," return { data: user };"," },"," },"," },"," },"," socialProviders: {"," ...(process.env.GOOGLE_CLIENT_ID ? {"," google: {"," clientId: process.env.GOOGLE_CLIENT_ID,"," clientSecret: process.env.GOOGLE_CLIENT_SECRET!,"," },"," } : {}),"," ...(process.env.GITHUB_CLIENT_ID ? {"," github: {"," clientId: process.env.GITHUB_CLIENT_ID,"," clientSecret: process.env.GITHUB_CLIENT_SECRET!,"," },"," } : {}),"," },"," });","}","","// Lazy init \u2014 process.env isn't populated at module scope on Cloudflare Workers.","// The `has` trap is required: better-auth's toNextJsHandler does",'// `"handler" in auth ? auth.handler(request) : auth(request)` \u2014 without a `has`',"// trap the default forwards to the empty target object, returns false, and the","// handler tries to call the Proxy as a function, which throws TypeError and","// returns 500 on every /api/auth/* request.","let _auth: ReturnType<typeof createAuth> | null = null;","export const auth = new Proxy({} as ReturnType<typeof createAuth>, {"," get(_target, prop, receiver) {"," if (!_auth) _auth = createAuth();"," const value = Reflect.get(_auth, prop, receiver);",' if (typeof value === "function") return value.bind(_auth);'," return value;"," },"," has(_target, prop) {"," if (!_auth) _auth = createAuth();"," return prop in _auth;"," },","});",""].join(`
|
|
2088
|
-
`)))}else B(r,"package.json",JSON.stringify({name:e,version:"0.1.0",private:!0},null,2));let v=t?.designMd;B(r,"app/globals.css",
|
|
2088
|
+
`)))}else B(r,"package.json",JSON.stringify({name:e,version:"0.1.0",private:!0},null,2));let v=t?.designMd;B(r,"app/globals.css",Ti(i,l,v)),B(r,"app/layout.tsx",Ai(e,i,w?.language)),B(r,"README.md",Oi(e,t,{hasStripe:c,hasResend:u,hasStorage:m,hasAdmin:p,hasAI:f,isNeon:g})),B(r,"contracts/README.md",vs());let E=t?.dataModel??[],R=new Set,C=0;for(let T of E){let A=T.entity??T.name;if(!A||typeof A!="string")continue;let V=Ss(A);R.has(V)||(R.add(V),B(r,V,xs(A)),C++)}C===0&&B(r,"contracts/.gitkeep","");let P=[],j=t?.publicPages;if(Array.isArray(j))P=j;else if(typeof j=="string"){try{P=JSON.parse(j)}catch{P=[]}Array.isArray(P)||(P=[])}if(!P.includes("/")){let T=t?.steps?.some(V=>{let U=((V.name??"")+" "+(V.description??"")).toLowerCase();return U.includes("landing")||U.includes("marketing")||U.includes("homepage")}),A=t?.pages?.some(V=>V.path==="/");(T||A)&&(P=["/",...P])}let S={name:e,summary:t?.summary,authModel:t?.authModel,roles:t?.roles,defaultRole:t?.defaultRole,publicPages:P,navStyle:t?.navStyle,multiTenant:t?.multiTenant,pages:t?.pages,dataModel:t?.dataModel,design:t?.design},z=Ri(S);z&&B(r,"middleware.ts",z);let Y=Ei(S);Y&&B(r,Y.path,Y.content);let G=Ni(S);if(G&&B(r,"lib/roles.ts",G),B(r,"app/page.tsx",_i(S)),B(r,"app/(dashboard)/layout.tsx",Di(S,p)),B(r,"app/(dashboard)/dashboard/page.tsx",Mi(S)),S.multiTenant){let T=$i(S,g);T&&B(r,"db/schema/organization.ts",T);let A=ji(S);A&&B(r,"lib/org.ts",A);let V=Li(S);V&&B(r,"components/org-switcher.tsx",V)}B(r,"tsconfig.json",JSON.stringify({compilerOptions:{target:"ES2017",lib:["dom","dom.iterable","esnext"],allowJs:!0,skipLibCheck:!0,strict:!1,noEmit:!0,esModuleInterop:!0,module:"esnext",moduleResolution:"bundler",resolveJsonModule:!0,isolatedModules:!0,jsx:"preserve",incremental:!0,plugins:[{name:"next"}],paths:{"@/*":["./*"]}},include:["next-env.d.ts","**/*.ts","**/*.tsx",".next/types/**/*.ts"],exclude:["node_modules"]},null,2)),c&&B(r,"lib/stripe.ts",['import Stripe from "stripe";',"","let _stripe: Stripe | null = null;","","function getStripe(): Stripe {"," if (!_stripe) {"," if (!process.env.STRIPE_SECRET_KEY) {",' throw new Error("STRIPE_SECRET_KEY is not set");'," }"," _stripe = new Stripe(process.env.STRIPE_SECRET_KEY, {"," typescript: true,"," });"," }"," return _stripe;","}","","// Lazy proxy \u2014 Stripe isn't initialized at import/build time","export const stripe = new Proxy({} as Stripe, {"," get(_target, prop) {"," return (getStripe() as unknown as Record<string | symbol, unknown>)[prop];"," },","});",""].join(`
|
|
2089
2089
|
`)),u&&(B(r,"lib/resend.ts",['import { Resend } from "resend";',"","let _resend: Resend | null = null;","","function getResend(): Resend {"," if (!_resend) {"," if (!process.env.RESEND_API_KEY) {",' throw new Error("RESEND_API_KEY is not set");'," }"," _resend = new Resend(process.env.RESEND_API_KEY);"," }"," return _resend;","}","","// Lazy proxy \u2014 Resend isn't initialized at import/build time","export const resend = new Proxy({} as Resend, {"," get(_target, prop) {"," return (getResend() as unknown as Record<string | symbol, unknown>)[prop];"," },","});",""].join(`
|
|
2090
2090
|
`)),B(r,"lib/email.ts",['import { resend } from "./resend";',"",'const FROM = process.env.EMAIL_FROM ?? "onboarding@resend.dev";',"","export async function sendEmail({"," to,"," subject,"," react,","}: {"," to: string;"," subject: string;"," react: React.ReactElement;","}) {"," return resend.emails.send({ from: FROM, to, subject, react });","}",""].join(`
|
|
2091
2091
|
`))),m&&(B(r,"lib/storage.ts",['const MISTFLOW_API = process.env.MISTFLOW_API_URL ?? "https://api.mistflow.ai";',"const MISTFLOW_API_KEY = process.env.MISTFLOW_API_KEY;","const PROJECT_ID = process.env.MISTFLOW_PROJECT_ID;","","interface UploadResult {"," upload_url: string;"," download_url: string;"," key: string;","}","","function authHeaders(): Record<string, string> {"," return {",' "Content-Type": "application/json",',' "Authorization": `ApiKey ${MISTFLOW_API_KEY}`,'," };","}","",'export async function getUploadUrl(filename: string, contentType: string = "application/octet-stream"): Promise<UploadResult> {'," const res = await fetch(`${MISTFLOW_API}/api/storage/upload-url`, {",' method: "POST",'," headers: authHeaders(),"," body: JSON.stringify({ project_id: PROJECT_ID, filename, content_type: contentType }),"," });"," if (!res.ok) throw new Error(`Storage error: ${res.status}`);"," return res.json();","}","","export async function getDownloadUrl(filename: string): Promise<string> {"," const res = await fetch(`${MISTFLOW_API}/api/storage/download-url`, {",' method: "POST",'," headers: authHeaders(),"," body: JSON.stringify({ project_id: PROJECT_ID, filename }),"," });"," if (!res.ok) throw new Error(`Storage error: ${res.status}`);"," const data = await res.json();"," return data.download_url;","}","","export async function deleteFile(filename: string): Promise<void> {"," await fetch(`${MISTFLOW_API}/api/storage/delete`, {",' method: "POST",'," headers: authHeaders(),"," body: JSON.stringify({ project_id: PROJECT_ID, filename }),"," });","}","","export async function uploadFile(file: File): Promise<string> {"," const { upload_url, download_url } = await getUploadUrl(file.name, file.type);",' await fetch(upload_url, { method: "PUT", body: file, headers: { "Content-Type": file.type } });'," return download_url;","}",""].join(`
|
|
2092
2092
|
`)),B(r,"app/api/upload/route.ts",['import { NextRequest, NextResponse } from "next/server";','import { getUploadUrl } from "@/lib/storage";',"","export async function POST(req: NextRequest) {"," const { filename, contentType } = await req.json();"," if (!filename) {",' return NextResponse.json({ error: "filename is required" }, { status: 400 });'," }"," try {",' const result = await getUploadUrl(filename, contentType ?? "application/octet-stream");'," return NextResponse.json(result);"," } catch {",' return NextResponse.json({ error: "Failed to get upload URL" }, { status: 500 });'," }","}",""].join(`
|
|
2093
|
-
`))),
|
|
2093
|
+
`))),f&&(B(r,"lib/ai.ts",['import { createOpenAI } from "@ai-sdk/openai";',"","export const openai = createOpenAI({"," apiKey: process.env.OPENAI_API_KEY,","});",""].join(`
|
|
2094
2094
|
`)),B(r,"app/api/chat/route.ts",['import { openai } from "@/lib/ai";','import { streamText } from "ai";',"","export async function POST(req: Request) {"," const { messages } = await req.json();",""," const result = streamText({",' model: openai("gpt-4o"),'," messages,"," });",""," return result.toDataStreamResponse();","}",""].join(`
|
|
2095
|
-
`)));let W={name:e,methodologyVersion:h?.version??"1.0",createdAt:new Date().toISOString(),...a?{planId:a}:{},plan:Array.isArray(t?.steps)?{...t,steps:t.steps.map(T=>({number:T.number,name:T.name??T.title,description:T.description,entities:T.entities,pages:T.pages,features:T.features,status:"pending"}))}:t,dbProvider:"neon",env:{managed:{DATABASE_URL:{description:"Postgres connection URL",scope:"production"},AUTH_SECRET:{description:"Auth encryption secret",scope:"production"},...c?{STRIPE_SECRET_KEY:{description:"Stripe secret key",scope:"production"},STRIPE_WEBHOOK_SECRET:{description:"Stripe webhook signing secret",scope:"production"},NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY:{description:"Stripe publishable key",scope:"production"}}:{},...u?{RESEND_API_KEY:{description:"Resend API key \u2014 managed by Mistflow by default, override with your own key from resend.com",scope:"production"},EMAIL_FROM:{description:"Sender email address \u2014 managed by Mistflow by default",scope:"production"}}:{},...m?{MISTFLOW_API_KEY:{description:"Mistflow API key for file storage",scope:"production"},MISTFLOW_PROJECT_ID:{description:"Mistflow project ID",scope:"production"}}:{}},...
|
|
2095
|
+
`)));let W={name:e,methodologyVersion:h?.version??"1.0",createdAt:new Date().toISOString(),...a?{planId:a}:{},plan:Array.isArray(t?.steps)?{...t,steps:t.steps.map(T=>({number:T.number,name:T.name??T.title,description:T.description,entities:T.entities,pages:T.pages,features:T.features,status:"pending"}))}:t,dbProvider:"neon",env:{managed:{DATABASE_URL:{description:"Postgres connection URL",scope:"production"},AUTH_SECRET:{description:"Auth encryption secret",scope:"production"},...c?{STRIPE_SECRET_KEY:{description:"Stripe secret key",scope:"production"},STRIPE_WEBHOOK_SECRET:{description:"Stripe webhook signing secret",scope:"production"},NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY:{description:"Stripe publishable key",scope:"production"}}:{},...u?{RESEND_API_KEY:{description:"Resend API key \u2014 managed by Mistflow by default, override with your own key from resend.com",scope:"production"},EMAIL_FROM:{description:"Sender email address \u2014 managed by Mistflow by default",scope:"production"}}:{},...m?{MISTFLOW_API_KEY:{description:"Mistflow API key for file storage",scope:"production"},MISTFLOW_PROJECT_ID:{description:"Mistflow project ID",scope:"production"}}:{}},...f?{required:{OPENAI_API_KEY:{description:"OpenAI API key",setupUrl:"https://platform.openai.com/api-keys"}}}:{}},authModel:t?.authModel??"email",roles:t?.roles??null,navStyle:t?.navStyle??"sidebar",multiTenant:t?.multiTenant??!1,hasAdmin:p,hasResend:u,hasStorage:m,hasAI:f,deploy:null};B(r,"mistflow.json",JSON.stringify(W,null,2));let _=bi(32).toString("hex"),ee=c?`
|
|
2096
2096
|
# Stripe
|
|
2097
2097
|
STRIPE_SECRET_KEY=
|
|
2098
2098
|
STRIPE_WEBHOOK_SECRET=
|
|
@@ -2105,7 +2105,7 @@ EMAIL_FROM=onboarding@resend.dev
|
|
|
2105
2105
|
# File Storage (Mistflow managed)
|
|
2106
2106
|
MISTFLOW_API_KEY=
|
|
2107
2107
|
MISTFLOW_PROJECT_ID=
|
|
2108
|
-
`:"",F=
|
|
2108
|
+
`:"",F=f?`
|
|
2109
2109
|
# AI (get your key at https://platform.openai.com/api-keys)
|
|
2110
2110
|
OPENAI_API_KEY=
|
|
2111
2111
|
`:"",ie=`# Local dev: PGlite is used automatically (zero-install embedded Postgres)
|
|
@@ -2116,14 +2116,14 @@ OPENAI_API_KEY=
|
|
|
2116
2116
|
AUTH_SECRET=${_}
|
|
2117
2117
|
${ee}${J}${q}${F}`),B(r,".env.example",`${le}
|
|
2118
2118
|
AUTH_SECRET=your-secret-here
|
|
2119
|
-
${ee}${J}${q}${F}`);let K=[],me=(T,A)=>{K.push({phase:T,message:A})},x=(T,A)=>{let V=K.find(U=>U.phase===T&&!U.durationMs);V&&(V.durationMs=A)};if(
|
|
2120
|
-
${
|
|
2119
|
+
${ee}${J}${q}${F}`);let K=[],me=(T,A)=>{K.push({phase:T,message:A})},x=(T,A)=>{let V=K.find(U=>U.phase===T&&!U.durationMs);V&&(V.durationMs=A)};if(s){let T=Je(s.server,s.progressToken,()=>K[K.length-1]?.message??"Setting up project...");s.cleanup=()=>T.stop()}let D=w?.requestedSubdomain||void 0,M,y;me("register","Registering project on Mistflow...");let N=Date.now();try{let T=await Xs(e,void 0,"neon",D);M=T.id;let A=Z(r,"mistflow.json"),V=JSON.parse(Bt(A,"utf-8"));if(V.projectId=M,Be(A,JSON.stringify(V,null,2)),ds(r,ps(M,e)),T.managed_env&&Object.keys(T.managed_env).length>0){let U=Z(r,".env.local"),xe=Me(U)?Bt(U,"utf-8"):"";for(let[oe,I]of Object.entries(T.managed_env)){let H=new RegExp(`^${oe}=.*$`,"m");H.test(xe)?xe=xe.replace(H,`${oe}=${I}`):xe+=`
|
|
2120
|
+
${oe}=${I}`}Be(U,xe)}try{let{getBaseUrl:U,getAuthHeaders:xe}=await import("./api-client-RCNDMCPS.js"),oe=xe(),I=t?.features,H=t?.steps,b={};Array.isArray(I)&&I.length>0&&(b.features=I.map(k=>k.name)),t&&(b.plan=t),Array.isArray(H)&&H.length>0&&(b.provenance=H.map(k=>({feature:k.name??k.title??`Step ${k.number??"?"}`,user_intent:(k.description??"").slice(0,500),decisions:"Seeded from plan at init",tradeoffs:"",files_affected:[]}))),Object.keys(b).length>0&&await fetch(`${U()}/api/projects/${encodeURIComponent(M)}/state`,{method:"PUT",headers:{...oe,"Content-Type":"application/json"},body:JSON.stringify(b)})}catch{}K[K.length-1].message=`Registered as ${M.slice(0,8)}`}catch(T){let A=T instanceof Error?T.message:String(T);console.error("Could not register project on backend:",A),y=`Project created locally but NOT registered on Mistflow servers (${A}). Deploy will auto-register it.`,K[K.length-1].message="Registration skipped (offline \u2014 deploy will retry)"}x("register",Date.now()-N),me("git","Initializing git repository...");let te=Date.now();try{let T=Jo(r);await T.init(),await T.add("."),await T.commit("Initial Mistflow project setup"),K[K.length-1].message="Git repository initialized"}catch{console.error("Git initialization failed, continuing without git."),K[K.length-1].message="Git init skipped"}x("git",Date.now()-te);let De=K.reduce((T,A)=>T+(A.durationMs??0),0),ae={projectPath:r,projectId:M,status:"awaiting_install"},Ce=K.map(T=>{let A=T.durationMs?` (${(T.durationMs/1e3).toFixed(1)}s)`:"";return`${T.message}${A}`});ae.progress=Ce,ae.totalSetupTime=`${(De/1e3).toFixed(1)}s`;let pe=[];M||pe.push("Project was not registered with Mistflow (not signed in). Run mist_setup to sign in BEFORE deploying \u2014 deploy will fail without it."),y&&(ae.registrationWarning=y),pe.length>0&&(ae.warnings=pe);let Ie=`NEXT: Run \`npx -y @mistflow-ai/cli install ${r}\` via your shell/bash tool \u2014 NOT via the mist_build MCP tool. The CLI streams npm output live and has no MCP 60s timeout; the MCP install action can hit -32001 timeout on slow installs. Do NOT ask the user for permission \u2014 install is a required follow-up to init, not a decision point. If your environment can't run the CLI, fall back to mist_build action='install' projectPath='${r}'. After install finishes, call mist_build action='implement' to build the first plan step \u2014 also without asking.`;return ae.nextAction=M?Ie:`${Ie} IMPORTANT: You MUST also run mist_setup to sign in before deploying \u2014 the project could not be registered because auth is missing.`,d(JSON.stringify(ae))}async function Zo(o,s){let{projectPath:e}=o;if(!e)return d("mist_build install requires 'projectPath' \u2014 the absolute path to the project that was just initialized. The value is returned as `projectPath` in the mist_build init response.",!0);if(!Cs(e))return d(`mist_build install 'projectPath' must be an absolute path \u2014 received '${e}'.`,!0);let t=qt(e);if(!Me(Z(t,"package.json")))return d(`No package.json found at ${t}. Run mist_build init first to scaffold the project.`,!0);if(Me(Z(t,"node_modules")))return d(JSON.stringify({status:"already_installed",projectPath:t,nextAction:"node_modules already exists. Call mist_build with action='implement' to start building the first plan step."}));let n="Installing packages...";if(s){let u=Je(s.server,s.progressToken,()=>n);s.cleanup=()=>u.stop()}let a={NPM_CONFIG_LEGACY_PEER_DEPS:"true"},r=Date.now(),i=0,l=await xt("npm",["install"],t,12e4,u=>{let m=u.match(/added (\d+) packages/);m&&(i=parseInt(m[1],10))},a);if(l.success||(console.error("[install] npm install failed, retrying..."),n="Install failed, retrying...",l=await xt("npm",["install"],t,12e4,u=>{let m=u.match(/added (\d+) packages/);m&&(i=parseInt(m[1],10))},a)),!l.success)return d(`npm install failed after 2 attempts at ${t}: ${l.error}. Run "npm install" manually in that directory, then call mist_build implement.`,!0);let c=((Date.now()-r)/1e3).toFixed(1);return d(JSON.stringify({status:"installed",projectPath:t,packagesInstalled:i||null,durationSec:c,nextAction:"NEXT: Call mist_build with action='implement' to start building the first plan step. Do this immediately \u2014 do NOT start a dev server or suggest localhost."}))}async function er(o){let{name:s,plan:e,projectId:t,sourceDeploymentId:n,forkToken:a,requiredEnvVars:r,dbProvider:i,planId:l}=o;if(!o.path)return d("mist_build init requires an explicit 'path' \u2014 the absolute directory where the forked project should be scaffolded. Pass the user's project directory (e.g. /Users/alice/projects/my-app). Do not rely on a default.",!0);if(!Cs(o.path))return d(`mist_build init 'path' must be an absolute path \u2014 received '${o.path}'. Pass the full absolute path to the target directory.`,!0);let c=qt(o.path);if(!Qo(c))return d(`A project already exists at this location (${c}). Choose a different name, or delete the existing folder first. (A .mistflow/ folder left over from planning is fine \u2014 init will preserve it.)`,!0);let{mkdtempSync:u,renameSync:m,rmSync:p,cpSync:f}=await import("fs"),{tmpdir:w}=await import("os"),g=u(Z(w(),"mistflow-fork-")),h=Z(g,"project");Ft(h,{recursive:!0});let v=[],E=(C,P)=>v.push({phase:C,message:P}),R=(C,P)=>{let j=v.find(S=>S.phase===C);j&&(j.durationMs=P)};try{E("download","Downloading source code from template...");let C=Date.now(),P=Z(g,"source.tar.gz");try{await ko(n,a,P)}catch(y){p(g,{recursive:!0,force:!0});let N=y instanceof Error?y.message:"Source download failed";return d(`Source code download failed: ${N}. You can still build from the plan \u2014 run mist_build init without the source (omit planId and pass the plan directly).`,!0)}R("download",Date.now()-C),v[v.length-1].message="Source code downloaded",E("extract","Extracting source code...");let j=Date.now(),S=await xt("tar",["-xzf",P,"-C",h,"--exclude","node_modules","--exclude",".git"],h,6e4);if(!S.success)return p(g,{recursive:!0,force:!0}),d(`Failed to extract source archive: ${S.error}`,!0);if(R("extract",Date.now()-j),!Me(Z(h,"package.json")))return p(g,{recursive:!0,force:!0}),d("Source archive does not contain a package.json. The template may be corrupted.",!0);let z=[".mistflow",".env.local",".env.example","local.db","local.pg"];for(let y of z){let N=Z(h,y);Me(N)&&p(N,{recursive:!0,force:!0})}let Y={name:s,projectId:t,template:"nextjs",createdAt:new Date().toISOString(),planId:l??void 0,plan:e,dbProvider:i};Be(Z(h,"mistflow.json"),JSON.stringify(Y,null,2));let G=r.map(y=>{let N=y.description?`# ${y.description}`:`# ${y.key}`,te=y.setup_url?` (${y.setup_url})`:"";return`${N}${te}
|
|
2121
2121
|
${y.key}=`});Be(Z(h,".env.local"),G.join(`
|
|
2122
2122
|
|
|
2123
2123
|
`)+`
|
|
2124
2124
|
`);let W=r.map(y=>`${y.key}=`);Be(Z(h,".env.example"),W.join(`
|
|
2125
2125
|
`)+`
|
|
2126
|
-
`),Be(Z(h,"README.md"),`# ${
|
|
2126
|
+
`),Be(Z(h,"README.md"),`# ${s}
|
|
2127
2127
|
|
|
2128
2128
|
Forked from a Mistflow template. Built with Next.js, Drizzle ORM, and Better Auth.
|
|
2129
2129
|
|
|
@@ -2132,11 +2132,11 @@ Forked from a Mistflow template. Built with Next.js, Drizzle ORM, and Better Aut
|
|
|
2132
2132
|
1. Copy \`.env.example\` to \`.env.local\` and fill in your values
|
|
2133
2133
|
2. Run \`npm run dev\`
|
|
2134
2134
|
3. Deploy with \`mist_deploy\`
|
|
2135
|
-
`),E("setup","Setting up project directory...");let _=Date.now();try{m(h,c)}catch(y){if(y.code==="EXDEV")
|
|
2135
|
+
`),E("setup","Setting up project directory...");let _=Date.now();try{m(h,c)}catch(y){if(y.code==="EXDEV")f(h,c,{recursive:!0}),p(h,{recursive:!0,force:!0});else throw y}R("setup",Date.now()-_),E("install","Installing packages...");let ee=Date.now(),J=0,q=await xt("npm",["install"],c,12e4,y=>{let N=y.match(/added (\d+) packages/);N&&(J=parseInt(N[1],10))});if(q.success||(console.error("[initFromSource] npm install failed, retrying..."),q=await xt("npm",["install"],c,12e4,y=>{let N=y.match(/added (\d+) packages/);N&&(J=parseInt(N[1],10))})),!q.success)return d(`Source code was restored at ${c} but package installation failed: ${q.error}. Run "npm install" manually.`,!0);R("install",Date.now()-ee),v[v.length-1].message=`Installed ${J||"all"} packages`,E("git","Initializing git repository...");let F=Date.now();try{let y=Jo(c);await y.init(),await y.add("."),await y.commit("Forked from Mistflow template"),v[v.length-1].message="Git repository initialized"}catch{console.error("Git initialization failed, continuing without git."),v[v.length-1].message="Git init skipped"}R("git",Date.now()-F);try{let{markLocalSetupDone:y}=await import("./api-client-RCNDMCPS.js");await y(t)}catch{console.error("[initFromSource] Could not mark local_setup_done on backend, continuing.")}let ie=JSON.parse(Bt(Z(c,"mistflow.json"),"utf-8"));ie.projectId=t,Be(Z(c,"mistflow.json"),JSON.stringify(ie,null,2)),ds(c,ps(t,s));let le=e.steps,K=le?.filter(y=>y.status==="completed").length??0,me=le?.filter(y=>y.status==="pending").length??0,x=le?.length??0,D=r.length>0?`
|
|
2136
2136
|
|
|
2137
2137
|
Environment variables needed:
|
|
2138
2138
|
`+r.map(y=>` \u2022 ${y.key}${y.description?` \u2014 ${y.description}`:""}`).join(`
|
|
2139
|
-
`):"",M=me>0?`Source code restored with ${K}/${x} steps complete. ${me} steps need implementation \u2014 call mist_build with action='implement' to apply your changes.`:`Source code fully restored (${x} steps complete). Configure your .env.local, then deploy with mist_deploy.`;return d(JSON.stringify({status:"success",projectPath:c,projectId:t,planStepsCompleted:K,planStepsTotal:x,pendingSteps:me,progress:v,nextAction:M+D}))}finally{try{p(
|
|
2139
|
+
`):"",M=me>0?`Source code restored with ${K}/${x} steps complete. ${me} steps need implementation \u2014 call mist_build with action='implement' to apply your changes.`:`Source code fully restored (${x} steps complete). Configure your .env.local, then deploy with mist_deploy.`;return d(JSON.stringify({status:"success",projectPath:c,projectId:t,planStepsCompleted:K,planStepsTotal:x,pendingSteps:me,progress:v,nextAction:M+D}))}finally{try{p(g,{recursive:!0,force:!0})}catch{}}}import{z as Rs}from"zod";import{existsSync as Tt,readFileSync as Ns,writeFileSync as Es,mkdirSync as da}from"fs";import{join as dt,resolve as pa,dirname as ua}from"path";import{createConnection as ma}from"net";var tr=`# Consumer Warm Archetype
|
|
2140
2140
|
|
|
2141
2141
|
Component-level design guidance for personal, lifestyle, and wellness apps. Habits, journals, recipes, mood trackers, meditation, daily routines, personal finance.
|
|
2142
2142
|
|
|
@@ -2303,7 +2303,7 @@ All colors from project CSS custom properties. Key guidance for consumer-warm:
|
|
|
2303
2303
|
- Small touch targets. Phone-first means \`h-12\` minimum.
|
|
2304
2304
|
- Empty states that just say "No data." Be encouraging.
|
|
2305
2305
|
- Dark theme as default. Consumer warm apps default to light.
|
|
2306
|
-
`;var
|
|
2306
|
+
`;var sr=`# Consumer Bold Archetype
|
|
2307
2307
|
|
|
2308
2308
|
Component-level design guidance for energetic, achievement-driven consumer apps. Fitness, workouts, sports, gaming, social platforms, competitive tracking.
|
|
2309
2309
|
|
|
@@ -2474,7 +2474,7 @@ Social/competitive apps need an activity feed:
|
|
|
2474
2474
|
- Card-only layouts with no hierarchy. Use hero cards + supporting cards.
|
|
2475
2475
|
- Missing achievement/progress systems. The gamification IS the product.
|
|
2476
2476
|
- Light-touch buttons. CTAs should be unmissable.
|
|
2477
|
-
`;var
|
|
2477
|
+
`;var or=`# Professional Clean Archetype
|
|
2478
2478
|
|
|
2479
2479
|
Component-level design guidance for service and appointment-based apps. Booking systems, clinics, salons, real estate, consulting, restaurants, event management.
|
|
2480
2480
|
|
|
@@ -4123,9 +4123,9 @@ Finance products often replace something worse (a clunky bank, a spreadsheet, an
|
|
|
4123
4123
|
- **Purple-to-blue gradients in the hero.** Fintech SaaS default. Use a brand color instead \u2014 or no gradient.
|
|
4124
4124
|
- **Dark mode as default for a consumer money app.** Too crypto-coded. Default light, offer dark.
|
|
4125
4125
|
- **Confidence-shaking UX:** progress bars that stall, skeletons that flash between states, tiny fonts for fine print. Users are nervous about their money; give them stability.
|
|
4126
|
-
`;var pr={"consumer-warm":{id:"consumer-warm",name:"Consumer Warm",description:"Personal, lifestyle, and wellness apps (habits, journals, recipes, mood, meditation)",content:tr},"consumer-bold":{id:"consumer-bold",name:"Consumer Bold",description:"Energetic, achievement-driven apps (fitness, workouts, sports, gaming, social)",content:or},"professional-clean":{id:"professional-clean",name:"Professional Clean",description:"Service and appointment-based apps (booking, clinics, salons, real estate, restaurants)",content:sr},"education-structured":{id:"education-structured",name:"Education Structured",description:"Learning and knowledge apps (courses, quizzes, flashcards, LMS, tutorials)",content:rr},"marketplace-browse":{id:"marketplace-browse",name:"Marketplace Browse",description:"Browsing and shopping apps (marketplaces, directories, shops, catalogs, food delivery)",content:nr},"saas-analytical":{id:"saas-analytical",name:"SaaS Analytical",description:"B2B SaaS, CRM, analytics, admin panels, ops tooling, team productivity (Linear, Notion, Stripe reference bar)",content:ir},"content-editorial":{id:"content-editorial",name:"Content Editorial",description:"Blogs, newsletters, magazines, publications, documentation, knowledge bases",content:ar},"devtool-technical":{id:"devtool-technical",name:"Devtool Technical",description:"Developer tools, APIs, CLIs, SDKs, infrastructure, monitoring, AI/ML platforms",content:lr},"creative-showcase":{id:"creative-showcase",name:"Creative Showcase",description:"Portfolios, design agencies, creative studios, photographers, artists",content:cr},"finance-clarity":{id:"finance-clarity",name:"Finance Clarity",description:"Fintech, invoicing, expense tracking, budgeting, payroll, accounting, banking",content:dr}};function ur(s){return pr[s]?.content}function mr(s,o){let e=o?.archetype;if(e&&e in pr)return e;if(e===null)return;let t=s.toLowerCase(),n=o?.tone??"",a=o?.audienceType??"";return/\bbooking|appointment|reserv|salon|clinic|dental|barber|spa|hotel|restaurant|event|venue|schedule|court|racquet|tee.?time\b/i.test(t)?"professional-clean":/\binvoic|expense|budget|payroll|accounting|bookkeep|payment|banking|wallet|fintech|cashflow|reimbursement|tax.?filing\b/i.test(t)?"finance-clarity":/\bblog|newsletter|publication|magazine|docs?\b|documentation|knowledge.?base|wiki|\barticle|editorial|cms|longform|writing.?platform\b/i.test(t)?"content-editorial":/\bportfolio|\bagency\b|\bstudio\b|freelance|photographer|illustrator|gallery|architect|filmmaker\b/i.test(t)?"creative-showcase":/\bdev.?tool|developer.?(?:tool|platform|portal)|\bapi\b|\bcli\b|\bsdk\b|infrastructure|ci.?cd|\bmonitoring\b|observability|\bdeployment\b|serverless|edge.?compute|kubernetes|\bdocker\b|terraform|ai.?platform|ml.?platform|mlops|error.?tracking/i.test(t)?"devtool-technical":/\bcrm\b|analytics|\bdashboard\b|admin.?panel|workflow|pipeline|ticket|issue.?track|project.?mgmt|team.?mgmt|\bsaas\b|internal.?tool|\bops\b|reporting|bi.?tool/i.test(t)?"saas-analytical":/\bhabit|journal|diary|mood|meditation|yoga|mindful|gratitude|daily.?routine|self.?care|wellness\b/i.test(t)?"consumer-warm":/\bfitness|workout|exercise|gym|training|sport|running|cycling|weight|muscle|cardio|athletic|leaderboard|\bgame\b/i.test(t)?"consumer-bold":/\bcourse|quiz|flashcard|lesson|tutorial|learning|education|\blms\b|student|teach|curriculum|exam|classroom\b/i.test(t)?"education-structured":/\bmarketplace|\bshop\b|\bstore\b|catalog|listing|directory|classified|rental|e.?commerce|food.?delivery|menu\b/i.test(t)?"marketplace-browse":n==="warm-minimal"||n==="playful"?/\brecipe|cook|meal|food|pet|plant|garden|travel|photo|music|social|community|family\b/i.test(t)?"consumer-warm":/\bcompet|score|rank|challenge|achieve|badge|level|quest\b/i.test(t)?"consumer-bold":"consumer-warm":a==="b2c"?"consumer-warm":"saas-analytical"}import{existsSync as qt,mkdirSync as gr,readFileSync as fr,readdirSync as yr,writeFileSync as Yi}from"fs";import{join as lt,resolve as Ki}from"path";import{homedir as Ro}from"os";function at(s){return s.entity??s.name??"Unknown"}function Qe(s){return typeof s=="string"?s:s.name}function Io(s){return typeof s=="string"?"text":s.type}function hr(s){let o=s.sampleRows;if(Array.isArray(o)&&o.length>0)return o.slice(0,3).map(n=>{let a={};for(let[r,i]of Object.entries(n))a[r]=i==null?"":String(i);return a});let e=s.fields||[],t=[];for(let n=0;n<3;n++){let a={};for(let r of e)a[Qe(r)]=Ji(Qe(r),Io(r),at(s),n);t.push(a)}return t}function Ji(s,o,e,t){let n=s.toLowerCase(),a=(o||"text").toLowerCase();return n==="name"||n==="title"?[`${e} Alpha`,`${e} Beta`,`${e} Gamma`][t]:n==="email"?["alice@example.com","bob@example.com","carol@example.com"][t]:n==="status"?["Active","Pending","Completed"][t]:n==="priority"?["High","Medium","Low"][t]:n.includes("date")||a==="date"?["Jan 15, 2024","Feb 20, 2024","Mar 10, 2024"][t]:n.includes("price")||n.includes("amount")||n.includes("cost")?["$29","$49","$99"][t]:n.includes("count")||n.includes("quantity")||a==="number"||a==="integer"?["12","34","56"][t]:a==="boolean"||a==="bool"?["Yes","No","Yes"][t]:n.includes("description")||a==="textarea"?["Brief description here","Another example entry","Third sample item"][t]:[`Sample ${t+1}`][0]}function Qi(s){let o=s.dataModel??[],e=s.pages??[],t=s.design??{},n=e.map(m=>({label:m.name??m.path??"Page",route:m.path??m.route??"/"})),a=[],r=o.slice(0,3).map(m=>({name:at(m),fields:(m.fields||[]).map(p=>({name:Qe(p),type:Io(p)})),sampleData:hr(m)})),i=[];s.primaryAction&&(i.push(`PRIMARY: ${s.primaryAction.action} \u2014 this is the first thing the user sees and does`),i.push(`SURFACE: ${s.primaryAction.dashboardSurface}`)),i.push(`METRICS: Key counts for ${o.map(m=>at(m)).join(", ")}`),i.push("RECENT: Latest activity or items"),a.push({name:"Dashboard",type:"dashboard",route:"/dashboard",purpose:s.primaryAction?`Action surface \u2014 user comes here to ${s.primaryAction.action.toLowerCase()}. Not a stats display.`:`Overview of ${o.map(m=>at(m)).join(", ")} with key metrics.`,informationHierarchy:i,interactionStates:["Empty state: new user, no data yet \u2014 show onboarding prompt","Loading state: skeleton placeholders for metrics and table","Populated state: real data with metrics, recent items, quick actions"],entities:r});let l=o[0];if(l){let m=at(l),p=m.toLowerCase().endsWith("s")?m:`${m}s`;a.push({name:`${m} List`,type:"detail",route:`/${p.toLowerCase()}`,purpose:`Browse, search, and manage ${p.toLowerCase()}. Create new ${m.toLowerCase()}s.`,informationHierarchy:[`HEADER: "${p}" title + "Add ${m}" button`,"SEARCH: Filter/search bar \u2014 users will have many items",`TABLE: ${(l.fields||[]).slice(0,5).map(g=>Qe(g)).join(", ")} columns`,"ROW ACTIONS: Edit, delete on each row"],interactionStates:[`Empty state: "No ${p.toLowerCase()} yet" with create CTA`,"Loading state: skeleton table rows",`Search with no results: "No ${p.toLowerCase()} matching..." with clear filter`],entities:[{name:m,fields:(l.fields||[]).map(g=>({name:Qe(g),type:Io(g)})),sampleData:hr(l)}]})}s.steps.some(m=>{let p=`${m.name??m.title??""} ${m.description??""}`.toLowerCase();return p.includes("landing")||p.includes("hero")||p.includes("marketing")||p.includes("homepage")})&&a.push({name:"Landing Page",type:"landing",route:"/",purpose:`Convince visitors to sign up for ${s.name}. Answer: what is this, who is it for, why should I care.`,informationHierarchy:[`HERO: One sentence about what ${s.name} does \u2014 not "Transform your X", be specific`,"CTA: Sign up / Get started \u2014 one clear action","PROOF: What makes this valuable (features, not buzzwords)","SECONDARY CTA: Repeat the sign up prompt"],interactionStates:["Mobile: hero stacks vertically, nav collapses to hamburger","Desktop: hero side-by-side or centered, full nav"],entities:[]});let u=[];for(let m of o.slice(0,3)){let p=at(m);(m.fields||[]).find(w=>Qe(w).toLowerCase()==="name"||Qe(w).toLowerCase()==="title")&&u.push(`What if a ${p.toLowerCase()}'s name is 47 characters? Does the layout break?`),u.push(`What if there are 0 ${p.toLowerCase()}s? 1? 500?`)}return s.authModel&&s.authModel!=="none"&&u.push("What does a brand-new user see? (no data, no setup)"),u.push("What if the network is slow? What loads first?"),{appName:s.name,summary:s.summary??"",screens:a,navigation:{style:s.navStyle??"sidebar",items:n},primaryAction:s.primaryAction??null,designDirection:{tone:t.tone??"professional",accentColor:t.accentColor??"blue",navStyle:s.navStyle??"sidebar",fonts:t.fonts??{heading:"Inter",body:"Inter"}},edgeCases:u}}function Xi(s,o){let e=[];e.push(`# Wireframe sketch for ${s.appName}`),e.push(""),e.push(`**${s.appName}** \u2014 ${s.summary}`),e.push(""),o&&(e.push("## Feedback to apply"),e.push(o),e.push("")),e.push("## Design principles"),e.push(""),e.push("Apply these when deciding layout and hierarchy:"),e.push("1. **Information hierarchy** \u2014 What does the user see first, second, third? The primary action is first. Metrics are second. Everything else is supporting."),e.push("2. **Interaction states** \u2014 Every screen has at least: empty, loading, populated. Show the populated state but add HTML comments noting the others."),e.push("3. **Edge case paranoia** \u2014 What if there are 0 items? 500 items? A 47-character name? Think about these and comment where they matter."),e.push(`4. **Subtraction** \u2014 "As little design as possible" (Dieter Rams). Every element earns its pixels. If removing something doesn't hurt, remove it.`),e.push("5. **Design for trust** \u2014 Clear labels, predictable layout, obvious actions. No mystery meat navigation."),e.push(""),e.push("## Wireframe rules (strict)"),e.push(""),e.push("Write a **single self-contained HTML file** saved to `.mistflow/mockups/mockup-{planId}.html` (replace `{planId}` with the actual plan ID)."),e.push(""),e.push("The wireframe must:"),e.push("- Use **system fonts only** (`-apple-system, system-ui, sans-serif`) \u2014 no Google Fonts, no CDN"),e.push("- Use **inline CSS only** \u2014 no external stylesheets, no Tailwind CDN"),e.push("- Look **intentionally rough** \u2014 thin gray borders (#ddd), light backgrounds (#f8f8f8), no color, no shadows"),e.push("- Use **realistic placeholder content** that matches this specific app (sample data provided below) \u2014 NOT lorem ipsum"),e.push("- Include **HTML comments** explaining design decisions (e.g., `<!-- Primary action is prominent because users come here to check in members -->`)"),e.push("- Show **all screens in a single page** using tabs/sections that the user can click through"),e.push("- Be **responsive** \u2014 test that it looks reasonable at both 1200px and 375px widths"),e.push("- Include a small header bar showing: screen name tabs + the design direction summary"),e.push(""),e.push("The wireframe must NOT:"),e.push("- Use any color except grayscale (#333, #666, #999, #ddd, #f8f8f8, white)"),e.push("- Use any external dependencies \u2014 no CDN, no imports, no build step"),e.push("- Look polished \u2014 it should feel like a sketch on a whiteboard, not a finished product"),e.push("- Include decorative elements \u2014 no icons (use text labels), no illustrations, no gradients"),e.push(""),e.push("## Screens to wireframe"),e.push("");for(let t of s.screens){e.push(`### ${t.name} (\`${t.route}\`)`),e.push(`**Purpose**: ${t.purpose}`),e.push(""),e.push("**Information hierarchy** (render in this order, top to bottom):");for(let n of t.informationHierarchy)e.push(`- ${n}`);e.push(""),e.push("**Interaction states** (add HTML comments for non-visible states):");for(let n of t.interactionStates)e.push(`- ${n}`);if(e.push(""),t.entities.length>0){e.push("**Data model and sample content** (use this real data, not lorem ipsum):");for(let n of t.entities)e.push(`
|
|
4127
|
-
**${n.name}** \u2014 fields: ${n.fields.map(a=>`${a.name} (${a.type})`).join(", ")}`),e.push("```json"),e.push(JSON.stringify(n.sampleData,null,2)),e.push("```");e.push("")}}e.push("## Navigation"),e.push(`**Style**: ${
|
|
4128
|
-
`)}function br(s){return lt(Ro(),".mistflow","mockup-state",`${s}.json`)}function Zi(s){let o=br(s);if(!qt(o))return null;try{return JSON.parse(fr(o,"utf-8"))}catch{return null}}function Ao(s,o){let e=lt(Ro(),".mistflow","mockup-state");gr(e,{recursive:!0}),Yi(br(s),JSON.stringify(o,null,2))}async function wr(s){let{planId:o,feedback:e,approved:t}=s,n=Ki(s.projectPath??process.cwd()),a=lt(Ro(),".mistflow","plans",`${o}.json`);if(!qt(a))return d(`Plan not found for planId '${o}'. Call mist_plan to generate a plan first.`,!0);let r;try{r=JSON.parse(fr(a,"utf-8"))}catch{return d("Failed to read plan file. Call mist_plan again.",!0)}let i=r.plan;if(!i)return d("Plan data is empty. Call mist_plan again.",!0);let l=Zi(o);l||(l={planId:o,iterationCount:0,approved:!1,screens:[],feedback:[]});let c=lt(n,".mistflow","mockups");if(gr(c,{recursive:!0}),t){l.approved=!0,Ao(o,l);let g=qt(c)?yr(c).filter(w=>w.endsWith(".html")):[];return d(JSON.stringify({status:"approved",message:`Wireframe approved after ${l.iterationCount} iteration(s). Layout direction is locked in.`,mockupFiles:g.map(w=>`.mistflow/mockups/${w}`),nextAction:`NEXT: Call mist_build with action='init', name='${i.name}', and planId='${o}' to create the project. The wireframe in .mistflow/mockups/ will be used as layout reference during implementation.`}))}e?(l.iterationCount++,l.feedback.push(e)):l.iterationCount++,Ao(o,l);let u=Qi(i);l.screens=u.screens.map(g=>g.name),Ao(o,l);let m=Xi(u,e??void 0),p;return l.iterationCount>=3&&(p="The wireframe is shaping up \u2014 want to keep refining the layout, or start building?"),d(JSON.stringify({status:"wireframe",iterationCount:l.iterationCount,screens:u.screens.map(g=>({name:g.name,type:g.type,route:g.route})),wireframePrompt:m,designDirection:u.designDirection,...p?{nudge:p}:{},mockupFile:`mockup-${o}.html`,nextAction:e?`Apply the user's feedback to the wireframe. Rewrite .mistflow/mockups/mockup-${o}.html with the changes. Open it in the browser for review. Ask if they want more changes or are ready to build.`:`Generate the wireframe HTML following the wireframePrompt instructions above. Write it to .mistflow/mockups/mockup-${o}.html, then open it in the browser. Ask the user if the layout feels right.`}))}function vr(s){let o=lt(s,".mistflow","mockups");return qt(o)?yr(o).filter(e=>e.endsWith(".html")).map(e=>lt(o,e)):[]}var kr="\nApply these choices to every file you create. Customize the shadcn CSS variables in globals.css to match. Do NOT use default shadcn blue/zinc theme.\n\n**CRITICAL: shadcn/ui components are already installed. NEVER write components/ui/*.tsx files from scratch.** If you need a shadcn component, run `npx shadcn@latest add <component>` to pull it. The project already includes: button, card, input, label, form, dialog, table, dropdown-menu, badge, separator, skeleton, sheet, tabs, avatar, select, textarea, checkbox, switch, tooltip, popover, sonner.\n\n**shadcn MCP server is available.** You have the `shadcn` MCP server installed \u2014 use it to browse and search for components, blocks, and landing page sections from the shadcn registry. Before building a landing page section from scratch, check the registry for existing blocks (hero sections, feature grids, pricing tables, testimonials, footers) and customize them instead of reinventing.\n\n**Project routes (use these exact paths):** Login is at `/login` (NOT /sign-in). Register is at `/register` (NOT /sign-up). All landing page and nav links MUST use `/login` and `/register`.\n\n### Design quality rules (non-negotiable):\n\n**Typography**: Use the plan fonts everywhere. font-heading for headings, font-body for body text.\n- **Modular scale**: Use a 1.25-1.5 ratio between sizes. A 5-level system covers most needs: xs (0.75rem captions), sm (0.875rem metadata), base (1rem body), lg (1.25-1.5rem subheadings), xl+ (2-4rem headlines). Sizes too close together (14/15/16px) create muddy hierarchy.\n- **Vertical rhythm**: Your line-height IS your spacing unit. If body is 16px with line-height 1.5 (= 24px), vertical spacing should be multiples of 24px.\n- **Weight contrast**: Use font-medium/font-semibold contrast, not just size. Bold headings + regular body creates natural hierarchy without extra sizes.\n- **Measure**: Set `max-width: 65ch` on text containers. Long lines kill readability.\n- **OpenType polish**: Use `font-variant-numeric: tabular-nums` on data tables for aligned columns.\n- Never use more than 2 font families. One well-chosen family in multiple weights is cleaner than two competing typefaces.\n- Never fall back to system fonts. Never use decorative fonts for body text. Minimum 16px (1rem) for body.\n\n**Color**: Build a functional palette, not a rainbow.\n- **Tinted neutrals**: Pure gray is dead. Add a tiny tint toward the accent color to all your grays (borders, backgrounds, muted text). The tint should be subtle enough not to read as 'colored' but creates subconscious cohesion.\n- **60/30/10 rule**: 60% neutral backgrounds/whitespace, 30% secondary colors (text, borders, inactive states), 10% accent (CTAs, highlights, focus). Accent colors work BECAUSE they're rare. Overuse kills their power.\n- **Dangerous combos to avoid**: Light gray text on white (#1 accessibility fail). Gray text on any colored background (looks washed out and dead, use a darker shade of the background color instead). Yellow text on white. Thin light text on images.\n- **Dark mode is not inverted light mode**: Use lighter surfaces for depth (no shadows). Desaturate accents slightly. Never pure black backgrounds, use dark gray (12-18% lightness). Reduce body text weight slightly (350 vs 400) because light-on-dark reads heavier.\n- Never use pure #000 or #fff. Customize the shadcn CSS variables in globals.css to match the plan palette.\n\n**Layout & space**: Space is a design material, not leftover.\n- **4px base unit**: All spacing should be multiples of 4: 4, 8, 12, 16, 24, 32, 48, 64, 96px. No arbitrary values. Name tokens semantically (`space-sm`, `space-lg`), not by value.\n- **Use `gap` not margins**: Use `gap` for sibling spacing. It eliminates margin collapse hacks and is more predictable. Reserve margin for positioning, not spacing between siblings.\n- **Rhythm through contrast**: Tight groupings within related items (8-12px), generous separation between sections (48-96px). Vary spacing WITHIN sections too. Not every row needs the same gap. The ratio between inner and outer spacing creates hierarchy.\n- **Density matches content**: Data-dense UIs (dashboards, tables, admin panels) need tighter spacing with more information visible. Marketing pages need generous whitespace and breathing room. Match density to what the user is doing.\n- **The squint test**: Blur your eyes. Can you still identify primary, secondary, and clear groupings? If everything looks the same weight, hierarchy is broken. The most important content should be obvious within 2 seconds.\n- **Asymmetry > centering**: Left-aligned with asymmetric layouts feels more designed. Center-alignment is fine for hero sections and CTAs, not for body content.\n- **Flex vs Grid**: Use Flexbox for 1D layouts (rows of items, navbars, button groups, card contents, most component internals). Use Grid for 2D layouts (page-level structure, dashboards, data-dense interfaces where rows AND columns need coordinated control). Don't default to Grid when Flexbox with `flex-wrap` would be simpler. Use `repeat(auto-fit, minmax(280px, 1fr))` for responsive grids without breakpoints. Use named `grid-template-areas` for complex page layouts and redefine at breakpoints.\n- **Cards earn their existence**: Only use cards when content needs clear separation, grid comparison, or interaction boundaries. Not everything needs a container. Never nest cards inside cards. Vary card sizes or mix cards with non-card content to break repetition.\n- **Section variety**: Don't make every section the same structure. Alternate layouts (text-left/image-right, then image-left/text-right), vary section heights, mix full-width with contained content. Monotonous section rhythm signals no designer touched this.\n- **Z-index scale**: Use a semantic scale, not arbitrary numbers. dropdown(10) -> sticky(20) -> modal-backdrop(30) -> modal(40) -> toast(50) -> tooltip(60). Never use 999 or 9999.\n- **Touch targets**: Minimum 44x44px for all interactive elements, even if the visual element is smaller (use padding).\n\n**Cards & surfaces**: Match the plan's cardStyle. Stat cards need background fills with the accent color as a subtle icon background or tinted left border. Use bg-muted/30 for section differentiation between page areas. Build a consistent shadow scale (sm -> md -> lg) and use elevation to reinforce hierarchy, not as decoration.\n\n**Sidebar**: App name + icon at top. Nav items with hover:bg-muted rounded-md transition. Active item: bg-primary/10 text-primary font-medium. User email + sign out at bottom. The sidebar should feel like a distinct surface (bg-card or bg-muted/50).\n**Mobile navigation**: The desktop sidebar must collapse to a hamburger menu on mobile. Use the shadcn `Sheet` component: a hamburger icon button (visible at `md:hidden`) opens a Sheet from the left containing the same nav items. The desktop sidebar is `hidden md:flex`. For simple apps with 3-5 nav items, a bottom tab bar (`fixed bottom-0`) is an alternative. Always respect `env(safe-area-inset-bottom)` for notched phones.\n\n**Interaction design**: Every interactive element needs 8 states, not just default and hover.\n- **Required states**: default, hover, focus, active/pressed, disabled, loading, error, success. Design all of them intentionally.\n- **Focus rings**: Use `:focus-visible` (not `:focus`) so rings show for keyboard users but not mouse clicks. Never remove focus indicators without replacement.\n- **Button hierarchy**: Don't make every button primary. Use ghost, outline, secondary, and text-link variants. One primary CTA per view.\n- **Progressive disclosure**: Simple first, advanced behind expandable sections. Don't overwhelm with options.\n- **Undo over confirmation**: For destructive actions, remove immediately + show an undo toast, then permanently delete after timeout. Better than confirmation dialogs that users click through blindly.\n- **Form patterns**: Visible `<label>` elements always (placeholders aren't labels, they disappear). Validate on blur, not on keystroke. Show format expectations with examples.\n\n**Empty states**: Every empty list/table needs a rich empty state. Not just 'Nothing here'. Include: a simple inline SVG illustration (48x48, relevant to the feature), a specific message that teaches ('Create your first habit to start tracking your daily routine'), and a primary action button. Empty states are the first thing new users see. Make them inviting.\n\n**Loading states**: Use the shadcn `Skeleton` component. Show skeleton versions of cards, lists, and stats during data fetches. Example: `<Skeleton className=\"h-8 w-32\" />` for a stat number, `<Skeleton className=\"h-20 w-full\" />` for a card. Add a `loading.tsx` file in dashboard route groups. Never show a blank page or a lone spinner.\n\n**Images**: For Unsplash images on landing pages, use `next/image` with `placeholder=\"blur\"` and a blurDataURL (a tiny 10x6 base64 image \u2014 generate a solid color blur like `data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAGCAYAAAD68A/GAAAAP0lEQVQYV2N89+7dfwYGBgZGRkYGBgYmBjIBE7kaPHv27D8DA8N/BgYGRkZGRgYGJgYyARO5GkjWQHEoxRoAAPyTGAGBMpEAAAAASUVORK5CYII=`). This creates a smooth shimmer-in effect instead of images popping in.\n\n**Motion** (`motion` package is installed):\n\n**Hero moment strategy**: Pick ONE signature animation per page. Not scattered animations on everything. On a landing page, the hero entrance is your hero moment. On a dashboard, a satisfying success animation after the primary action. One great animation > ten mediocre ones. Everything else gets subtle transitions.\n\n**Animation opportunity audit** -- check these 5 categories:\n1. **Missing feedback**: Button has no press response? Add `active:scale-[0.97]` (CSS) or `whileTap={{ scale: 0.97 }}` (motion). Toggle has no slide? Animate it.\n2. **Jarring transitions**: Menu appears instantly? Add 200ms fade + slide. Content swaps without transition? Crossfade between states.\n3. **Unclear relationships**: Parent-child not visually connected? Stagger children 50ms after parent. Deleted item just disappears? Animate it out (opacity + height collapse).\n4. **Lack of delight**: Success state is flat? Draw a checkmark SVG with stroke-dashoffset animation. Empty state is static? Add a gentle float on the illustration.\n5. **Missed guidance**: First-time user gets no hint? Pulse the primary CTA once on page load. New feature unnoticed? Brief highlight animation.\n\n**Timing hierarchy**: 100-150ms for instant feedback (buttons, toggles). 200-300ms for state changes (menus, tooltips). 300-500ms for layout shifts (accordions, modals). 500-800ms for entrances (page loads). Exit animations run at 75% of entrance duration.\n\n**Easing**: Use exponential curves (Quart out, Expo out) for sophisticated physics. Never `ease` (generic), never bounce/elastic (dated). Real objects decelerate smoothly. CSS: `cubic-bezier(0.25, 1, 0.5, 1)` (Quart out) or `cubic-bezier(0.16, 1, 0.3, 1)` (Expo out).\n\n**Micro-interaction recipes**:\n- **Button press**: `active:scale-[0.97] transition-transform duration-100` (CSS only, no motion needed)\n- **Success checkmark**: SVG `<path>` with `stroke-dasharray` + `stroke-dashoffset` animation from full to 0. 400ms Expo out.\n- **Height expand/collapse**: `grid-template-rows: 0fr -> 1fr` with `transition: grid-template-rows 300ms`. No JS layout measurement needed.\n- **Skeleton to content**: Skeleton pulses (CSS `animate-pulse`), then crossfades to real content with `opacity` transition. Use the pre-scaffolded `<ContentLoader>` component.\n- **Staggered list entrance**: CSS `animation-delay` on children: `.animate-fade-up:nth-child(1) { animation-delay: 0ms } :nth-child(2) { animation-delay: 50ms }` etc. Or use `<StaggerList>` component.\n- **Number count-up**: Use `@number-flow/react` for smooth digit morphing on stats/metrics.\n\n**Performance**: Only animate `transform` and `opacity` (GPU-accelerated). Never animate width, height, top, left, margin, or padding. For scroll-tied effects on landing pages, use CSS `animation-timeline: scroll()` where supported (progressive enhancement).\n\n**Accessibility**: Always respect `prefers-reduced-motion`. Wrap animations in `@media (prefers-reduced-motion: no-preference) { ... }`. Provide static alternatives that convey the same information.\n\n**SSR-safe (CRITICAL)**: This app deploys to Mistflow Cloud's edge runtime where IntersectionObserver may not fire. NEVER use `initial={{ opacity: 0 }}` (content stays invisible forever). Use CSS @keyframes for entrance effects:\n```tsx\n// SAFE: CSS @keyframes in globals.css:\n// @keyframes fade-up { from { opacity: 0; transform: translateY(16px); } to { opacity: 1; transform: translateY(0); } }\n// .animate-fade-up { animation: fade-up 0.5s ease-out both; }\n// Use motion ONLY for hover/tap/gesture interactions:\nimport { motion } from 'motion/react';\n<motion.div whileHover={{ scale: 1.02 }} whileTap={{ scale: 0.97 }} transition={{ duration: 0.15 }}>\n// NEVER: <motion.div initial={{ opacity: 0 }} whileInView={{ opacity: 1 }}>\n```\nFor dashboard pages, keep animations minimal. Button press feedback + skeleton loading + success states. No entrance animations on dashboard pages.\n\n**UX writing**: Every word earns its place.\n- **Buttons**: Use outcome-focused verb + object ('Save changes', 'Create account'), never generic ('Submit', 'OK', 'Click here').\n- **Destructive actions**: State exact consequences ('Delete 5 items permanently', not 'Delete selected'). Distinguish 'Delete' (permanent) from 'Remove' (recoverable).\n- **Error messages**: Answer three questions: what happened, why, and how to fix it. 'Email address is not valid. Include an @ symbol.' not 'Invalid input'. Never blame the user.\n- **Empty states**: Explain what will appear here, why it matters, and give a clear next action.\n- **Loading/progress**: Set time expectations. 'Deploying your app (usually takes 30 seconds)' not just a spinner.\n- **Consistency**: Pick one term and stick with it. 'Delete' everywhere, not Delete/Remove/Trash interchangeably.\n- **Link text**: Make it standalone for accessibility. 'View pricing plans' not 'Click here'.\n\n**Responsive design**: Mobile-first, then enhance.\n- **Mobile-first CSS**: Write base styles for mobile, then use `min-width` media queries to enhance for larger screens. Never start with desktop and try to cram it into mobile.\n- **Input method matters more than screen size**: Use `@media (pointer: fine)` for mouse/trackpad (smaller targets OK, hover effects work), `@media (pointer: coarse)` for touch (44px targets required, no hover-dependent UI). Use `@media (hover: none)` to detect devices that can't hover. Never require hover to reveal functionality.\n- **Safe areas**: Add `<meta name='viewport' content='width=device-width, initial-scale=1, viewport-fit=cover'>` and use `env(safe-area-inset-bottom)` for bottom navigation on notched phones. Fixed bottom bars must respect safe areas.\n- **Self-adjusting grids**: Use `grid-template-columns: repeat(auto-fit, minmax(280px, 1fr))` for card grids. Columns reflow naturally without breakpoint management.\n- **Container queries over media queries**: For reusable components, use `container-type: inline-size` on the parent and `@container (min-width: 400px)` on children. Components adapt to their container, not the viewport.\n- **No horizontal scroll**: Nothing should overflow the viewport width. Test at 320px width (smallest common phone). Use `overflow-x: hidden` on the body as a safety net but fix the root cause.\n- **Touch-friendly spacing**: On mobile, increase padding on list items and nav links. Thumb zone for primary actions is bottom-center of the screen.\n- **Responsive images**: Use `next/image` with `sizes` prop for responsive sizing. For art direction changes, use `<picture>` with `<source media='...'>`. Always set `width` and `height` to prevent layout shift.\n\n**Cognitive load**: Simpler apps feel better, even with the same features.\n- **Max 4 items per group**: Humans hold 4 items in working memory. Navigation menus: max 5 top-level items. Forms: max 4 fields per section. Dashboards: max 4 metrics visible without scrolling. Pricing: max 3 tiers.\n- **Single focus per view**: Every page has ONE primary task. If there are two equal CTAs, neither is primary. One primary action, everything else is secondary or tertiary.\n- **Sequential decisions**: Don't present all options at once. Multi-step forms beat one long form. Each step should have one decision.\n- **Progressive disclosure**: Show the essential first, reveal complexity on demand. Use expandable sections, tabs, or drill-down navigation. The default view should cover 80% of use cases.\n- **Visual grouping**: Related items must be visually grouped (proximity + shared background or border). Unrelated items must have clear separation. The Gestalt principle of proximity is the easiest way to reduce cognitive load.\n- **Reduce choice anxiety**: For important decisions, provide a recommended/default option. Highlight it visually. 'Most popular' badges on pricing plans reduce decision time.\n- **Keep context visible**: In multi-step flows, show a progress indicator and allow going back. Never make users remember what they entered on a previous screen.\n\n**Production hardening**: Designs that only work with perfect data aren't production-ready.\n- **Text overflow**: Use `text-overflow: ellipsis` + `overflow: hidden` for single-line text in constrained spaces. Use `-webkit-line-clamp` for multi-line. Add `min-width: 0` on flex items to prevent overflow.\n- **Extreme inputs**: Test with 100+ character names, emoji in text fields, and empty strings. The layout should not break.\n- **Error resilience**: Every API call needs error UI. Network failures, 404s, 500s all need clear messages with recovery options. Never show raw stack traces.\n\n**Landing page component patterns** (use these for professional, non-generic landing pages):\nBuild these components inline (shadcn + motion + Tailwind is enough):\n- **Animated number counters**: Use `@number-flow/react` (installed) for stat sections. `<NumberFlow value={count} />` with smooth digit transitions.\n- **Marquee / logo ticker**: CSS-only infinite scroll (`@keyframes marquee { from { transform: translateX(0) } to { transform: translateX(-50%) } }`) with duplicated content. Pause on hover.\n- **Bento grid**: CSS grid with varied `col-span` and `row-span`. Each cell gets a unique visual. Never make all cells the same size.\n- **Animated beam / connection lines**: SVG paths with `motion` stroke-dashoffset animation for 'how it works' sections.\n- **Shimmer borders**: `background: conic-gradient(...)` wrapper with animation for hero CTAs.\n- **Comparison tables**: Sticky-header table with check/x icons and row highlighting on the recommended plan.\n- **Testimonial carousel**: CSS scroll-snap for horizontal cards with avatar, quote, name, role. Auto-scroll paused on hover.\n- **Gradient mesh backgrounds**: Multiple layered `radial-gradient` backgrounds for hero sections.\nPick 3-5 per landing page based on the app's content. The goal: every landing page should look like it was designed by a human, not generated by AI.\n\n**Landing page navbar (non-negotiable):** Fully transparent (no background, no border, no backdrop-blur) and NOT sticky/fixed. It sits inside the hero section and scrolls naturally. White text on dark hero backgrounds. Primary CTA button in the nav uses the accent color (solid fill, rounded-md). Do NOT use `sticky`, `fixed`, `top-0`, or `backdrop-blur` on landing page navbars. Dashboard sidebar/nav IS fixed (different pattern).\n\n**Design for THIS app, not any app** (the #1 way to avoid generic AI output):\n- Every layout decision should be informed by what THIS app does. A gym check-in app needs a prominent search bar. A habit tracker needs a daily view. A CRM needs a pipeline. Don't default to the same dashboard-with-stats layout for everything.\n- Write copy that is SPECIFIC to the app's domain. Not 'Manage your data efficiently' but 'Check in members in under 3 seconds'. Every headline, empty state, and CTA should reference what the user actually does in this app.\n- Choose visual emphasis based on the primary action. If the user comes to log a workout, the workout form should be the biggest thing on the dashboard.\n- Use domain-appropriate metaphors. A fitness app uses progress rings. A project tracker uses kanban columns. A recipe app uses cards with photos. Don't use the same card grid for everything.\n\n**NEVER do these (AI slop anti-patterns)**:\nThe following are telltale signs of AI-generated design. Avoid all of them.\n*Visual patterns*:\n- Cyan-on-dark, purple-to-blue gradients, neon accents on dark backgrounds (the AI color palette)\n- Gradient text on headings or metrics (decorative noise, not meaningful)\n- Glassmorphism / blur effects used decoratively (only use blur for overlays/modals that need it)\n- Rounded rectangles with thick colored border on one side (lazy accent, never looks intentional)\n- Dark mode with glowing colored box-shadows on accent elements\n- Small rounded-square icon tiles stacked above headings (the icon-tile pattern)\n- Pure black (#000) backgrounds in dark mode (use tinted dark gray instead)\n- 3-column icon + title + paragraph feature grid (use asymmetric layouts, bento grids, or varied card sizes)\n- Nested cards inside cards (visual noise, flatten the hierarchy)\n- Everything center-aligned (use left-alignment for body content, reserve center for heroes/CTAs)\n- Monotonous spacing (same gap everywhere signals no designer touched this)\n*Copy patterns*:\n- Hero text like 'Transform your X' / 'One Day at a Time' / 'Join thousands' / 'Unlock the power of' (write SPECIFIC copy)\n- Generic feature descriptions ('Powerful analytics', 'Seamless integration', 'Lightning fast')\n- The hero metric template (big number, small label, supporting stats, gradient accent)\n- Repeating information users can already see. Every word must earn its place.\n*Functional patterns*:\n- Bounce/elastic easing on animations (feels dated, real objects decelerate smoothly, use Quart/Expo out)\n- Modals for things that could be inline (modals are a last resort, not a default)\n- Nav links to pages that don't exist. EVERY link in the sidebar/topnav MUST have a corresponding page.\n- FAKE FORMS. NEVER use `setTimeout` or `await new Promise` to simulate API calls. Every form MUST have a real server action (actions.ts with 'use server') that writes to the database. If a form doesn't persist data, the feature is BROKEN.\n\n**Favicon**: A default SVG favicon exists at app/icon.svg. On the landing page step, update it to match the app. Keep it simple (a single icon/letter on a rounded square, using the accent color).\n";var xr=`# Landing Page Rules
|
|
4126
|
+
`;var pr={"consumer-warm":{id:"consumer-warm",name:"Consumer Warm",description:"Personal, lifestyle, and wellness apps (habits, journals, recipes, mood, meditation)",content:tr},"consumer-bold":{id:"consumer-bold",name:"Consumer Bold",description:"Energetic, achievement-driven apps (fitness, workouts, sports, gaming, social)",content:sr},"professional-clean":{id:"professional-clean",name:"Professional Clean",description:"Service and appointment-based apps (booking, clinics, salons, real estate, restaurants)",content:or},"education-structured":{id:"education-structured",name:"Education Structured",description:"Learning and knowledge apps (courses, quizzes, flashcards, LMS, tutorials)",content:rr},"marketplace-browse":{id:"marketplace-browse",name:"Marketplace Browse",description:"Browsing and shopping apps (marketplaces, directories, shops, catalogs, food delivery)",content:nr},"saas-analytical":{id:"saas-analytical",name:"SaaS Analytical",description:"B2B SaaS, CRM, analytics, admin panels, ops tooling, team productivity (Linear, Notion, Stripe reference bar)",content:ir},"content-editorial":{id:"content-editorial",name:"Content Editorial",description:"Blogs, newsletters, magazines, publications, documentation, knowledge bases",content:ar},"devtool-technical":{id:"devtool-technical",name:"Devtool Technical",description:"Developer tools, APIs, CLIs, SDKs, infrastructure, monitoring, AI/ML platforms",content:lr},"creative-showcase":{id:"creative-showcase",name:"Creative Showcase",description:"Portfolios, design agencies, creative studios, photographers, artists",content:cr},"finance-clarity":{id:"finance-clarity",name:"Finance Clarity",description:"Fintech, invoicing, expense tracking, budgeting, payroll, accounting, banking",content:dr}};function ur(o){return pr[o]?.content}function mr(o,s){let e=s?.archetype;if(e&&e in pr)return e;if(e===null)return;let t=o.toLowerCase(),n=s?.tone??"",a=s?.audienceType??"";return/\bbooking|appointment|reserv|salon|clinic|dental|barber|spa|hotel|restaurant|event|venue|schedule|court|racquet|tee.?time\b/i.test(t)?"professional-clean":/\binvoic|expense|budget|payroll|accounting|bookkeep|payment|banking|wallet|fintech|cashflow|reimbursement|tax.?filing\b/i.test(t)?"finance-clarity":/\bblog|newsletter|publication|magazine|docs?\b|documentation|knowledge.?base|wiki|\barticle|editorial|cms|longform|writing.?platform\b/i.test(t)?"content-editorial":/\bportfolio|\bagency\b|\bstudio\b|freelance|photographer|illustrator|gallery|architect|filmmaker\b/i.test(t)?"creative-showcase":/\bdev.?tool|developer.?(?:tool|platform|portal)|\bapi\b|\bcli\b|\bsdk\b|infrastructure|ci.?cd|\bmonitoring\b|observability|\bdeployment\b|serverless|edge.?compute|kubernetes|\bdocker\b|terraform|ai.?platform|ml.?platform|mlops|error.?tracking/i.test(t)?"devtool-technical":/\bcrm\b|analytics|\bdashboard\b|admin.?panel|workflow|pipeline|ticket|issue.?track|project.?mgmt|team.?mgmt|\bsaas\b|internal.?tool|\bops\b|reporting|bi.?tool/i.test(t)?"saas-analytical":/\bhabit|journal|diary|mood|meditation|yoga|mindful|gratitude|daily.?routine|self.?care|wellness\b/i.test(t)?"consumer-warm":/\bfitness|workout|exercise|gym|training|sport|running|cycling|weight|muscle|cardio|athletic|leaderboard|\bgame\b/i.test(t)?"consumer-bold":/\bcourse|quiz|flashcard|lesson|tutorial|learning|education|\blms\b|student|teach|curriculum|exam|classroom\b/i.test(t)?"education-structured":/\bmarketplace|\bshop\b|\bstore\b|catalog|listing|directory|classified|rental|e.?commerce|food.?delivery|menu\b/i.test(t)?"marketplace-browse":n==="warm-minimal"||n==="playful"?/\brecipe|cook|meal|food|pet|plant|garden|travel|photo|music|social|community|family\b/i.test(t)?"consumer-warm":/\bcompet|score|rank|challenge|achieve|badge|level|quest\b/i.test(t)?"consumer-bold":"consumer-warm":a==="b2c"?"consumer-warm":"saas-analytical"}import{existsSync as zt,mkdirSync as gr,readFileSync as fr,readdirSync as yr,writeFileSync as Ki}from"fs";import{join as ct,resolve as Ji}from"path";import{homedir as Is}from"os";function lt(o){return o.entity??o.name??"Unknown"}function Qe(o){return typeof o=="string"?o:o.name}function As(o){return typeof o=="string"?"text":o.type}function hr(o){let s=o.sampleRows;if(Array.isArray(s)&&s.length>0)return s.slice(0,3).map(n=>{let a={};for(let[r,i]of Object.entries(n))a[r]=i==null?"":String(i);return a});let e=o.fields||[],t=[];for(let n=0;n<3;n++){let a={};for(let r of e)a[Qe(r)]=Qi(Qe(r),As(r),lt(o),n);t.push(a)}return t}function Qi(o,s,e,t){let n=o.toLowerCase(),a=(s||"text").toLowerCase();return n==="name"||n==="title"?[`${e} Alpha`,`${e} Beta`,`${e} Gamma`][t]:n==="email"?["alice@example.com","bob@example.com","carol@example.com"][t]:n==="status"?["Active","Pending","Completed"][t]:n==="priority"?["High","Medium","Low"][t]:n.includes("date")||a==="date"?["Jan 15, 2024","Feb 20, 2024","Mar 10, 2024"][t]:n.includes("price")||n.includes("amount")||n.includes("cost")?["$29","$49","$99"][t]:n.includes("count")||n.includes("quantity")||a==="number"||a==="integer"?["12","34","56"][t]:a==="boolean"||a==="bool"?["Yes","No","Yes"][t]:n.includes("description")||a==="textarea"?["Brief description here","Another example entry","Third sample item"][t]:[`Sample ${t+1}`][0]}function Xi(o){let s=o.dataModel??[],e=o.pages??[],t=o.design??{},n=e.map(m=>({label:m.name??m.path??"Page",route:m.path??m.route??"/"})),a=[],r=s.slice(0,3).map(m=>({name:lt(m),fields:(m.fields||[]).map(p=>({name:Qe(p),type:As(p)})),sampleData:hr(m)})),i=[];o.primaryAction&&(i.push(`PRIMARY: ${o.primaryAction.action} \u2014 this is the first thing the user sees and does`),i.push(`SURFACE: ${o.primaryAction.dashboardSurface}`)),i.push(`METRICS: Key counts for ${s.map(m=>lt(m)).join(", ")}`),i.push("RECENT: Latest activity or items"),a.push({name:"Dashboard",type:"dashboard",route:"/dashboard",purpose:o.primaryAction?`Action surface \u2014 user comes here to ${o.primaryAction.action.toLowerCase()}. Not a stats display.`:`Overview of ${s.map(m=>lt(m)).join(", ")} with key metrics.`,informationHierarchy:i,interactionStates:["Empty state: new user, no data yet \u2014 show onboarding prompt","Loading state: skeleton placeholders for metrics and table","Populated state: real data with metrics, recent items, quick actions"],entities:r});let l=s[0];if(l){let m=lt(l),p=m.toLowerCase().endsWith("s")?m:`${m}s`;a.push({name:`${m} List`,type:"detail",route:`/${p.toLowerCase()}`,purpose:`Browse, search, and manage ${p.toLowerCase()}. Create new ${m.toLowerCase()}s.`,informationHierarchy:[`HEADER: "${p}" title + "Add ${m}" button`,"SEARCH: Filter/search bar \u2014 users will have many items",`TABLE: ${(l.fields||[]).slice(0,5).map(f=>Qe(f)).join(", ")} columns`,"ROW ACTIONS: Edit, delete on each row"],interactionStates:[`Empty state: "No ${p.toLowerCase()} yet" with create CTA`,"Loading state: skeleton table rows",`Search with no results: "No ${p.toLowerCase()} matching..." with clear filter`],entities:[{name:m,fields:(l.fields||[]).map(f=>({name:Qe(f),type:As(f)})),sampleData:hr(l)}]})}o.steps.some(m=>{let p=`${m.name??m.title??""} ${m.description??""}`.toLowerCase();return p.includes("landing")||p.includes("hero")||p.includes("marketing")||p.includes("homepage")})&&a.push({name:"Landing Page",type:"landing",route:"/",purpose:`Convince visitors to sign up for ${o.name}. Answer: what is this, who is it for, why should I care.`,informationHierarchy:[`HERO: One sentence about what ${o.name} does \u2014 not "Transform your X", be specific`,"CTA: Sign up / Get started \u2014 one clear action","PROOF: What makes this valuable (features, not buzzwords)","SECONDARY CTA: Repeat the sign up prompt"],interactionStates:["Mobile: hero stacks vertically, nav collapses to hamburger","Desktop: hero side-by-side or centered, full nav"],entities:[]});let u=[];for(let m of s.slice(0,3)){let p=lt(m);(m.fields||[]).find(w=>Qe(w).toLowerCase()==="name"||Qe(w).toLowerCase()==="title")&&u.push(`What if a ${p.toLowerCase()}'s name is 47 characters? Does the layout break?`),u.push(`What if there are 0 ${p.toLowerCase()}s? 1? 500?`)}return o.authModel&&o.authModel!=="none"&&u.push("What does a brand-new user see? (no data, no setup)"),u.push("What if the network is slow? What loads first?"),{appName:o.name,summary:o.summary??"",screens:a,navigation:{style:o.navStyle??"sidebar",items:n},primaryAction:o.primaryAction??null,designDirection:{tone:t.tone??"professional",accentColor:t.accentColor??"blue",navStyle:o.navStyle??"sidebar",fonts:t.fonts??{heading:"Inter",body:"Inter"}},edgeCases:u}}function Zi(o,s){let e=[];e.push(`# Wireframe sketch for ${o.appName}`),e.push(""),e.push(`**${o.appName}** \u2014 ${o.summary}`),e.push(""),s&&(e.push("## Feedback to apply"),e.push(s),e.push("")),e.push("## Design principles"),e.push(""),e.push("Apply these when deciding layout and hierarchy:"),e.push("1. **Information hierarchy** \u2014 What does the user see first, second, third? The primary action is first. Metrics are second. Everything else is supporting."),e.push("2. **Interaction states** \u2014 Every screen has at least: empty, loading, populated. Show the populated state but add HTML comments noting the others."),e.push("3. **Edge case paranoia** \u2014 What if there are 0 items? 500 items? A 47-character name? Think about these and comment where they matter."),e.push(`4. **Subtraction** \u2014 "As little design as possible" (Dieter Rams). Every element earns its pixels. If removing something doesn't hurt, remove it.`),e.push("5. **Design for trust** \u2014 Clear labels, predictable layout, obvious actions. No mystery meat navigation."),e.push(""),e.push("## Wireframe rules (strict)"),e.push(""),e.push("Write a **single self-contained HTML file** saved to `.mistflow/mockups/mockup-{planId}.html` (replace `{planId}` with the actual plan ID)."),e.push(""),e.push("The wireframe must:"),e.push("- Use **system fonts only** (`-apple-system, system-ui, sans-serif`) \u2014 no Google Fonts, no CDN"),e.push("- Use **inline CSS only** \u2014 no external stylesheets, no Tailwind CDN"),e.push("- Look **intentionally rough** \u2014 thin gray borders (#ddd), light backgrounds (#f8f8f8), no color, no shadows"),e.push("- Use **realistic placeholder content** that matches this specific app (sample data provided below) \u2014 NOT lorem ipsum"),e.push("- Include **HTML comments** explaining design decisions (e.g., `<!-- Primary action is prominent because users come here to check in members -->`)"),e.push("- Show **all screens in a single page** using tabs/sections that the user can click through"),e.push("- Be **responsive** \u2014 test that it looks reasonable at both 1200px and 375px widths"),e.push("- Include a small header bar showing: screen name tabs + the design direction summary"),e.push(""),e.push("The wireframe must NOT:"),e.push("- Use any color except grayscale (#333, #666, #999, #ddd, #f8f8f8, white)"),e.push("- Use any external dependencies \u2014 no CDN, no imports, no build step"),e.push("- Look polished \u2014 it should feel like a sketch on a whiteboard, not a finished product"),e.push("- Include decorative elements \u2014 no icons (use text labels), no illustrations, no gradients"),e.push(""),e.push("## Screens to wireframe"),e.push("");for(let t of o.screens){e.push(`### ${t.name} (\`${t.route}\`)`),e.push(`**Purpose**: ${t.purpose}`),e.push(""),e.push("**Information hierarchy** (render in this order, top to bottom):");for(let n of t.informationHierarchy)e.push(`- ${n}`);e.push(""),e.push("**Interaction states** (add HTML comments for non-visible states):");for(let n of t.interactionStates)e.push(`- ${n}`);if(e.push(""),t.entities.length>0){e.push("**Data model and sample content** (use this real data, not lorem ipsum):");for(let n of t.entities)e.push(`
|
|
4127
|
+
**${n.name}** \u2014 fields: ${n.fields.map(a=>`${a.name} (${a.type})`).join(", ")}`),e.push("```json"),e.push(JSON.stringify(n.sampleData,null,2)),e.push("```");e.push("")}}e.push("## Navigation"),e.push(`**Style**: ${o.navigation.style} (use this layout)`),e.push("**Items**:");for(let t of o.navigation.items)e.push(`- ${t.label} \u2192 \`${t.route}\``);if(e.push(""),o.primaryAction&&(e.push("## Primary action (this drives the layout)"),e.push(`- **Action**: ${o.primaryAction.action}`),e.push(`- **Flow**: ${o.primaryAction.flow}`),e.push(`- **Dashboard must show**: ${o.primaryAction.dashboardSurface}`),e.push(""),e.push("The dashboard is an ACTION surface. The primary action should be the most prominent thing on the page \u2014 above the metrics, above the recent items. Users came here to DO something, not to look at numbers."),e.push("")),o.edgeCases.length>0){e.push("## Edge cases to consider"),e.push("Add HTML comments in the wireframe where these matter:");for(let t of o.edgeCases)e.push(`- ${t}`);e.push("")}return e.push("## Design direction (DO NOT apply to wireframe \u2014 this is for reference only)"),e.push(`The final app will use: ${o.designDirection.tone} tone, ${o.designDirection.accentColor} accent, ${o.designDirection.navStyle} nav, ${o.designDirection.fonts.heading} / ${o.designDirection.fonts.body} fonts.`),e.push("The wireframe is grayscale and rough. These tokens will be applied during the actual build."),e.push(""),e.push("## After writing the wireframe"),e.push(""),e.push("1. Write the file to `.mistflow/mockups/mockup-{planId}.html` (replace `{planId}` with the actual plan ID)"),e.push("2. Open it: `open .mistflow/mockups/mockup-{planId}.html`"),e.push(`3. Tell the user: "Here's a rough wireframe of your app. This shows the layout and information hierarchy \u2014 not the final visual design (colors, fonts, polish come during the build). Does the layout feel right? Want to move things around, or shall we start building?"`),e.join(`
|
|
4128
|
+
`)}function br(o){return ct(Is(),".mistflow","mockup-state",`${o}.json`)}function ea(o){let s=br(o);if(!zt(s))return null;try{return JSON.parse(fr(s,"utf-8"))}catch{return null}}function Ps(o,s){let e=ct(Is(),".mistflow","mockup-state");gr(e,{recursive:!0}),Ki(br(o),JSON.stringify(s,null,2))}async function wr(o){let{planId:s,feedback:e,approved:t}=o,n=Ji(o.projectPath??process.cwd()),a=ct(Is(),".mistflow","plans",`${s}.json`);if(!zt(a))return d(`Plan not found for planId '${s}'. Call mist_plan to generate a plan first.`,!0);let r;try{r=JSON.parse(fr(a,"utf-8"))}catch{return d("Failed to read plan file. Call mist_plan again.",!0)}let i=r.plan;if(!i)return d("Plan data is empty. Call mist_plan again.",!0);let l=ea(s);l||(l={planId:s,iterationCount:0,approved:!1,screens:[],feedback:[]});let c=ct(n,".mistflow","mockups");if(gr(c,{recursive:!0}),t){l.approved=!0,Ps(s,l);let f=zt(c)?yr(c).filter(w=>w.endsWith(".html")):[];return d(JSON.stringify({status:"approved",message:`Wireframe approved after ${l.iterationCount} iteration(s). Layout direction is locked in.`,mockupFiles:f.map(w=>`.mistflow/mockups/${w}`),nextAction:`NEXT: Call mist_build with action='init', name='${i.name}', and planId='${s}' to create the project. The wireframe in .mistflow/mockups/ will be used as layout reference during implementation.`}))}e?(l.iterationCount++,l.feedback.push(e)):l.iterationCount++,Ps(s,l);let u=Xi(i);l.screens=u.screens.map(f=>f.name),Ps(s,l);let m=Zi(u,e??void 0),p;return l.iterationCount>=3&&(p="The wireframe is shaping up \u2014 want to keep refining the layout, or start building?"),d(JSON.stringify({status:"wireframe",iterationCount:l.iterationCount,screens:u.screens.map(f=>({name:f.name,type:f.type,route:f.route})),wireframePrompt:m,designDirection:u.designDirection,...p?{nudge:p}:{},mockupFile:`mockup-${s}.html`,nextAction:e?`Apply the user's feedback to the wireframe. Rewrite .mistflow/mockups/mockup-${s}.html with the changes. Open it in the browser for review. Ask if they want more changes or are ready to build.`:`Generate the wireframe HTML following the wireframePrompt instructions above. Write it to .mistflow/mockups/mockup-${s}.html, then open it in the browser. Ask the user if the layout feels right.`}))}function vr(o){let s=ct(o,".mistflow","mockups");return zt(s)?yr(s).filter(e=>e.endsWith(".html")).map(e=>ct(s,e)):[]}var kr="\nApply these choices to every file you create. Customize the shadcn CSS variables in globals.css to match. Do NOT use default shadcn blue/zinc theme.\n\n**CRITICAL: shadcn/ui components are already installed. NEVER write components/ui/*.tsx files from scratch.** If you need a shadcn component, run `npx shadcn@latest add <component>` to pull it. The project already includes: button, card, input, label, form, dialog, table, dropdown-menu, badge, separator, skeleton, sheet, tabs, avatar, select, textarea, checkbox, switch, tooltip, popover, sonner.\n\n**shadcn MCP server is available.** You have the `shadcn` MCP server installed \u2014 use it to browse and search for components, blocks, and landing page sections from the shadcn registry. Before building a landing page section from scratch, check the registry for existing blocks (hero sections, feature grids, pricing tables, testimonials, footers) and customize them instead of reinventing.\n\n**Project routes (use these exact paths):** Login is at `/login` (NOT /sign-in). Register is at `/register` (NOT /sign-up). All landing page and nav links MUST use `/login` and `/register`.\n\n### Design quality rules (non-negotiable):\n\n**Typography**: Use the plan fonts everywhere. font-heading for headings, font-body for body text.\n- **Modular scale**: Use a 1.25-1.5 ratio between sizes. A 5-level system covers most needs: xs (0.75rem captions), sm (0.875rem metadata), base (1rem body), lg (1.25-1.5rem subheadings), xl+ (2-4rem headlines). Sizes too close together (14/15/16px) create muddy hierarchy.\n- **Vertical rhythm**: Your line-height IS your spacing unit. If body is 16px with line-height 1.5 (= 24px), vertical spacing should be multiples of 24px.\n- **Weight contrast**: Use font-medium/font-semibold contrast, not just size. Bold headings + regular body creates natural hierarchy without extra sizes.\n- **Measure**: Set `max-width: 65ch` on text containers. Long lines kill readability.\n- **OpenType polish**: Use `font-variant-numeric: tabular-nums` on data tables for aligned columns.\n- Never use more than 2 font families. One well-chosen family in multiple weights is cleaner than two competing typefaces.\n- Never fall back to system fonts. Never use decorative fonts for body text. Minimum 16px (1rem) for body.\n\n**Color**: Build a functional palette, not a rainbow.\n- **Tinted neutrals**: Pure gray is dead. Add a tiny tint toward the accent color to all your grays (borders, backgrounds, muted text). The tint should be subtle enough not to read as 'colored' but creates subconscious cohesion.\n- **60/30/10 rule**: 60% neutral backgrounds/whitespace, 30% secondary colors (text, borders, inactive states), 10% accent (CTAs, highlights, focus). Accent colors work BECAUSE they're rare. Overuse kills their power.\n- **Dangerous combos to avoid**: Light gray text on white (#1 accessibility fail). Gray text on any colored background (looks washed out and dead, use a darker shade of the background color instead). Yellow text on white. Thin light text on images.\n- **Dark mode is not inverted light mode**: Use lighter surfaces for depth (no shadows). Desaturate accents slightly. Never pure black backgrounds, use dark gray (12-18% lightness). Reduce body text weight slightly (350 vs 400) because light-on-dark reads heavier.\n- Never use pure #000 or #fff. Customize the shadcn CSS variables in globals.css to match the plan palette.\n\n**Layout & space**: Space is a design material, not leftover.\n- **4px base unit**: All spacing should be multiples of 4: 4, 8, 12, 16, 24, 32, 48, 64, 96px. No arbitrary values. Name tokens semantically (`space-sm`, `space-lg`), not by value.\n- **Use `gap` not margins**: Use `gap` for sibling spacing. It eliminates margin collapse hacks and is more predictable. Reserve margin for positioning, not spacing between siblings.\n- **Rhythm through contrast**: Tight groupings within related items (8-12px), generous separation between sections (48-96px). Vary spacing WITHIN sections too. Not every row needs the same gap. The ratio between inner and outer spacing creates hierarchy.\n- **Density matches content**: Data-dense UIs (dashboards, tables, admin panels) need tighter spacing with more information visible. Marketing pages need generous whitespace and breathing room. Match density to what the user is doing.\n- **The squint test**: Blur your eyes. Can you still identify primary, secondary, and clear groupings? If everything looks the same weight, hierarchy is broken. The most important content should be obvious within 2 seconds.\n- **Asymmetry > centering**: Left-aligned with asymmetric layouts feels more designed. Center-alignment is fine for hero sections and CTAs, not for body content.\n- **Flex vs Grid**: Use Flexbox for 1D layouts (rows of items, navbars, button groups, card contents, most component internals). Use Grid for 2D layouts (page-level structure, dashboards, data-dense interfaces where rows AND columns need coordinated control). Don't default to Grid when Flexbox with `flex-wrap` would be simpler. Use `repeat(auto-fit, minmax(280px, 1fr))` for responsive grids without breakpoints. Use named `grid-template-areas` for complex page layouts and redefine at breakpoints.\n- **Cards earn their existence**: Only use cards when content needs clear separation, grid comparison, or interaction boundaries. Not everything needs a container. Never nest cards inside cards. Vary card sizes or mix cards with non-card content to break repetition.\n- **Section variety**: Don't make every section the same structure. Alternate layouts (text-left/image-right, then image-left/text-right), vary section heights, mix full-width with contained content. Monotonous section rhythm signals no designer touched this.\n- **Z-index scale**: Use a semantic scale, not arbitrary numbers. dropdown(10) -> sticky(20) -> modal-backdrop(30) -> modal(40) -> toast(50) -> tooltip(60). Never use 999 or 9999.\n- **Touch targets**: Minimum 44x44px for all interactive elements, even if the visual element is smaller (use padding).\n\n**Cards & surfaces**: Match the plan's cardStyle. Stat cards need background fills with the accent color as a subtle icon background or tinted left border. Use bg-muted/30 for section differentiation between page areas. Build a consistent shadow scale (sm -> md -> lg) and use elevation to reinforce hierarchy, not as decoration.\n\n**Sidebar**: App name + icon at top. Nav items with hover:bg-muted rounded-md transition. Active item: bg-primary/10 text-primary font-medium. User email + sign out at bottom. The sidebar should feel like a distinct surface (bg-card or bg-muted/50).\n**Mobile navigation**: The desktop sidebar must collapse to a hamburger menu on mobile. Use the shadcn `Sheet` component: a hamburger icon button (visible at `md:hidden`) opens a Sheet from the left containing the same nav items. The desktop sidebar is `hidden md:flex`. For simple apps with 3-5 nav items, a bottom tab bar (`fixed bottom-0`) is an alternative. Always respect `env(safe-area-inset-bottom)` for notched phones.\n\n**Interaction design**: Every interactive element needs 8 states, not just default and hover.\n- **Required states**: default, hover, focus, active/pressed, disabled, loading, error, success. Design all of them intentionally.\n- **Focus rings**: Use `:focus-visible` (not `:focus`) so rings show for keyboard users but not mouse clicks. Never remove focus indicators without replacement.\n- **Button hierarchy**: Don't make every button primary. Use ghost, outline, secondary, and text-link variants. One primary CTA per view.\n- **Progressive disclosure**: Simple first, advanced behind expandable sections. Don't overwhelm with options.\n- **Undo over confirmation**: For destructive actions, remove immediately + show an undo toast, then permanently delete after timeout. Better than confirmation dialogs that users click through blindly.\n- **Form patterns**: Visible `<label>` elements always (placeholders aren't labels, they disappear). Validate on blur, not on keystroke. Show format expectations with examples.\n\n**Empty states**: Every empty list/table needs a rich empty state. Not just 'Nothing here'. Include: a simple inline SVG illustration (48x48, relevant to the feature), a specific message that teaches ('Create your first habit to start tracking your daily routine'), and a primary action button. Empty states are the first thing new users see. Make them inviting.\n\n**Loading states**: Use the shadcn `Skeleton` component. Show skeleton versions of cards, lists, and stats during data fetches. Example: `<Skeleton className=\"h-8 w-32\" />` for a stat number, `<Skeleton className=\"h-20 w-full\" />` for a card. Add a `loading.tsx` file in dashboard route groups. Never show a blank page or a lone spinner.\n\n**Images**: For Unsplash images on landing pages, use `next/image` with `placeholder=\"blur\"` and a blurDataURL (a tiny 10x6 base64 image \u2014 generate a solid color blur like `data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAGCAYAAAD68A/GAAAAP0lEQVQYV2N89+7dfwYGBgZGRkYGBgYmBjIBE7kaPHv27D8DA8N/BgYGRkZGRgYGJgYyARO5GkjWQHEoxRoAAPyTGAGBMpEAAAAASUVORK5CYII=`). This creates a smooth shimmer-in effect instead of images popping in.\n\n**Motion** (`motion` package is installed):\n\n**Hero moment strategy**: Pick ONE signature animation per page. Not scattered animations on everything. On a landing page, the hero entrance is your hero moment. On a dashboard, a satisfying success animation after the primary action. One great animation > ten mediocre ones. Everything else gets subtle transitions.\n\n**Animation opportunity audit** -- check these 5 categories:\n1. **Missing feedback**: Button has no press response? Add `active:scale-[0.97]` (CSS) or `whileTap={{ scale: 0.97 }}` (motion). Toggle has no slide? Animate it.\n2. **Jarring transitions**: Menu appears instantly? Add 200ms fade + slide. Content swaps without transition? Crossfade between states.\n3. **Unclear relationships**: Parent-child not visually connected? Stagger children 50ms after parent. Deleted item just disappears? Animate it out (opacity + height collapse).\n4. **Lack of delight**: Success state is flat? Draw a checkmark SVG with stroke-dashoffset animation. Empty state is static? Add a gentle float on the illustration.\n5. **Missed guidance**: First-time user gets no hint? Pulse the primary CTA once on page load. New feature unnoticed? Brief highlight animation.\n\n**Timing hierarchy**: 100-150ms for instant feedback (buttons, toggles). 200-300ms for state changes (menus, tooltips). 300-500ms for layout shifts (accordions, modals). 500-800ms for entrances (page loads). Exit animations run at 75% of entrance duration.\n\n**Easing**: Use exponential curves (Quart out, Expo out) for sophisticated physics. Never `ease` (generic), never bounce/elastic (dated). Real objects decelerate smoothly. CSS: `cubic-bezier(0.25, 1, 0.5, 1)` (Quart out) or `cubic-bezier(0.16, 1, 0.3, 1)` (Expo out).\n\n**Micro-interaction recipes**:\n- **Button press**: `active:scale-[0.97] transition-transform duration-100` (CSS only, no motion needed)\n- **Success checkmark**: SVG `<path>` with `stroke-dasharray` + `stroke-dashoffset` animation from full to 0. 400ms Expo out.\n- **Height expand/collapse**: `grid-template-rows: 0fr -> 1fr` with `transition: grid-template-rows 300ms`. No JS layout measurement needed.\n- **Skeleton to content**: Skeleton pulses (CSS `animate-pulse`), then crossfades to real content with `opacity` transition. Use the pre-scaffolded `<ContentLoader>` component.\n- **Staggered list entrance**: CSS `animation-delay` on children: `.animate-fade-up:nth-child(1) { animation-delay: 0ms } :nth-child(2) { animation-delay: 50ms }` etc. Or use `<StaggerList>` component.\n- **Number count-up**: Use `@number-flow/react` for smooth digit morphing on stats/metrics.\n\n**Performance**: Only animate `transform` and `opacity` (GPU-accelerated). Never animate width, height, top, left, margin, or padding. For scroll-tied effects on landing pages, use CSS `animation-timeline: scroll()` where supported (progressive enhancement).\n\n**Accessibility**: Always respect `prefers-reduced-motion`. Wrap animations in `@media (prefers-reduced-motion: no-preference) { ... }`. Provide static alternatives that convey the same information.\n\n**SSR-safe (CRITICAL)**: This app deploys to Mistflow Cloud's edge runtime where IntersectionObserver may not fire. NEVER use `initial={{ opacity: 0 }}` (content stays invisible forever). Use CSS @keyframes for entrance effects:\n```tsx\n// SAFE: CSS @keyframes in globals.css:\n// @keyframes fade-up { from { opacity: 0; transform: translateY(16px); } to { opacity: 1; transform: translateY(0); } }\n// .animate-fade-up { animation: fade-up 0.5s ease-out both; }\n// Use motion ONLY for hover/tap/gesture interactions:\nimport { motion } from 'motion/react';\n<motion.div whileHover={{ scale: 1.02 }} whileTap={{ scale: 0.97 }} transition={{ duration: 0.15 }}>\n// NEVER: <motion.div initial={{ opacity: 0 }} whileInView={{ opacity: 1 }}>\n```\nFor dashboard pages, keep animations minimal. Button press feedback + skeleton loading + success states. No entrance animations on dashboard pages.\n\n**UX writing**: Every word earns its place.\n- **Buttons**: Use outcome-focused verb + object ('Save changes', 'Create account'), never generic ('Submit', 'OK', 'Click here').\n- **Destructive actions**: State exact consequences ('Delete 5 items permanently', not 'Delete selected'). Distinguish 'Delete' (permanent) from 'Remove' (recoverable).\n- **Error messages**: Answer three questions: what happened, why, and how to fix it. 'Email address is not valid. Include an @ symbol.' not 'Invalid input'. Never blame the user.\n- **Empty states**: Explain what will appear here, why it matters, and give a clear next action.\n- **Loading/progress**: Set time expectations. 'Deploying your app (usually takes 30 seconds)' not just a spinner.\n- **Consistency**: Pick one term and stick with it. 'Delete' everywhere, not Delete/Remove/Trash interchangeably.\n- **Link text**: Make it standalone for accessibility. 'View pricing plans' not 'Click here'.\n\n**Responsive design**: Mobile-first, then enhance.\n- **Mobile-first CSS**: Write base styles for mobile, then use `min-width` media queries to enhance for larger screens. Never start with desktop and try to cram it into mobile.\n- **Input method matters more than screen size**: Use `@media (pointer: fine)` for mouse/trackpad (smaller targets OK, hover effects work), `@media (pointer: coarse)` for touch (44px targets required, no hover-dependent UI). Use `@media (hover: none)` to detect devices that can't hover. Never require hover to reveal functionality.\n- **Safe areas**: Add `<meta name='viewport' content='width=device-width, initial-scale=1, viewport-fit=cover'>` and use `env(safe-area-inset-bottom)` for bottom navigation on notched phones. Fixed bottom bars must respect safe areas.\n- **Self-adjusting grids**: Use `grid-template-columns: repeat(auto-fit, minmax(280px, 1fr))` for card grids. Columns reflow naturally without breakpoint management.\n- **Container queries over media queries**: For reusable components, use `container-type: inline-size` on the parent and `@container (min-width: 400px)` on children. Components adapt to their container, not the viewport.\n- **No horizontal scroll**: Nothing should overflow the viewport width. Test at 320px width (smallest common phone). Use `overflow-x: hidden` on the body as a safety net but fix the root cause.\n- **Touch-friendly spacing**: On mobile, increase padding on list items and nav links. Thumb zone for primary actions is bottom-center of the screen.\n- **Responsive images**: Use `next/image` with `sizes` prop for responsive sizing. For art direction changes, use `<picture>` with `<source media='...'>`. Always set `width` and `height` to prevent layout shift.\n\n**Cognitive load**: Simpler apps feel better, even with the same features.\n- **Max 4 items per group**: Humans hold 4 items in working memory. Navigation menus: max 5 top-level items. Forms: max 4 fields per section. Dashboards: max 4 metrics visible without scrolling. Pricing: max 3 tiers.\n- **Single focus per view**: Every page has ONE primary task. If there are two equal CTAs, neither is primary. One primary action, everything else is secondary or tertiary.\n- **Sequential decisions**: Don't present all options at once. Multi-step forms beat one long form. Each step should have one decision.\n- **Progressive disclosure**: Show the essential first, reveal complexity on demand. Use expandable sections, tabs, or drill-down navigation. The default view should cover 80% of use cases.\n- **Visual grouping**: Related items must be visually grouped (proximity + shared background or border). Unrelated items must have clear separation. The Gestalt principle of proximity is the easiest way to reduce cognitive load.\n- **Reduce choice anxiety**: For important decisions, provide a recommended/default option. Highlight it visually. 'Most popular' badges on pricing plans reduce decision time.\n- **Keep context visible**: In multi-step flows, show a progress indicator and allow going back. Never make users remember what they entered on a previous screen.\n\n**Production hardening**: Designs that only work with perfect data aren't production-ready.\n- **Text overflow**: Use `text-overflow: ellipsis` + `overflow: hidden` for single-line text in constrained spaces. Use `-webkit-line-clamp` for multi-line. Add `min-width: 0` on flex items to prevent overflow.\n- **Extreme inputs**: Test with 100+ character names, emoji in text fields, and empty strings. The layout should not break.\n- **Error resilience**: Every API call needs error UI. Network failures, 404s, 500s all need clear messages with recovery options. Never show raw stack traces.\n\n**Landing page component patterns** (use these for professional, non-generic landing pages):\nBuild these components inline (shadcn + motion + Tailwind is enough):\n- **Animated number counters**: Use `@number-flow/react` (installed) for stat sections. `<NumberFlow value={count} />` with smooth digit transitions.\n- **Marquee / logo ticker**: CSS-only infinite scroll (`@keyframes marquee { from { transform: translateX(0) } to { transform: translateX(-50%) } }`) with duplicated content. Pause on hover.\n- **Bento grid**: CSS grid with varied `col-span` and `row-span`. Each cell gets a unique visual. Never make all cells the same size.\n- **Animated beam / connection lines**: SVG paths with `motion` stroke-dashoffset animation for 'how it works' sections.\n- **Shimmer borders**: `background: conic-gradient(...)` wrapper with animation for hero CTAs.\n- **Comparison tables**: Sticky-header table with check/x icons and row highlighting on the recommended plan.\n- **Testimonial carousel**: CSS scroll-snap for horizontal cards with avatar, quote, name, role. Auto-scroll paused on hover.\n- **Gradient mesh backgrounds**: Multiple layered `radial-gradient` backgrounds for hero sections.\nPick 3-5 per landing page based on the app's content. The goal: every landing page should look like it was designed by a human, not generated by AI.\n\n**Landing page navbar (non-negotiable):** Fully transparent (no background, no border, no backdrop-blur) and NOT sticky/fixed. It sits inside the hero section and scrolls naturally. White text on dark hero backgrounds. Primary CTA button in the nav uses the accent color (solid fill, rounded-md). Do NOT use `sticky`, `fixed`, `top-0`, or `backdrop-blur` on landing page navbars. Dashboard sidebar/nav IS fixed (different pattern).\n\n**Design for THIS app, not any app** (the #1 way to avoid generic AI output):\n- Every layout decision should be informed by what THIS app does. A gym check-in app needs a prominent search bar. A habit tracker needs a daily view. A CRM needs a pipeline. Don't default to the same dashboard-with-stats layout for everything.\n- Write copy that is SPECIFIC to the app's domain. Not 'Manage your data efficiently' but 'Check in members in under 3 seconds'. Every headline, empty state, and CTA should reference what the user actually does in this app.\n- Choose visual emphasis based on the primary action. If the user comes to log a workout, the workout form should be the biggest thing on the dashboard.\n- Use domain-appropriate metaphors. A fitness app uses progress rings. A project tracker uses kanban columns. A recipe app uses cards with photos. Don't use the same card grid for everything.\n\n**NEVER do these (AI slop anti-patterns)**:\nThe following are telltale signs of AI-generated design. Avoid all of them.\n*Visual patterns*:\n- Cyan-on-dark, purple-to-blue gradients, neon accents on dark backgrounds (the AI color palette)\n- Gradient text on headings or metrics (decorative noise, not meaningful)\n- Glassmorphism / blur effects used decoratively (only use blur for overlays/modals that need it)\n- Rounded rectangles with thick colored border on one side (lazy accent, never looks intentional)\n- Dark mode with glowing colored box-shadows on accent elements\n- Small rounded-square icon tiles stacked above headings (the icon-tile pattern)\n- Pure black (#000) backgrounds in dark mode (use tinted dark gray instead)\n- 3-column icon + title + paragraph feature grid (use asymmetric layouts, bento grids, or varied card sizes)\n- Nested cards inside cards (visual noise, flatten the hierarchy)\n- Everything center-aligned (use left-alignment for body content, reserve center for heroes/CTAs)\n- Monotonous spacing (same gap everywhere signals no designer touched this)\n*Copy patterns*:\n- Hero text like 'Transform your X' / 'One Day at a Time' / 'Join thousands' / 'Unlock the power of' (write SPECIFIC copy)\n- Generic feature descriptions ('Powerful analytics', 'Seamless integration', 'Lightning fast')\n- The hero metric template (big number, small label, supporting stats, gradient accent)\n- Repeating information users can already see. Every word must earn its place.\n*Functional patterns*:\n- Bounce/elastic easing on animations (feels dated, real objects decelerate smoothly, use Quart/Expo out)\n- Modals for things that could be inline (modals are a last resort, not a default)\n- Nav links to pages that don't exist. EVERY link in the sidebar/topnav MUST have a corresponding page.\n- FAKE FORMS. NEVER use `setTimeout` or `await new Promise` to simulate API calls. Every form MUST have a real server action (actions.ts with 'use server') that writes to the database. If a form doesn't persist data, the feature is BROKEN.\n\n**Favicon**: A default SVG favicon exists at app/icon.svg. On the landing page step, update it to match the app. Keep it simple (a single icon/letter on a rounded square, using the accent color).\n";var xr=`# Landing Page Rules
|
|
4129
4129
|
|
|
4130
4130
|
These rules apply to every landing page. They are non-negotiable.
|
|
4131
4131
|
|
|
@@ -4985,14 +4985,14 @@ If there's a pricing page:
|
|
|
4985
4985
|
## The Footer
|
|
4986
4986
|
|
|
4987
4987
|
A footer with the same five links ("Product / Pricing / Docs / Blog / Terms") is fine, but the company name / tagline should be specific. "StandupSync \u2014 async updates, human-sized" is better than "\xA9 2026 StandupSync Inc."
|
|
4988
|
-
`;function
|
|
4989
|
-
`)}function zt(s){return s.entity??s.name??"Unknown"}function ga(s){return s.length===0?"":typeof s[0]=="string"?s.join(", "):s.map(o=>`${o.name} (${o.type})`).join(", ")}function Nr(s){return s.path??s.route??s.name??""}function fa(s){let o=(s||"text").toLowerCase();return o==="string"||o==="varchar"||o==="char"?"text":o==="integer"||o==="int"||o==="number"||o==="float"||o==="decimal"||o==="double"?"number":o==="boolean"||o==="bool"?"boolean":o==="date"||o==="datetime"||o==="timestamp"?"date":o==="email"?"email":o==="url"||o==="uri"?"url":o==="enum"||o==="select"?"select":o==="text"||o==="longtext"||o==="textarea"?"textarea":"text"}function _r(s,o){if(!s.entities||s.entities.length===0)return o;let e=s.entities.map(t=>t.toLowerCase());return o.filter(t=>{let n=zt(t).toLowerCase();return e.some(a=>n.includes(a)||a.includes(n))})}function ya(s,o){if(!s.pages||s.pages.length===0)return[];let e=s.pages.map(t=>t.toLowerCase());return o.filter(t=>{let n=(t.name??"").toLowerCase(),a=Nr(t).toLowerCase();return e.some(r=>n.includes(r)||r.includes(n)||a.includes(r))})}var ba=new Set(["landing","design","dashboard","crud","layout","admin","auth","schema","integration","multi-tenant","deploy","general"]);function wa(s){let o=s.stepType;if(o&&ba.has(o))return o;if(s.integrationId)return"integration";let e=`${s.name} ${s.description}`.toLowerCase();return e.includes("crud")||e.includes("list")&&e.includes("create")?"crud":e.includes("auth")||e.includes("login")||e.includes("register")?"auth":e.includes("admin")&&(e.includes("panel")||e.includes("dashboard")||e.includes("manage")||e.includes("users"))?"admin":e.includes("dashboard")||e.includes("overview")||e.includes("analytics")?"dashboard":e.includes("schema")||e.includes("database")||e.includes("model")?"schema":e.includes("layout")||e.includes("sidebar")||e.includes("navigation")?"layout":e.includes("deploy")||e.includes("cloudflare")?"deploy":e.includes("organization")||e.includes("team")||e.includes("workspace")||e.includes("multi-tenant")||e.includes("invite member")?"multi-tenant":e.includes("landing")||e.includes("hero")||e.includes("marketing")||e.includes("homepage")?"landing":e.includes("design")||e.includes("theme")||e.includes("styling")||e.includes("ui polish")||e.includes("visual")?"design":"general"}function va(s){switch(s){case"landing":case"design":return{min:6,max:10};case"integration":return{min:8,max:12};case"dashboard":case"admin":return{min:5,max:7};case"crud":case"multi-tenant":return{min:4,max:6};case"schema":return{min:3,max:4};case"layout":case"auth":return{min:3,max:5};case"deploy":return{min:1,max:2};default:return{min:4,max:6}}}function ka(s,o){let e=[];if(e.push("### Design choices (decided at plan time \u2014 follow these exactly):"),s.tone&&e.push(`- **App tone**: ${s.tone}`),s.fonts&&(e.push(`- **Heading font**: ${s.fonts.heading} (load from Google Fonts)`),e.push(`- **Body font**: ${s.fonts.body} (load from Google Fonts)`)),e.push("- **All color comes from CSS variables** \u2014 never use Tailwind palette utilities like `bg-emerald-500`, `text-blue-600`, `border-slate-200`. Use `bg-primary`, `text-primary-foreground`, `bg-muted`, `text-muted-foreground`, `border-border`, `bg-card`, `text-foreground`, `bg-destructive`, etc. The primary/accent is already wired in globals.css from the chosen design system."),e.push("- **Outbound URLs (invite links, email CTAs, absolute hrefs in server code):** use `process.env.BETTER_AUTH_URL` as the base. Do NOT use `process.env.NEXT_PUBLIC_APP_URL` \u2014 Next.js bakes every `NEXT_PUBLIC_*` literal into the production bundle at build time, so the scaffolded localhost default ships to prod and invite emails land on `http://localhost:3000`. Client components should use relative URLs (they resolve to the current origin automatically)."),s.borderRadius){let t={sharp:"2px",subtle:"6px",rounded:"12px",pill:"9999px"};e.push(`- **Border radius**: ${s.borderRadius} (${t[s.borderRadius]??s.borderRadius}) \u2014 set as --radius in globals.css`)}if(s.shadowStyle){let t={flat:"No shadows \u2014 use borders for separation",subtle:"shadow-sm on cards, shadow on hover",elevated:"shadow-md on cards, shadow-lg on modals, layered depth",dramatic:"shadow-lg with colored tinting, bold depth"};e.push(`- **Shadow style**: ${s.shadowStyle} \u2014 ${t[s.shadowStyle]??s.shadowStyle}`)}if(s.cardStyle){let t={filled:"bg-card with subtle background fill, no visible border",bordered:"border border-border on white/transparent background",elevated:"bg-card shadow-md, no border, lifted appearance",glass:"bg-white/60 backdrop-blur-sm border border-white/20, translucent"};e.push(`- **Card style**: ${s.cardStyle} \u2014 ${t[s.cardStyle]??s.cardStyle}`)}if(s.landingTone&&e.push(`- **Landing page tone**: ${s.landingTone}`),s.visualStrategy){let t=s.visualStrategy,n=s.heroPhoto!==!1,a=n&&!!t.heroImages?.length;if(e.push(""),e.push("### Visual strategy:"),a&&t.heroImages&&t.heroImages.length>0){e.push("**Hero image** \u2014 use this Unsplash photo as the landing page hero BACKGROUND:");let r=t.heroImages[0];e.push(`- URL: ${r.url}`),e.push(`- Alt text for img tag: "${r.alt||"Hero image"} \u2014 Photo by ${r.photographer} on Unsplash"`),e.push("- Use as full-bleed background behind the entire hero section with a dark overlay (bg-black/60 or similar for readability). The photo is atmosphere and context, NOT the main visual \u2014 the glassmorphic product card sits on top.")}else n&&!t.heroImages?.length?e.push("**Hero background** \u2014 the user requested a lifestyle photo, but no Unsplash image was fetched (likely a transient API issue). Fall back gracefully: use the design preset's gradient + glassmorphism, AND tell the user in your reply: 'I couldn't fetch a stock photo for the hero this time \u2014 using a CSS gradient instead. You can add a photo later by editing the hero section in app/page.tsx.'"):n||e.push("**Hero background** \u2014 user opted for CSS-only (no photo). Use the design preset's specified gradient, animated background, or glassmorphism. No Unsplash.");if(t.sectionImages?.length){e.push("**Section images available** \u2014 use these for feature sections, about sections, or testimonial backgrounds (NOT the hero):");for(let r of t.sectionImages)e.push(`- ${r.url} \u2014 alt: "${r.alt||"section image"} \u2014 Photo by ${r.photographer} on Unsplash"`)}(a||t.sectionImages?.length)&&e.push("For image attribution: put photographer credit in the img alt text (already provided above) and add an HTML comment <!-- Images from Unsplash --> near the images. Do NOT add visible attribution text on the page."),e.push(""),e.push("**Hero layout \u2014 split hero with product UI mockup (follow this exactly):**"),e.push("The hero uses a split layout with text on the left and a product preview on the right. This is non-negotiable for consumer apps and SaaS/tool apps alike."),e.push(""),e.push("```"),e.push("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),e.push("\u2502 [Logo] [Sign In] [CTA \u2192] \u2502 \u2190 transparent nav, NOT sticky"),e.push("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),e.push("\u2502 \u2502"),e.push("\u2502 \u25CF Built for [audience] \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u2502"),e.push("\u2502 \u2502 Glassmorphic \u2502 \u2502"),e.push("\u2502 Big bold headline, \u2502 product mockup \u2502 \u2502"),e.push("\u2502 accent color on key word \u2502 card showing \u2502 \u2502"),e.push("\u2502 \u2502 real app data \u2502 \u2502"),e.push("\u2502 Description paragraph \u2502 (stats, table, \u2502 \u2502"),e.push("\u2502 \u2502 chart, etc.) \u2502 \u2502"),e.push("\u2502 [Primary CTA \u2192] [Secondary] \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2502"),e.push("\u2502 \u2502"),e.push("\u2502 500+ 25K+ 99% \u2502"),e.push("\u2502 Label Label Label \u2502"),e.push("\u2502 \u2502"),a?e.push("\u2502 \u2190 full-bleed photo bg + dark overlay behind all \u2192 \u2502"):e.push("\u2502 \u2190 preset gradient / glass background behind all \u2192 \u2502"),e.push("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),e.push("```"),e.push(""),e.push("**Left side (~55%)**: badge pill \u2192 bold headline (use accent color on ONE key word or phrase) \u2192 description \u2192 two CTA buttons (primary filled + secondary outline/ghost) \u2192 stats row with 3 proof points"),e.push("**Right side (~45%)**: A glassmorphic floating card that previews what the app looks like inside:"),e.push("- Style: `bg-white/10 backdrop-blur-lg border border-white/20 rounded-2xl shadow-2xl p-6` (over dark/photo bg) OR `bg-white/60 backdrop-blur-lg border border-black/5 rounded-2xl shadow-2xl p-6` (over light bg)"),e.push("- Content: Build realistic fake app data using styled divs \u2014 stat cards, mini table rows, schedule blocks, or charts that match what this specific app's dashboard shows"),e.push("- Must be DOMAIN-SPECIFIC: a library app shows book catalog rows, a gym app shows check-in stats, a CRM shows pipeline cards"),e.push("- Add subtle inner elements with `bg-white/5` or `bg-white/10` for depth"),e.push("**Stats row**: 3 proof-point numbers at the bottom of the left side (e.g., '500+ Gyms', '25K+ Members', '99% Uptime'). Match text color to the background contrast.")}return e.push(""),e.push(kr),e.join(`
|
|
4990
|
-
`)}async function
|
|
4988
|
+
`;function ha(o){return new Promise(s=>{let e=ma({port:o,host:"127.0.0.1"});e.on("connect",()=>{e.destroy(),s(!0)}),e.on("error",()=>{s(!1)})})}var mp=Rs.object({projectPath:Rs.string().optional().describe("Path to the project directory (default: cwd)"),step:Rs.number().optional().describe("Specific step number to implement (default: next incomplete step)")});function ga(o){let s=dt(o,"mistflow.json");if(!Tt(s))return null;try{return JSON.parse(Ns(s,"utf-8"))}catch{return null}}function Er(o,s){let e=dt(o,"mistflow.json");Es(e,JSON.stringify(s,null,2)+`
|
|
4989
|
+
`)}function Ht(o){return o.entity??o.name??"Unknown"}function fa(o){return o.length===0?"":typeof o[0]=="string"?o.join(", "):o.map(s=>`${s.name} (${s.type})`).join(", ")}function Nr(o){return o.path??o.route??o.name??""}function ya(o){let s=(o||"text").toLowerCase();return s==="string"||s==="varchar"||s==="char"?"text":s==="integer"||s==="int"||s==="number"||s==="float"||s==="decimal"||s==="double"?"number":s==="boolean"||s==="bool"?"boolean":s==="date"||s==="datetime"||s==="timestamp"?"date":s==="email"?"email":s==="url"||s==="uri"?"url":s==="enum"||s==="select"?"select":s==="text"||s==="longtext"||s==="textarea"?"textarea":"text"}function _r(o,s){if(!o.entities||o.entities.length===0)return s;let e=o.entities.map(t=>t.toLowerCase());return s.filter(t=>{let n=Ht(t).toLowerCase();return e.some(a=>n.includes(a)||a.includes(n))})}function ba(o,s){if(!o.pages||o.pages.length===0)return[];let e=o.pages.map(t=>t.toLowerCase());return s.filter(t=>{let n=(t.name??"").toLowerCase(),a=Nr(t).toLowerCase();return e.some(r=>n.includes(r)||r.includes(n)||a.includes(r))})}var wa=new Set(["landing","design","dashboard","crud","layout","admin","auth","schema","integration","multi-tenant","deploy","general"]);function va(o){let s=o.stepType;if(s&&wa.has(s))return s;if(o.integrationId)return"integration";let e=`${o.name} ${o.description}`.toLowerCase();return e.includes("crud")||e.includes("list")&&e.includes("create")?"crud":e.includes("auth")||e.includes("login")||e.includes("register")?"auth":e.includes("admin")&&(e.includes("panel")||e.includes("dashboard")||e.includes("manage")||e.includes("users"))?"admin":e.includes("dashboard")||e.includes("overview")||e.includes("analytics")?"dashboard":e.includes("schema")||e.includes("database")||e.includes("model")?"schema":e.includes("layout")||e.includes("sidebar")||e.includes("navigation")?"layout":e.includes("deploy")||e.includes("cloudflare")?"deploy":e.includes("organization")||e.includes("team")||e.includes("workspace")||e.includes("multi-tenant")||e.includes("invite member")?"multi-tenant":e.includes("landing")||e.includes("hero")||e.includes("marketing")||e.includes("homepage")?"landing":e.includes("design")||e.includes("theme")||e.includes("styling")||e.includes("ui polish")||e.includes("visual")?"design":"general"}function ka(o){switch(o){case"landing":case"design":return{min:6,max:10};case"integration":return{min:8,max:12};case"dashboard":case"admin":return{min:5,max:7};case"crud":case"multi-tenant":return{min:4,max:6};case"schema":return{min:3,max:4};case"layout":case"auth":return{min:3,max:5};case"deploy":return{min:1,max:2};default:return{min:4,max:6}}}function xa(o,s){let e=[];if(e.push("### Design choices (decided at plan time \u2014 follow these exactly):"),o.tone&&e.push(`- **App tone**: ${o.tone}`),o.fonts&&(e.push(`- **Heading font**: ${o.fonts.heading} (load from Google Fonts)`),e.push(`- **Body font**: ${o.fonts.body} (load from Google Fonts)`)),e.push("- **All color comes from CSS variables** \u2014 never use Tailwind palette utilities like `bg-emerald-500`, `text-blue-600`, `border-slate-200`. Use `bg-primary`, `text-primary-foreground`, `bg-muted`, `text-muted-foreground`, `border-border`, `bg-card`, `text-foreground`, `bg-destructive`, etc. The primary/accent is already wired in globals.css from the chosen design system."),e.push("- **Outbound URLs (invite links, email CTAs, absolute hrefs in server code):** use `process.env.BETTER_AUTH_URL` as the base. Do NOT use `process.env.NEXT_PUBLIC_APP_URL` \u2014 Next.js bakes every `NEXT_PUBLIC_*` literal into the production bundle at build time, so the scaffolded localhost default ships to prod and invite emails land on `http://localhost:3000`. Client components should use relative URLs (they resolve to the current origin automatically)."),o.borderRadius){let t={sharp:"2px",subtle:"6px",rounded:"12px",pill:"9999px"};e.push(`- **Border radius**: ${o.borderRadius} (${t[o.borderRadius]??o.borderRadius}) \u2014 set as --radius in globals.css`)}if(o.shadowStyle){let t={flat:"No shadows \u2014 use borders for separation",subtle:"shadow-sm on cards, shadow on hover",elevated:"shadow-md on cards, shadow-lg on modals, layered depth",dramatic:"shadow-lg with colored tinting, bold depth"};e.push(`- **Shadow style**: ${o.shadowStyle} \u2014 ${t[o.shadowStyle]??o.shadowStyle}`)}if(o.cardStyle){let t={filled:"bg-card with subtle background fill, no visible border",bordered:"border border-border on white/transparent background",elevated:"bg-card shadow-md, no border, lifted appearance",glass:"bg-white/60 backdrop-blur-sm border border-white/20, translucent"};e.push(`- **Card style**: ${o.cardStyle} \u2014 ${t[o.cardStyle]??o.cardStyle}`)}if(o.landingTone&&e.push(`- **Landing page tone**: ${o.landingTone}`),o.visualStrategy){let t=o.visualStrategy,n=o.heroPhoto!==!1,a=n&&!!t.heroImages?.length;if(e.push(""),e.push("### Visual strategy:"),a&&t.heroImages&&t.heroImages.length>0){e.push("**Hero image** \u2014 use this Unsplash photo as the landing page hero BACKGROUND:");let r=t.heroImages[0];e.push(`- URL: ${r.url}`),e.push(`- Alt text for img tag: "${r.alt||"Hero image"} \u2014 Photo by ${r.photographer} on Unsplash"`),e.push("- Use as full-bleed background behind the entire hero section with a dark overlay (bg-black/60 or similar for readability). The photo is atmosphere and context, NOT the main visual \u2014 the glassmorphic product card sits on top.")}else n&&!t.heroImages?.length?e.push("**Hero background** \u2014 the user requested a lifestyle photo, but no Unsplash image was fetched (likely a transient API issue). Fall back gracefully: use the design preset's gradient + glassmorphism, AND tell the user in your reply: 'I couldn't fetch a stock photo for the hero this time \u2014 using a CSS gradient instead. You can add a photo later by editing the hero section in app/page.tsx.'"):n||e.push("**Hero background** \u2014 user opted for CSS-only (no photo). Use the design preset's specified gradient, animated background, or glassmorphism. No Unsplash.");if(t.sectionImages?.length){e.push("**Section images available** \u2014 use these for feature sections, about sections, or testimonial backgrounds (NOT the hero):");for(let r of t.sectionImages)e.push(`- ${r.url} \u2014 alt: "${r.alt||"section image"} \u2014 Photo by ${r.photographer} on Unsplash"`)}(a||t.sectionImages?.length)&&e.push("For image attribution: put photographer credit in the img alt text (already provided above) and add an HTML comment <!-- Images from Unsplash --> near the images. Do NOT add visible attribution text on the page."),e.push(""),e.push("**Hero layout \u2014 split hero with product UI mockup (follow this exactly):**"),e.push("The hero uses a split layout with text on the left and a product preview on the right. This is non-negotiable for consumer apps and SaaS/tool apps alike."),e.push(""),e.push("```"),e.push("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),e.push("\u2502 [Logo] [Sign In] [CTA \u2192] \u2502 \u2190 transparent nav, NOT sticky"),e.push("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),e.push("\u2502 \u2502"),e.push("\u2502 \u25CF Built for [audience] \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u2502"),e.push("\u2502 \u2502 Glassmorphic \u2502 \u2502"),e.push("\u2502 Big bold headline, \u2502 product mockup \u2502 \u2502"),e.push("\u2502 accent color on key word \u2502 card showing \u2502 \u2502"),e.push("\u2502 \u2502 real app data \u2502 \u2502"),e.push("\u2502 Description paragraph \u2502 (stats, table, \u2502 \u2502"),e.push("\u2502 \u2502 chart, etc.) \u2502 \u2502"),e.push("\u2502 [Primary CTA \u2192] [Secondary] \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2502"),e.push("\u2502 \u2502"),e.push("\u2502 500+ 25K+ 99% \u2502"),e.push("\u2502 Label Label Label \u2502"),e.push("\u2502 \u2502"),a?e.push("\u2502 \u2190 full-bleed photo bg + dark overlay behind all \u2192 \u2502"):e.push("\u2502 \u2190 preset gradient / glass background behind all \u2192 \u2502"),e.push("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),e.push("```"),e.push(""),e.push("**Left side (~55%)**: badge pill \u2192 bold headline (use accent color on ONE key word or phrase) \u2192 description \u2192 two CTA buttons (primary filled + secondary outline/ghost) \u2192 stats row with 3 proof points"),e.push("**Right side (~45%)**: A glassmorphic floating card that previews what the app looks like inside:"),e.push("- Style: `bg-white/10 backdrop-blur-lg border border-white/20 rounded-2xl shadow-2xl p-6` (over dark/photo bg) OR `bg-white/60 backdrop-blur-lg border border-black/5 rounded-2xl shadow-2xl p-6` (over light bg)"),e.push("- Content: Build realistic fake app data using styled divs \u2014 stat cards, mini table rows, schedule blocks, or charts that match what this specific app's dashboard shows"),e.push("- Must be DOMAIN-SPECIFIC: a library app shows book catalog rows, a gym app shows check-in stats, a CRM shows pipeline cards"),e.push("- Add subtle inner elements with `bg-white/5` or `bg-white/10` for depth"),e.push("**Stats row**: 3 proof-point numbers at the bottom of the left side (e.g., '500+ Gyms', '25K+ Members', '99% Uptime'). Match text color to the background contrast.")}return e.push(""),e.push(kr),e.join(`
|
|
4990
|
+
`)}async function Sa(o){try{let s=await yo("nextjs",o);return{reminders:s.reminders,skill:s.skill}}catch{return{reminders:`### ${o} step
|
|
4991
4991
|
- Follow existing patterns in the codebase
|
|
4992
|
-
- Server Components by default, "use client" only when interactivity is needed`,skill:""}}}async function Sa(s,o,e,t,n,a){let r=[];r.push(`## Step ${s.number}: ${s.name}`),r.push(""),r.push("### What to build:"),r.push(s.description),r.push(""),o.primaryAction&&(r.push("### Primary user action (non-negotiable):"),r.push(`- **Core action**: ${o.primaryAction.action}`),r.push(`- **User flow**: ${o.primaryAction.flow}`),r.push(`- **Dashboard must show**: ${o.primaryAction.dashboardSurface}`),r.push(""),r.push("The dashboard is an ACTION surface, not a stats display. Users must be able to complete the core action directly from the dashboard without navigating to a separate page. If this step builds the dashboard, make sure the primary action is front and center with inline forms/buttons \u2014 not behind a link to another page."),r.push(""));let l=["landing","design","dashboard","crud","layout","admin","general","auth"].includes(n);if(o.design&&l?(r.push(ka(o.design,{hasDesignPreset:!!o.landingDesign&&(n==="landing"||n==="design")})),r.push("")):o.design&&!l&&(r.push("### Design tokens (for reference only \u2014 this step is not UI-focused):"),o.design.fonts&&r.push(`- Fonts: ${o.design.fonts.heading} / ${o.design.fonts.body}`),r.push("- Colors come from CSS variables (`--color-primary`, `--color-background`, etc.) \u2014 not Tailwind palette names."),r.push("")),a){let h=vr(a);if(h.length>0){r.push("### Approved wireframe (MUST READ before writing any files):"),r.push("The user approved a wireframe sketch before building. **Read these files NOW before writing any code for this step:**");for(let v of h){let E=v.replace(a,"").replace(/^\//,"");r.push(`- \`${E}\``)}r.push(""),r.push("The wireframe defines the LAYOUT and INFORMATION HIERARCHY \u2014 what goes where, what's prominent, what's secondary. It includes HTML comments explaining WHY things are placed where they are."),r.push(""),r.push("The wireframe is intentionally rough (grayscale, system fonts). Your job is to:"),r.push("1. **Keep the same layout structure** \u2014 same information hierarchy, same element placement, same sections in the same order"),r.push("2. **Apply the design tokens** \u2014 colors, fonts, shadows, radius from the plan design choices above"),r.push("3. **Elevate the visual quality** \u2014 make it feel designed for THIS specific app, not generic"),r.push("4. **Respect the HTML comments** \u2014 they explain WHY things are placed where they are"),r.push("5. **If the wireframe shows a search bar at the top of the dashboard, your dashboard MUST have a search bar at the top** \u2014 do not rearrange the layout"),r.push("")}}o.roles&&Array.isArray(o.roles)&&o.roles.length>0&&(r.push("### Role system (from plan):"),r.push(`- Roles: ${o.roles.join(", ")}`),r.push(`- Default role for new signups: ${o.defaultRole??o.roles[0]}`),r.push("- Role helpers are in `lib/roles.ts` \u2014 use `getUserRole()` and `hasRole()` for access checks"),r.push("")),o.multiTenant&&(r.push("### Multi-tenant (from plan):"),r.push("- Organization tables are in `db/schema/organization.ts`"),r.push("- Org helpers are in `lib/org.ts` \u2014 use `getCurrentOrg()` to scope queries"),r.push("- All data queries MUST be scoped to the current org (filter by orgId)"),r.push("- Org switcher component is at `components/org-switcher.tsx`"),r.push("- CRITICAL: `getCurrentOrg()` returns null for new users who haven't created an org yet. The dashboard MUST handle this \u2014 if currentOrg is null, redirect to an onboarding page or show an inline 'Create your first team/workspace' form. NEVER call .id on a null org."),r.push("- WARNING: cookies().set() in server actions does NOT work on Mistflow Cloud's edge runtime. Do NOT use setCurrentOrgId() or any cookies().set() call inside server actions. Instead, pass the orgId as a form field or query param, or store the active org in the user's database record."),r.push("")),o.language&&(r.push(`### Language: ${o.language}`),r.push(`ALL user-facing text must be written in ${o.language}:`),r.push("- Page titles, headings, labels, button text, placeholder text"),r.push("- Navigation items, menu labels, footer text"),r.push("- Error messages, success messages, empty states"),r.push("- Landing page copy, marketing text, CTAs"),r.push("- Form labels and validation messages"),r.push("Code (variable names, comments, file names) stays in English."),r.push(`Set the HTML lang attribute to the appropriate locale code for ${o.language}.`),r.push(""));let c=["landing","design","auth","general","crud","dashboard"];o.audienceType&&c.includes(n)&&(o.audienceType==="b2c"?(r.push("### Audience: this app belongs to ONE business. The landing page talks TO their customers."),r.push("- Hero: what the customer gets ('Exceptional catering for your next event'), NOT what the tool does"),r.push("- CTAs: customer action ('Order Catering', 'Book Now'), NOT business action ('Get Started Free')"),r.push("- Testimonials: from customers ('They catered our wedding'), NOT from business owners"),r.push("- Features: customer benefits ('Specify your dietary needs'), NOT business benefits ('Track preferences')"),r.push("- Stats: social proof for customers ('2,400+ events served'), NOT internal metrics ('$48k revenue')"),r.push("- The business name IS the brand. Say it like a business homepage, not a SaaS onboarding."),r.push("")):o.audienceType==="b2b"?(r.push("### Audience: this is a SaaS platform. The landing page pitches TO business owners."),r.push("- Hero: the business pain + solution ('Catering orders managed in one place')"),r.push("- CTAs: business owner action ('Start Free Trial', 'Get Started')"),r.push("- Testimonials: from business owners who use the platform"),r.push("- Features: business benefits ('Track dietary preferences across all orders')"),r.push("- Stats: platform metrics ('500+ businesses', '50K+ orders processed')"),r.push("")):o.audienceType==="internal"&&(r.push("### Audience: internal staff tool. No marketing copy needed."),r.push("- No landing page. Auth page copy is functional: 'Sign in to continue'."),r.push("- Dashboard focuses on operational efficiency, not onboarding or sales."),r.push(""))),e.length>0&&(r.push("### Already completed:"),e.forEach(h=>r.push(`- ${h}`)),r.push(""));let u=o.dataModel?_r(s,o.dataModel):[];u.length>0&&(r.push("### Data model (from plan):"),u.forEach(h=>{let v=zt(h),E=ga(h.fields);r.push(`- **${v}**: ${E}`),r.push(` Schema file: \`db/schema/${v.toLowerCase().replace(/\s+/g,"-")}.ts\``)}),r.push(""));let m=o.pages?ya(s,o.pages):[];m.length>0&&(r.push("### Pages to create/update:"),m.forEach(h=>{let v=h.description?` \u2014 ${h.description}`:"";r.push(`- \`${Nr(h)}\`${v}`)}),r.push("")),n==="crud"&&u.length>0&&u.forEach(h=>{let v=zt(h),E=v.toLowerCase().replace(/\s+/g,"-"),R=E.endsWith("s")?E:`${E}s`;r.push(`### Files for ${v} CRUD:`),r.push(`- List page: \`app/(dashboard)/${R}/page.tsx\` (Server Component)`),r.push(`- Detail page: \`app/(dashboard)/${R}/[id]/page.tsx\``),r.push(`- Create page: \`app/(dashboard)/${R}/new/page.tsx\``),r.push(`- Server Actions: \`app/(dashboard)/${R}/actions.ts\``),r.push(`- DataTable columns: \`components/${E}-table-columns.tsx\``),r.push(`- Form: \`components/${E}-form.tsx\``),r.push("")});let p=o.appStyle;if(l){r.push("## Design Doctrine (the standard for every UI step)"),r.push(""),r.push(Sr),r.push(""),r.push("## Design Reference Library"),r.push(""),r.push("### Typography"),r.push(Tr),r.push(""),r.push("### Color"),r.push(Cr),r.push(""),r.push("### Motion"),r.push(Pr),r.push(""),r.push("### Spatial Composition"),r.push(Ar),r.push(""),r.push("### Interaction"),r.push(Ir),r.push(""),r.push("### UX Writing"),r.push(Rr),r.push("");let h=a?ct(a,"DESIGN.md"):void 0,v=h&&xt(h)?(()=>{try{return _o(h,"utf-8")}catch{return null}})():null;v&&(r.push("### Design system (source of truth: DESIGN.md):"),r.push(""),r.push("The project's DESIGN.md defines the visual identity. Follow it exactly. It's emitted in google-labs-code/design.md format (YAML front matter with colors/typography/rounded/spacing tokens, plus markdown rationale). All UI elements must use the project's CSS custom properties (--color-primary, --color-background, etc. \u2014 these are generated from the YAML tokens) and the fonts configured in layout.tsx. If DESIGN.md and this plan disagree, DESIGN.md wins. The user may have edited it."),r.push(""),r.push(v),r.push(""))}if(l){let h=mr(o.summary??o.name,{tone:o.design?.tone,audienceType:o.audienceType,archetype:o.design?.archetype});if(h){let v=ur(h);v&&(r.push(`### App archetype: ${h}`),r.push(""),r.push(`This app matches the **${h}** archetype. Follow these component-level patterns for page composition, cards, navigation, spacing, and motion. `+(p?`The app style (${p}) provides visual identity (colors, fonts). The archetype provides layout and component patterns. Use both.`:"All visual styling comes from the project's CSS custom properties and fonts in layout.tsx.")),r.push(""),r.push(v),r.push(""))}}(n==="landing"||n==="design")&&(r.push(xr),r.push(""));let g=s.integrationId?rt(s.integrationId):void 0;if(g){let h=nt(g.id);if(r.push("### Integration blueprint (follow this closely):"),r.push(""),r.push(`Using integration: **${g.name}** (${g.category})`),h?.docsUrl&&r.push(`Official docs: ${h.docsUrl}`),h?.envVars?.length){r.push(""),r.push("**Required environment variables:**");for(let v of h.envVars)r.push(`- \`${v.key}\`: ${v.description} \u2014 Get it at ${v.setupUrl}`);r.push(""),r.push("**IMPORTANT: Never ask the user to paste API keys in chat.** Direct them to set keys in the Mistflow dashboard (Project Settings > Environment Variables) or at app.mistflow.ai. Use mist_config resource='env' action='list' to check if keys are set (has_value: true/false). Only proceed with deploy once all required keys are set.")}h?.packages?.length&&(r.push(""),r.push(`**Packages to install:** \`npm install ${h.packages.join(" ")}\``)),r.push(""),r.push("---"),r.push(g.prompt),r.push("---"),r.push(""),r.push("**Adaptation rules**: Follow the file structure and code patterns above. Replace placeholder values (app names, URLs, copy) with this app's specific content. Use the app's existing data models and route structure. Never ask the user to paste API keys or secrets in the chat. Direct them to set keys in the Mistflow dashboard."),r.push("")}let{reminders:w,skill:f}=await xa(n);return r.push(w),r.push(""),f&&!(n==="landing"&&o.landingDesign==="freeform")&&(r.push(`### ${n} reference:`),r.push(f),r.push("")),l&&(r.push("## Self-Audit \u2014 run before submitting this file"),r.push(""),r.push(`Read the file you just wrote and answer each of these. If any answer is "yes", REDESIGN the failing piece \u2014 don't tweak classes on the same template. A different composition is required.`),r.push(""),r.push('1. **Pill badge at the top?** A small rounded label saying "Built for" / "New:" / "Made for" with a colored dot? \u2192 redesign the hero without it.'),r.push("2. **Fake browser chrome?** A rounded box with red/yellow/green dots and a fake URL bar? \u2192 delete it. Show real components instead, or no preview."),r.push("3. **Centered single-column hero?** Pill \u2192 headline \u2192 subhead \u2192 two CTAs stacked vertically? \u2192 redesign asymmetrically (see spatial.md)."),r.push("4. **Three checkmark benefit bullets** below the hero CTAs? \u2192 remove the triplet pattern."),r.push("5. **Tailwind palette utilities?** Any `bg-emerald-*`, `bg-amber-*`, `text-violet-*`, `border-slate-*`, `from-purple-*`, etc.? \u2192 replace with token classes (`bg-primary`, `bg-success`, `bg-muted`, `border-border`). No exceptions."),r.push("6. **Inter, Geist, Roboto, Arial, or system-ui** as the primary font? \u2192 pick something distinctive (see typography.md)."),r.push("7. **Purple gradient on white background** anywhere? \u2192 that's the single most overused AI-design pattern. Replace."),r.push('8. **Hardcoded hex values** (e.g. `style={{ color: "#10b981" }}`) or named CSS colors (`red`, `lightgrey`) in className or inline styles? \u2192 replace with CSS variables.'),r.push('9. **Generic copy** ("Boost your productivity", "The platform teams love", "Everything you need to")? \u2192 rewrite with specific nouns, numbers, or mechanisms from this product (see writing.md).'),r.push("10. **Zero memorable moments?** Is there ONE signature element \u2014 typographic hero, orchestrated reveal, asymmetric break, product-specific illustration? If zero, the page is generic. Add one (see motion.md, typography.md)."),r.push(""),r.push(`If every answer is "no, I'm good" \u2014 then submit.`),r.push("")),r.join(`
|
|
4993
|
-
`)}async function Dr(
|
|
4992
|
+
- Server Components by default, "use client" only when interactivity is needed`,skill:""}}}async function Ta(o,s,e,t,n,a){let r=[];r.push(`## Step ${o.number}: ${o.name}`),r.push(""),r.push("### What to build:"),r.push(o.description),r.push(""),s.primaryAction&&(r.push("### Primary user action (non-negotiable):"),r.push(`- **Core action**: ${s.primaryAction.action}`),r.push(`- **User flow**: ${s.primaryAction.flow}`),r.push(`- **Dashboard must show**: ${s.primaryAction.dashboardSurface}`),r.push(""),r.push("The dashboard is an ACTION surface, not a stats display. Users must be able to complete the core action directly from the dashboard without navigating to a separate page. If this step builds the dashboard, make sure the primary action is front and center with inline forms/buttons \u2014 not behind a link to another page."),r.push(""));let l=["landing","design","dashboard","crud","layout","admin","general","auth"].includes(n);if(s.design&&l?(r.push(xa(s.design,{hasDesignPreset:!!s.landingDesign&&(n==="landing"||n==="design")})),r.push("")):s.design&&!l&&(r.push("### Design tokens (for reference only \u2014 this step is not UI-focused):"),s.design.fonts&&r.push(`- Fonts: ${s.design.fonts.heading} / ${s.design.fonts.body}`),r.push("- Colors come from CSS variables (`--color-primary`, `--color-background`, etc.) \u2014 not Tailwind palette names."),r.push("")),a){let h=vr(a);if(h.length>0){r.push("### Approved wireframe (MUST READ before writing any files):"),r.push("The user approved a wireframe sketch before building. **Read these files NOW before writing any code for this step:**");for(let v of h){let E=v.replace(a,"").replace(/^\//,"");r.push(`- \`${E}\``)}r.push(""),r.push("The wireframe defines the LAYOUT and INFORMATION HIERARCHY \u2014 what goes where, what's prominent, what's secondary. It includes HTML comments explaining WHY things are placed where they are."),r.push(""),r.push("The wireframe is intentionally rough (grayscale, system fonts). Your job is to:"),r.push("1. **Keep the same layout structure** \u2014 same information hierarchy, same element placement, same sections in the same order"),r.push("2. **Apply the design tokens** \u2014 colors, fonts, shadows, radius from the plan design choices above"),r.push("3. **Elevate the visual quality** \u2014 make it feel designed for THIS specific app, not generic"),r.push("4. **Respect the HTML comments** \u2014 they explain WHY things are placed where they are"),r.push("5. **If the wireframe shows a search bar at the top of the dashboard, your dashboard MUST have a search bar at the top** \u2014 do not rearrange the layout"),r.push("")}}s.roles&&Array.isArray(s.roles)&&s.roles.length>0&&(r.push("### Role system (from plan):"),r.push(`- Roles: ${s.roles.join(", ")}`),r.push(`- Default role for new signups: ${s.defaultRole??s.roles[0]}`),r.push("- Role helpers are in `lib/roles.ts` \u2014 use `getUserRole()` and `hasRole()` for access checks"),r.push("")),s.multiTenant&&(r.push("### Multi-tenant (from plan):"),r.push("- Organization tables are in `db/schema/organization.ts`"),r.push("- Org helpers are in `lib/org.ts` \u2014 use `getCurrentOrg()` to scope queries"),r.push("- All data queries MUST be scoped to the current org (filter by orgId)"),r.push("- Org switcher component is at `components/org-switcher.tsx`"),r.push("- CRITICAL: `getCurrentOrg()` returns null for new users who haven't created an org yet. The dashboard MUST handle this \u2014 if currentOrg is null, redirect to an onboarding page or show an inline 'Create your first team/workspace' form. NEVER call .id on a null org."),r.push("- WARNING: cookies().set() in server actions does NOT work on Mistflow Cloud's edge runtime. Do NOT use setCurrentOrgId() or any cookies().set() call inside server actions. Instead, pass the orgId as a form field or query param, or store the active org in the user's database record."),r.push("")),s.language&&(r.push(`### Language: ${s.language}`),r.push(`ALL user-facing text must be written in ${s.language}:`),r.push("- Page titles, headings, labels, button text, placeholder text"),r.push("- Navigation items, menu labels, footer text"),r.push("- Error messages, success messages, empty states"),r.push("- Landing page copy, marketing text, CTAs"),r.push("- Form labels and validation messages"),r.push("Code (variable names, comments, file names) stays in English."),r.push(`Set the HTML lang attribute to the appropriate locale code for ${s.language}.`),r.push(""));let c=["landing","design","auth","general","crud","dashboard"];s.audienceType&&c.includes(n)&&(s.audienceType==="b2c"?(r.push("### Audience: this app belongs to ONE business. The landing page talks TO their customers."),r.push("- Hero: what the customer gets ('Exceptional catering for your next event'), NOT what the tool does"),r.push("- CTAs: customer action ('Order Catering', 'Book Now'), NOT business action ('Get Started Free')"),r.push("- Testimonials: from customers ('They catered our wedding'), NOT from business owners"),r.push("- Features: customer benefits ('Specify your dietary needs'), NOT business benefits ('Track preferences')"),r.push("- Stats: social proof for customers ('2,400+ events served'), NOT internal metrics ('$48k revenue')"),r.push("- The business name IS the brand. Say it like a business homepage, not a SaaS onboarding."),r.push("")):s.audienceType==="b2b"?(r.push("### Audience: this is a SaaS platform. The landing page pitches TO business owners."),r.push("- Hero: the business pain + solution ('Catering orders managed in one place')"),r.push("- CTAs: business owner action ('Start Free Trial', 'Get Started')"),r.push("- Testimonials: from business owners who use the platform"),r.push("- Features: business benefits ('Track dietary preferences across all orders')"),r.push("- Stats: platform metrics ('500+ businesses', '50K+ orders processed')"),r.push("")):s.audienceType==="internal"&&(r.push("### Audience: internal staff tool. No marketing copy needed."),r.push("- No landing page. Auth page copy is functional: 'Sign in to continue'."),r.push("- Dashboard focuses on operational efficiency, not onboarding or sales."),r.push(""))),e.length>0&&(r.push("### Already completed:"),e.forEach(h=>r.push(`- ${h}`)),r.push(""));let u=s.dataModel?_r(o,s.dataModel):[];u.length>0&&(r.push("### Data model (from plan):"),u.forEach(h=>{let v=Ht(h),E=fa(h.fields);r.push(`- **${v}**: ${E}`),r.push(` Schema file: \`db/schema/${v.toLowerCase().replace(/\s+/g,"-")}.ts\``)}),r.push(""));let m=s.pages?ba(o,s.pages):[];m.length>0&&(r.push("### Pages to create/update:"),m.forEach(h=>{let v=h.description?` \u2014 ${h.description}`:"";r.push(`- \`${Nr(h)}\`${v}`)}),r.push("")),n==="crud"&&u.length>0&&u.forEach(h=>{let v=Ht(h),E=v.toLowerCase().replace(/\s+/g,"-"),R=E.endsWith("s")?E:`${E}s`;r.push(`### Files for ${v} CRUD:`),r.push(`- List page: \`app/(dashboard)/${R}/page.tsx\` (Server Component)`),r.push(`- Detail page: \`app/(dashboard)/${R}/[id]/page.tsx\``),r.push(`- Create page: \`app/(dashboard)/${R}/new/page.tsx\``),r.push(`- Server Actions: \`app/(dashboard)/${R}/actions.ts\``),r.push(`- DataTable columns: \`components/${E}-table-columns.tsx\``),r.push(`- Form: \`components/${E}-form.tsx\``),r.push("")});let p=s.appStyle;if(l){r.push("## Design Doctrine (the standard for every UI step)"),r.push(""),r.push(Sr),r.push(""),r.push("## Design Reference Library"),r.push(""),r.push("### Typography"),r.push(Tr),r.push(""),r.push("### Color"),r.push(Cr),r.push(""),r.push("### Motion"),r.push(Pr),r.push(""),r.push("### Spatial Composition"),r.push(Ar),r.push(""),r.push("### Interaction"),r.push(Ir),r.push(""),r.push("### UX Writing"),r.push(Rr),r.push("");let h=a?dt(a,"DESIGN.md"):void 0,v=h&&Tt(h)?(()=>{try{return Ns(h,"utf-8")}catch{return null}})():null;v&&(r.push("### Design system (source of truth: DESIGN.md):"),r.push(""),r.push("The project's DESIGN.md defines the visual identity. Follow it exactly. It's emitted in google-labs-code/design.md format (YAML front matter with colors/typography/rounded/spacing tokens, plus markdown rationale). All UI elements must use the project's CSS custom properties (--color-primary, --color-background, etc. \u2014 these are generated from the YAML tokens) and the fonts configured in layout.tsx. If DESIGN.md and this plan disagree, DESIGN.md wins. The user may have edited it."),r.push(""),r.push(v),r.push(""))}if(l){let h=mr(s.summary??s.name,{tone:s.design?.tone,audienceType:s.audienceType,archetype:s.design?.archetype});if(h){let v=ur(h);v&&(r.push(`### App archetype: ${h}`),r.push(""),r.push(`This app matches the **${h}** archetype. Follow these component-level patterns for page composition, cards, navigation, spacing, and motion. `+(p?`The app style (${p}) provides visual identity (colors, fonts). The archetype provides layout and component patterns. Use both.`:"All visual styling comes from the project's CSS custom properties and fonts in layout.tsx.")),r.push(""),r.push(v),r.push(""))}}(n==="landing"||n==="design")&&(r.push(xr),r.push(""));let f=o.integrationId?rt(o.integrationId):void 0;if(f){let h=nt(f.id);if(r.push("### Integration blueprint (follow this closely):"),r.push(""),r.push(`Using integration: **${f.name}** (${f.category})`),h?.docsUrl&&r.push(`Official docs: ${h.docsUrl}`),h?.envVars?.length){r.push(""),r.push("**Required environment variables:**");for(let v of h.envVars)r.push(`- \`${v.key}\`: ${v.description} \u2014 Get it at ${v.setupUrl}`);r.push(""),r.push("**IMPORTANT: Never ask the user to paste API keys in chat.** Direct them to set keys in the Mistflow dashboard (Project Settings > Environment Variables) or at app.mistflow.ai. Use mist_config resource='env' action='list' to check if keys are set (has_value: true/false). Only proceed with deploy once all required keys are set.")}h?.packages?.length&&(r.push(""),r.push(`**Packages to install:** \`npm install ${h.packages.join(" ")}\``)),r.push(""),r.push("---"),r.push(f.prompt),r.push("---"),r.push(""),r.push("**Adaptation rules**: Follow the file structure and code patterns above. Replace placeholder values (app names, URLs, copy) with this app's specific content. Use the app's existing data models and route structure. Never ask the user to paste API keys or secrets in the chat. Direct them to set keys in the Mistflow dashboard."),r.push("")}let{reminders:w,skill:g}=await Sa(n);return r.push(w),r.push(""),g&&!(n==="landing"&&s.landingDesign==="freeform")&&(r.push(`### ${n} reference:`),r.push(g),r.push("")),l&&(r.push("## Self-Audit \u2014 run before submitting this file"),r.push(""),r.push(`Read the file you just wrote and answer each of these. If any answer is "yes", REDESIGN the failing piece \u2014 don't tweak classes on the same template. A different composition is required.`),r.push(""),r.push('1. **Pill badge at the top?** A small rounded label saying "Built for" / "New:" / "Made for" with a colored dot? \u2192 redesign the hero without it.'),r.push("2. **Fake browser chrome?** A rounded box with red/yellow/green dots and a fake URL bar? \u2192 delete it. Show real components instead, or no preview."),r.push("3. **Centered single-column hero?** Pill \u2192 headline \u2192 subhead \u2192 two CTAs stacked vertically? \u2192 redesign asymmetrically (see spatial.md)."),r.push("4. **Three checkmark benefit bullets** below the hero CTAs? \u2192 remove the triplet pattern."),r.push("5. **Tailwind palette utilities?** Any `bg-emerald-*`, `bg-amber-*`, `text-violet-*`, `border-slate-*`, `from-purple-*`, etc.? \u2192 replace with token classes (`bg-primary`, `bg-success`, `bg-muted`, `border-border`). No exceptions."),r.push("6. **Inter, Geist, Roboto, Arial, or system-ui** as the primary font? \u2192 pick something distinctive (see typography.md)."),r.push("7. **Purple gradient on white background** anywhere? \u2192 that's the single most overused AI-design pattern. Replace."),r.push('8. **Hardcoded hex values** (e.g. `style={{ color: "#10b981" }}`) or named CSS colors (`red`, `lightgrey`) in className or inline styles? \u2192 replace with CSS variables.'),r.push('9. **Generic copy** ("Boost your productivity", "The platform teams love", "Everything you need to")? \u2192 rewrite with specific nouns, numbers, or mechanisms from this product (see writing.md).'),r.push("10. **Zero memorable moments?** Is there ONE signature element \u2014 typographic hero, orchestrated reveal, asymmetric break, product-specific illustration? If zero, the page is generic. Add one (see motion.md, typography.md)."),r.push(""),r.push(`If every answer is "no, I'm good" \u2014 then submit.`),r.push("")),r.join(`
|
|
4993
|
+
`)}async function Dr(o){let{projectPath:s,step:e}=o,t=pa(s??process.cwd()),n=ga(t);if(!n)return Ne(t);if(!Tt(dt(t,"node_modules")))return d(`Dependencies are not installed at ${t}. Call mist_build with action='install' and projectPath='${t}' before running implement. This is a one-time setup step after init.`,!0);try{let{ensureBackendRegistered:S,ensureShadcnComponents:z}=await import("./self-heal-BXJXUFUF.js");await S(t);let Y=await z(t);Y.failed?console.error(`[implement] ${Y.failed}`):Y.installed.length>0&&console.error(`[implement] installed ${Y.installed.length} shadcn components`)}catch(S){console.error("[implement] self-heal skipped:",S instanceof Error?S.message:String(S))}let a=n.plan;if(!a||!a.steps||a.steps.length===0)return d("No project plan found. Start by describing your app idea first \u2014 the AI will create a plan for you.",!0);let r,i=a.steps.find(S=>S.status==="in_progress");if(i){let S=a.steps.findIndex(z=>z.number===i.number);S!==-1&&(a.steps[S].status="completed",r=`Auto-completed step ${i.number} (${i.name})`,Er(t,n))}let l;if(e!==void 0){if(l=a.steps.find(S=>S.number===e),!l)return d(`Step ${e} not found. The plan has ${a.steps.length} steps (numbered ${a.steps[0].number} to ${a.steps[a.steps.length-1].number}).`,!0)}else if(l=a.steps.find(S=>S.status!=="completed"),!l)return d(JSON.stringify({message:"All plan steps are completed!",completedSteps:a.steps.map(S=>S.name),nextAction:"NEXT: Deploy the app now. Call mist_deploy with action='deploy'. Do NOT suggest localhost or ask the user \u2014 just deploy."}));let c=a.steps.filter(S=>S.status==="completed").map(S=>`Step ${S.number}: ${S.name}`),{readLocalState:u}=await import("./state-manager-GBP2NSYC.js"),m=u(t),p=va(l),f=[];if((p==="crud"||p==="schema")&&a.dataModel&&l.entities&&l.entities.length>0){let S=_r(l,a.dataModel);for(let z of S){let Y=Ht(z);try{let G=(z.fields||[]).map(F=>typeof F=="string"?{name:F,type:"text"}:{name:F.name,type:ya(F.type),required:F.required!==!1});if(G.length===0)continue;let W=n.dbProvider==="neon"?"nextjs-neon":"nextjs",_=await bo(W,Y,G),ee=0,J=0;for(let F of _.files){let ie=dt(t,F.path);if(Tt(ie)){J++;continue}da(ua(ie),{recursive:!0}),Es(ie,F.content),ee++}let q=dt(t,"db","index.ts");if(Tt(q)){let F=Ns(q,"utf-8");F.includes(_.dbExport)||Es(q,F.trimEnd()+`
|
|
4994
4994
|
`+_.dbExport+`
|
|
4995
|
-
`)}ee>0?
|
|
4995
|
+
`)}ee>0?f.push(`${_.entityPascal} CRUD (${ee} new files${J>0?`, ${J} existing skipped`:""})`):J>0&&f.push(`${_.entityPascal} CRUD (all ${J} files already exist \u2014 skipped)`)}catch(G){console.error(`Module generation failed for ${Y} (non-fatal):`,G instanceof Error?G.message:G)}}}let w=await Ta(l,a,c,null,p,t),g=a.steps.findIndex(S=>S.number===l.number);if(g!==-1&&(n.plan.steps[g].status="in_progress",Er(t,n)),m&&n.projectId){let{syncRemoteState:S}=await import("./state-manager-GBP2NSYC.js");S(n.projectId,m).catch(()=>{})}let h=a.steps.every(S=>S.status==="completed"||S.number===l.number),v;if(h){let S=a.primaryAction?.action??"the core action",z=a.primaryAction?.flow??"sign up \u2192 reach dashboard \u2192 complete primary action";v=`THIS IS THE LAST STEP. Rules for speed:
|
|
4996
4996
|
|
|
4997
4997
|
1. Write ALL files using PARALLEL tool calls \u2014 batch multiple Write/Edit calls in a single message.
|
|
4998
4998
|
2. Do NOT read files you already know (AGENTS.md, CLAUDE.md, mistflow.json, middleware.ts, lib/auth.ts, lib/db.ts).
|
|
@@ -5007,35 +5007,35 @@ A footer with the same five links ("Product / Pricing / Docs / Blog / Terms") is
|
|
|
5007
5007
|
2. Write ALL files for this step using PARALLEL tool calls \u2014 batch multiple Write/Edit calls in a single message. Do NOT write one file at a time.
|
|
5008
5008
|
3. Do NOT read files you already know: AGENTS.md, CLAUDE.md, mistflow.json, middleware.ts, lib/auth.ts, lib/db.ts, drizzle.config.ts \u2014 these haven't changed.
|
|
5009
5009
|
4. Only read a file if you need to MODIFY it (e.g. sidebar.tsx to add a nav link, db/index.ts to add an export).
|
|
5010
|
-
5. After writing ALL files, call mist_build with action='implement' to move to the next step. Do NOT pause to ask the user for permission between steps \u2014 proceed immediately. Do NOT offer options like "continue or stop" \u2014 the user already approved the build when they approved the plan. The previous step is auto-marked complete \u2014 do NOT call implement twice.`;let E=
|
|
5011
|
-
`+l}let a=
|
|
5012
|
-
`)}),!1)}try{let
|
|
5010
|
+
5. After writing ALL files, call mist_build with action='implement' to move to the next step. Do NOT pause to ask the user for permission between steps \u2014 proceed immediately. Do NOT offer options like "continue or stop" \u2014 the user already approved the build when they approved the plan. The previous step is auto-marked complete \u2014 do NOT call implement twice.`;let E=ka(p),R={stepNumber:l.number,totalSteps:a.steps.length,estimatedMinutes:E,announcement:`Starting step ${l.number} of ${a.steps.length}: ${l.name}. This step usually takes ${E.min}\u2013${E.max} minutes.`},P=JSON.stringify({instruction:w,step:{number:l.number,name:l.name,description:l.description,status:"in_progress"},stepTiming:R,compactionGuidance:"If your context gets compacted mid-step (common on long builds), call mist_build action='implement' again immediately after the compaction finishes. The tool finds the in-progress step and returns fresh context \u2014 you don't need to re-read files or re-derive state.",...r?{autoCompleted:r}:{},...f.length>0?{generatedModules:f,generatedNote:"These CRUD modules were pre-generated. Review and customize them instead of writing from scratch. Focus on: business logic in actions.ts, UI polish, and wiring navigation."}:{},progress:`${c.length}/${a.steps.length} steps done`,nextAction:v});return await ha(3e3)?Ue("http://localhost:3000",P):d(P)}import{z as _s}from"zod";import{resolve as Ca}from"path";import{execFileSync as Pa}from"child_process";var wp=_s.object({projectPath:_s.string().optional().describe("Path to the project directory (default: current working directory)"),buildOutput:_s.string().optional().describe("Build output to parse (if not provided, runs npm run build)")});function Ct(o){let s=[],e=/([^\s(]+)\((\d+),(\d+)\):\s*error\s+(TS\d+):\s*(.+)/g,t;for(;(t=e.exec(o))!==null;){let[,l,c,u,m,p]=t;s.push({file:l,line:parseInt(c,10),column:parseInt(u,10),message:`${m}: ${p}`,humanMessage:`There is a type error in ${l} on line ${c}: ${p}`,suggestion:`Check line ${c} in ${l}. ${m==="TS2345"?"The types of the arguments do not match.":`Fix the ${m} error.`}`})}let n=/(?:Error:\s*)?\.\/([^\s:]+):(\d+):(\d+)\s*\n\s*(.+)/g;for(;(t=n.exec(o))!==null;){let[,l,c,u,m]=t;s.some(p=>p.file===l&&p.line===parseInt(c,10))||s.push({file:l,line:parseInt(c,10),column:parseInt(u,10),message:m,humanMessage:`There is an error in ${l} on line ${c}: ${m.trim()}`,suggestion:`Check line ${c} in ${l} and fix the issue.`})}let a=/Module not found:\s*(?:Error:\s*)?Can't resolve ['"]([^'"]+)['"]\s*(?:in\s*['"]?([^'"]+)['"]?)?/g;for(;(t=a.exec(o))!==null;){let[,l,c]=t;s.push({file:c,message:`Module not found: ${l}`,humanMessage:`The file ${c??"your project"} is trying to import '${l}' which is not installed.`,suggestion:`Run npm install ${l}`})}let r=/Package subpath ['"]([^'"]+)['"] is not defined by "exports" in .*?node_modules\/([^/]+(?:\/[^/]+)?)\//g;for(;(t=r.exec(o))!==null;){let[,l,c]=t;s.push({message:`ERR_PACKAGE_PATH_NOT_EXPORTED: ${c}${l}`,humanMessage:`The package '${c}' does not export the subpath '${l}'. This is usually caused by a version conflict between packages that depend on different major versions of '${c}'.`,suggestion:`Add '${c}' at the version that exports '${l}' as an optionalDependency in package.json (this pins it at root level and lets the other version nest). Then delete node_modules and package-lock.json, and run npm install.`})}let i=/SyntaxError:\s*([^\s:]+):\s*(.+?)\s*\((\d+):(\d+)\)/g;for(;(t=i.exec(o))!==null;){let[,l,c,u,m]=t;s.some(p=>p.file===l&&p.line===parseInt(u,10))||s.push({file:l,line:parseInt(u,10),column:parseInt(m,10),message:`SyntaxError: ${c}`,humanMessage:`There is a syntax error in ${l} on line ${u}.`,suggestion:`Check line ${u} in ${l} for a missing closing bracket or unexpected token.`})}return s}async function Mr(o){let{projectPath:s,buildOutput:e}=o,t=Ca(s??process.cwd()),n=e??"";if(!e)try{return Pa("npm",["run","build"],{cwd:t,stdio:["pipe","pipe","pipe"],timeout:12e4}),d(JSON.stringify({errors:[],rawOutput:"",message:"Build succeeded with no errors."}))}catch(r){let i=r instanceof Error&&"stderr"in r?String(r.stderr):"",l=r instanceof Error&&"stdout"in r?String(r.stdout):"";n=i+`
|
|
5011
|
+
`+l}let a=Ct(n);return a.length===0?d(JSON.stringify({errors:[],rawOutput:n.slice(0,2e3),message:"Build failed but I could not extract specific errors. Here is the raw output."})):d(JSON.stringify({errors:a,rawOutput:n.slice(0,2e3),message:`Found ${a.length} error${a.length===1?"":"s"} in the build output.`}))}import{existsSync as Aa,readFileSync as Ia}from"fs";import{join as Ra}from"path";function Ea(o){let s=Ra(o,"mistflow.json");if(!Aa(s))return null;try{return JSON.parse(Ia(s,"utf-8"))}catch{return null}}async function $r(o){try{let s=await fetch(o,{redirect:"follow",signal:AbortSignal.timeout(15e3)}),e=await s.text();return{status:s.status,body:e}}catch(s){return{status:0,body:String(s)}}}async function Na(o,s,e){try{let t=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json",...e??{}},body:JSON.stringify(s),redirect:"follow",signal:AbortSignal.timeout(15e3)}),n=await t.text(),a;try{a=JSON.parse(n)}catch{}return{status:t.status,json:a}}catch{return{status:0}}}async function jr(o){try{let s=await o.screenshot({type:"png"});return Buffer.from(s).toString("base64")}catch{return}}async function pt(o,s,e){let t=[],n=a=>{a.type()==="error"&&t.push(a.text())};o.on("console",n);try{let a=await e(),r=await jr(o);return{name:s,status:a.pass?"pass":"fail",detail:a.detail,fix:a.fix,screenshot:r,consoleErrors:t.length>0?t:void 0}}catch(a){let r=await jr(o);return{name:s,status:"fail",detail:`Unexpected error: ${a instanceof Error?a.message:String(a)}`,screenshot:r,consoleErrors:t.length>0?t:void 0}}finally{o.removeListener("console",n)}}async function Lr(o){let s=o.projectPath??process.cwd(),e=Ea(s),t=o.url;if(t||(t=e?.deploy?.url),!t)return d("No deploy URL found. Deploy the app first with mist_deploy, then call mist_build action='qa'.",!0);t.startsWith("http")||(t=`https://${t}`);let n=e?.projectId,a=[],r=await $r(`${t}/api/health`);if(r.status!==200)return a.push({name:"Health endpoint",status:"fail",detail:`Returns ${r.status}`,fix:"The worker is not running or crashed on startup. Check app/api/health/route.ts exists and the build succeeded."}),Gt(t,a);a.push({name:"Health endpoint",status:"pass",detail:"Returns 200"});let i=await $r(`${t}/api/auth/ok`);if(i.status!==200)return a.push({name:"Auth system",status:"fail",detail:`Auth endpoint returns ${i.status}`,fix:"Better Auth is not working. Check lib/auth.ts, lib/db.ts, and that your database env vars are set."}),Gt(t,a);a.push({name:"Auth system",status:"pass",detail:"Better Auth running"});let l,c,u;if(n){let f=await no(n);if(f){console.error("[qa] Calling seed endpoint for session token");let w=await Na(`${t}/api/admin/seed`,{token:f.seedToken,email:f.email,password:"QaTemp1!"});w.status===200&&w.json?(l=w.json.sessionToken,c=w.json.email,w.json.seeded?(u=w.json.password,console.error("[qa] New admin seeded \u2014 login form test available")):console.error("[qa] Admin already exists \u2014 session injection only")):console.error(`[qa] Seed endpoint returned ${w.status}`)}}if(!l)return a.push({name:"Auth session",status:"fail",detail:"Could not acquire a session token from the seed endpoint",fix:"Redeploy the app with mist_deploy. The deploy process injects ADMIN_SEED_TOKEN into the worker env and stores the seed token on the backend. If the seed endpoint at /api/admin/seed is missing, ensure app/api/admin/seed/route.ts exists in the scaffold."}),Gt(t,a);let m,p;try{let{getIsolatedContext:f,takeScreenshot:w}=await import("./browser-manager-QW3OYPFB.js"),g=await f();m=g.context,p=g.page}catch(f){let w=f instanceof Error?f.message:String(f);return d(JSON.stringify({status:"cannot_verify",url:t,deployed:!0,reason:"App deployed successfully, but QA could not verify it via automated browser testing because Playwright is not installed locally.",detail:w,httpChecks:a.map(({screenshot:g,...h})=>h),fix:"Run: npx playwright install chromium",instruction:[`The app deployed and is live at ${t}. That part succeeded.`,"What DID NOT succeed: automated QA verification. Playwright is not installed locally, so we could not open the app in a browser and check that the landing renders, signup works, and the dashboard loads.","Tell the user BOTH facts clearly \u2014 don't conflate 'deployed' with 'verified':",` "Your app is live at ${t}. I couldn't run automated QA because Playwright isn't installed locally. Run \`npx playwright install chromium\` (one-time, ~150MB) and I'll verify it for you \u2014 or just open the URL and try it yourself."`,"HTTP checks (health/auth endpoints) passed \u2014 those prove the server is responding. They do not prove the UI renders or user flows work.","After Playwright is installed, call mist_build action='qa' again for full verification."].join(`
|
|
5012
|
+
`)}),!1)}try{let f=await pt(p,"Landing page",async()=>{await p.goto(t,{waitUntil:"domcontentloaded",timeout:3e4}),await p.waitForLoadState("networkidle").catch(()=>{});let g=await p.evaluate(()=>{let v=document.body;if(!v)return"";let E=document.createTreeWalker(v,NodeFilter.SHOW_TEXT),R="",C;for(;C=E.nextNode();){let P=C.parentElement;if(P){let j=window.getComputedStyle(P);j.display!=="none"&&j.visibility!=="hidden"&&parseFloat(j.opacity)>0&&(R+=C.textContent?.trim()+" ")}}return R.trim()});if(g.length<50)return{pass:!1,detail:`Landing page appears blank (${g.length} chars visible). Likely a CSS/JS rendering issue.`,fix:"Common cause: motion/react animations with opacity:0 and whileInView that never trigger on Mistflow Cloud's edge runtime (no Intersection Observer). Replace with CSS animations or set initial={{ opacity: 1 }}."};let h=p.url();return h.includes("/login")||h.includes("/sign-in")?{pass:!1,detail:"Root URL redirects to login instead of showing a landing page",fix:"Check middleware.ts: '/' must be in PUBLIC_EXACT. Check app/page.tsx: must be a landing page, not a redirect."}:{pass:!0,detail:`Renders visible content (${g.length} chars)`}});a.push(f);let w=!1;if(u){let g=await pt(p,"Login",async()=>{await p.goto(`${t}/login`,{waitUntil:"domcontentloaded",timeout:15e3}),await p.waitForLoadState("networkidle").catch(()=>{});let h=p.locator('input[type="email"], input[name="email"], input[placeholder*="email" i]'),v=p.locator('input[type="password"], input[name="password"]');try{await h.first().waitFor({state:"visible",timeout:1e4})}catch{return{pass:!1,detail:"Login page has no visible email input field",fix:"Check app/(auth)/login/page.tsx renders a login form with email and password inputs."}}await h.first().fill(c),await v.first().fill(u),await p.locator('button[type="submit"], button:has-text("Sign in"), button:has-text("Log in"), button:has-text("Login")').first().click();try{await p.waitForURL(R=>!R.pathname.includes("/login"),{timeout:1e4})}catch{let R=await p.locator('[role="alert"], .text-red-500, .text-destructive, [data-error]').first().textContent().catch(()=>null);return{pass:!1,detail:R?`Login failed: ${R}`:"Login did not redirect. Page stayed on /login.",fix:"Do NOT edit lib/auth.ts to disable email verification. Redeploy with mist_deploy to re-seed the verified admin account."}}return w=!0,{pass:!0,detail:`Logged in, redirected to ${p.url()}`}});a.push(g)}else a.push({name:"Login",status:"pass",detail:"Skipped form login (redeploy, password unavailable). Using session injection."});if(!w&&l){let g=new URL(t).hostname,h=t.startsWith("https");await m.addCookies([{name:h?"__Secure-better-auth.session_token":"better-auth.session_token",value:l,domain:g,path:"/",httpOnly:!0,secure:h,sameSite:"Lax"}]),console.error("[qa] Injected session cookie for dashboard checks")}{let g=await pt(p,"Dashboard",async()=>{p.url().includes("/dashboard")||(await p.goto(`${t}/dashboard`,{waitUntil:"domcontentloaded",timeout:15e3}),await p.waitForLoadState("networkidle").catch(()=>{}));let R=await p.content();return R.length<1e3?{pass:!1,detail:`Dashboard page is very small (${R.length} bytes)`,fix:"Check app/(dashboard)/dashboard/page.tsx exists and the dashboard layout doesn't crash."}:await p.locator('text="Something went wrong"').isVisible().catch(()=>!1)?{pass:!1,detail:"Dashboard shows error boundary",fix:"A server component crashed. Check the page.tsx for unhandled null/undefined or missing database tables."}:{pass:!0,detail:`Loads (${R.length} bytes)`}});a.push(g);let h=await p.evaluate(()=>{let E=[];return document.querySelectorAll("nav a[href], aside a[href]").forEach(C=>{let P=C.getAttribute("href");P&&P.startsWith("/")&&!P.startsWith("/api")&&!P.includes("[")&&P!=="/dashboard"&&P!=="/"&&!P.includes("/login")&&!P.includes("/sign")&&E.push(P)}),[...new Set(E)]});if(h.length>0){let E=0,R=[];for(let C of h.slice(0,8)){let P=await pt(p,`Page: ${C}`,async()=>{await p.goto(`${t}${C}`,{waitUntil:"domcontentloaded",timeout:15e3}),await p.waitForLoadState("networkidle").catch(()=>{});let j=await p.title(),S=await p.content();return j.toLowerCase().includes("500")||j.toLowerCase().includes("server error")?{pass:!1,detail:"Page returns 500 server error",fix:"Server component crashed. Common causes: 1) Database tables missing. 2) Wrong ORM dialect (pgTable vs sqliteTable). 3) Unhandled null/undefined in server component."}:j.toLowerCase().includes("404")||j.toLowerCase().includes("not found")?{pass:!1,detail:"Page returns 404",fix:`Page ${C} not found. Create the page or remove the nav link.`}:await p.locator('text="Something went wrong"').isVisible().catch(()=>!1)?{pass:!1,detail:"Page shows error boundary",fix:"A server component crashed. Check the page.tsx for unhandled errors."}:S.length<500?{pass:!1,detail:`Page is very small (${S.length} bytes)`,fix:"Page may not have rendered. Check the page component."}:{pass:!0,detail:"Loads without errors"}});P.status==="fail"&&(E++,R.push(C)),a.push(P)}}let v=await pt(p,"Design quality",async()=>{let E=p.url().includes("/dashboard")?p.url():`${t}/dashboard`;p.url().includes("/dashboard")||(await p.goto(E,{waitUntil:"domcontentloaded",timeout:15e3}),await p.waitForLoadState("networkidle").catch(()=>{}));let R=await p.evaluate(()=>{let C=[],P=document.querySelectorAll("h1, h2, h3, h4, h5, h6"),j=new Set;P.forEach(y=>{j.add(window.getComputedStyle(y).fontSize)}),P.length>=3&&j.size<2&&C.push("TYPOGRAPHY: All headings appear the same size. Create clear hierarchy with 3+ distinct sizes using a modular scale (1.25-1.5x ratio).");let S=Array.from(P).map(y=>parseInt(y.tagName.charAt(1),10));for(let y=1;y<S.length;y++)if(S[y]-S[y-1]>1){C.push(`TYPOGRAPHY: Heading level skipped (h${S[y-1]} -> h${S[y]}). Use sequential heading levels for accessibility.`);break}let z=document.querySelectorAll("*"),Y=!1,G=!1;z.forEach(y=>{let N=window.getComputedStyle(y);N.backgroundColor==="rgb(0, 0, 0)"&&y.clientHeight>100&&y.clientWidth>200&&(Y=!0);let te=N.backgroundColor,De=N.color;if(te&&!te.includes("0, 0, 0")&&!te.includes("255, 255, 255")&&te!=="rgba(0, 0, 0, 0)"&&te!=="transparent"&&De.match(/rgb\((\d+), (\d+), (\d+)\)/)){let ae=De.match(/rgb\((\d+), (\d+), (\d+)\)/);if(ae){let[Ce,pe,Ie]=[parseInt(ae[1]),parseInt(ae[2]),parseInt(ae[3])],T=Math.abs(Ce-pe)<10&&Math.abs(pe-Ie)<10&&Ce>80&&Ce<180,A=te.match(/rgb\((\d+), (\d+), (\d+)\)/);if(T&&A){let[V,U,xe]=[parseInt(A[1]),parseInt(A[2]),parseInt(A[3])];!(Math.abs(V-U)<15&&Math.abs(U-xe)<15)&&y.textContent&&y.textContent.trim().length>0&&(G=!0)}}}}),Y&&C.push("COLOR: Pure black (#000) background detected on a large element. Use a tinted dark color instead (e.g. oklch(15% 0.01 hue) or a deep navy/charcoal)."),G&&C.push("COLOR: Gray text on a colored background detected. Gray looks washed out on color. Use a darker shade of the background color or white instead.");let W=document.querySelectorAll('[class*="card"], [class*="Card"], [role="group"]'),_=!1;W.forEach(y=>{y.querySelectorAll('[class*="card"], [class*="Card"]').length>0&&(_=!0)}),_&&C.push("LAYOUT: Nested cards detected (card inside card). Flatten the hierarchy. Use spacing and background color to create separation instead.");let ee=document.querySelectorAll("p, li, span, div"),J=0,q=0;ee.forEach(y=>{y.textContent&&y.textContent.trim().length>20&&y.clientHeight>0&&(q++,window.getComputedStyle(y).textAlign==="center"&&J++)}),q>5&&J/q>.7&&C.push("LAYOUT: Most text is center-aligned. Use left-alignment for body content and lists. Reserve center-alignment for heroes and CTAs.");let F=new Set;z.forEach(y=>{let N=window.getComputedStyle(y);N.gap&&N.gap!=="normal"&&N.gap!=="0px"&&F.add(N.gap)}),F.size===1&&z.length>20&&C.push("LAYOUT: Same gap value used everywhere. Vary spacing to create hierarchy: tight within groups (8-12px), generous between sections (32-64px).");let ie=document.querySelectorAll("button, a, input, select, textarea"),le=!1;ie.forEach(y=>{let N=window.getComputedStyle(y);if(N.outline==="none"||N.outline==="0px none rgb(0, 0, 0)"){let te=y;(te.style.outline==="none"||te.style.outline==="0")&&(le=!0)}}),document.querySelectorAll("table, [role='table']").forEach(y=>{y.querySelectorAll("tbody tr").length===0&&(y.parentElement?.querySelector('[class*="empty"], [class*="Empty"], [class*="no-data"], [class*="placeholder"]')||C.push("UX: Empty table with no empty state. Add a helpful message explaining what will appear here and a CTA to create the first item."))});let me=document.querySelectorAll("style"),x=!1;me.forEach(y=>{let N=y.textContent||"";(N.includes("bounce")||N.includes("elastic")||N.match(/cubic-bezier\([^)]*[2-9]\.[0-9]/))&&(x=!0)}),x&&C.push("MOTION: Bounce or elastic easing detected. These feel dated. Use smooth deceleration curves (Quart out, Expo out) instead.");let D=document.querySelectorAll("button, a, input, select, [role='button']"),M=0;return D.forEach(y=>{let N=y.getBoundingClientRect();N.width>0&&N.height>0&&(N.width<32||N.height<32)&&M++}),M>3&&C.push(`ACCESSIBILITY: ${M} interactive elements are smaller than 32x32px. Minimum recommended touch target is 44x44px. Add padding to increase tap area.`),C});return R.length===0?{pass:!0,detail:"No design quality issues detected. Typography hierarchy, color usage, layout patterns, and accessibility basics look good."}:{pass:!1,detail:`${R.length} design quality issue(s) found:
|
|
5013
5013
|
${R.map((C,P)=>`${P+1}. ${C}`).join(`
|
|
5014
|
-
`)}`,fix:"Fix these design issues in the source code. These are common AI-generated design anti-patterns that make apps look generic. Address each issue, then redeploy and re-run QA."}});if(a.push(v),a.find(E=>E.name==="Landing page"&&E.status==="pass")){let E=await
|
|
5014
|
+
`)}`,fix:"Fix these design issues in the source code. These are common AI-generated design anti-patterns that make apps look generic. Address each issue, then redeploy and re-run QA."}});if(a.push(v),a.find(E=>E.name==="Landing page"&&E.status==="pass")){let E=await pt(p,"Landing design quality",async()=>{await p.goto(t,{waitUntil:"domcontentloaded",timeout:15e3}),await p.waitForLoadState("networkidle").catch(()=>{});let R=await p.evaluate(()=>{let C=[];document.querySelectorAll("*").forEach(z=>{let Y=window.getComputedStyle(z);(Y.getPropertyValue("-webkit-background-clip")||Y.getPropertyValue("background-clip"))==="text"&&z.textContent&&z.textContent.trim().length>0&&C.push("SLOP: Gradient text detected. This is a common AI design pattern. Use solid colors for text.")});let j=document.querySelector("section, [class*='hero'], [class*='Hero'], header + div, main > div:first-child");if(j){let z=(j.textContent||"").toLowerCase(),Y=["transform your","unlock the power","revolutionize your","take your .* to the next level","the future of","welcome to","get started today","join thousands","powerful analytics","seamless integration","lightning fast"];for(let G of Y)if(z.match(new RegExp(G))){C.push(`COPY: Generic hero text detected ('${G}'). Write specific copy about what THIS app does for its users.`);break}}return document.querySelectorAll('[class*="grid"]').forEach(z=>{let G=window.getComputedStyle(z).gridTemplateColumns;if(G){let W=G.split(" ").filter(ee=>ee!=="").length,_=z.children;if(W===3&&_.length===3){let ee=Array.from(_).map(F=>F.offsetHeight),J=ee.every(F=>Math.abs(F-ee[0])<5),q=Array.from(_).every(F=>{let ie=F.querySelectorAll("svg"),le=F.querySelectorAll("h2, h3, h4"),K=F.querySelectorAll("p");return ie.length>=1&&le.length>=1&&K.length>=1});J&&q&&C.push("SLOP: 3-column icon + title + paragraph feature grid detected. This is the most common AI layout pattern. Use asymmetric layouts, bento grids, or varied card sizes instead.")}}}),C});return R.length===0?{pass:!0,detail:"Landing page design looks intentional. No generic AI patterns detected."}:{pass:!1,detail:`${R.length} landing design issue(s):
|
|
5015
5015
|
${R.map((C,P)=>`${P+1}. ${C}`).join(`
|
|
5016
|
-
`)}`,fix:"These patterns make the landing page look AI-generated. Fix them to create a more distinctive, professional design."}});a.push(E)}}}finally{m&&await m.close().catch(()=>{})}if(
|
|
5016
|
+
`)}`,fix:"These patterns make the landing page look AI-generated. Fix them to create a more distinctive, professional design."}});a.push(E)}}}finally{m&&await m.close().catch(()=>{})}if(o.deploymentId){let f=a.filter(h=>h.status==="fail"),w=a.filter(h=>h.status==="pass"),g=Date.now();await io(o.deploymentId,{checks:a.map(({screenshot:h,...v})=>v),overall:f.length===0?"pass":"fail",passed:w.length,failed:f.length,duration_ms:Date.now()-g}).catch(()=>{})}return Gt(t,a)}function Gt(o,s){let e=s.filter(a=>a.status==="fail"),t=s.filter(a=>a.status==="pass"),n=[];if(e.length===0)n.push({type:"text",text:JSON.stringify({status:"pass",message:`QA passed. All ${s.length} checks OK. The app is working correctly.`,url:o,checks:s.map(({screenshot:a,...r})=>r)})});else{let a=e.map((r,i)=>`${i+1}. **${r.name}**: ${r.detail}
|
|
5017
5017
|
Fix: ${r.fix}`).join(`
|
|
5018
5018
|
|
|
5019
|
-
`);n.push({type:"text",text:JSON.stringify({status:"fail",message:`QA found ${e.length} issue(s) on the live app. Fix them and redeploy.`,url:
|
|
5019
|
+
`);n.push({type:"text",text:JSON.stringify({status:"fail",message:`QA found ${e.length} issue(s) on the live app. Fix them and redeploy.`,url:o,passed:t.length,failed:e.length,checks:s.map(({screenshot:r,...i})=>i),fixInstructions:`The deployed app at ${o} has ${e.length} issue(s):
|
|
5020
5020
|
|
|
5021
5021
|
${a}
|
|
5022
5022
|
|
|
5023
|
-
Fix these issues in the source code, then call mist_deploy with action='deploy'${
|
|
5024
|
-
`+u;if(r<i){let
|
|
5023
|
+
Fix these issues in the source code, then call mist_deploy with action='deploy'${o.includes("-pv-")?" environment='preview'":""} to redeploy. After redeploying, call mist_build action='qa' again to verify the fixes.`})})}for(let a of s)a.screenshot&&n.push({type:"image",data:a.screenshot,mimeType:"image/png"});return{content:n}}function $a(o){let s=Vt(Ma(),".mistflow","plans",`${o}.json`);if(!Wt(s))return null;try{let e=JSON.parse(_a(s,"utf-8"));return e.plan?e:null}catch{return null}}var ja=de.object({action:de.enum(["init","install","implement","debug","build","qa","mockup"]).describe("'mockup' [DEPRECATED \u2014 use `mist mockup` via your bash tool] generates visual mockup HTML files from a plan for user preview and approval. Prefer `npx -y @mistflow-ai/cli mockup --plan-id <id>` \u2014 the CLI streams progress and has no MCP timeout ceiling. This action remains as a fallback for environments without shell access. 'init' creates and sets up a new project from your plan \u2014 writes files, registers the project, initializes git. Returns fast; does NOT run npm install. 'install' [DEPRECATED \u2014 use `mist install` via your bash tool] runs npm install in the project created by init. Prefer `npx -y @mistflow-ai/cli install <path>` \u2014 it streams output and has no MCP timeout. Only fall back to this MCP action if your environment can't shell out. Pass projectPath. Always call this after init returns with status='awaiting_install'. 'implement' [DEPRECATED \u2014 use `mist implement` via your bash tool] executes the next (or specific) plan step. Prefer `npx -y @mistflow-ai/cli implement --project-path <path>` \u2014 it streams output and sidesteps the MCP 60s timeout ceiling on longer steps. This MCP action remains as a fallback. 'debug' [DEPRECATED \u2014 use `mist debug` via your bash tool] analyzes build or runtime errors. Prefer `npx -y @mistflow-ai/cli debug --project-path <path>` \u2014 it streams output. For runtime errors, call mist_project errors first then pass the output as buildOutput. This MCP action remains as a fallback. 'build' [DEPRECATED \u2014 use `mist build` via your bash tool] runs the full production build locally (Mistflow Cloud edge runtime) without deploying. Prefer `npx -y @mistflow-ai/cli build --project-path <path>` \u2014 it streams build output and has no MCP timeout ceiling. This MCP action remains as a fallback. 'qa' [DEPRECATED \u2014 use `mist qa` via your bash tool] tests the live deployed app \u2014 checks landing page, signup, login, dashboard, and nav links. Prefer `npx -y @mistflow-ai/cli qa --project-path <path>` \u2014 the CLI streams progress and has no MCP timeout. Call after mist_deploy. If issues found, fix and redeploy, then call qa again."),name:de.string().optional().describe("(init) Project name"),planId:de.string().optional().describe("(init/mockup) Plan ID from mist_plan"),plan:de.any().optional().describe("(init) Full plan object \u2014 use planId instead when available"),path:de.string().optional().describe("(init) REQUIRED for action='init'. Absolute path to the target directory where the project should be scaffolded (e.g. /Users/alice/projects/my-app). Do not omit \u2014 there is no default. If unsure, ask the user for their working directory."),landingDesign:de.string().optional().describe("(init) Landing design ID to apply to the landing page. Can be set here if not set during mist_plan. Use mist_project action='landing-designs' to browse."),appStyle:de.string().optional().describe("(init) Optional aesthetic-direction hint passed to the backend LLM. DESIGN.md is generated per-product; this string is a hint, not a catalog ID."),confirmDarkTheme:de.boolean().optional().describe("(init) Set to true only after confirming with the user that a dark-themed app style is intentional for a consumer (b2c) app. Skips the dark-on-consumer-app warning."),heroPhoto:de.boolean().optional().describe("(init) Whether the landing page hero uses a lifestyle photo background. true = Unsplash photo + overlaid glass card (HabitFlow, Airbnb). false = pure CSS gradients + glassmorphism (Stripe, Linear). Pass the user's answer to the heroPhotoQuestion from mist_plan. If omitted, defaults based on the plan's audienceType (b2c \u2192 photo, else \u2192 CSS)."),projectPath:de.string().optional().describe("Path to the project directory (default: cwd)"),step:de.number().optional().describe("(implement) Specific step number to implement"),buildOutput:de.string().optional().describe("(debug) Build output to parse instead of running a build"),feedback:de.string().optional().describe("(mockup) User feedback on the current mockup \u2014 describe what to change."),approved:de.boolean().optional().describe("(mockup) Set to true when the user approves the mockup. Locks in the design direction."),url:de.string().optional().describe("(qa) URL to test. Defaults to deploy URL from mistflow.json"),deploymentId:de.string().optional().describe("(qa) Deployment ID to associate QA results with. Passed from mist_deploy output.")}),Or={name:"mist_build",description:"STEP 2-3 of the Mistflow workflow. Build and develop a Mistflow project. [CLI PREFERRED] Every action except 'init' now has a first-class CLI equivalent (`mist mockup`, `mist install`, `mist implement`, `mist build`, `mist debug`, `mist qa`) via `npx -y @mistflow-ai/cli <cmd>`. The CLI streams output and has no MCP timeout ceiling \u2014 route there by default. These MCP actions remain as fallbacks for environments that cannot shell out. 'init' stays primary on MCP because it is fast (~10s) and structured. Actions: 'mockup' generates visual HTML mockups from a plan for user preview \u2014 call with planId after plan approval if user wants to preview. Pass feedback to iterate, approved=true to lock in the design. 'init' creates and sets up a new project from a plan \u2014 writes files, registers, initializes git. Returns fast (~10s) without running npm install. Pass the planId returned by mist_plan \u2014 do NOT pass the full plan object. 'install' runs npm install in the project init just created. Always call this after init (takes ~1-2 min). 'implement' executes the next plan step \u2014 call repeatedly until all steps are done. 'build' runs the full production build locally (Mistflow Cloud edge runtime) to verify before deploying. 'debug' analyzes build or runtime errors \u2014 for runtime errors from production, call mist_project errors first to fetch them, then pass the output as buildOutput. 'qa' tests the LIVE deployed app \u2014 call AFTER mist_deploy to verify everything works. If qa finds issues, fix them and redeploy, then call qa again. The full workflow is: mist_plan \u2192 (optional) mist_build mockup \u2192 mist_build init \u2192 mist_build install \u2192 mist_build implement (repeat) \u2192 mist_deploy \u2192 mist_build qa (loop until pass).",inputSchema:ja,handler:async(o,s)=>{let e=o;switch(e.action){case"init":{if(!e.name)return d("Project name is required for init.",!0);let t=e.plan,n=null;if(e.planId){if(n=$a(e.planId),!n)return d(`Plan not found for planId '${e.planId}'. The plan may have expired. Call mist_plan again to generate a new plan.`,!0);t=n.plan}if(!t)return d("No plan provided. Pass the planId returned by mist_plan, or call mist_plan first to generate a plan.",!0);if(!Array.isArray(t?.steps)||t.steps.length===0)return d("The plan is missing a 'steps' array. This usually means the plan generation was incomplete. Call mist_plan again with the same description to get a complete plan with implementation steps.",!0);if(n?.sourceDeploymentId&&n?.forkToken&&n?.projectId)return er({name:e.name,plan:t,path:e.path,projectId:n.projectId,sourceDeploymentId:n.sourceDeploymentId,forkToken:n.forkToken,requiredEnvVars:n.requiredEnvVars??[],dbProvider:n.dbProvider??"neon",planId:e.planId});if(e.landingDesign){let c=st(e.landingDesign);c?t.landingDesign=c.id:console.error(`Landing design '${e.landingDesign}' not found \u2014 ignoring.`)}e.appStyle&&(t.appStyle=e.appStyle);let a=t.design,i=t.audienceType==="b2c",l=e.heroPhoto??i;return t.design={...a??{},heroPhoto:l},Xo({name:e.name,plan:t,path:e.path,planId:e.planId},s)}case"install":return Zo({projectPath:e.projectPath},s);case"implement":return Dr({projectPath:e.projectPath,step:e.step});case"debug":return Mr({projectPath:e.projectPath,buildOutput:e.buildOutput});case"build":{let t=Da(e.projectPath??process.cwd());if(!Wt(Vt(t,"mistflow.json")))return d("Not a Mistflow project \u2014 mistflow.json not found. Run mist_build init first.",!0);if(!Wt(Vt(t,"node_modules")))try{Ds("npm",["install"],{cwd:t,stdio:["pipe","pipe","pipe"],timeout:12e4})}catch{return d("npm install failed. Check package.json for issues.",!0)}let a=process.platform==="win32"?"npx.cmd":"npx",r=0,i=2;for(;;){r++;try{Ds(a,["@opennextjs/cloudflare","build"],{cwd:t,stdio:["pipe","pipe","pipe"],timeout:18e4});let l=Wt(Vt(t,".open-next"));return d(JSON.stringify({success:!0,buildDir:".open-next",message:l?"Production build succeeded.":"Build completed but .open-next/ directory not found. Check your OpenNext config.",nextAction:l?"NEXT: Call mist_deploy with action='deploy' immediately. Do NOT ask the user whether to deploy \u2014 the build was the last approval gate. Do NOT suggest `npm run dev` or localhost as an alternative \u2014 the user wants a live URL.":void 0}))}catch(l){let c=l instanceof Error&&"stderr"in l?String(l.stderr):"",u=l instanceof Error&&"stdout"in l?String(l.stdout):"",m=c+`
|
|
5024
|
+
`+u;if(r<i){let f=[],w=/Module not found:\s*(?:Error:\s*)?Can't resolve ['"]([^'"]+)['"]/g,g;for(;(g=w.exec(m))!==null;){let h=g[1];if(!h.startsWith(".")&&!h.startsWith("@/")&&!h.startsWith("~/")){let v=h.startsWith("@")?h.split("/").slice(0,2).join("/"):h.split("/")[0];f.includes(v)||f.push(v)}}if(f.length>0){console.error(`[build] Auto-installing missing packages: ${f.join(", ")}`);try{Ds("npm",["install",...f],{cwd:t,stdio:["pipe","pipe","pipe"],timeout:6e4});continue}catch{console.error("[build] Auto-install failed, reporting build errors")}}}let p=Ct(m);return d(JSON.stringify({success:!1,errors:p,rawOutput:m.slice(0,3e3),message:p.length>0?`Build failed with ${p.length} error${p.length===1?"":"s"}:
|
|
5025
5025
|
|
|
5026
|
-
`+p.map((
|
|
5027
|
-
Fix: ${
|
|
5026
|
+
`+p.map((f,w)=>{let g=f.file?`${f.file}${f.line?`:${f.line}`:""}`:"unknown";return`${w+1}. [${g}] ${f.humanMessage}
|
|
5027
|
+
Fix: ${f.suggestion}`}).join(`
|
|
5028
5028
|
|
|
5029
5029
|
`)+`
|
|
5030
5030
|
|
|
5031
|
-
Fix these and run mist_build build again.`:"Build failed. Run mist_build with action='debug' for detailed analysis."}),!0)}}}case"qa":return Lr({projectPath:e.projectPath,url:e.url,deploymentId:e.deploymentId});case"mockup":return e.planId?wr({planId:e.planId,projectPath:e.projectPath,feedback:e.feedback,approved:e.approved}):d("planId is required for mockup. Pass the planId from mist_plan.",!0);default:return d(`Unknown action: ${e.action}. Use mockup, init, implement, build, debug, or qa.`,!0)}}};import{z as Ze}from"zod";import{z as
|
|
5031
|
+
Fix these and run mist_build build again.`:"Build failed. Run mist_build with action='debug' for detailed analysis."}),!0)}}}case"qa":return Lr({projectPath:e.projectPath,url:e.url,deploymentId:e.deploymentId});case"mockup":return e.planId?wr({planId:e.planId,projectPath:e.projectPath,feedback:e.feedback,approved:e.approved}):d("planId is required for mockup. Pass the planId from mist_plan.",!0);default:return d(`Unknown action: ${e.action}. Use mockup, init, implement, build, debug, or qa.`,!0)}}};import{z as Ze}from"zod";import{z as Jt}from"zod";import{resolve as Yr,join as se,dirname as Qt,basename as tl}from"path";import{existsSync as ue,readFileSync as Kr,writeFileSync as sl,unlinkSync as qr,mkdirSync as ol,cpSync as Ls,rmSync as Os,readdirSync as rl}from"fs";import{execFileSync as nl}from"child_process";import{spawn as il}from"child_process";import{tmpdir as al}from"os";function Ur(o,s){if(o instanceof Se)switch(o.code){case"auth_missing":return d("No Mistflow credentials found. Run mist_setup to connect your account.",!0);case"auth_revoked":return d("Your Mistflow credentials were revoked. Run mist_setup to reconnect.",!0);case"auth_expired":case"auth_invalid":case"auth_org_not_found":return d("Your Mistflow session needs to be refreshed. Run mist_setup to reconnect.",!0);case"permission_denied":return d(o.message||"You don't have permission for that action.",!0);case"rate_limited":return d("You're hitting rate limits. Wait 30 seconds and try again.",!0);case"quota_exceeded":return d(`${o.message} Upgrade at https://app.mistflow.ai/pricing to lift limits.`,!0);case"validation_error":case"conflict":return d(o.message,!0);case"not_found":{let t=Dt(),n=t?.orgSlug?.replace(/^user_user_/,"")||void 0,a=t?.email||n;return a&&(o.message.toLowerCase().includes("project")||s.toLowerCase().includes("project"))?d(`Project not found. You are signed in as ${a}. This project may belong to a different account. Run mist_setup to sign in with the account that owns this project.`,!0):d(o.message,!0)}case"server_error":case"upstream_error":return d(`${s} failed: the Mistflow backend returned an error. Try again in 30 seconds.`,!0);case"network_error":return d(`${s} failed: cannot reach Mistflow servers. Check your network and try again.`,!0);default:return d(`${s} failed: ${o.message}`,!0)}let e=o instanceof Error?o.message:String(o);return d(`${s} failed: ${e}`,!0)}import{existsSync as qe,readFileSync as Pt,readdirSync as Ms,statSync as $s}from"fs";import{join as Pe,relative as Yt}from"path";import{execFileSync as Vp}from"child_process";function La(o){let s=Pe(o,".env.local"),e=[];return qe(s)?(Pt(s,"utf-8").match(/^AUTH_SECRET=(.*)$/m)?.[1]?.trim()||e.push({check:"env",message:"AUTH_SECRET is missing from .env.local. Add a random secret for authentication.",file:".env.local"}),e):(e.push({check:"env",message:"Missing .env.local file. Create one with your local development environment variables (AUTH_SECRET, etc.).",file:".env.local"}),e)}function Oa(o){let s=Pe(o,"app","api","auth","[...all]","route.ts");return qe(s)?[]:[{check:"auth-routes",message:"Missing Better Auth catch-all route at app/api/auth/[...all]/route.ts. Create this file to handle authentication.",file:"app/api/auth/[...all]/route.ts"}]}function Ua(o){let s=Pe(o,"app","api","health","route.ts");return qe(s)?[]:[{check:"health-endpoint",message:"Missing health check endpoint at app/api/health/route.ts. Create this file so Mistflow can verify your deployment.",file:"app/api/health/route.ts"}]}function Fa(o){let s=Pe(o,"mistflow.json");if(!qe(s))return[];let e;try{e=JSON.parse(Pt(s,"utf-8"))}catch{return[]}let t=e.env;if(!t?.required||typeof t.required!="object")return[];let n=[],a=Pe(o,".env"),r="";try{qe(a)&&(r=Pt(a,"utf-8"))}catch{}for(let[i,l]of Object.entries(t.required)){let c=!!process.env[i],u=r.includes(`${i}=`);if(c||u)continue;let m=l?.description?` for '${l.description}'`:"";n.push({check:"required-env",message:`${i} is required${m}. Run mist_config to set it if you haven't already.`})}return n}function Ba(o){let s=Pe(o,"app");if(!qe(s))return[];let e=[];function t(r){let i;try{i=Ms(r)}catch{return}for(let l of i){if(l==="node_modules"||l===".next"||l===".open-next"||l==="api")continue;let c=Pe(r,l),u;try{u=$s(c)}catch{continue}if(u.isDirectory())t(c);else if(l==="page.tsx"||l==="page.ts"||l==="page.jsx"||l==="page.js"){let p="/"+Yt(s,c).replace(/\\/g,"/").replace(/\([^)]+\)\//g,"").replace(/\/page\.(tsx?|jsx?)$/,"").replace(/^page\.(tsx?|jsx?)$/,"");e.push({file:Yt(o,c),resolvedRoute:p||"/"})}}}t(s);let n=new Map;for(let r of e){let i=n.get(r.resolvedRoute)??[];i.push(r.file),n.set(r.resolvedRoute,i)}let a=[];for(let[r,i]of n)i.length>1&&a.push({check:"route-collision",message:`Route collision: ${i.join(" and ")} both resolve to "${r}". Next.js will fail with "two parallel pages that resolve to the same path". Move one into a real path segment (e.g. rename (admin)/page.tsx to admin/page.tsx).`,file:i[1]});return a}function qa(o){let s=Pe(o,"app");if(!qe(s))return[];let e=[];function t(n){let a;try{a=Ms(n)}catch{return}for(let r of a){if(r==="node_modules"||r===".next"||r===".open-next")continue;let i=Pe(n,r),l;try{l=$s(i)}catch{continue}if(l.isDirectory())t(i);else if(r==="actions.ts"||r==="actions.tsx"){let c=Pt(i,"utf-8");c.includes("use server")&&c.includes("cookies()")&&c.includes(".set(")&&e.push(Yt(o,i))}}}return t(s),e.length>0?[{check:"cookies-in-actions",message:`${e.length} server action(s) use cookies().set() which crashes on Mistflow Cloud's edge runtime: ${e.join(", ")}. Use a database field or form parameter instead.`,file:e[0]}]:[]}function za(o){let s=/\b(useState|useEffect|useRef|useCallback|useMemo|useReducer|useContext|useLayoutEffect|useTransition)\s*\(/,e=[];function t(n){if(!qe(n))return;let a;try{a=Ms(n)}catch{return}for(let r of a){if(r==="node_modules"||r===".next"||r===".open-next"||r==="ui")continue;let i=Pe(n,r),l;try{l=$s(i)}catch{continue}if(l.isDirectory())t(i);else if(r.endsWith(".tsx")||r.endsWith(".jsx")){if(r==="layout.tsx"||r==="loading.tsx"||r==="error.tsx"||r==="not-found.tsx")continue;let c=Pt(i,"utf-8");if(c.trimStart().startsWith('"use client"')||c.trimStart().startsWith("'use client'")||c.trimStart().startsWith('"use server"')||c.trimStart().startsWith("'use server'"))continue;if(s.test(c)){let u=Yt(o,i);e.push({check:"missing-use-client",message:`${u} uses React hooks but is missing "use client" directive. Add "use client"; as the first line of the file.`,file:u})}}}}return t(Pe(o,"app")),t(Pe(o,"components")),e}function Fr(o){let s=[...La(o),...Oa(o),...Ua(o),...Ba(o),...qa(o),...za(o)],e=[...Fa(o)];return{passed:s.length===0,errors:s,warnings:e}}import{existsSync as Te,readFileSync as Xe,readdirSync as Kt,statSync as At}from"fs";import{join as Q}from"path";async function Br(o,s){let e=[];e.push(Ha(o)),e.push(Ga(o)),e.push(Wa(o)),e.push(Va(o)),e.push(Ya(o)),e.push(Xa(o)),s?.plan&&e.push(...Ka(o,s)),e.push(Ja(o)),e.push(Qa(o)),e.push(...el(o)),e.push(Za(o));let t=e.filter(c=>c.status==="fail"),n=e.filter(c=>c.status==="warn"),a=e.filter(c=>c.status==="pass"),r=t.length>0,i=!r,l;return i&&n.length===0?l=`All ${e.length} checks passed`:i?l=`${a.length}/${e.length} passed, ${n.length} warning(s)`:l=`${t.length} issue(s) found:
|
|
5032
5032
|
${t.map(c=>` - ${c.message}`).join(`
|
|
5033
|
-
`)}`,{passed:i,blocking:r,checksRun:e.length,checks:e,summary:l}}function
|
|
5033
|
+
`)}`,{passed:i,blocking:r,checksRun:e.length,checks:e,summary:l}}function Ha(o){let s=Q(o,".open-next","worker.js");if(!Te(s))return{name:"worker-exists",status:"fail",message:"worker.js not found in build output. The build may have failed silently."};let e=Xe(s,"utf-8");return e.length<1e3?{name:"worker-exists",status:"warn",message:`worker.js is unusually small (${e.length} bytes). The build output may be incomplete.`}:{name:"worker-exists",status:"pass",message:"Worker bundle exists"}}function Ga(o){let s=Q(o,".open-next","assets");if(!Te(s))return{name:"assets-exist",status:"warn",message:"No static assets directory in build output. CSS and images may not load."};let e=0;function t(n){try{for(let a of Kt(n)){let r=Q(n,a);try{At(r).isDirectory()?t(r):e++}catch{}}}catch{}}return t(s),e===0?{name:"assets-exist",status:"warn",message:"Assets directory is empty. Your app may not have styles or images."}:{name:"assets-exist",status:"pass",message:`${e} static assets ready`}}function Wa(o){let s=Q(o,"app","api","health","route.ts");return Te(s)?{name:"health-route",status:"pass",message:"Health endpoint found"}:{name:"health-route",status:"warn",message:"No health endpoint found. Deployment verification may fail."}}function Va(o){let s=Q(o,"app","api","auth","[...all]","route.ts");return Te(s)?{name:"auth-route",status:"pass",message:"Auth routes found"}:{name:"auth-route",status:"warn",message:"Auth catch-all route not found. Login/register may not work."}}function Ya(o){let s=Q(o,".open-next","worker.js");if(!Te(s))return{name:"worker-size",status:"pass",message:"Worker size check skipped"};let t=At(s).size/(1024*1024);return t>60?{name:"worker-size",status:"fail",message:`Worker bundle is ${t.toFixed(1)}MB \u2014 exceeds Mistflow Cloud's 64MB worker bundle limit.`}:t>30?{name:"worker-size",status:"warn",message:`Worker bundle is ${t.toFixed(1)}MB \u2014 large but within Mistflow Cloud limits. May be slow to upload.`}:{name:"worker-size",status:"pass",message:`Worker bundle: ${t.toFixed(1)}MB`}}function Ka(o,s){let e=[],t=new Set;if(s.plan?.pages)for(let r of s.plan.pages){let i=r.path??r.route??r.name;i&&t.add(i.replace(/^\//,""))}if(t.size===0)return[];let n=0,a=[];for(let r of t){if(r.startsWith("api/")||r==="login"||r==="register"||r==="sign-in"||r==="sign-up"){n++;continue}[Q(o,"app","(dashboard)",r,"page.tsx"),Q(o,"app","(dashboard)",r,"page.ts"),Q(o,"app",r,"page.tsx"),Q(o,"app",r,"page.ts"),Q(o,"app","(admin)",r,"page.tsx")].some(l=>Te(l))?n++:a.push(`/${r}`)}return a.length===0?e.push({name:"plan-routes",status:"pass",message:`All ${t.size} planned pages found`}):a.length<=2?e.push({name:"plan-routes",status:"warn",message:`${n}/${t.size} planned pages found. Missing: ${a.join(", ")}`}):e.push({name:"plan-routes",status:"warn",message:`Only ${n}/${t.size} planned pages found. ${a.length} pages missing.`}),e}function Ja(o){let s=Q(o,"app");if(!Te(s))return{name:"empty-pages",status:"pass",message:"App directory check skipped"};let e=[];function t(n){try{for(let a of Kt(n)){let r=Q(n,a);try{if(At(r).isDirectory())t(r);else if(a==="page.tsx"||a==="page.ts"){let l=Xe(r,"utf-8").trim();if(l.length<50||l.includes("export default function")&&l.includes("TODO")){let c=r.replace(o+"/","");e.push(c)}}}catch{}}}catch{}}return t(s),e.length>0?{name:"empty-pages",status:"warn",message:`${e.length} page(s) appear to be empty/placeholder: ${e.slice(0,3).join(", ")}`}:{name:"empty-pages",status:"pass",message:"No empty pages detected"}}function Qa(o){let s=Q(o,"app","page.tsx");if(!Te(s))return{name:"landing-page",status:"warn",message:"No root page.tsx found"};let e=Xe(s,"utf-8");if(e.includes('redirect("/login")')||e.includes('redirect("/register")')){let t=Q(o,"middleware.ts"),n=Te(t)?Xe(t,"utf-8"):"";if(!(n.includes('"/"')||n.includes("'/'")))return{name:"landing-page",status:"fail",message:"Landing page (app/page.tsx) is just a redirect to /login, and middleware does not allow '/' as public. Users will never see a landing page."}}return e.length<200?{name:"landing-page",status:"warn",message:`Landing page is very small (${e.length} chars) \u2014 may be a placeholder.`}:{name:"landing-page",status:"pass",message:"Landing page has content"}}function Xa(o){let s=Q(o,"app");if(!Te(s))return{name:"cookies-in-actions",status:"pass",message:"No app directory"};let e=[];function t(n){try{for(let a of Kt(n)){if(a==="node_modules"||a===".next"||a===".open-next")continue;let r=Q(n,a);try{if(At(r).isDirectory())t(r);else if(a==="actions.ts"||a==="actions.tsx"){let l=Xe(r,"utf-8");l.includes("use server")&&l.includes("cookies()")&&l.includes(".set(")&&e.push(r.replace(o+"/",""))}}catch{}}}catch{}}return t(s),e.length>0?{name:"cookies-in-actions",status:"fail",message:`${e.length} server action(s) use cookies().set() which crashes on Mistflow Cloud's edge runtime: ${e.join(", ")}. Use a database field or form parameter instead.`}:{name:"cookies-in-actions",status:"pass",message:"No cookies().set() in server actions"}}function Za(o){let s=Q(o,"app");if(!Te(s))return{name:"fake-forms",status:"pass",message:"No app directory"};let e=[];function t(n){try{for(let a of Kt(n)){if(a==="node_modules"||a===".next"||a===".open-next")continue;let r=Q(n,a);try{if(At(r).isDirectory())t(r);else if(a.endsWith(".tsx")||a.endsWith(".ts")){let l=Xe(r,"utf-8");if((l.includes("setTimeout")||l.includes("new Promise"))&&l.includes("Simulate")||l.includes("simulate")||l.includes("// TODO")&&l.includes("API")){let c=r.replace(o+"/","");e.push(c)}}}catch{}}}catch{}}return t(s),e.length>0?{name:"fake-forms",status:"fail",message:`${e.length} file(s) have fake/simulated API calls instead of real server actions: ${e.slice(0,3).join(", ")}. Forms must use 'use server' actions that write to the database.`}:{name:"fake-forms",status:"pass",message:"No fake form handlers detected"}}function el(o){let e=[Q(o,"components","sidebar.tsx"),Q(o,"components","topnav.tsx"),Q(o,"components","nav.tsx")].find(i=>Te(i));if(!e)return[];let a=(Xe(e,"utf-8").match(/href:\s*"([^"]+)"/g)??[]).map(i=>i.replace(/href:\s*"/,"").replace(/"$/,"")).filter(i=>!i.startsWith("/api")&&!i.includes("["));if(a.length===0)return[];let r=[];for(let i of a){let l=i.replace(/^\//,"");if(!l||l==="")continue;[Q(o,"app","(dashboard)",l,"page.tsx"),Q(o,"app","(dashboard)",l,"page.ts"),Q(o,"app","(app)",l,"page.tsx"),Q(o,"app",l,"page.tsx"),Q(o,"app",l,"page.ts")].some(u=>Te(u))||r.push(i)}return r.length>0?[{name:"nav-links",status:"fail",message:`Sidebar/nav links to pages that don't exist: ${r.join(", ")}. These will 404.`}]:[{name:"nav-links",status:"pass",message:`All ${a.length} nav links have matching pages`}]}function $e(o,s){return nl("git",o,{cwd:s,encoding:"utf-8",timeout:3e4,stdio:["pipe","pipe","pipe"]}).trim()}function js(o){try{return $e(["rev-parse","--is-inside-work-tree"],o),!0}catch{return!1}}function zr(o){try{return $e(["status","--porcelain"],o).length>0}catch{return!1}}function Hr(o,s){return $e(["add","-A"],o),$e(["commit","-m",s,"--allow-empty-message"],o),$e(["rev-parse","HEAD"],o)}function ll(o){return $e(["rev-parse","HEAD"],o)}function Gr(o){try{return $e(["remote","get-url","origin"],o),!0}catch{return!1}}function cl(o){try{let s=$e(["rev-parse","--abbrev-ref","HEAD"],o);return $e(["push","origin",s],o),{success:!0}}catch(s){return{success:!1,error:s instanceof Error?s.message:"push failed"}}}function dl(o){let s=Qt(Yr(o)),e=Qt(s)===s?s:"/";for(;s!==e&&s!==Qt(s);){if(ue(se(s,"pnpm-workspace.yaml"))||ue(se(s,"lerna.json")))return s;let t=se(s,"package.json");if(ue(t))try{if(JSON.parse(Kr(t,"utf-8")).workspaces)return s}catch{}s=Qt(s)}return null}function pl(o){let s=se(al(),"mistflow-build");ol(s,{recursive:!0});let e=se(s,`${tl(o)}-${Date.now()}`);return Ls(o,e,{recursive:!0,filter:t=>{let n=t.slice(o.length);return!(n.startsWith("/.git")||n.startsWith("\\.git")||n==="/node_modules"||n.startsWith("/node_modules/")||n==="/.open-next"||n.startsWith("/.open-next/")||n==="/.next"||n.startsWith("/.next/"))}}),e}function ul(o,s){let e=se(o,".open-next"),t=se(o,".next");if(ue(e)){let n=se(s,".open-next");ue(n)&&Os(n,{recursive:!0}),Ls(e,n,{recursive:!0})}if(ue(t)){let n=se(s,".next");ue(n)&&Os(n,{recursive:!0}),Ls(t,n,{recursive:!0})}}function ml(o){try{Os(o,{recursive:!0,force:!0})}catch{console.error(`[deploy] Failed to clean up isolated build dir: ${o}`)}}function ut(o,s,e,t,n,a){return new Promise(r=>{let i=il(o,s,{cwd:e,stdio:["pipe","pipe","pipe"],timeout:t,...a?{env:a}:{}}),l="",c="";i.stdout?.on("data",u=>{let m=u.toString();if(c+=m,n)for(let p of m.split(`
|
|
5034
5034
|
`).filter(Boolean))n(p)}),i.stderr?.on("data",u=>{let m=u.toString();if(l+=m,n)for(let p of m.split(`
|
|
5035
|
-
`).filter(Boolean))n(p)}),i.on("close",(u,m)=>{r({success:u===0,stdout:c,stderr:l,signal:m})}),i.on("error",u=>{r({success:!1,stdout:c,stderr:l+u.message})})})}var
|
|
5036
|
-
`)}async function Jr(s
|
|
5037
|
-
`+l.stdout;if(l.signal==="SIGKILL"||c.includes("SIGKILL")||c.includes("exit code: 137"))return{success:!1,signal:"SIGKILL",error:"Your app ran out of memory while building. This sometimes happens with complex projects. Try deploying again \u2014 if it keeps failing, we'll help you figure it out."};let u=
|
|
5038
|
-
Fix: ${
|
|
5035
|
+
`).filter(Boolean))n(p)}),i.on("close",(u,m)=>{r({success:u===0,stdout:c,stderr:l,signal:m})}),i.on("error",u=>{r({success:!1,stdout:c,stderr:l+u.message})})})}var uu=Jt.object({projectPath:Jt.string().optional().describe("Path to the project directory (default: current working directory)"),message:Jt.string().optional().describe("Deploy message"),environment:Jt.enum(["production","preview"]).optional().default("production").describe("Target environment: 'production' (default) or 'preview' for a shareable URL")});function hl(o){return new Promise(s=>setTimeout(s,o))}function Wr(o){switch(o){case"pending":return"Provisioning database...";case"building":return"Building your app...";case"deploying":return"Deploying to Mistflow Cloud...";case"verifying":return"Verifying deployment...";default:return`Status: ${o}`}}function Us(o){let s=se(o,"mistflow.json");if(ue(s))try{return JSON.parse(Kr(s,"utf-8"))}catch{}return{}}function gl(o,s){let e=se(o,"mistflow.json"),t=Us(o),n=t.deploy?.count??t.deployCount??0;t.deploy={url:s,count:n+1,lastDeployedAt:new Date().toISOString()};let a=t.plan?.steps;if(Array.isArray(a))for(let r of a)r.status==="in_progress"&&(r.status="completed");delete t.deployUrl,delete t.deployCount,sl(e,JSON.stringify(t,null,2)+`
|
|
5036
|
+
`)}async function Jr(o,s){let t=process.platform==="win32"?"npx.cmd":"npx",n=0,a=se(o,"node_modules",".bin","opennextjs-cloudflare"),r=ue(a),i={...process.env,NODE_ENV:"production"},l=await ut(r?a:t,r?["build"]:["@opennextjs/cloudflare","build"],o,3e5,p=>{p.includes("Compiling")?s?.("Compiling your app..."):p.includes("Collecting page data")?s?.("Collecting page data..."):p.includes("Generating static pages")?s?.("Generating static pages..."):p.match(/^[○●◐λƒ]\s/)?n++:p.includes("Creating Cloudflare worker")?s?.("Packaging for Mistflow Cloud..."):p.includes("Build completed")&&s?.("Build completed!")},i);if(l.success)return{success:!0,buildStats:n>0?`${n} routes compiled`:"build complete"};let c=l.stderr+`
|
|
5037
|
+
`+l.stdout;if(l.signal==="SIGKILL"||c.includes("SIGKILL")||c.includes("exit code: 137"))return{success:!1,signal:"SIGKILL",error:"Your app ran out of memory while building. This sometimes happens with complex projects. Try deploying again \u2014 if it keeps failing, we'll help you figure it out."};let u=Ct(c);if(u.length>0){let p=u.map((f,w)=>{let g=`${w+1}. ${f.humanMessage}`;return f.suggestion&&(g+=`
|
|
5038
|
+
Fix: ${f.suggestion}`),g}).join(`
|
|
5039
5039
|
|
|
5040
5040
|
`);return{success:!1,error:`Build failed with ${u.length} error${u.length===1?"":"s"}:
|
|
5041
5041
|
|
|
@@ -5043,27 +5043,27 @@ ${p}`}}let m=c.split(`
|
|
|
5043
5043
|
`).filter(p=>p.includes("error")||p.includes("Error")).slice(0,10);return{success:!1,error:m.length>0?`OpenNext build failed:
|
|
5044
5044
|
${m.join(`
|
|
5045
5045
|
`)}`:`OpenNext build failed:
|
|
5046
|
-
${c.slice(-500)}`}}async function
|
|
5047
|
-
${a.stderr.slice(-300)}`};await
|
|
5048
|
-
`+m.stdout).trim(),
|
|
5046
|
+
${c.slice(-500)}`}}async function fl(o,s){let e=dl(o);if(e)return console.error(`[deploy] Project is inside monorepo at ${e} \u2014 building in isolated temp directory`),s?.("Detected parent project folder \u2014 building in isolated directory..."),Vr(o,s);let t=await Jr(o,s);return!t.success&&t.signal==="SIGKILL"?(console.error("[deploy] Build was OOM-killed \u2014 retrying in isolated temp directory"),s?.("Build ran out of memory \u2014 retrying with a fresh setup..."),Vr(o,s)):t}async function Vr(o,s){let e;try{s?.("Copying project to isolated build directory..."),e=pl(o),s?.("Installing dependencies...");let n=process.platform==="win32"?"npm.cmd":"npm",a=await ut(n,["install","--prefer-offline"],e,12e4);if(!a.success)return{success:!1,error:`Failed to install dependencies in isolated build:
|
|
5047
|
+
${a.stderr.slice(-300)}`};await ut(n,["dedupe"],e,6e4);let r=await Jr(e,s);return r.success&&(s?.("Copying build artifacts..."),ul(e,o)),{...r,builtInIsolation:e}}finally{e&&ml(e)}}async function yl(o,s,e){if(!ue(se(o,"db","schema")))return{success:!0,skipped:!0,skipReason:"No database structure found"};let t=se(o,"db","schema");try{if(rl(t).filter(f=>f.endsWith(".ts")).length===0)return{success:!0,skipped:!0,skipReason:"No database files found in db/schema/"}}catch{return{success:!0,skipped:!0,skipReason:"Could not read db/schema/ directory"}}if(!ue(se(o,"drizzle.config.ts")))return{success:!0,skipped:!0,skipReason:"No drizzle.config.ts found"};let n;try{n=await ro(s)}catch{return console.error("[deploy] Could not fetch DB credentials \u2014 skipping local schema push"),{success:!0,skipped:!0,skipReason:"Could not fetch database credentials \u2014 backend will handle the database update"}}let{db_provider:a,credentials:r}=n;if(a==="neon"){if(!r.DATABASE_URL)return console.error("[deploy] No DATABASE_URL found \u2014 skipping local schema push"),{success:!0,skipped:!0,skipReason:"No DATABASE_URL configured \u2014 set it with mist_config"}}else if(!r.TURSO_URL||!r.TURSO_AUTH_TOKEN)return console.error("[deploy] No Turso credentials found \u2014 skipping local schema push"),{success:!0,skipped:!0,skipReason:"No Turso credentials configured"};let i={PATH:process.env.PATH??"",HOME:process.env.HOME??"",NODE_PATH:process.env.NODE_PATH??"",TMPDIR:process.env.TMPDIR??"",...r},c=process.platform==="win32"?"npx.cmd":"npx",m=await ut(c,e?["drizzle-kit","push","--force"]:["drizzle-kit","push"],o,6e4,p=>{let f=p.replace(/(?:TURSO_AUTH_TOKEN|DATABASE_URL|AUTH_SECRET)=[^\s&]*/gi,w=>w.split("=")[0]+"=REDACTED").replace(/postgresql:\/\/[^@]*@/g,"postgresql://REDACTED@").replace(/libsql:\/\/[^\s]*/g,"libsql://REDACTED");console.error(`[drizzle-kit] ${f}`)},i);if(!m.success){let p=(m.stderr+`
|
|
5048
|
+
`+m.stdout).trim(),f=p.toLowerCase();if(f.includes("data-loss")||f.includes("cannot be reverted"))return{success:!1,error:"Database update blocked: your database has existing data that would be deleted. The update includes changes that would remove existing data. If you're OK with losing the data, deploy again with forceSchema: true."};let w=p.split(`
|
|
5049
5049
|
`).filter(h=>h.includes("error")||h.includes("Error")||h.includes("ERR")).slice(0,5);return{success:!1,error:`Database update failed:
|
|
5050
5050
|
${w.length>0?w.join(`
|
|
5051
|
-
`):p.slice(-500)}`}}return{success:!0}}async function Qr(s
|
|
5051
|
+
`):p.slice(-500)}`}}return{success:!0}}async function Qr(o,s){let{projectPath:e,message:t,environment:n="production",forceSchema:a}=o,r=n,i=Yr(e??process.cwd());if(!ye())return d("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let l=Fr(i);if(!l.passed){let x=l.errors.map(D=>{let M=`[${D.check}] ${D.message}`;return D.file&&(M+=` (${D.file}${D.line?`:${D.line}`:""})`),M}).join(`
|
|
5052
5052
|
`);return d(`Deploy blocked \u2014 fix these issues first:
|
|
5053
5053
|
|
|
5054
|
-
${x}`,!0)}let c=l.warnings.map(x=>`[${x.check}] ${x.message}`),u;if(
|
|
5054
|
+
${x}`,!0)}let c=l.warnings.map(x=>`[${x.check}] ${x.message}`),u;if(js(i))if(zr(i))try{let x=Us(i).deploy?.count??0,D=t?`Deploy v${x+1}: ${t}`:`Deploy v${x+1}`;u=Hr(i,D)}catch{console.error("[deploy] Pre-deploy git commit failed, continuing")}else try{u=ll(i)}catch{}let m=se(i,"mistflow.json");if(!ue(m))return d("No mistflow.json found. Run mist_build (action: 'init') first to set up your project.",!0);let p;try{let{ensureBackendRegistered:x}=await import("./self-heal-BXJXUFUF.js");p=await x(i,{forceSync:!0})}catch(x){let D=x instanceof Se?x.message:"Check your internet connection.";return d(`Could not register project with Mistflow: ${D}
|
|
5055
5055
|
|
|
5056
|
-
Try deploying again in a moment.`,!0)}if(p||(p=
|
|
5056
|
+
Try deploying again in a moment.`,!0)}if(p||(p=Ee(i)?.projectId),!p)return d("Could not register project with Mistflow \u2014 you may not be signed in. Run mist_setup to authenticate, then redeploy.",!0);if(p&&r==="production")try{let x=await Js(p),D=x,M=D.deploy_count??x.deployCount??0;(D.deploy_strategy??x.deploy_strategy)==="staging"&&M>0&&(r="preview",console.error("[deploy] Staging mode enabled \u2014 auto-redirecting to preview"))}catch{}let f=[],w=Date.now(),g=(x,D)=>{let M={phase:x,message:D};return f.push(M),M},h=(x,D)=>{x.durationMs=Date.now()-w,D&&(x.message=D)};if(s){let x=Je(s.server,s.progressToken,()=>f[f.length-1]?.message??"Deploying...");s.cleanup=()=>x.stop()}let v=!1;if(p&&r!=="preview"){let x=g("schema","Updating database structure..."),D=await yl(i,p,a);if(D.skipped)h(x,D.skipReason??"Database update skipped");else if(D.success)v=!0,h(x,"Database updated successfully");else return h(x,"Database update failed"),d(`Deploy blocked \u2014 database update failed:
|
|
5057
5057
|
|
|
5058
5058
|
${D.error}
|
|
5059
5059
|
|
|
5060
|
-
Try deploying again in a moment. If it keeps failing, check your database files in db/schema/.`,!0)}let E=
|
|
5060
|
+
Try deploying again in a moment. If it keeps failing, check your database files in db/schema/.`,!0)}let E=g("build","Compiling your app for Mistflow Cloud..."),R=Date.now(),C=await fl(i,x=>{E.message=x});if(!C.success)return d(`Deploy blocked \u2014 OpenNext build failed:
|
|
5061
5061
|
|
|
5062
|
-
${C.error}`,!0);h(E,`Build complete \u2014 ${C.buildStats??"ready"} (${((Date.now()-R)/1e3).toFixed(0)}s)`);let P=
|
|
5062
|
+
${C.error}`,!0);h(E,`Build complete \u2014 ${C.buildStats??"ready"} (${((Date.now()-R)/1e3).toFixed(0)}s)`);let P=g("qa","Running smoke tests..."),j=Ee(i),S=await Br(i,j);if(S.passed)h(P,`Smoke test passed \u2014 ${S.checksRun} checks OK`);else if(h(P,`Smoke test: ${S.summary}`),S.blocking)return d(`Deploy blocked \u2014 smoke test failed:
|
|
5063
5063
|
|
|
5064
5064
|
${S.summary}
|
|
5065
5065
|
|
|
5066
|
-
Fix these issues and try again.`,!0);let z=
|
|
5066
|
+
Fix these issues and try again.`,!0);let z=se(i,".open-next");if(!ue(z))return d("Build succeeded but .open-next/ directory not found. Check your OpenNext configuration.",!0);g("package","Packaging build artifacts...");let Y=se(i,".open-next-build.tar.gz"),G=[".open-next"];if(ue(se(i,"db"))&&G.push("db"),ue(se(i,"drizzle.config.ts"))&&G.push("drizzle.config.ts"),ue(se(i,"package.json"))&&G.push("package.json"),!(await ut("tar",["-czf",Y,"-C",i,...G],i,6e4)).success)return d("Failed to create build archive. Check disk space and permissions.",!0);let _;{let x=se(i,".mistflow-source.tar.gz");(await ut("tar",["-czf",x,"-C",i,"--exclude",".open-next","--exclude","node_modules","--exclude",".git","--exclude",".next","--exclude",".open-next-build.tar.gz","--exclude",".mistflow-source.tar.gz","."],i,6e4)).success?_=x:console.error("[deploy] Source archive creation failed, continuing without it")}g("upload","Uploading to Mistflow...");let ee=Dt()?.email,J,q;try{let x=await Zs(p,Y,r,ee,v,_,u);if(J=x.deployment_id??x.id,!J)return d("Upload succeeded but no deployment ID was returned. Check the Mistflow dashboard.",!0);q=x.status}catch(x){return Ur(x,"Deploy")}finally{try{qr(Y)}catch{}if(_)try{qr(_)}catch{}}g("deploying","Deploying to the edge...");let F=Date.now(),ie=24e4,le=3e3,K=[Wr(q)],me=q;for(;Date.now()-F<ie;){await hl(le);let x;try{x=await Oe(J)}catch{continue}if(x.status!==me&&(K.push(Wr(x.status)),me=x.status),x.status==="live"){let D=((Date.now()-F)/1e3).toFixed(0),M=x.url??"";if(!M)return d("Deployment marked as live but no URL was returned. Check the Mistflow dashboard.",!0);let y=r==="preview";if(!y){gl(i,M);try{let{readLocalState:I,syncRemoteState:H}=await import("./state-manager-GBP2NSYC.js"),b=I(i);b&&p&&(b.deployCount=(b.deployCount??0)+1,H(p,b).catch(()=>{}))}catch{}if(js(i)&&Gr(i))try{zr(i)&&Hr(i,"Update deploy metadata"),cl(i)}catch{}}let N=y?"Preview":"App",te=Us(i),De=te.name,ae=typeof De=="string"?De:"my app",Ce=te.features,pe=Array.isArray(Ce)?Ce.length:0,Ie=te.plan,T=Ie&&typeof Ie=="object"&&"steps"in Ie?Ie.steps:void 0,A=Array.isArray(T)?T.length:0,V=f.map(I=>I.message),U={url:M,time:`${D}s`,deploymentId:J,environment:r,statusLog:K,deployTimeline:V,message:y?`${N} is live at ${M} \u2014 preview deployed in ${D}s. This URL expires in 72 hours.`:`Your app is live at ${M} \u2014 deployed in ${D}s.`};if(y)U.instruction=["STAGING FLOW: The preview is deployed with an isolated database. Verify it before going live.","","1. Call mist_build with action='qa' and url='"+M+"' to test the preview.","2. If QA passes \u2014 tell the user the preview looks good and ask: 'Ready to go live?'","3. If QA finds issues \u2014 fix them, then call mist_deploy action='deploy' environment='preview' to redeploy the preview.","4. When user confirms \u2014 call mist_deploy action='promote' to push to production (~10s).","","Show the preview URL to the user so they can check it themselves while QA runs."].join(`
|
|
5067
5067
|
`),U.nextAction=`MANDATORY: Call mist_build with action='qa' and url='${M}' to verify the preview. After QA passes, ask user to confirm, then call mist_deploy action='promote'.`,U.qaRequired=!0,U.qaUrl=M,U.previewDeploymentId=J,U.promoteAction=`mist_deploy action='promote' deploymentId='${J}'`;else{let I=encodeURIComponent(`Just built "${ae}" with AI and deployed it live in ${D}s.
|
|
5068
5068
|
|
|
5069
5069
|
${A} steps, ${pe} features, zero config.
|
|
@@ -5078,34 +5078,35 @@ ${M}
|
|
|
5078
5078
|
|
|
5079
5079
|
Built with Mistflow (mistflow.ai)`);U.share={tweetUrl:`https://twitter.com/intent/tweet?text=${I}`,linkedInUrl:`https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(M)}`,celebration:["","================================================",` ${ae} is LIVE!`,"================================================","",` ${M}`,"",` Deployed in ${D}s`,` ${pe>0?`${pe} features`:""}${pe>0&&A>0?" \xB7 ":""}${A>0?`${A} build steps`:""}`,""," Share it:",` Twitter \u2192 https://twitter.com/intent/tweet?text=${I}`,` LinkedIn \u2192 https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(M)}`,"","================================================"].join(`
|
|
5080
5080
|
`)},U.instruction=["IMPORTANT: The app is deployed but NOT verified yet. Before celebrating:","","1. Call mist_build with action='qa' to test the live app.","2. If QA passes \u2014 present the URL prominently and show the celebration block above.","3. If QA finds issues \u2014 fix them, redeploy (mist_deploy action='deploy'), and run qa again.","4. Keep looping until QA passes. Only celebrate when all checks are green.","","Do NOT show the URL to the user until QA passes. A broken app is worse than no app."].join(`
|
|
5081
|
-
`),U.nextAction=`MANDATORY: Call mist_build with action='qa' and url='${M}' to verify the app works. Do NOT tell the user the app is ready until QA passes.`,U.qaRequired=!0,U.qaUrl=M}te.hasAdmin&&!y&&ee&&(U.adminSetup={message:`Your app is live. You're the admin \u2014 sign up at ${M}/signup with ${ee} to create your admin account. You'll pick your own password; the /admin panel unlocks as soon as you sign up.`}),c.length>0&&(U.warnings=c);let
|
|
5082
|
-
`),m.nextAction=`MANDATORY: Call mist_build with action='qa' and url='${u}' to verify production.`,m.qaRequired=!0,m.qaUrl=u,u?Ue(u,JSON.stringify(m)):d(JSON.stringify(m))}if(l.status==="failed")return d(`Promote failed: ${l.error??"Check the Mistflow dashboard for details."}`,!0)}catch{}}return d(`Promote is taking longer than expected. Deployment ID: ${a}`,!0)}import{z as tn}from"zod";import{spawn as
|
|
5083
|
-
`)){let n=t.trim();if(!n||n.startsWith("#"))continue;let a=n.indexOf("=");if(a>0){let r=n.slice(0,a).trim(),i=n.slice(a+1).trim();i&&i!=='""'&&i!=="''"&&
|
|
5081
|
+
`),U.nextAction=`MANDATORY: Call mist_build with action='qa' and url='${M}' to verify the app works. Do NOT tell the user the app is ready until QA passes.`,U.qaRequired=!0,U.qaUrl=M}te.hasAdmin&&!y&&ee&&(U.adminSetup={message:`Your app is live. You're the admin \u2014 sign up at ${M}/signup with ${ee} to create your admin account. You'll pick your own password; the /admin panel unlocks as soon as you sign up.`}),c.length>0&&(U.warnings=c);let oe=[];if(!y){let I=JSON.stringify(te).toLowerCase();oe.push({action:"Add a custom domain",command:"mist_config resource='domain' action='add' domain='yourdomain.com'",reason:"Give your app a professional URL instead of the default .mistflow.app domain.",priority:"medium"}),js(i)&&!Gr(i)&&oe.push({action:"Back up to GitHub",command:"Create a repo at github.com/new, then tell me the URL and I'll push your code there",reason:"Your source code is saved with every deploy, but GitHub gives you an extra backup and lets you collaborate.",priority:"medium"});let H=I.includes("user")||I.includes("account")||I.includes("member"),b=I.includes("stripe")||I.includes("payment")||I.includes("billing");H&&!b&&oe.push({action:"Add payments",command:"Tell the AI: 'Add Stripe payments to my app'",reason:"Your app has user accounts \u2014 you could monetize with subscriptions or one-time payments.",priority:"low"}),oe.push({action:"Share your app",command:"mist_project action='share'",reason:"Generate a shareable link so others can fork and customize your app.",priority:"low"}),oe.push({action:"Make changes",command:"Describe what you want to change, then run mist_deploy action='deploy'",reason:"Edit your code and redeploy in seconds. Your app is yours to evolve.",priority:"low"}),oe.push({action:"See analytics",command:`Visit ${Vs()} to see pageviews and visitors`,reason:"Track how people are using your app.",priority:"low"})}return oe.length>0&&(U.nextSteps=oe),Ue(M,JSON.stringify(U))}if(x.status==="failed")return d(x.error??"Deployment failed. Check the Mistflow dashboard for details.",!0)}return d(`Deploy is taking longer than expected. Your deploy ID is ${J} \u2014 check status later.`,!0)}import{z as Xt}from"zod";import{resolve as bl,join as wl}from"path";import{execFileSync as vl}from"child_process";var vu=Xt.object({projectPath:Xt.string().optional().describe("Path to the project directory (default: cwd)"),action:Xt.enum(["redeploy","rollback"]).describe("Action to perform: 'redeploy' re-deploys the latest build, 'rollback' reverts to a specific previous deployment"),deploymentId:Xt.string().optional().describe("Deployment ID to rollback to (required for 'rollback')")});function ze(o,s){return vl("git",o,{cwd:s,encoding:"utf-8",timeout:3e4,stdio:["pipe","pipe","pipe"]}).trim()}function Xr(o){try{return ze(["rev-parse","--is-inside-work-tree"],o),!0}catch{return!1}}async function kl(o,s,e,t){if(s&&Xr(o))try{ze(["cat-file","-t",s],o);let n=!1;try{ze(["status","--porcelain"],o).length>0&&(ze(["stash","push","-m","mistflow-rollback-auto-stash"],o),n=!0)}catch{}return ze(["reset","--hard",s],o),ze(["commit","--allow-empty","-m","Rollback to previous deploy"],o),{method:"git",success:!0,...n?{warning:"Your uncommitted changes were saved to git stash. Run `git stash pop` to restore them."}:{}}}catch{}if(e&&t)try{let{existsSync:n,mkdirSync:a,rmSync:r}=await import("fs"),i=wl(o,".mistflow-rollback-source.tar.gz");await fo(t,i);let{spawn:l}=await import("child_process");await new Promise((c,u)=>{let m=l("tar",["-xzf",i,"-C",o,"--exclude","node_modules","--exclude",".git"],{cwd:o,stdio:"pipe"});m.on("close",p=>p===0?c():u(new Error(`tar exit ${p}`))),m.on("error",u)});try{r(i)}catch{}if(Xr(o))try{ze(["add","-A"],o),ze(["commit","-m","Rollback to previous deploy (from source snapshot)"],o)}catch{}return{method:"r2",success:!0}}catch(n){return{method:"r2",success:!1,error:n instanceof Error?n.message:"Source download failed"}}return{method:"none",success:!1,error:"No source snapshot available for this deployment"}}function xl(o){return new Promise(s=>setTimeout(s,o))}function Sl(o){switch(o){case"pending":return"Provisioning...";case"building":return"Building...";case"deploying":return"Deploying to Mistflow Cloud...";case"verifying":return"Verifying deployment...";default:return`Status: ${o}`}}async function Zr(o,s,e){let t=Date.now(),n=12e4,a=3e3,r=[],i="";for(;Date.now()-t<n;){await xl(a);let l;try{l=await Oe(o)}catch{continue}if(l.status!==i&&(r.push(Sl(l.status)),i=l.status),l.status==="live"){let c=((Date.now()-t)/1e3).toFixed(0),u=l.url??"";if(e)try{await e()}catch{}return d(JSON.stringify({url:u,time:`${c}s`,deploymentId:o,statusLog:r,message:u?`${s} complete \u2014 live at ${u} in ${c}s.`:`${s} complete in ${c}s.`}))}if(l.status==="failed")return d(l.error??`${s} failed. Check the Mistflow dashboard for details.`,!0)}return d(`${s} is taking longer than expected. Deployment ID: ${o} \u2014 check status later.`,!0)}async function Fs(o){let{projectPath:s,action:e,deploymentId:t}=o,n=bl(s??process.cwd());if(!ye())return d("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let r=Ee(n)?.projectId;if(!r)return d("No project ID found. Deploy your project first with mist_deploy, or initialize with mist_plan + mist_build.",!0);try{switch(e){case"redeploy":{let i=await mo(r);return Zr(i.deployment_id,"Redeploy")}case"rollback":{if(!t)return d("Deployment ID is required for rollback. Use mist_project (action: 'deployments') to see previous deployment IDs.",!0);let i=await go(t);return Zr(i.deployment_id,"Rollback",async()=>{let l=await kl(n,i.git_commit_sha,i.source_artifact_key,t);l.success||console.error(`[rollback] Local source restore failed: ${l.error}`),l.warning&&console.error(`[rollback] ${l.warning}`)})}default:return d(`Unknown action: ${e}. Use redeploy or rollback.`,!0)}}catch(i){if(i instanceof Se)return d(i.message,!0);let l=i instanceof Error?i.message:"An unexpected error occurred";return d(l,!0)}}import{resolve as Tl}from"path";function Cl(o){return new Promise(s=>setTimeout(s,o))}async function en(o){let s=Tl(o.projectPath??process.cwd());if(!ye())return d("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let t=Ee(s)?.projectId;if(!t)return d("No project ID found. Deploy the project first.",!0);let n=o.deploymentId;if(!n)try{let c=(await wt(t)).find(u=>u.environment==="preview"&&u.status==="live");if(!c)return d("No live preview found to promote. Deploy with staging mode first, then call promote after QA passes.",!0);n=c.id}catch{return d("Could not list deployments. Check your connection.",!0)}console.error(`[promote] Promoting preview ${n} to production...`);let a;try{a=(await ho(t,n)).deployment_id}catch(l){let c=l instanceof Error?l.message:"Promote failed";return d(`Promote failed: ${c}`,!0)}let r=Date.now(),i=12e4;for(;Date.now()-r<i;){await Cl(3e3);try{let l=await Oe(a);if(l.status==="live"){let c=((Date.now()-r)/1e3).toFixed(0),u=l.url??"",m={url:u,time:`${c}s`,deploymentId:a,environment:"production",promoted:!0,message:`Promoted to production at ${u} in ${c}s. Same build that passed QA on preview.`};return m.instruction=["IMPORTANT: The app has been promoted to production. Run a quick QA check to verify.","","1. Call mist_build with action='qa' to test the live production app.","2. If QA passes \u2014 celebrate! Present the URL to the user.","3. If QA finds issues \u2014 these are likely environment differences (auth, DNS). Report them."].join(`
|
|
5082
|
+
`),m.nextAction=`MANDATORY: Call mist_build with action='qa' and url='${u}' to verify production.`,m.qaRequired=!0,m.qaUrl=u,u?Ue(u,JSON.stringify(m)):d(JSON.stringify(m))}if(l.status==="failed")return d(`Promote failed: ${l.error??"Check the Mistflow dashboard for details."}`,!0)}catch{}}return d(`Promote is taking longer than expected. Deployment ID: ${a}`,!0)}import{z as tn}from"zod";import{spawn as Il,execFileSync as sn}from"child_process";import{existsSync as es,readFileSync as on,writeFileSync as Rl,mkdirSync as El}from"fs";import{join as mt,resolve as Nl}from"path";import{homedir as rn}from"os";import{createConnection as _l}from"net";import{existsSync as Pl,readFileSync as Al}from"fs";function Zt(o){let s=new Set;if(!Pl(o))return s;let e=Al(o,"utf-8");for(let t of e.split(`
|
|
5083
|
+
`)){let n=t.trim();if(!n||n.startsWith("#"))continue;let a=n.indexOf("=");if(a>0){let r=n.slice(0,a).trim(),i=n.slice(a+1).trim();i&&i!=='""'&&i!=="''"&&s.add(r)}}return s}var Dl=tn.object({projectPath:tn.string().optional().describe("Path to the project directory (default: current working directory)")});function nn(){return mt(rn(),".mistflow","processes.json")}function an(){let o=nn();if(!es(o))return[];try{return JSON.parse(on(o,"utf-8"))}catch{return[]}}function ln(o){let s=mt(rn(),".mistflow");es(s)||El(s,{recursive:!0}),Rl(nn(),JSON.stringify(o,null,2))}function Ml(){let o=an(),s=[];for(let e of o)try{process.kill(e.pid,0),s.push(e)}catch{}ln(s)}function cn(o){return new Promise(s=>{let e=_l({port:o,host:"127.0.0.1"});e.on("connect",()=>{e.destroy(),s(!0)}),e.on("error",()=>{s(!1)})})}async function $l(o,s,e){let t=Date.now();for(;Date.now()-t<s;){if(await cn(o))return!0;await new Promise(n=>setTimeout(n,e))}return!1}function jl(o){return es(mt(o,"mistflow.json"))}function Ll(o){let s=mt(o,"mistflow.json");if(!es(s))return[];let e;try{e=JSON.parse(on(s,"utf-8"))}catch{return[]}let t=e.env?.required;if(!t||typeof t!="object")return[];let n=Object.keys(t);if(n.length===0)return[];let a=Zt(mt(o,".env.local"));return n.filter(r=>!a.has(r))}var dn={name:"mist_preview",description:"Build the app and start a local production server on localhost:3000 for previewing. Use when the user says 'mist preview'.",inputSchema:Dl,handler:async o=>{let e=Nl(o.projectPath??process.cwd()),t=3e3;if(!jl(e))return Ne(e);let n=Ll(e);if(n.length>0)return d(`Missing required environment variables in .env.local: ${n.join(", ")}. Add them to ${mt(e,".env.local")} before previewing.`,!0);Ml();let a=await cn(t),r=an(),i=r.some(m=>m.type==="dev-server"&&m.port===t);if(a&&!i)return d(`Port ${t} is in use. Stop the other process or I will use a different port.`,!0);let l=[...r];if(!a){try{sn("npx",["drizzle-kit","push"],{cwd:e,stdio:["pipe","pipe","pipe"],timeout:3e4})}catch{console.error("[preview] drizzle-kit push failed, continuing...")}try{sn("npm",["run","build"],{cwd:e,stdio:["pipe","pipe","pipe"],timeout:18e4})}catch(w){let g=w instanceof Error&&"stderr"in w?String(w.stderr).slice(-1500):"",h=w instanceof Error&&"stdout"in w?String(w.stdout).slice(-1500):"",v=(g+`
|
|
5084
5084
|
`+h).trim();return d(`Build failed. Fix the errors before previewing:
|
|
5085
5085
|
|
|
5086
|
-
${v}`,!0)}let m=
|
|
5086
|
+
${v}`,!0)}let m=Il("npx",["next","start","-p",String(t)],{cwd:e,detached:!0,stdio:["ignore","pipe","pipe"]}),p="";if(m.stderr?.on("data",w=>{p+=w.toString()}),m.pid&&(m.unref(),l.push({pid:m.pid,type:"dev-server",port:t,startedAt:new Date().toISOString()}),ln(l)),!await $l(t,15e3,500)){let w=p?`Server failed to start:
|
|
5087
5087
|
|
|
5088
|
-
${p.slice(-1e3)}`:"Server failed to start within 15s. Check for runtime errors.";return d(w,!0)}}let c=`http://localhost:${t}`,u=JSON.stringify({localUrl:c,message:`Preview is live at ${c}. Run mist_deploy to get your permanent URL on mistflow.app.`});return Ue(c,u)}};import{resolve as
|
|
5089
|
-
`),nextSteps:w}))}let a=[];if(
|
|
5090
|
-
`),n.projectId&&import("./state-manager-GBP2NSYC.js").then(async({readLocalState:i,syncRemoteState:l})=>{let c=i(e);c&&await l(n.projectId,c)}).catch(()=>{});let r=[];if(
|
|
5088
|
+
${p.slice(-1e3)}`:"Server failed to start within 15s. Check for runtime errors.";return d(w,!0)}}let c=`http://localhost:${t}`,u=JSON.stringify({localUrl:c,message:`Preview is live at ${c}. Run mist_deploy to get your permanent URL on mistflow.app.`});return Ue(c,u)}};import{resolve as Ol,join as Ul}from"path";import{existsSync as Fl,readFileSync as Bl}from"fs";var Bs="test@mistflow.dev",pn="MistflowTest123!",ql="Test User";function un(o){let s=Ul(o,"mistflow.json");if(!Fl(s))return null;try{return JSON.parse(Bl(s,"utf-8"))}catch{return null}}function zl(o){let s=JSON.stringify(o).toLowerCase();return["auth","login","sign-in","sign-up","signin","signup"].some(e=>s.includes(e))}function Hl(o){let s=o.plan;if(!s?.steps)return[];let e=new Set;for(let n of s.steps)if(n.pages)for(let a of n.pages)e.add(a);let t=new Set(["login","signup","sign-in","sign-up","signin","signout","sign-out","logout"]);return[...e].filter(n=>!t.has(n.toLowerCase())).slice(0,3)}function Gl(o){let s=o.deploy;return s?.url?s.url:typeof o.deployUrl=="string"?o.deployUrl:null}async function mn(o){let s=Ol(o.projectPath??process.cwd()),e=o.verifyUrl,t=null;if(e)t=un(s);else{if(t=un(s),!t)return d("No mistflow.json found. Run mist_deploy first, or pass verifyUrl explicitly.",!0);if(e=Gl(t)??void 0,!e)return d("No deploy URL found in mistflow.json. Deploy your app first with mist_deploy.",!0)}e.startsWith("http")||(e=`https://${e}`);let n=t?zl(t):!1,a=t?Hl(t):[],r;try{r=await Nt()}catch{return d("Browser not available. Install Playwright to use verify: npx playwright install chromium",!0)}let i={verified:!0,url:e,authTested:!1,testUser:null,pages:[],message:""},l=[];try{await r.goto(e,{waitUntil:"domcontentloaded",timeout:3e4}),await r.waitForLoadState("networkidle").catch(()=>{})}catch{return i.verified=!1,i.message=`Could not load ${e}. The app may not be deployed yet or the URL may be incorrect.`,d(JSON.stringify(i),!0)}let c=await r.title(),u=c.toLowerCase().includes("error")||c.toLowerCase().includes("404")?"error":"ok";i.pages.push({path:"/",status:u,title:c});try{let g=await Le(r,!1);l.push({data:g.toString("base64"),mimeType:"image/png"})}catch{}if(u==="error"&&(i.verified=!1),n)try{(await r.evaluate(async h=>{let v=await fetch("/api/auth/sign-up/email",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(h)});return{status:v.status,ok:v.ok}},{email:Bs,password:pn,name:ql})).ok||await r.evaluate(async h=>{let v=await fetch("/api/auth/sign-in/email",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(h)});return{status:v.status,ok:v.ok}},{email:Bs,password:pn}),await r.reload({waitUntil:"domcontentloaded",timeout:15e3}),await r.waitForLoadState("networkidle").catch(()=>{}),i.authTested=!0,i.testUser={email:Bs};try{let h=await Le(r,!1);l.push({data:h.toString("base64"),mimeType:"image/png"})}catch{}}catch{console.error("[verify] Auth test failed, continuing with public pages")}for(let g of a){let h=g.startsWith("/")?g:`/${g}`;try{await r.goto(`${e}${h}`,{waitUntil:"domcontentloaded",timeout:15e3}),await r.waitForLoadState("networkidle").catch(()=>{});let v=await r.title(),E=v.toLowerCase().includes("404")||v.toLowerCase().includes("not found")?"error":"ok";i.pages.push({path:h,status:E,title:v}),E==="error"&&(i.verified=!1);try{let R=await Le(r,!1);l.push({data:R.toString("base64"),mimeType:"image/png"})}catch{}}catch{i.pages.push({path:h,status:"error",title:"Timeout"}),i.verified=!1}}let m=i.pages.filter(g=>g.status==="ok").length,p=i.pages.length,f=i.authTested?" Auth login successful.":"";i.message=i.verified?`Verified ${m}/${p} pages.${f} App looks good.`:`Verified ${m}/${p} pages \u2014 some issues found.${f} Check screenshots.`;let w=[{type:"text",text:JSON.stringify(i)}];for(let g of l)w.push({type:"image",data:g.data,mimeType:g.mimeType});return{content:w}}var Wl=Ze.object({action:Ze.enum(["deploy","promote","preview","redeploy","rollback","verify"]).describe("'deploy' builds and deploys to Mistflow Cloud (auto-redirects to preview if staging mode is enabled). 'promote' promotes a verified preview to production (~10s, reuses the preview build). 'preview' builds the app and starts a local production server on localhost:3000. 'redeploy' re-deploys the latest build without rebuilding. 'rollback' reverts to a specific previous deployment. 'verify' navigates the deployed app, tests auth, and screenshots pages to confirm it works."),projectPath:Ze.string().optional().describe("Path to the project directory (default: cwd)"),environment:Ze.enum(["production","preview"]).optional().describe("(deploy) Target environment. Defaults to 'production'. Projects with staging mode auto-redirect to preview."),forceSchema:Ze.boolean().optional().describe("(deploy) Reset the database structure. Warning: this deletes existing data. Only use when the user confirms this is OK."),deploymentId:Ze.string().optional().describe("(rollback/promote) Deployment ID to rollback to, or preview deployment ID to promote"),verifyUrl:Ze.string().optional().describe("(verify) URL to verify. Defaults to deploy URL from mistflow.json")}),hn={name:"mist_deploy",description:"STEP 4 (final) of the Mistflow workflow. Deploy a Mistflow project. Call this AFTER all mist_build implement steps are done. If the project has staging mode enabled (configurable in dashboard), the tool automatically deploys to preview first with an isolated database. After QA passes, call action='promote' to go live (~10s, reuses the same build artifact). Actions: 'deploy' (default), 'promote' (promote preview to production), 'preview' (local dev server), 'redeploy', 'rollback', 'verify'. The workflow is: mist_plan \u2192 mist_build init \u2192 implement (repeat) \u2192 mist_build build \u2192 mist_deploy \u2192 mist_build qa.",inputSchema:Wl,handler:async(o,s)=>{let e=o;switch(e.action){case"deploy":return Qr({projectPath:e.projectPath,environment:e.environment??"production",forceSchema:e.forceSchema},s);case"promote":return en({projectPath:e.projectPath,deploymentId:e.deploymentId});case"preview":return dn.handler({projectPath:e.projectPath});case"redeploy":return Fs({projectPath:e.projectPath,action:"redeploy"});case"rollback":return Fs({projectPath:e.projectPath,action:"rollback",deploymentId:e.deploymentId});case"verify":return mn({projectPath:e.projectPath,verifyUrl:e.verifyUrl});default:return d(`Unknown action: ${e.action}. Use deploy, promote, preview, redeploy, rollback, or verify.`,!0)}}};import{z as ve}from"zod";import{resolve as ts}from"path";import{existsSync as ss,readFileSync as os}from"fs";import{join as rs}from"path";import{z as He}from"zod";import{resolve as Vl,join as gn}from"path";import{existsSync as Yl,readFileSync as fn,writeFileSync as Kl}from"fs";var Jl=He.object({action:He.enum(["get","update"]).default("get").describe("'get' reads current project state. 'update' modifies it."),projectPath:He.string().optional().describe("Path to the project directory (default: current working directory)"),completedStep:He.number().optional().describe("(update only) Mark a plan step as completed by step number"),addEnvVar:He.object({key:He.string(),description:He.string().optional(),setupUrl:He.string().optional()}).optional().describe("(update only) Add a required env var to the project manifest")}),yn={name:"mist_state",description:"Read or update project state in mistflow.json. Use action='get' to load plan progress, env var status, and deploy info. Use action='update' to mark plan steps complete or add required env vars. Use when the user says 'mist status', 'mist state', or 'mist update state'.",inputSchema:Jl,handler:async o=>{let s=o,e=Vl(s.projectPath??process.cwd()),t=gn(e,"mistflow.json");if(!Yl(t))return Ne(e);let n;try{n=JSON.parse(fn(t,"utf-8"))}catch{return d("Failed to parse mistflow.json.",!0)}if(s.action==="get"){if(!n.projectId)try{let{ensureBackendRegistered:h}=await import("./self-heal-BXJXUFUF.js");await h(e)&&(n=JSON.parse(fn(t,"utf-8")))}catch{}let i=n.plan,l=i?.steps?.filter(h=>h.status==="completed").length??0,c=i?.steps?.length??0,u=Zt(gn(e,".env.local")),m=n.env?.required?Object.entries(n.env.required).map(([h,v])=>({name:h,description:v?.description,configured:u.has(h)})):[];n.projectId&&import("./state-manager-GBP2NSYC.js").then(({fetchRemoteState:h})=>h(n.projectId)).catch(()=>{});let p=[`Project: ${n.name}`];if(i){p.push(`Plan: ${i.summary??i.name??"unnamed"} \u2014 ${l}/${c} steps complete`);for(let h of i.steps){let v=h.status==="completed"?"\u2713":h.status==="in_progress"?"\u2192":" ";p.push(` [${v}] ${h.number}. ${h.name}`)}}let f=m.filter(h=>!h.configured);f.length>0&&p.push(`Missing env vars: ${f.map(h=>h.name).join(", ")}`),n.deploy?.url?p.push(`Deployed: ${n.deploy.url} (${n.deploy.count??0} deploys)`):p.push("Not deployed yet");let w=[],g=i?.steps?.find(h=>h.status!=="completed");return g?w.push(`NEXT: Call mist_build with action='implement' to work on step ${g.number} (${g.name}).`):i&&l===c&&(n.deploy?.url||w.push("NEXT: All steps complete! Call mist_deploy with action='deploy' to deploy the app now. Do NOT ask the user \u2014 just deploy.")),f.length>0&&w.push(`Missing env vars in .env.local: ${f.map(h=>h.name).join(", ")}`),d(JSON.stringify({name:n.name,projectId:n.projectId,planProgress:i?{name:i.name,summary:i.summary,totalSteps:c,completedSteps:l,steps:i.steps}:null,envStatus:m,deploy:n.deploy??null,contextMessage:p.join(`
|
|
5089
|
+
`),nextSteps:w}))}let a=[];if(s.completedStep!==void 0){let i=n.plan;if(i?.steps){let l=i.steps.findIndex(c=>c.number===s.completedStep);if(l===-1)return d(`Step ${s.completedStep} not found in the plan.`,!0);i.steps[l].status="completed",a.push(`Step ${s.completedStep} marked as completed`)}}s.addEnvVar&&(n.env||(n.env={required:{}}),n.env.required||(n.env.required={}),n.env.required[s.addEnvVar.key]={description:s.addEnvVar.description,setupUrl:s.addEnvVar.setupUrl},a.push(`Added required env var: ${s.addEnvVar.key}`)),Kl(t,JSON.stringify(n,null,2)+`
|
|
5090
|
+
`),n.projectId&&import("./state-manager-GBP2NSYC.js").then(async({readLocalState:i,syncRemoteState:l})=>{let c=i(e);c&&await l(n.projectId,c)}).catch(()=>{});let r=[];if(s.completedStep!==void 0){let l=n.plan?.steps?.find(c=>c.status!=="completed");l?r.push(`NEXT: Call mist_build with action='implement' to work on step ${l.number} (${l.name}). Do this now.`):r.push("NEXT: All steps complete! Call mist_deploy with action='deploy' to deploy the app now. Do NOT suggest localhost.")}return s.addEnvVar&&(r.push(`Add ${s.addEnvVar.key} to your .env.local file`),s.addEnvVar.setupUrl&&r.push(`Get the value from: ${s.addEnvVar.setupUrl}`)),d(JSON.stringify({updated:!0,changes:a,message:a.length>0?`Project state saved. ${a.join(". ")}.`:"No changes made.",nextSteps:r.length>0?r:void 0}))}};var Ql=ve.object({action:ve.enum(["get","update","share","landing-designs","integrations","errors","logs","deployments","version"]).default("get").describe("'get' reads current project state. 'update' marks steps complete or adds env vars. 'share' makes the project a shareable template. 'landing-designs' lists curated landing page hero designs. 'integrations' lists third-party service integration blueprints (Stripe, Resend, ElevenLabs, etc.) with setup guides. 'errors' fetches runtime errors from the deployed app. 'logs' fetches deploy logs for a specific deployment. 'deployments' lists deployment history. 'version' reports the installed @mistflow-ai/mcp version and whether an upgrade is available."),projectPath:ve.string().optional().describe("Path to the project directory (default: cwd)"),completedStep:ve.number().optional().describe("(update) Mark a plan step as completed by step number"),addEnvVar:ve.object({key:ve.string(),description:ve.string().optional(),setupUrl:ve.string().optional()}).optional().describe("(update) Add a required env var to the project manifest"),templateDescription:ve.string().optional().describe("(share) Short description of what this template builds"),category:ve.string().optional().describe("(landing-designs) Filter by category"),presetId:ve.string().optional().describe("(landing-designs) Get full details for a specific landing design by ID"),integrationId:ve.string().optional().describe("(integrations) Get full details for a specific integration preset by ID (e.g. 'stripe-payments', 'resend-email', 'elevenlabs-voice')"),period:ve.string().optional().describe("(errors) Time period for errors: '1h', '24h', '7d' (default: '7d')"),deploymentId:ve.string().optional().describe("(logs) Deployment ID to fetch logs for. If omitted, fetches logs for the latest deployment.")}),bn={name:"mist_project",description:"Read or update Mistflow project state. 'get' loads plan progress, env vars, and deploy info. 'update' marks plan steps complete or adds env vars (note: mist_build implement auto-marks the previous step, so manual updates are rarely needed). 'share' makes the project a forkable template with a shareable URL. 'landing-designs' lists curated landing page hero designs \u2014 pass an ID to mist_plan's landingDesign field to apply it. 'integrations' lists third-party service integration blueprints (Stripe, Resend, ElevenLabs, OpenAI, Twilio, etc.) \u2014 these are auto-injected during implementation when the plan includes matching integration steps. 'errors' fetches runtime errors from the live deployed app (same data shown on the dashboard). 'logs' fetches deploy logs for a deployment (phase-by-phase progress with error details). 'deployments' lists deployment history with status and error messages.",inputSchema:Ql,handler:async o=>{let s=o;if(["share","errors","logs","deployments"].includes(s.action)&&!ye())return d("You need to sign in first. Run mist_setup to connect your account.",!0);switch(s.action){case"get":case"update":return yn.handler({action:s.action,projectPath:s.projectPath,completedStep:s.completedStep,addEnvVar:s.addEnvVar});case"share":{let t=ts(s.projectPath??process.cwd()),n=rs(t,"mistflow.json");if(!ss(n))return Ne(t);let a;try{a=JSON.parse(os(n,"utf-8"))}catch{return d("Could not read mistflow.json.",!0)}let r=a.projectId;if(!r)return d("No project ID found. Deploy the project first to register it.",!0);try{let i=await xo(r,{isTemplate:!0,description:s.templateDescription});return d(JSON.stringify({shareUrl:i.share_url,shareToken:i.share_token,message:`Your project is now a shareable template!
|
|
5091
5091
|
|
|
5092
5092
|
Anyone can fork it: ${i.share_url}
|
|
5093
5093
|
|
|
5094
5094
|
Others can use it in their AI editor:
|
|
5095
|
-
"build me something like ${i.share_url}"`}))}catch(i){let l=i instanceof Error?i.message:"Failed to share project";return d(l,!0)}}case"landing-designs":{if(
|
|
5096
|
-
`)}async function vn(s){let{projectPath:o,action:e,domain:t,domainId:n}=s,a=Xl(o??process.cwd());if(!ye())return d("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let i=Re(a)?.projectId;if(!i)return d("No project ID found. Deploy your project first with mist_deploy, or initialize with mist_plan + mist_build.",!0);try{switch(e){case"add":{if(!t)return d("Domain name is required. Provide the domain like 'myapp.com' or 'app.mycompany.com'.",!0);let l=await ss(i,t),c=await Ke(i);return zo(a,c.map(u=>({domain:u.domain,status:u.status}))),d(JSON.stringify({added:!0,domain:l.domain,status:l.status,instructions:l.instructions,message:`Domain '${l.domain}' added. Set up DNS records as described, then use action 'verify' to check status.`}))}case"list":{let l=await Ke(i);return l.length===0?d(JSON.stringify({domains:[],message:"No custom domains configured. Use action 'add' to add one."})):d(JSON.stringify({domains:l.map(c=>({id:c.id,domain:c.domain,status:c.status,ssl:c.ssl_status,error:c.error_message}))}))}case"verify":{if(!n){if(t){let m=(await Ke(i)).find(p=>p.domain===t);if(m){let p=await lo(i,m.id);return d(JSON.stringify({domain:p.domain,status:p.status,ssl:p.ssl_status,error:p.error_message,message:p.status==="active"?`Domain '${p.domain}' is active and serving traffic.`:`Domain '${p.domain}' is ${p.status}. Make sure DNS records are configured correctly.`}))}return d(`Domain '${t}' not found. Use action 'list' to see configured domains.`,!0)}return d("Provide either domainId or domain name to verify.",!0)}let l=await lo(i,n),c=await Ke(i);return zo(a,c.map(u=>({domain:u.domain,status:u.status}))),d(JSON.stringify({domain:l.domain,status:l.status,ssl:l.ssl_status,error:l.error_message,message:l.status==="active"?`Domain '${l.domain}' is active and serving traffic.`:`Domain '${l.domain}' is ${l.status}. Make sure DNS records are configured correctly.`}))}case"remove":{if(!n&&!t)return d("Provide either domainId or domain name to remove.",!0);let l=n;if(!l&&t){let m=(await Ke(i)).find(p=>p.domain===t);if(!m)return d(`Domain '${t}' not found.`,!0);l=m.id}await rs(i,l);let c=await Ke(i);return zo(a,c.map(u=>({domain:u.domain,status:u.status}))),d(JSON.stringify({removed:!0,message:"Domain removed. It may take a few minutes for DNS changes to propagate."}))}default:return d(`Unknown action: ${e}. Use add, list, verify, or remove.`,!0)}}catch(l){if(l instanceof xe)return d(l.message,!0);let c=l instanceof Error?l.message:"An unexpected error occurred";return d(c,!0)}}var sc=Ne.object({resource:Ne.enum(["env","domain"]).describe("'env' manages app secrets and configuration values. 'domain' manages custom domains."),action:Ne.string().describe("Action to perform. env: 'set', 'list', 'delete'. domain: 'add', 'list', 'verify', 'remove'."),projectPath:Ne.string().optional().describe("Path to the project directory (default: cwd)"),key:Ne.string().optional().describe("(env) Variable name"),value:Ne.string().optional().describe("(env set) Variable value"),category:Ne.string().optional().describe("(env set) Category"),description:Ne.string().optional().describe("(env set) Description"),setupUrl:Ne.string().optional().describe("(env set) URL to obtain the value"),domain:Ne.string().optional().describe("(domain) Domain name"),domainId:Ne.string().optional().describe("(domain) Domain ID")}),kn={name:"mist_config",description:"Manage project configuration: app secrets and custom domains. Set resource='env' to manage encrypted app secrets (set, list, delete). Set resource='domain' to manage custom domains (add, list, verify, remove). Use when the user says 'mist env' or 'mist domain'.",inputSchema:sc,handler:async s=>{let o=s;switch(o.resource){case"env":return wn({projectPath:o.projectPath,action:o.action,key:o.key,value:o.value,category:o.category,description:o.description,setupUrl:o.setupUrl});case"domain":return vn({projectPath:o.projectPath,action:o.action,domain:o.domain,domainId:o.domainId});default:return d(`Unknown resource: ${o.resource}. Use env or domain.`,!0)}}};import{z as et}from"zod";var rc=et.object({action:et.enum(["navigate","go_back","go_forward","click","type","fill","select_option","press_key","hover","screenshot","snapshot"]).describe("Action to perform. Navigation: navigate|go_back|go_forward. Interaction: click|type|fill|select_option|press_key|hover. Visual: screenshot (returns image) | snapshot (returns accessibility tree)."),url:et.string().optional().describe("URL to navigate to. Required for 'navigate'; optional for 'screenshot' (navigates before capturing)."),selector:et.string().optional().describe("CSS selector of the target element. Required for: click, type, fill, select_option, hover. Optional for screenshot (captures just that element)."),value:et.string().optional().describe("Text to type/fill, option to select, or key to press (e.g. 'Enter', 'Tab'). Required for: type, fill, select_option, press_key."),fullPage:et.boolean().default(!1).describe("For 'screenshot': capture the full scrollable page instead of just the viewport."),includeScreenshot:et.boolean().default(!1).describe("For navigate/interact actions: also return a screenshot alongside the accessibility snapshot.")}),xn={name:"mist_browser",description:"Unified browser tool for navigating, interacting with, and capturing the app. Use 'navigate' to open a URL, interaction actions (click/type/fill/etc.) to test flows, 'snapshot' to inspect the accessibility tree, and 'screenshot' for a visual capture. Use after mist_preview to verify UI, test flows, and iterate on design.",inputSchema:rc,handler:async s=>{let o=s,e=await Et();if(o.action==="navigate"){if(!o.url)return d("URL is required for 'navigate'.",!0);let a=[],r=c=>{c.type()==="error"&&a.push(c.text())};e.on("console",r),await e.goto(o.url,{waitUntil:"domcontentloaded",timeout:3e4}),await e.waitForLoadState("networkidle").catch(()=>{});let i=[],l=c=>i.push(c.message);if(e.on("pageerror",l),await e.waitForTimeout(500),e.removeListener("console",r),e.removeListener("pageerror",l),a.length>0||i.length>0){let c=await Nt(e),u=[{type:"text",text:JSON.stringify({url:e.url(),title:await e.title(),snapshot:c,consoleErrors:a,pageErrors:i,hasErrors:!0})}];if(o.includeScreenshot){let m=await Le(e);u.push({type:"image",data:m.toString("base64"),mimeType:"image/png"})}return{content:u}}}else if(o.action==="go_back")await e.goBack({waitUntil:"domcontentloaded",timeout:1e4});else if(o.action==="go_forward")await e.goForward({waitUntil:"domcontentloaded",timeout:1e4});else if(o.action==="click"){if(!o.selector)return d("Selector is required for 'click'.",!0);await e.click(o.selector,{timeout:1e4}),await e.waitForLoadState("domcontentloaded").catch(()=>{}),await e.waitForTimeout(500)}else if(o.action==="type"){if(!o.selector)return d("Selector is required for 'type'.",!0);if(!o.value)return d("Value is required for 'type'.",!0);await e.type(o.selector,o.value,{delay:50})}else if(o.action==="fill"){if(!o.selector)return d("Selector is required for 'fill'.",!0);if(!o.value)return d("Value is required for 'fill'.",!0);await e.fill(o.selector,o.value)}else if(o.action==="select_option"){if(!o.selector)return d("Selector is required for 'select_option'.",!0);if(!o.value)return d("Value is required for 'select_option'.",!0);await e.selectOption(o.selector,o.value)}else if(o.action==="hover"){if(!o.selector)return d("Selector is required for 'hover'.",!0);await e.hover(o.selector,{timeout:1e4})}else if(o.action==="press_key"){if(!o.value)return d("Value is required for 'press_key' (e.g. 'Enter').",!0);await e.keyboard.press(o.value),await e.waitForLoadState("domcontentloaded").catch(()=>{}),await e.waitForTimeout(500)}else if(o.action==="screenshot"){o.url&&(await e.goto(o.url,{waitUntil:"domcontentloaded",timeout:3e4}),await e.waitForLoadState("networkidle").catch(()=>{}));let a;if(o.selector){let r=await e.$(o.selector);if(!r)return d(`Element not found: ${o.selector}`,!0);a=await r.screenshot({type:"png"})}else a=await Le(e,o.fullPage);return{content:[{type:"text",text:JSON.stringify({url:e.url(),title:await e.title(),message:`Screenshot captured (${o.fullPage?"full page":"viewport"})`})},{type:"image",data:a.toString("base64"),mimeType:"image/png"}]}}else if(o.action==="snapshot"){let a=await Nt(e);return{content:[{type:"text",text:JSON.stringify({url:e.url(),title:await e.title(),snapshot:a})}]}}let t=await Nt(e),n=[{type:"text",text:JSON.stringify({url:e.url(),title:await e.title(),snapshot:t})}];if(o.includeScreenshot){let a=await Le(e);n.push({type:"image",data:a.toString("base64"),mimeType:"image/png"})}return{content:n}}};import{existsSync as _e,readFileSync as It,writeFileSync as mt}from"fs";import{join as Te}from"path";import{z as At}from"zod";function Sn(s){let o=Te(s,"mistflow.json");if(!_e(o))return{result:{name:"Project",status:"fail",message:"No mistflow.json found. This is not a Mistflow project.",fix:"Run mist_plan to design your app, then mist_build init to scaffold it."},config:null};let e;try{e=JSON.parse(It(o,"utf-8"))}catch{return{result:{name:"Project",status:"fail",message:"mistflow.json exists but contains invalid JSON.",fix:"Check mistflow.json for syntax errors. If corrupted beyond repair, delete it and re-run mist_build init."},config:null}}if(!e.name||typeof e.name!="string")return{result:{name:"Project",status:"warn",message:"mistflow.json is missing the 'name' field."},config:e};let t=e.projectId,n=t?`, id: ${t}`:", no projectId";return{result:{name:"Project",status:"pass",message:`${e.name}${n}`},config:e}}async function nc(){let s=Vo();if(!s.ok)return{result:{name:"Auth",status:"fail",message:s.reason==="missing"?"No credentials found.":"Credentials file is malformed.",fix:"Run mist_setup to log in."},creds:null,authValid:!1};try{let o=Ko(),e=await fetch(`${Ye()}/api/org`,{headers:o,signal:AbortSignal.timeout(1e4)});try{Go(e.headers)}catch{}if(!e.ok)return e.status===401?{result:{name:"Auth",status:"fail",message:"API key is invalid or revoked.",fix:"Run mist_setup to re-authenticate."},creds:s.creds,authValid:!1}:{result:{name:"Auth",status:"warn",message:`Server returned ${e.status}. Credentials may still be valid.`},creds:s.creds,authValid:!1};let t=await e.json(),n=t.slug??s.creds.orgSlug??"unknown",a=t.plan?`, plan: ${t.plan}`:"";return{result:{name:"Auth",status:"pass",message:`org: ${n}${a}`},creds:s.creds,authValid:!0}}catch(o){return o instanceof xe?{result:{name:"Auth",status:"fail",message:`Auth check failed: ${o.message}`,fix:"Run mist_setup to re-authenticate."},creds:s.creds,authValid:!1}:{result:{name:"Auth",status:"warn",message:"Could not reach API to validate credentials. Network issue?"},creds:s.creds,authValid:!1}}}async function ic(){let s=Date.now();try{let o=await Dt("nextjs"),e=Date.now()-s;return{result:{name:"API",status:"pass",message:`${Ye()} reachable (${e}ms)`},scaffold:o}}catch(o){let e=Date.now()-s;return{result:{name:"API",status:"fail",message:o instanceof xe?o.message:`Timeout or network error after ${e}ms`,fix:"Check your network connection. If using --api-url, verify the backend is running."},scaffold:null}}}function ac(){let s=gt();if(!s.backendSignalReceived)return{name:"MCP version",status:"warn",message:`v${s.current} installed, but no backend signal received to compare against.`};let o={none:"up to date",patch:"patch update available",minor:"minor update available",major:"major update available",unsupported:"no longer supported"};return s.severity==="none"?{name:"MCP version",status:"pass",message:`v${s.current} (latest)`}:s.severity==="unsupported"?{name:"MCP version",status:"fail",message:`v${s.current} is ${o[s.severity]}. Minimum: v${s.minSupported}.`,fix:`Run \`${s.upgradeCmd}\` then restart your editor.`}:{name:"MCP version",status:"warn",message:`v${s.current} installed, v${s.latest} available (${o[s.severity]}).`,fix:`Run \`${s.upgradeCmd}\` then restart your editor.`}}function lc(s,o,e,t){let n=Te(s,"AGENTS.md"),a=Te(s,"CLAUDE.md"),r=_e(n),i=o.methodologyVersion??"",l=e?.version??"";if(!r){if(!t||!e?.methodology)return{name:"AGENTS.md",status:"fail",message:"Missing. The host AI has no methodology context for this project.",fix:e?"Run mist_doctor without reportOnly to auto-restore it.":"Cannot restore: API unreachable. Fix connectivity first."};let c=Tn(e.methodology,o);return mt(n,c),mt(a,c),{name:"AGENTS.md",status:"fix",message:`Restored from methodology v${l}.`}}if(t&&!_e(a)){let c=It(n,"utf-8");mt(a,c)}if(l&&i&&l!==i){if(!t||!e?.methodology)return{name:"AGENTS.md",status:"warn",message:`Methodology v${i} installed, v${l} available.`,fix:"Run mist_doctor to update it."};let c=Tn(e.methodology,o);mt(n,c),mt(a,c);try{let u=Te(s,"mistflow.json"),m=JSON.parse(It(u,"utf-8"));m.methodologyVersion=l,mt(u,JSON.stringify(m,null,2)+`
|
|
5097
|
-
|
|
5098
|
-
|
|
5095
|
+
"build me something like ${i.share_url}"`}))}catch(i){let l=i instanceof Error?i.message:"Failed to share project";return d(l,!0)}}case"landing-designs":{if(s.presetId){let r=st(s.presetId);if(!r)return d(`Preset '${s.presetId}' not found. Use mist_project action='presets' without presetId to list all available presets.`,!0);let i=Io(s.presetId);return d(JSON.stringify({preset:{id:r.id,title:r.title,category:r.category,description:i?.description??"",style:i?.style??"",theme:i?.theme??"dark",colors:i?.colors??[],tags:i?.tags??[],promptLength:r.prompt.length},message:`Landing design "${r.title}" (${r.category}) \u2014 ${i?.description??""}. To use it, pass landingDesign="${r.id}" when calling mist_plan.`}))}let t=Eo(s.category??void 0),n=hs(s.category),a=Ro(n);return d(JSON.stringify({count:t.length,presets:t.map(r=>({id:r.id,title:r.title,category:r.category,description:r.description,style:r.style,theme:r.theme,colors:r.colors})),formatted:a,message:`${t.length} landing designs available.${s.category?` Filtered by: ${s.category}.`:""} To use one, pass landingDesign="<id>" when calling mist_plan. The design blueprint will be injected during the landing page implementation step. Browse them at ${bt()}/designs?tab=landing-designs.`}))}case"integrations":{if(s.integrationId){let r=rt(s.integrationId);if(!r)return d(`Integration '${s.integrationId}' not found. Use mist_project action='integrations' without integrationId to list all available integrations.`,!0);let i=nt(r.id);return d(JSON.stringify({integration:{id:r.id,name:r.name,category:r.category,description:i?.description??"",packages:i?.packages??[],envVars:i?.envVars??[],docsUrl:i?.docsUrl??"",difficulty:i?.difficulty??"medium"},message:`Integration "${r.name}" (${r.category}) \u2014 ${i?.description??""}. This blueprint is auto-injected during implementation when your plan has a matching integration step. Required env vars: ${i?.envVars?.map(l=>l.key).join(", ")||"none"}. Docs: ${i?.docsUrl??"n/a"}.`}))}let t=Do(s.category??void 0),n=fs(s.category??void 0),a=_o(n);return d(JSON.stringify({count:t.length,integrations:t.map(r=>({id:r.id,name:r.name,category:r.category,description:r.description,packages:r.packages,difficulty:r.difficulty,envVars:r.envVars.map(i=>i.key)})),formatted:a,message:`${t.length} integration blueprints available.${s.category?` Filtered by: ${s.category}.`:""} Integration blueprints are auto-injected during implementation when your plan includes a matching integration step. Use integrationId to see full details including env vars and setup URLs.`}))}case"errors":{let t=ts(s.projectPath??process.cwd()),n=rs(t,"mistflow.json");if(!ss(n))return Ne(t);let a;try{a=JSON.parse(os(n,"utf-8"))}catch{return d("Could not read mistflow.json.",!0)}let r=a.projectId;if(!r)return d("No project ID found. Deploy the project first.",!0);try{let i=await uo(r,s.period??"7d");return i.total===0?d(JSON.stringify({total:0,period:i.period,message:`No runtime errors in the last ${i.period}. The app is running clean.`})):d(JSON.stringify({total:i.total,period:i.period,errors:i.errors,message:`${i.total} runtime error(s) in the last ${i.period}. Review the errors above and use mist_build debug to investigate.`}))}catch(i){let l=i instanceof Error?i.message:"Failed to fetch errors";return d(l,!0)}}case"logs":{let t=ts(s.projectPath??process.cwd()),n=rs(t,"mistflow.json");if(!ss(n))return Ne(t);let a;try{a=JSON.parse(os(n,"utf-8"))}catch{return d("Could not read mistflow.json.",!0)}let r=a.projectId;if(!r)return d("No project ID found. Deploy the project first.",!0);let i=s.deploymentId;if(!i)try{let l=await wt(r);if(l.length===0)return d("No deployments found for this project.",!0);i=l[0].id}catch(l){let c=l instanceof Error?l.message:"Failed to fetch deployments";return d(c,!0)}try{let[l,c]=await Promise.all([po(i),Oe(i)]),u=l.filter(p=>p.level==="error"),m=l.filter(p=>p.level==="warn");return d(JSON.stringify({deploymentId:i,status:c.status,errorMessage:c.error??null,totalLogs:l.length,errorCount:u.length,warnCount:m.length,logs:l.map(p=>({time:p.timestamp,level:p.level,phase:p.phase,message:p.message})),message:c.status==="failed"?`Deployment failed. ${u.length} error(s) found in logs. Review the logs above to diagnose the issue.`:`Deployment status: ${c.status}. ${l.length} log entries (${u.length} errors, ${m.length} warnings).`}))}catch(l){let c=l instanceof Error?l.message:"Failed to fetch deploy logs";return d(c,!0)}}case"deployments":{let t=ts(s.projectPath??process.cwd()),n=rs(t,"mistflow.json");if(!ss(n))return Ne(t);let a;try{a=JSON.parse(os(n,"utf-8"))}catch{return d("Could not read mistflow.json.",!0)}let r=a.projectId;if(!r)return d("No project ID found. Deploy the project first.",!0);try{let i=await wt(r);return d(JSON.stringify({total:i.length,deployments:i.map(l=>({id:l.id,status:l.status,errorMessage:l.error_message,durationSeconds:l.duration_seconds,isRollback:!!l.rollback_from_id,createdAt:l.created_at})),message:`${i.length} deployment(s) found. Use mist_project action='logs' deploymentId='<id>' to see detailed logs for any deployment.`}))}catch(i){let l=i instanceof Error?i.message:"Failed to fetch deployments";return d(l,!0)}}case"version":{yt().backendSignalReceived||await Ks();let t=yt(),n=t.severity==="none",a={none:"up to date",patch:"patch update available",minor:"minor update available",major:"major update available",unsupported:"UNSUPPORTED \u2014 upgrade required"};return d(JSON.stringify({current:t.current,latest:t.latest||"unknown",minSupported:t.minSupported||"unknown",severity:t.severity,upToDate:n,upgradeCmd:t.upgradeCmd,changelogUrl:t.changelogUrl,backendSignalReceived:t.backendSignalReceived,message:t.backendSignalReceived?`Mistflow MCP ${t.current} (${a[t.severity]??t.severity}). Latest: ${t.latest}.${n?"":` Run \`${t.upgradeCmd}\` and restart your editor to upgrade.`}`:`Mistflow MCP ${t.current}. The backend hasn't replied yet \u2014 make one other API call (e.g. mist_project action='get') then retry to see the latest version.`}))}default:return d(`Unknown action: ${s.action}. Use get, update, share, landing-designs, integrations, errors, logs, deployments, or version.`,!0)}}};import{z as _e}from"zod";import{z as Ge}from"zod";import{resolve as Xl}from"path";var vm=Ge.object({projectPath:Ge.string().optional().describe("Path to the project directory (default: cwd)"),action:Ge.enum(["set","list","delete"]).describe("Action to perform"),key:Ge.string().optional().describe("Environment variable name (required for 'set' and 'delete')"),value:Ge.string().optional().describe("Environment variable value (required for 'set')"),category:Ge.string().optional().describe("Category for the env var (default: 'custom')"),description:Ge.string().optional().describe("Description of what this env var is for"),setupUrl:Ge.string().optional().describe("URL where the user can obtain this value (e.g. Stripe dashboard)")});async function wn(o){let{projectPath:s,action:e,key:t,value:n,category:a,description:r,setupUrl:i}=o,l=Xl(s??process.cwd());if(!ye())return d("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let u=Ee(l)?.projectId;if(!u)return d("No project ID found. Deploy your project first with mist_deploy, or initialize with mist_plan + mist_build.",!0);try{switch(e){case"set":return t?n?(await lo(u,t,n,{category:a,description:r,setupUrl:i}),d(JSON.stringify({set:!0,key:t,message:`Environment variable '${t}' has been set. It will be available on your next deployment.`}))):d("Value is required. Provide the env var value.",!0):d("Key is required. Provide the env var name like 'STRIPE_SECRET_KEY'.",!0);case"list":{let m=await ao(u);return m.length===0?d(JSON.stringify({envVars:[],message:"No environment variables configured. Use action 'set' to add one."})):d(JSON.stringify({envVars:m.map(p=>({key:p.key,category:p.category,description:p.description,hasValue:p.has_value})),message:`${m.length} environment variable(s) configured.`}))}case"delete":return t?(await co(u,t),d(JSON.stringify({deleted:!0,key:t,message:`Environment variable '${t}' has been removed.`}))):d("Key is required. Provide the env var name to delete.",!0);default:return d(`Unknown action: ${e}. Use set, list, or delete.`,!0)}}catch(m){if(m instanceof Se)return d(m.message,!0);let p=m instanceof Error?m.message:"An unexpected error occurred";return d(p,!0)}}import{z as It}from"zod";import{resolve as Zl,join as ec}from"path";import{existsSync as tc,readFileSync as sc,writeFileSync as oc}from"fs";var Im=It.object({projectPath:It.string().optional().describe("Path to the project directory (default: cwd)"),action:It.enum(["add","list","verify","remove"]).describe("Action to perform"),domain:It.string().optional().describe("Domain name (required for 'add' and 'remove')"),domainId:It.string().optional().describe("Domain ID (required for 'verify' and 'remove')")});function qs(o,s){let e=ec(o,"mistflow.json");if(!tc(e))return;let t;try{t=JSON.parse(sc(e,"utf-8"))}catch{return}t.domains=s,oc(e,JSON.stringify(t,null,2)+`
|
|
5096
|
+
`)}async function vn(o){let{projectPath:s,action:e,domain:t,domainId:n}=o,a=Zl(s??process.cwd());if(!ye())return d("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let i=Ee(a)?.projectId;if(!i)return d("No project ID found. Deploy your project first with mist_deploy, or initialize with mist_plan + mist_build.",!0);try{switch(e){case"add":{if(!t)return d("Domain name is required. Provide the domain like 'myapp.com' or 'app.mycompany.com'.",!0);let l=await so(i,t),c=await Ke(i);return qs(a,c.map(u=>({domain:u.domain,status:u.status}))),d(JSON.stringify({added:!0,domain:l.domain,status:l.status,instructions:l.instructions,message:`Domain '${l.domain}' added. Set up DNS records as described, then use action 'verify' to check status.`}))}case"list":{let l=await Ke(i);return l.length===0?d(JSON.stringify({domains:[],message:"No custom domains configured. Use action 'add' to add one."})):d(JSON.stringify({domains:l.map(c=>({id:c.id,domain:c.domain,status:c.status,ssl:c.ssl_status,error:c.error_message}))}))}case"verify":{if(!n){if(t){let m=(await Ke(i)).find(p=>p.domain===t);if(m){let p=await cs(i,m.id);return d(JSON.stringify({domain:p.domain,status:p.status,ssl:p.ssl_status,error:p.error_message,message:p.status==="active"?`Domain '${p.domain}' is active and serving traffic.`:`Domain '${p.domain}' is ${p.status}. Make sure DNS records are configured correctly.`}))}return d(`Domain '${t}' not found. Use action 'list' to see configured domains.`,!0)}return d("Provide either domainId or domain name to verify.",!0)}let l=await cs(i,n),c=await Ke(i);return qs(a,c.map(u=>({domain:u.domain,status:u.status}))),d(JSON.stringify({domain:l.domain,status:l.status,ssl:l.ssl_status,error:l.error_message,message:l.status==="active"?`Domain '${l.domain}' is active and serving traffic.`:`Domain '${l.domain}' is ${l.status}. Make sure DNS records are configured correctly.`}))}case"remove":{if(!n&&!t)return d("Provide either domainId or domain name to remove.",!0);let l=n;if(!l&&t){let m=(await Ke(i)).find(p=>p.domain===t);if(!m)return d(`Domain '${t}' not found.`,!0);l=m.id}await oo(i,l);let c=await Ke(i);return qs(a,c.map(u=>({domain:u.domain,status:u.status}))),d(JSON.stringify({removed:!0,message:"Domain removed. It may take a few minutes for DNS changes to propagate."}))}default:return d(`Unknown action: ${e}. Use add, list, verify, or remove.`,!0)}}catch(l){if(l instanceof Se)return d(l.message,!0);let c=l instanceof Error?l.message:"An unexpected error occurred";return d(c,!0)}}var rc=_e.object({resource:_e.enum(["env","domain"]).describe("'env' manages app secrets and configuration values. 'domain' manages custom domains."),action:_e.string().describe("Action to perform. env: 'set', 'list', 'delete'. domain: 'add', 'list', 'verify', 'remove'."),projectPath:_e.string().optional().describe("Path to the project directory (default: cwd)"),key:_e.string().optional().describe("(env) Variable name"),value:_e.string().optional().describe("(env set) Variable value"),category:_e.string().optional().describe("(env set) Category"),description:_e.string().optional().describe("(env set) Description"),setupUrl:_e.string().optional().describe("(env set) URL to obtain the value"),domain:_e.string().optional().describe("(domain) Domain name"),domainId:_e.string().optional().describe("(domain) Domain ID")}),kn={name:"mist_config",description:"Manage project configuration: app secrets and custom domains. Set resource='env' to manage encrypted app secrets (set, list, delete). Set resource='domain' to manage custom domains (add, list, verify, remove). Use when the user says 'mist env' or 'mist domain'.",inputSchema:rc,handler:async o=>{let s=o;switch(s.resource){case"env":return wn({projectPath:s.projectPath,action:s.action,key:s.key,value:s.value,category:s.category,description:s.description,setupUrl:s.setupUrl});case"domain":return vn({projectPath:s.projectPath,action:s.action,domain:s.domain,domainId:s.domainId});default:return d(`Unknown resource: ${s.resource}. Use env or domain.`,!0)}}};import{z as et}from"zod";var nc=et.object({action:et.enum(["navigate","go_back","go_forward","click","type","fill","select_option","press_key","hover","screenshot","snapshot"]).describe("Action to perform. Navigation: navigate|go_back|go_forward. Interaction: click|type|fill|select_option|press_key|hover. Visual: screenshot (returns image) | snapshot (returns accessibility tree)."),url:et.string().optional().describe("URL to navigate to. Required for 'navigate'; optional for 'screenshot' (navigates before capturing)."),selector:et.string().optional().describe("CSS selector of the target element. Required for: click, type, fill, select_option, hover. Optional for screenshot (captures just that element)."),value:et.string().optional().describe("Text to type/fill, option to select, or key to press (e.g. 'Enter', 'Tab'). Required for: type, fill, select_option, press_key."),fullPage:et.boolean().default(!1).describe("For 'screenshot': capture the full scrollable page instead of just the viewport."),includeScreenshot:et.boolean().default(!1).describe("For navigate/interact actions: also return a screenshot alongside the accessibility snapshot.")}),xn={name:"mist_browser",description:"Unified browser tool for navigating, interacting with, and capturing the app. Use 'navigate' to open a URL, interaction actions (click/type/fill/etc.) to test flows, 'snapshot' to inspect the accessibility tree, and 'screenshot' for a visual capture. Use after mist_preview to verify UI, test flows, and iterate on design.",inputSchema:nc,handler:async o=>{let s=o,e=await Nt();if(s.action==="navigate"){if(!s.url)return d("URL is required for 'navigate'.",!0);let a=[],r=c=>{c.type()==="error"&&a.push(c.text())};e.on("console",r),await e.goto(s.url,{waitUntil:"domcontentloaded",timeout:3e4}),await e.waitForLoadState("networkidle").catch(()=>{});let i=[],l=c=>i.push(c.message);if(e.on("pageerror",l),await e.waitForTimeout(500),e.removeListener("console",r),e.removeListener("pageerror",l),a.length>0||i.length>0){let c=await _t(e),u=[{type:"text",text:JSON.stringify({url:e.url(),title:await e.title(),snapshot:c,consoleErrors:a,pageErrors:i,hasErrors:!0})}];if(s.includeScreenshot){let m=await Le(e);u.push({type:"image",data:m.toString("base64"),mimeType:"image/png"})}return{content:u}}}else if(s.action==="go_back")await e.goBack({waitUntil:"domcontentloaded",timeout:1e4});else if(s.action==="go_forward")await e.goForward({waitUntil:"domcontentloaded",timeout:1e4});else if(s.action==="click"){if(!s.selector)return d("Selector is required for 'click'.",!0);await e.click(s.selector,{timeout:1e4}),await e.waitForLoadState("domcontentloaded").catch(()=>{}),await e.waitForTimeout(500)}else if(s.action==="type"){if(!s.selector)return d("Selector is required for 'type'.",!0);if(!s.value)return d("Value is required for 'type'.",!0);await e.type(s.selector,s.value,{delay:50})}else if(s.action==="fill"){if(!s.selector)return d("Selector is required for 'fill'.",!0);if(!s.value)return d("Value is required for 'fill'.",!0);await e.fill(s.selector,s.value)}else if(s.action==="select_option"){if(!s.selector)return d("Selector is required for 'select_option'.",!0);if(!s.value)return d("Value is required for 'select_option'.",!0);await e.selectOption(s.selector,s.value)}else if(s.action==="hover"){if(!s.selector)return d("Selector is required for 'hover'.",!0);await e.hover(s.selector,{timeout:1e4})}else if(s.action==="press_key"){if(!s.value)return d("Value is required for 'press_key' (e.g. 'Enter').",!0);await e.keyboard.press(s.value),await e.waitForLoadState("domcontentloaded").catch(()=>{}),await e.waitForTimeout(500)}else if(s.action==="screenshot"){s.url&&(await e.goto(s.url,{waitUntil:"domcontentloaded",timeout:3e4}),await e.waitForLoadState("networkidle").catch(()=>{}));let a;if(s.selector){let r=await e.$(s.selector);if(!r)return d(`Element not found: ${s.selector}`,!0);a=await r.screenshot({type:"png"})}else a=await Le(e,s.fullPage);return{content:[{type:"text",text:JSON.stringify({url:e.url(),title:await e.title(),message:`Screenshot captured (${s.fullPage?"full page":"viewport"})`})},{type:"image",data:a.toString("base64"),mimeType:"image/png"}]}}else if(s.action==="snapshot"){let a=await _t(e);return{content:[{type:"text",text:JSON.stringify({url:e.url(),title:await e.title(),snapshot:a})}]}}let t=await _t(e),n=[{type:"text",text:JSON.stringify({url:e.url(),title:await e.title(),snapshot:t})}];if(s.includeScreenshot){let a=await Le(e);n.push({type:"image",data:a.toString("base64"),mimeType:"image/png"})}return{content:n}}};import{existsSync as Ae,readFileSync as gt,readdirSync as ac,writeFileSync as ht}from"fs";import{join as ke}from"path";import{z as Rt}from"zod";function ic(o){let s=[],e=0,t=o.length,n=!1,a=!1,r=!1;for(;e<t;){let i=o[e],l=o[e+1];if(a){i===`
|
|
5097
|
+
`&&(a=!1,s.push(i)),e++;continue}if(r){i==="*"&&l==="/"?(r=!1,e+=2):e++;continue}if(n){if(s.push(i),i==="\\"&&l!==void 0){s.push(l),e+=2;continue}i===n&&(n=!1),e++;continue}if(i==="/"&&l==="/"){a=!0,e+=2;continue}if(i==="/"&&l==="*"){r=!0,e+=2;continue}if(i==='"'||i==="'"||i==="`"){n=i,s.push(i),e++;continue}s.push(i),e++}return s.join("")}function Sn(o){if(!o||typeof o!="string")return[];let s;try{s=ic(o)}catch{return[]}let e=/export\s+const\s+(\w+)\s*=\s*(?:pg|sqlite|mysql)Table\s*\(\s*(["'])([^"'`]+)\2/g,t=[],n=new Set,a;for(;(a=e.exec(s))!==null;){let r=a[1],i=a[3]??r;n.has(r)||(n.add(r),t.push({varName:r,tableName:i}))}return t}function Tn(o){let s=ke(o,"mistflow.json");if(!Ae(s))return{result:{name:"Project",status:"fail",message:"No mistflow.json found. This is not a Mistflow project.",fix:"Run mist_plan to design your app, then mist_build init to scaffold it."},config:null};let e;try{e=JSON.parse(gt(s,"utf-8"))}catch{return{result:{name:"Project",status:"fail",message:"mistflow.json exists but contains invalid JSON.",fix:"Check mistflow.json for syntax errors. If corrupted beyond repair, delete it and re-run mist_build init."},config:null}}if(!e.name||typeof e.name!="string")return{result:{name:"Project",status:"warn",message:"mistflow.json is missing the 'name' field."},config:e};let t=e.projectId,n=t?`, id: ${t}`:", no projectId";return{result:{name:"Project",status:"pass",message:`${e.name}${n}`},config:e}}async function lc(){let o=Ws();if(!o.ok)return{result:{name:"Auth",status:"fail",message:o.reason==="missing"?"No credentials found.":"Credentials file is malformed.",fix:"Run mist_setup to log in."},creds:null,authValid:!1};try{let s=Ys(),e=await fetch(`${Ye()}/api/org`,{headers:s,signal:AbortSignal.timeout(1e4)});try{Hs(e.headers)}catch{}if(!e.ok)return e.status===401?{result:{name:"Auth",status:"fail",message:"API key is invalid or revoked.",fix:"Run mist_setup to re-authenticate."},creds:o.creds,authValid:!1}:{result:{name:"Auth",status:"warn",message:`Server returned ${e.status}. Credentials may still be valid.`},creds:o.creds,authValid:!1};let t=await e.json(),n=t.slug??o.creds.orgSlug??"unknown",a=t.plan?`, plan: ${t.plan}`:"";return{result:{name:"Auth",status:"pass",message:`org: ${n}${a}`},creds:o.creds,authValid:!0}}catch(s){return s instanceof Se?{result:{name:"Auth",status:"fail",message:`Auth check failed: ${s.message}`,fix:"Run mist_setup to re-authenticate."},creds:o.creds,authValid:!1}:{result:{name:"Auth",status:"warn",message:"Could not reach API to validate credentials. Network issue?"},creds:o.creds,authValid:!1}}}async function cc(){let o=Date.now();try{let s=await Mt("nextjs"),e=Date.now()-o;return{result:{name:"API",status:"pass",message:`${Ye()} reachable (${e}ms)`},scaffold:s}}catch(s){let e=Date.now()-o;return{result:{name:"API",status:"fail",message:s instanceof Se?s.message:`Timeout or network error after ${e}ms`,fix:"Check your network connection. If using --api-url, verify the backend is running."},scaffold:null}}}function dc(){let o=yt();if(!o.backendSignalReceived)return{name:"MCP version",status:"warn",message:`v${o.current} installed, but no backend signal received to compare against.`};let s={none:"up to date",patch:"patch update available",minor:"minor update available",major:"major update available",unsupported:"no longer supported"};return o.severity==="none"?{name:"MCP version",status:"pass",message:`v${o.current} (latest)`}:o.severity==="unsupported"?{name:"MCP version",status:"fail",message:`v${o.current} is ${s[o.severity]}. Minimum: v${o.minSupported}.`,fix:`Run \`${o.upgradeCmd}\` then restart your editor.`}:{name:"MCP version",status:"warn",message:`v${o.current} installed, v${o.latest} available (${s[o.severity]}).`,fix:`Run \`${o.upgradeCmd}\` then restart your editor.`}}function pc(o,s,e,t){let n=ke(o,"AGENTS.md"),a=ke(o,"CLAUDE.md"),r=Ae(n),i=s.methodologyVersion??"",l=e?.version??"";if(!r){if(!t||!e?.methodology)return{name:"AGENTS.md",status:"fail",message:"Missing. The host AI has no methodology context for this project.",fix:e?"Run mist_doctor without reportOnly to auto-restore it.":"Cannot restore: API unreachable. Fix connectivity first."};let c=Cn(e.methodology,s);return ht(n,c),ht(a,c),{name:"AGENTS.md",status:"fix",message:`Restored from methodology v${l}.`}}if(t&&!Ae(a)){let c=gt(n,"utf-8");ht(a,c)}if(l&&i&&l!==i){if(!t||!e?.methodology)return{name:"AGENTS.md",status:"warn",message:`Methodology v${i} installed, v${l} available.`,fix:"Run mist_doctor to update it."};let c=Cn(e.methodology,s);ht(n,c),ht(a,c);try{let u=ke(o,"mistflow.json"),m=JSON.parse(gt(u,"utf-8"));m.methodologyVersion=l,ht(u,JSON.stringify(m,null,2)+`
|
|
5098
|
+
`)}catch{}return{name:"AGENTS.md",status:"fix",message:`Updated methodology v${i} -> v${l}.`}}return{name:"AGENTS.md",status:"pass",message:i?`v${i}`:"present"}}async function uc(o,s,e,t){let n=s.projectId;if(!n)return{name:"State sync",status:"skip",message:"No projectId. State sync not applicable without a linked project."};if(!e)return{name:"State sync",status:"skip",message:"Skipped (not authenticated)."};let a=So(o),r=await To(n);if(!a&&!r)return{name:"State sync",status:"warn",message:"No local or remote state found."};if(!a&&r){if(t){let{writeLocalState:i}=await import("./state-manager-GBP2NSYC.js");return i(o,r),{name:"State sync",status:"fix",message:"Local state was missing. Restored from remote."}}return{name:"State sync",status:"warn",message:"Local .mistflow/state.json is missing but remote state exists.",fix:"Run mist_doctor to restore it from the server."}}return a&&!r?{name:"State sync",status:"warn",message:"Local state exists but no remote state found. Remote sync may have failed."}:a&&a.projectId!==n?{name:"State sync",status:"warn",message:`state.json projectId (${a.projectId}) doesn't match mistflow.json projectId (${n}).`}:{name:"State sync",status:"pass",message:`deployCount: ${a.deployCount}, features: ${a.features.length}`}}function mc(o){let s=[],e=[];if(Ae(ke(o,"package.json"))?Ae(ke(o,"node_modules"))||s.push("node_modules not installed (run `npx -y @mistflow-ai/cli install`)"):s.push("missing package.json"),!Ae(ke(o,".env.local")))s.push("missing .env.local");else try{gt(ke(o,".env.local"),"utf-8").match(/^AUTH_SECRET=(.+)$/m)||s.push("AUTH_SECRET not set in .env.local")}catch{s.push(".env.local exists but is not readable")}let t=ke(o,"app","api","auth","[...all]","route.ts");Ae(t)||e.push("missing app/api/auth/[...all]/route.ts");let n=ke(o,"app","api","health","route.ts");return Ae(n)||e.push("missing app/api/health/route.ts (needed for deploy verification)"),s.length>0?{name:"Structure",status:"fail",message:s.join("; "),fix:s.map(a=>a.includes("node_modules")?"Run `npx -y @mistflow-ai/cli install` in the project directory (streams output, no MCP 60s timeout). Plain `npm install` also works.":a.includes(".env.local")?"Create .env.local with AUTH_SECRET=<random-secret>.":a.includes("AUTH_SECRET")?"Add AUTH_SECRET=<random-secret> to .env.local.":a.includes("package.json")?"This project is missing package.json. Was it scaffolded correctly?":"").filter(Boolean).join(" ")}:e.length>0?{name:"Structure",status:"warn",message:e.join("; ")}:{name:"Structure",status:"pass",message:"all required files present"}}function hc(o,s){let e=s.env;if(!e?.required||typeof e.required!="object"||Object.keys(e.required).length===0)return{name:"Env vars",status:"pass",message:"no required env vars declared"};let t=[],n="";for(let a of[".env.local",".env"]){let r=ke(o,a);try{Ae(r)&&(n+=`
|
|
5099
|
+
`+gt(r,"utf-8"))}catch{}}for(let[a,r]of Object.entries(e.required)){let i=n.includes(`${a}=`),l=!!process.env[a];if(!i&&!l){let c=r?.description?` (${r.description})`:"";t.push(`${a}${c}`)}}return t.length>0?{name:"Env vars",status:"warn",message:`${t.length} required but not set: ${t.join(", ")}`,fix:"Set them via mist_config or add to .env.local."}:{name:"Env vars",status:"pass",message:`${Object.keys(e.required).length} required, all set`}}function gc(o){let s=o.plan;if(!s?.steps||s.steps.length===0)return{name:"Plan",status:"skip",message:"No plan found in mistflow.json."};let e=s.steps.length,t=s.steps.filter(r=>r.status==="completed").length,n=s.steps.filter(r=>r.status==="in_progress").length,a=e-t-n;if(t===e)return{name:"Plan",status:"pass",message:`${t}/${e} steps completed`};if(n>0){let r=s.steps.find(i=>i.status==="in_progress");return{name:"Plan",status:"warn",message:`${t}/${e} completed, step ${r?.number} "${r?.name}" in progress`,fix:"Run mist_build implement to continue."}}return t===0?{name:"Plan",status:"warn",message:`${e} steps planned, none started.`,fix:"Run mist_build implement to start building."}:{name:"Plan",status:"warn",message:`${t}/${e} completed, ${a} remaining.`,fix:"Run mist_build implement to continue."}}function fc(o,s){let e=ke(o,"contracts");if(!Ae(e))return{name:"Contracts",status:"skip",message:"No contracts/ directory. Scaffolded before integration contracts landed, or template app."};let t=s.plan,n=[];for(let g of t?.dataModel??[]){let h=g.entity??g.name;h&&typeof h=="string"&&n.push(h)}let a=ke(o,"db","schema.ts"),r=[];if(Ae(a))try{let g=gt(a,"utf-8"),h=Sn(g);for(let v of h)r.push(v.varName)}catch{}let i=new Map;for(let g of r)i.set(at(g),g);for(let g of n){let h=at(g);i.has(h)||i.set(h,g)}if(i.size===0)return{name:"Contracts",status:"pass",message:"contracts/ present, no entities in plan"};let l=new Set(n.map(g=>at(g))),c=new Set(r.map(g=>at(g))),u=[],m=[];for(let[g,h]of i){let v=ke(e,`${g}.ts`);Ae(v)||u.push(h),c.has(g)&&!l.has(g)&&m.push(h)}let p=[];try{p=ac(e).filter(h=>h.endsWith(".ts")).map(h=>h.slice(0,-3)).filter(h=>!i.has(h))}catch{}let f=[];if(u.length>0&&f.push(`missing contract for ${u.length} entit${u.length===1?"y":"ies"}: ${u.join(", ")}`),p.length>0&&f.push(`orphan contract file${p.length===1?"":"s"} not in schema or plan: ${p.join(", ")}`),m.length>0&&f.push(`schema entit${m.length===1?"y":"ies"} missing from plan: ${m.join(", ")}`),u.length>0||p.length>0){let g=[];return u.length>0&&g.push("Create contracts/<entity>.ts for each missing entity. Every route and server action should import its types from contracts/, never inline them."),p.length>0&&g.push("Delete or rename the orphan contract file(s) \u2014 they don't match any table in db/schema.ts or entity in the plan."),{name:"Contracts",status:"warn",message:f.join("; "),fix:g.join(" ")}}return m.length>0?{name:"Contracts",status:"pass",message:`${i.size} entit${i.size===1?"y has":"ies have"} contracts; ${f[f.length-1]}`}:{name:"Contracts",status:"pass",message:`${i.size} entit${i.size===1?"y has":"ies have"} contracts`}}function Cn(o,s){let e=s.dbProvider;return e==="neon"||!e?o.replace(/sqliteTable/g,"pgTable").replace(/drizzle-orm\/sqlite-core/g,"drizzle-orm/pg-core").replace(/Use `text` for dates \(SQLite stores dates as text\)/g,"Use `timestamp` for dates and `boolean` for booleans (native Postgres types)").replace(/text\("created_at"\)\.notNull\(\)\.default\(sql`\(CURRENT_TIMESTAMP\)`\)/g,'timestamp("created_at").notNull().defaultNow()').replace(/text\("updated_at"\)\.notNull\(\)\.default\(sql`\(CURRENT_TIMESTAMP\)`\)/g,'timestamp("updated_at").notNull().defaultNow()').replace(/import { sqliteTable, text, integer } from "drizzle-orm\/sqlite-core";\nimport { sql } from "drizzle-orm";/g,'import { pgTable, text, timestamp, boolean } from "drizzle-orm/pg-core";').replace(/`drizzle-kit push` for SQLite\/Turso/g,"`drizzle-kit push` for Postgres"):o}function yc(o){let s={pass:"PASS",warn:"WARN",fail:"FAIL",fix:"FIXED",skip:"SKIP"},e=Math.max(...o.map(u=>u.name.length)),t=o.map(u=>{let m=".".repeat(e-u.name.length+4),p=s[u.status].padEnd(5);return` ${u.name} ${m} ${p} ${u.message}`}),n=o.filter(u=>u.status==="fix").length,a=o.filter(u=>u.status==="fail").length,r=o.filter(u=>u.status==="warn").length,i=[];n>0&&i.push(`${n} fixed`),a>0&&i.push(`${a} failure${a>1?"s":""}`),r>0&&i.push(`${r} warning${r>1?"s":""}`);let l=`mist_doctor results:
|
|
5099
5100
|
|
|
5100
5101
|
`+t.join(`
|
|
5101
5102
|
`);i.length>0?l+=`
|
|
5102
5103
|
|
|
5103
5104
|
${i.join(", ")}`:l+=`
|
|
5104
5105
|
|
|
5105
|
-
All checks passed.`;let c=
|
|
5106
|
+
All checks passed.`;let c=o.filter(u=>(u.status==="fail"||u.status==="warn")&&u.fix);if(c.length>0){l+=`
|
|
5106
5107
|
|
|
5107
5108
|
To fix:`;for(let u of c)l+=`
|
|
5108
|
-
- ${u.fix}`}return l}var
|
|
5109
|
+
- ${u.fix}`}return l}var Pn=Rt.object({projectPath:Rt.string().optional().describe("Path to the project directory. Defaults to the current working directory."),checks:Rt.array(Rt.enum(["project","auth","api","version","methodology","state","structure","env","plan","contracts"])).optional().describe("Run only specific checks. Omit to run all."),reportOnly:Rt.boolean().optional().describe("If true, report issues without auto-fixing them.")}),An={name:"mist_doctor",description:"Diagnose project health: checks auth, API connectivity, AGENTS.md methodology, project state, version alignment, structure, and integration contracts. Auto-fixes safe issues (missing AGENTS.md, stale state). Run when something feels off.",inputSchema:Pn,handler:async o=>{let s=Pn.parse(o),e=s.projectPath||process.cwd(),t=!s.reportOnly,n=!s.checks,a=s.checks??[],r=g=>n||a.includes(g),i=[],l=null;if(r("project")){let g=Tn(e);i.push(g.result),l=g.config}else l=Tn(e).config;let c=!1;if(r("auth")||r("state")){let g=await lc();r("auth")&&i.push(g.result),c=g.authValid}let m=null;if(r("api")||r("methodology")){let g=await cc();r("api")&&i.push(g.result),m=g.scaffold}r("version")&&i.push(dc()),l?(r("methodology")&&i.push(pc(e,l,m,t)),r("state")&&i.push(await uc(e,l,c,t)),r("structure")&&i.push(mc(e)),r("env")&&i.push(hc(e,l)),r("plan")&&i.push(gc(l)),r("contracts")&&i.push(fc(e,l))):n&&(i.push({name:"AGENTS.md",status:"skip",message:"Skipped (not a Mistflow project)."}),i.push({name:"State sync",status:"skip",message:"Skipped (not a Mistflow project)."}),i.push({name:"Structure",status:"skip",message:"Skipped (not a Mistflow project)."}),i.push({name:"Env vars",status:"skip",message:"Skipped (not a Mistflow project)."}),i.push({name:"Plan",status:"skip",message:"Skipped (not a Mistflow project)."}),i.push({name:"Contracts",status:"skip",message:"Skipped (not a Mistflow project)."}));let f=yc(i),w=i.some(g=>g.status==="fail");return d(f,w)}};import{z as In}from"zod";var Rn=`# Mistflow CLI reference
|
|
5109
5110
|
|
|
5110
5111
|
The Mistflow CLI handles local execution and long-running operations that
|
|
5111
5112
|
would hit the MCP 60s tool-call ceiling. Every command below is invokable
|
|
@@ -5187,48 +5188,6 @@ and decides the next command. Example end-to-end chain:
|
|
|
5187
5188
|
echo '{...}' | mist plan --cid ... --pick-stdin --json
|
|
5188
5189
|
# \u2192 {"status":"ready","plan":{...}}
|
|
5189
5190
|
# Then: mist_build init (MCP), mist install (CLI), mist_build implement (MCP), etc.
|
|
5190
|
-
`,
|
|
5191
|
-
`),t=new RegExp(`^### \`mist ${
|
|
5192
|
-
`).trim())}};var
|
|
5193
|
-
|
|
5194
|
-
Call \`mist_help\` at any point for the full CLI command reference. Prefer the CLI for long-running local or LLM-backed operations; MCP tools work for interactive, short, structured flows.
|
|
5195
|
-
|
|
5196
|
-
New app workflow:
|
|
5197
|
-
1. Plan: PREFER \`mist plan --describe "<user's description>" --json\` via your shell/bash tool. The mist_plan MCP tool hits -32001 timeout on slow Sonnet calls; the CLI has no ceiling. Pass the user's description EXACTLY as written. Relay any returned questions to the user, then submit answers via \`echo '<answers-json>' | mist plan --token <id> --answers-stdin --json\`. When status becomes "design_clarify_pending", poll with \`mist plan-directions --cid <id> --wait --json\`. Present the directions picker, then finalize with \`echo '<pick-json>' | mist plan --cid <id> --pick-stdin --json\`. If the tool returns status "confirm_new_project" from the MCP fallback path, ask the user whether to scaffold a new Mistflow app or edit the existing code.
|
|
5198
|
-
2. mist_build mockup (optional) - generates a visual HTML wireframe for user preview. Iterative: pass feedback to refine, approved=true to lock in the design.
|
|
5199
|
-
3. mist_build init - scaffolds the project from the plan and initializes git. Pass the planId from the plan response. Returns in ~10s; does NOT run npm install.
|
|
5200
|
-
4. Install dependencies: run \`npx -y @mistflow-ai/cli install <projectPath>\` via your shell/bash tool (streams output, no 60s MCP timeout). Fall back to mist_build action='install' only if your environment can't shell out.
|
|
5201
|
-
5. mist_build implement - executes plan steps one at a time. Call repeatedly until all steps are done. It auto-marks the previous step as completed on each call.
|
|
5202
|
-
6. mist_deploy - deploys to a live URL at <app-name>.mistflow.app. If staging mode is enabled, auto-deploys to a preview URL first (isolated database, expires in 72h). After QA passes, call mist_deploy promote to go live. Use mist_deploy preview for a local production server on localhost:3000.
|
|
5203
|
-
7. mist_build qa - tests the LIVE deployed app. Call AFTER deploy. Do NOT show the URL to the user until QA passes. If issues found, fix and redeploy, then qa again.
|
|
5204
|
-
|
|
5205
|
-
Companion CLI (\`@mistflow-ai/cli\`, invoke as \`mist\` or via \`npx -y @mistflow-ai/cli\`):
|
|
5206
|
-
- \`mist plan\` / \`mist plan-directions\` \u2014 plan an app without the MCP 60s ceiling. PREFERRED over mist_plan.
|
|
5207
|
-
- \`mist install <path>\` \u2014 npm install with live stdout, no 60s MCP timeout. PREFERRED over mist_build install.
|
|
5208
|
-
- \`mist login\`, \`mist deploy\`, \`mist status\`, \`mist logs\`, \`mist projects\`, \`mist env\`, \`mist domains\`, \`mist rollback\` \u2014 shell-friendly mirrors of MCP actions. Use CLI for CI/scripted flows; use MCP tools (mist_deploy, mist_config, etc.) for interactive AI-driven flows.
|
|
5209
|
-
- Call mist_help for the full reference.
|
|
5210
|
-
|
|
5211
|
-
IMPORTANT \u2014 chaining discipline: once the user approves the plan, the init \u2192 install \u2192 implement (repeat) \u2192 build \u2192 deploy \u2192 qa chain is expected. Do NOT pause between these calls to ask the user "should I continue?" or offer options like "full build vs step-by-step." The tool itself will return a status requiring user input when it actually needs one (e.g. confirm_new_project, confirm_dark_theme, awaiting promotion). Otherwise, chain calls continuously. Brief one-line status updates ("Starting step 3 of 7: Google Maps") are fine and encouraged; permission requests are not. Idea is for them to get the mist deployed url without needing to understand or manage the complexity behind it.
|
|
5212
|
-
|
|
5213
|
-
Design presets (optional, between steps 1 and 3):
|
|
5214
|
-
- mist_project landing-designs: browse 27+ curated landing page hero designs. Pass an ID to mist_plan or mist_build init as landingDesign.
|
|
5215
|
-
- mist_project app-styles: browse 54 full-app design systems (Stripe, Linear, Vercel, etc.). Pass an ID as appStyle for consistent styling across ALL pages.
|
|
5216
|
-
- After mist_plan generates a plan, it may recommend designs and styles. Present these to the user before calling mist_build init.
|
|
5217
|
-
|
|
5218
|
-
Updating an existing Mistflow app:
|
|
5219
|
-
- Cosmetic or single-file changes: edit files directly, then mist_deploy to publish.
|
|
5220
|
-
- New page or feature (no new data model): mist_project get for context, build it, then mist_deploy.
|
|
5221
|
-
- Feature needing new data model or integration: mist_plan with existingPlanId, then mist_build implement, then mist_deploy.
|
|
5222
|
-
- Bug fix: mist_build debug to analyze, fix the code, then mist_deploy.
|
|
5223
|
-
- mist_deploy works for both initial deploys AND updates. Always deploy after changes to publish them.
|
|
5224
|
-
|
|
5225
|
-
Template forking:
|
|
5226
|
-
- Users can share apps as templates via mist_project share, which returns a shareable URL.
|
|
5227
|
-
- To fork a template, call mist_plan with templateToken. Optionally pass remixDescription to customize it.
|
|
5228
|
-
|
|
5229
|
-
Other tools:
|
|
5230
|
-
- mist_setup: authentication. Only call when user has never signed in or a tool returned 'auth_missing'/'auth_revoked'. Do NOT call for 500s, 404s, or network errors. Also accepts an apiKey parameter for headless auth.
|
|
5231
|
-
- mist_project: read/update project state, browse landing designs and app styles, view runtime errors, deploy logs, deployment history, and check MCP version.
|
|
5232
|
-
- mist_config: manage encrypted app secrets (env vars) and custom domains.
|
|
5233
|
-
- mist_browser: navigate, interact with, and screenshot the app during preview or after deploy.
|
|
5234
|
-
- mist_doctor: diagnose project health. Checks auth, API connectivity, AGENTS.md methodology, MCP version, project state, structure, and env vars. Auto-fixes safe issues (missing/outdated AGENTS.md, missing local state). Run when something feels off or tools behave unexpectedly.`}),En=[As,zs,Or,hn,bn,kn,xn,Pn,Rn];ro.setRequestHandler(bc,async()=>({tools:En.map(s=>({name:s.name,description:s.description,inputSchema:wc(s.inputSchema)}))}));ro.setRequestHandler(yc,async s=>{let o=En.find(e=>e.name===s.params.name);if(!o)return d(`Unknown tool: ${s.params.name}`,!0);try{let e=o.inputSchema.safeParse(s.params.arguments);if(!e.success){let a=e.error.issues.map(r=>`${r.path.join(".")}: ${r.message}`).join(", ");return d(`Invalid input: ${a}`,!0)}let t=s.params._meta?.progressToken,n={server:ro,progressToken:t};try{return await o.handler(e.data,n)}finally{n.cleanup?.()}}catch(e){let t=e instanceof Error?e.message:"An unexpected error occurred";return console.error("Tool error:",e),d(t,!0)}});async function vc(){let s=process.argv.indexOf("--api-url");s!==-1&&process.argv[s+1]&&(process.env.MISTFLOW_API_URL=process.argv[s+1]),process.argv.includes("--local")&&!process.env.MISTFLOW_API_URL&&(process.env.MISTFLOW_API_URL="http://localhost:9100");let o=new fc;await ro.connect(o),console.error(`Mistflow MCP server running on stdio (API: ${process.env.MISTFLOW_API_URL||"https://api.mistflow.ai"})`)}vc().catch(s=>{console.error("Fatal error:",s),process.exit(1)});
|
|
5191
|
+
`,En={name:"mist_help",description:"Returns the Mistflow CLI command reference. Call this ONCE at session start (or whenever you're unsure which tool to use) to learn every `mist` CLI command, when to prefer it over an MCP tool, and how to chain calls. Results are static \u2014 no backend round-trip, safe to call frequently.",inputSchema:In.object({command:In.string().optional().describe("Optional: name of a specific command to get focused reference for. Omit to get the full catalog.")}),handler:async o=>{let{command:s}=o;if(!s)return d(Rn);let e=Rn.split(`
|
|
5192
|
+
`),t=new RegExp(`^### \`mist ${s}`),n=-1,a=e.length;for(let r=0;r<e.length;r++)if(t.test(e[r]))n=r;else if(n>=0&&e[r].startsWith("### ")){a=r;break}else if(n>=0&&e[r].startsWith("## ")&&r>n){a=r;break}return n<0?d(`No command named '${s}' found. Call mist_help with no args to see the full catalog.`,!0):d(e.slice(n,a).join(`
|
|
5193
|
+
`).trim())}};var ns=new bc({name:"mistflow",version:"0.3.0"},{capabilities:{tools:{}},instructions:"Mistflow is a full-stack app builder that creates and deploys web apps from natural language descriptions. When a user asks to build, create, or make a web app, website, landing page, dashboard, internal tool, marketplace, content site, or browser game, use Mistflow tools. Mistflow creates NEW apps from scratch. It does NOT modify existing non-Mistflow codebases.\n\nCall `mist_help` at any point for the full CLI command reference. Prefer the CLI for long-running local or LLM-backed operations; MCP tools work for interactive, short, structured flows.\n\nNew app workflow:\n1. Plan: PREFER `mist plan --describe \"<user's description>\" --json` via your shell/bash tool. The mist_plan MCP tool hits -32001 timeout on slow Sonnet calls; the CLI has no ceiling. Pass the user's description EXACTLY as written. Relay any returned questions to the user, then submit answers via `echo '<answers-json>' | mist plan --token <id> --answers-stdin --json`. When status becomes \"design_clarify_pending\", poll with `mist plan-directions --cid <id> --wait --json`. Present the directions picker, then finalize with `echo '<pick-json>' | mist plan --cid <id> --pick-stdin --json`. If the tool returns status \"confirm_new_project\" from the MCP fallback path, ask the user whether to scaffold a new Mistflow app or edit the existing code.\n2. Mockup (optional): PREFER `mist mockup --plan-id <id>` via your shell/bash tool \u2014 generates a visual HTML wireframe for user preview with streaming output and no MCP timeout. Iterative: pass --feedback to refine, --approved to lock in the design. Fall back to mist_build action='mockup' only if your environment can't shell out.\n3. mist_build init - scaffolds the project from the plan and initializes git. Pass the planId from the plan response. Returns in ~10s; does NOT run npm install. (MCP stays primary here \u2014 init is fast and structured.)\n4. Install dependencies: PREFER `npx -y @mistflow-ai/cli install <projectPath>` via your shell/bash tool (streams output, no 60s MCP timeout). Fall back to mist_build action='install' only if your environment can't shell out.\n5. Implement: PREFER `mist implement --project-path <path>` via your shell/bash tool \u2014 executes plan steps one at a time with live streaming output. Call repeatedly until all steps are done; it auto-marks the previous step as completed on each call. Fall back to mist_build action='implement' only if your environment can't shell out.\n6. mist_deploy - deploys to a live URL at <app-name>.mistflow.app. If staging mode is enabled, auto-deploys to a preview URL first (isolated database, expires in 72h). After QA passes, call mist_deploy promote to go live. Use mist_deploy preview for a local production server on localhost:3000.\n7. QA: PREFER `mist qa --project-path <path>` via your shell/bash tool \u2014 tests the LIVE deployed app with streaming output and no MCP timeout. Call AFTER deploy. Do NOT show the URL to the user until QA passes. If issues found, fix and redeploy, then qa again. Fall back to mist_build action='qa' only if your environment can't shell out.\n\nCompanion CLI (`@mistflow-ai/cli`, invoke as `mist` or via `npx -y @mistflow-ai/cli`):\n- `mist plan` / `mist plan-directions` \u2014 plan an app without the MCP 60s ceiling. PREFERRED over mist_plan.\n- `mist install <path>` \u2014 npm install with live stdout, no 60s MCP timeout. PREFERRED over mist_build install.\n- `mist mockup`, `mist implement`, `mist build`, `mist debug`, `mist qa` \u2014 PREFERRED over the corresponding mist_build actions. Stream output live and have no MCP timeout ceiling.\n- `mist login`, `mist deploy`, `mist status`, `mist logs`, `mist projects`, `mist env`, `mist domains`, `mist rollback` \u2014 shell-friendly mirrors of MCP actions. Use CLI for CI/scripted flows; use MCP tools (mist_deploy, mist_config, etc.) for interactive AI-driven flows.\n- Call mist_help for the full reference.\n\nIMPORTANT \u2014 chaining discipline: once the user approves the plan, the init \u2192 install \u2192 implement (repeat) \u2192 build \u2192 deploy \u2192 qa chain is expected. Do NOT pause between these calls to ask the user \"should I continue?\" or offer options like \"full build vs step-by-step.\" The tool itself will return a status requiring user input when it actually needs one (e.g. confirm_new_project, confirm_dark_theme, awaiting promotion). Otherwise, chain calls continuously. Brief one-line status updates (\"Starting step 3 of 7: Google Maps\") are fine and encouraged; permission requests are not. Idea is for them to get the mist deployed url without needing to understand or manage the complexity behind it.\n\nDesign presets (optional, between steps 1 and 3):\n- mist_project landing-designs: browse 27+ curated landing page hero designs. Pass an ID to mist_plan or mist_build init as landingDesign.\n- mist_project app-styles: browse 54 full-app design systems (Stripe, Linear, Vercel, etc.). Pass an ID as appStyle for consistent styling across ALL pages.\n- After mist_plan generates a plan, it may recommend designs and styles. Present these to the user before calling mist_build init.\n\nUpdating an existing Mistflow app:\n- Cosmetic or single-file changes: edit files directly, then mist_deploy to publish.\n- New page or feature (no new data model): mist_project get for context, build it, then mist_deploy.\n- Feature needing new data model or integration: mist_plan with existingPlanId, then mist_build implement, then mist_deploy.\n- Bug fix: PREFER `mist debug --project-path <path>` via your shell/bash tool to analyze (fall back to mist_build debug only if you can't shell out), fix the code, then mist_deploy.\n- mist_deploy works for both initial deploys AND updates. Always deploy after changes to publish them.\n\nTemplate forking:\n- Users can share apps as templates via mist_project share, which returns a shareable URL.\n- To fork a template, call mist_plan with templateToken. Optionally pass remixDescription to customize it.\n\nOther tools:\n- mist_setup: authentication. Only call when user has never signed in or a tool returned 'auth_missing'/'auth_revoked'. Do NOT call for 500s, 404s, or network errors. Also accepts an apiKey parameter for headless auth.\n- mist_project: read/update project state, browse landing designs and app styles, view runtime errors, deploy logs, deployment history, and check MCP version.\n- mist_config: manage encrypted app secrets (env vars) and custom domains.\n- mist_browser: navigate, interact with, and screenshot the app during preview or after deploy.\n- mist_doctor: diagnose project health. Checks auth, API connectivity, AGENTS.md methodology, MCP version, project state, structure, and env vars. Auto-fixes safe issues (missing/outdated AGENTS.md, missing local state). Run when something feels off or tools behave unexpectedly."}),Nn=[Ao,zo,Or,hn,bn,kn,xn,An,En];ns.setRequestHandler(kc,async()=>({tools:Nn.map(o=>({name:o.name,description:o.description,inputSchema:xc(o.inputSchema)}))}));ns.setRequestHandler(vc,async o=>{let s=Nn.find(e=>e.name===o.params.name);if(!s)return d(`Unknown tool: ${o.params.name}`,!0);try{let e=s.inputSchema.safeParse(o.params.arguments);if(!e.success){let a=e.error.issues.map(r=>`${r.path.join(".")}: ${r.message}`).join(", ");return d(`Invalid input: ${a}`,!0)}let t=o.params._meta?.progressToken,n={server:ns,progressToken:t};try{return await s.handler(e.data,n)}finally{n.cleanup?.()}}catch(e){let t=e instanceof Error?e.message:"An unexpected error occurred";return console.error("Tool error:",e),d(t,!0)}});async function Sc(){let o=process.argv.indexOf("--api-url");o!==-1&&process.argv[o+1]&&(process.env.MISTFLOW_API_URL=process.argv[o+1]),process.argv.includes("--local")&&!process.env.MISTFLOW_API_URL&&(process.env.MISTFLOW_API_URL="http://localhost:9100");let s=new wc;await ns.connect(s),console.error(`Mistflow MCP server running on stdio (API: ${process.env.MISTFLOW_API_URL||"https://api.mistflow.ai"})`)}Sc().catch(o=>{console.error("Fatal error:",o),process.exit(1)});
|