@mistflow-ai/mcp 0.1.6 → 0.1.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 +60 -60
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as Ct,d as Tt,e as Fe}from"./chunk-ANYHR4WA.js";import{b as gr,c as ia,d as na,e as mr}from"./chunk-6ISXH6NJ.js";import{A as Ka,B as qe,C as oa,D as Ya,E as Ja,F as Qa,G as Xa,H as Za,I as er,J as tr,K as ar,L as rr,M as pt,N as or,O as ir,P as nr,Q as sr,R as Dt,S as lr,T as dr,U as cr,V as pr,W as ur,Y as hr,b as Oa,c as Ga,d as St,e as Wa,f as aa,g as Pt,h as ce,i as De,j as Ve,k as Ae,l as _a,m as
|
|
1
|
+
import{a as Ct,d as Tt,e as Fe}from"./chunk-ANYHR4WA.js";import{b as gr,c as ia,d as na,e as mr}from"./chunk-6ISXH6NJ.js";import{A as Ka,B as qe,C as oa,D as Ya,E as Ja,F as Qa,G as Xa,H as Za,I as er,J as tr,K as ar,L as rr,M as pt,N as or,O as ir,P as nr,Q as sr,R as Dt,S as lr,T as dr,U as cr,V as pr,W as ur,Y as hr,b as Oa,c as Ga,d as St,e as Wa,f as aa,g as Pt,h as ce,i as De,j as Ve,k as Ae,l as _a,m as he,n as ja,r as za,s as $a,t as Bt,v as Va,w as Ue,x as qa,y as ra}from"./chunk-FKB6Y7BA.js";import{Server as Wl}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as _l}from"@modelcontextprotocol/sdk/server/stdio.js";import{CallToolRequestSchema as jl,ListToolsRequestSchema as zl}from"@modelcontextprotocol/sdk/types.js";import{zodToJsonSchema as $l}from"zod-to-json-schema";function p(r,e=!1){let t=r;try{let a=Ga();a&&(t=r+a)}catch{}return{content:[{type:"text",text:t}],isError:e}}function Te(r){return p(`This is not a Mistflow project (no mistflow.json found at ${r}).
|
|
2
2
|
|
|
3
3
|
Mistflow creates new projects from scratch \u2014 it doesn't work inside existing codebases.
|
|
4
4
|
|
|
@@ -10,7 +10,7 @@ To get started:
|
|
|
10
10
|
If you want to deploy an existing project, use your framework's deploy tools directly.`,!0)}async function Ee(r,e){try{let{getPage:t,takeScreenshot:a}=await import("./browser-manager-K5BT5YXO.js"),i=await t();await i.goto(r,{waitUntil:"domcontentloaded",timeout:15e3}),await i.waitForLoadState("networkidle").catch(()=>{});let n=await a(i,!1);return{content:[{type:"text",text:e},{type:"image",data:n.toString("base64"),mimeType:"image/png"}]}}catch{return p(e)}}import{z as sa}from"zod";import{platform as bi}from"os";import{execFile as fr}from"child_process";var yi=sa.object({apiKey:sa.string().optional().describe("API key (mist_...) for headless auth. Skips the device code flow entirely. Generate one at app.mistflow.ai/mcp-keys."),deviceCode:sa.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 xi(r){return"error"in r}function wi(r){return new Promise(e=>setTimeout(e,r))}function vi(r){return new Promise(e=>{let t=bi();t==="win32"?fr("cmd.exe",["/c","start","",r],a=>{a&&console.error("Could not open browser:",a.message),e(!a)}):fr(t==="darwin"?"open":"xdg-open",[r],i=>{i&&console.error("Could not open browser:",i.message),e(!i)}),setTimeout(()=>e(!1),5e3)})}var ki={fetch:globalThis.fetch,openBrowser:vi};async function br(r,e,t,a){let i=t;for(let n=0;n<e;n++){await wi(i);let o;try{let l=await a.fetch(`${Ve()}/auth/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:r})});if(!l.ok)continue;o=await l.json()}catch{continue}if(xi(o))switch(o.error){case"authorization_pending":continue;case"slow_down":i+=5e3;continue;case"expired_token":return p("The sign-in link expired. Run mist_setup again to get a new code.",!0);case"access_denied":return p("Sign-in was cancelled. Run mist_setup again to try again.",!0);case"already_exchanged":return p("This sign-in link was already used. Run mist_setup again to get a new code.",!0)}let s=o.email||o.org_name||o.org_slug;return aa({apiKey:o.api_key,apiKeyId:o.api_key_id,apiKeyName:o.api_key_name,orgId:o.org_id,orgSlug:o.org_slug,email:o.email}),p(`Connected to Mistflow as ${s}. You are ready to build and deploy.`)}return null}async function Si(r,e=ki){let t=r;if(t?.apiKey)try{let o=await e.fetch(`${Ve()}/api/org`,{headers:{Authorization:`ApiKey ${t.apiKey}`}});if(!o.ok)return p("Invalid API key. Check the key and try again.",!0);let s=await o.json();return aa({apiKey:t.apiKey,orgId:s.id,orgSlug:s.slug}),p(`Connected to Mistflow as ${s.slug} via API key. You are ready to build and deploy.`)}catch{return p("Cannot reach Mistflow servers. Check your internet connection.",!0)}if(t?.deviceCode){let o=await br(t.deviceCode,6,5e3,e);return o||p(JSON.stringify({status:"pending",deviceCode:t.deviceCode,instruction:"The user hasn't approved yet. Wait ~15 seconds and call mist_setup again with the same deviceCode."}))}let a;try{let o=await e.fetch(`${Ve()}/auth/device`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!o.ok)return p("Cannot reach Mistflow servers. Check your internet connection.",!0);a=await o.json()}catch{return p("Cannot reach Mistflow servers. Check your internet connection.",!0)}let i=`${a.verification_uri}?code=${a.user_code}`;console.error(`
|
|
11
11
|
Sign in at: ${i}
|
|
12
12
|
Your code: ${a.user_code}
|
|
13
|
-
`);try{await e.openBrowser(i)}catch{}let n=await br(a.device_code,6,5e3,e);return n||p(JSON.stringify({status:"pending",deviceCode:a.device_code,signInUrl:i,userCode:a.user_code,instruction:"The user hasn't approved yet. Wait ~15 seconds, then call mist_setup again with deviceCode='"+a.device_code+"' to check if they approved."}))}var yr={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:yi,handler:r=>Si(r)};import{z as te}from"zod";import{existsSync as ht,mkdirSync as ma,readFileSync as Lr,readdirSync as Di,statSync as Ai,unlinkSync as Ii,writeFileSync as fa}from"fs";import{dirname as Mi,isAbsolute as Ri,join as
|
|
13
|
+
`);try{await e.openBrowser(i)}catch{}let n=await br(a.device_code,6,5e3,e);return n||p(JSON.stringify({status:"pending",deviceCode:a.device_code,signInUrl:i,userCode:a.user_code,instruction:"The user hasn't approved yet. Wait ~15 seconds, then call mist_setup again with deviceCode='"+a.device_code+"' to check if they approved."}))}var yr={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:yi,handler:r=>Si(r)};import{z as te}from"zod";import{existsSync as ht,mkdirSync as ma,readFileSync as Lr,readdirSync as Di,statSync as Ai,unlinkSync as Ii,writeFileSync as fa}from"fs";import{dirname as Mi,isAbsolute as Ri,join as be}from"path";import{homedir as He}from"os";import{createHash as Li,createHmac as Nr,randomBytes as Ni,randomUUID as Rr,timingSafeEqual as Fi}from"crypto";var la={},Ze=[];function et(r){let e=Ze.find(a=>a.id===r);if(e)return e;let t=r.toLowerCase().replace(/[^a-z0-9]/g,"");return Ze.find(a=>{let i=a.title.toLowerCase().replace(/[^a-z0-9]/g,"");return i===t||i.includes(t)||t.includes(i)})}function xr(r){return la[r]}function da(r){return r?Ze.filter(e=>e.category.toLowerCase()===r.toLowerCase()):Ze}function wr(r){let e=r??Ze;if(e.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 t={};for(let i of e){t[i.category]||(t[i.category]=[]);let n=la[i.id],o=n?` \u2014 ${n.description}`:"";t[i.category].push(`${i.id} \u2014 "${i.title}"${o}`)}let a=[];for(let[i,n]of Object.entries(t))a.push(`**${i}**:
|
|
14
14
|
${n.map(o=>` \u2022 ${o}`).join(`
|
|
15
15
|
`)}`);return a.join(`
|
|
16
16
|
|
|
@@ -8794,8 +8794,8 @@ What makes Uber's design truly distinctive is its use of full-bleed photography
|
|
|
8794
8794
|
5. For shadows, use "whisper shadow (rgba(0,0,0,0.12) 0px 4px 16px)" -- never heavy drop shadows
|
|
8795
8795
|
6. Keep layouts compact and information-dense -- Uber is efficient, not airy
|
|
8796
8796
|
7. Illustrations should be warm and human -- describe "stylized people in warm tones" not abstract shapes
|
|
8797
|
-
8. Pair black CTAs with white secondaries for balanced dual-action layouts`}]}],ca={cohere:{description:"Cohere's interface is a polished enterprise command deck \u2014 confident, clean, and designed to make AI feel like serious infrastructure rather than a consumer toy. The experience lives on a bright wh...",category:"AI & Machine Learning",theme:"light",colors:["#000000","#212121","#17171c","#1863dc","#4c6ee6","#9b60aa"],fonts:{heading:"CohereText",body:"Unica77 Cohere Web"},tags:["light","ai-machine-learning","minimal","bold","enterprise","gradient"]},elevenlabs:{description:"ElevenLabs' website is a study in restrained elegance \u2014 a near-white canvas (`#ffffff`, `#f5f5f5`) where typography and subtle shadows do all the heavy lifting. The design feels like a premium audi...",category:"AI & Machine Learning",theme:"light",colors:["#ffffff","#f5f5f5","#f5f2ef","#000000","#4e4e4e","#777169"],fonts:{heading:"Waldenburg",body:"Inter"},tags:["light","ai-machine-learning","minimal","bold"]},minimax:{description:"MiniMax's website is a clean, product-showcase platform for a Chinese AI technology company that bridges consumer-friendly appeal with technical credibility. The design language is predominantly wh...",category:"AI & Machine Learning",theme:"light",colors:["#1456f0","#3daeff","#ea5ec1","#bfdbfe","#60a5fa","#3b82f6"],fonts:{heading:"DM Sans",body:"DM Sans"},tags:["light","ai-machine-learning","minimal","bold","playful","gradient"]},mistral:{description:"Mistral AI's interface is a sun-drenched landscape rendered in code \u2014 a warm, bold, unapologetically European design that trades the typical blue-screen AI aesthetic for golden amber, burnt orange,...",category:"AI & Machine Learning",theme:"light",colors:["#fa520f","#fb6424","#ff8105","#ff8a00","#ffa110","#ffb83e"],fonts:{heading:"Arial",body:"Inter"},tags:["light","ai-machine-learning","minimal","bold","elegant","gradient"]},ollama:{description:"Ollama's interface is radical minimalism taken to its logical conclusion \u2014 a pure-white void where content floats without decoration, shadow, or color. The design philosophy mirrors the product its...",category:"AI & Machine Learning",theme:"light",colors:["#000000","#262626","#090909","#ffffff","#fafafa","#e5e5e5"],fonts:{heading:"SF Pro Rounded",body:"ui-sans-serif"},tags:["light","ai-machine-learning","minimal","playful"]},opencode:{description:"OpenCode's website embodies a terminal-native, monospace-first aesthetic that reflects its identity as an open source AI coding agent. The entire visual system is built on a stark dark-on-light con...",category:"AI & Machine Learning",theme:"light",colors:["#201d1d","#fdfcfc","#9a9898","#302c2c","#646262","#f1eeee"],fonts:{heading:"Inter",body:"16px (1.00rem)"},tags:["light","ai-machine-learning","minimal","bold"]},replicate:{description:"Replicate's interface is a developer playground crackling with creative energy \u2014 a bold, high-contrast design that feels more like a music festival poster than a typical API platform. The hero sect...",category:"AI & Machine Learning",theme:"dark",colors:["#202020","#ea2804","#dd4425","#2b9a66","#24292e","#ffffff"],fonts:{heading:"rb-freigeist-neue",body:"basier-square"},tags:["dark","ai-machine-learning","minimal","bold","playful","gradient"]},runwayml:{description:"Runway's interface is a cinematic reel brought to life as a website \u2014 a dark, editorial, film-production-grade design where full-bleed photography and video ARE the primary UI elements. This is not...",category:"AI & Machine Learning",theme:"dark",colors:["#000000","#030303","#1a1a1a","#ffffff","#fefefe","#e9ecf2"],fonts:{heading:"Inter",body:"Inter"},tags:["dark","ai-machine-learning","minimal","bold"]},together:{description:"Together AI's interface is a pastel-gradient dreamscape built for enterprise AI infrastructure \u2014 a design that somehow makes GPU clusters and model inference feel light, airy, and optimistic. The h...",category:"AI & Machine Learning",theme:"light",colors:["#ef2cc1","#fc4c02","#010120","#bdbbff","#ffffff","#000000"],fonts:{heading:"The Future",body:"Inter"},tags:["light","ai-machine-learning","minimal","playful","enterprise","modern","elegant","data-dense","gradient"]},voltagent:{description:"VoltAgent's interface is a deep-space command terminal for the AI age \u2014 a developer-facing darkness built on near-pure-black surfaces (`#050507`) where the only interruption is the electric pulse o...",category:"AI & Machine Learning",theme:"dark",colors:["#00d992","#2fd6a1","#10b981","#818cf8","#306cce","#2554a0"],fonts:{heading:"system-ui",body:"Inter"},tags:["dark","ai-machine-learning","playful","data-dense"]},x:{description:"xAI's website is a masterclass in dark-first, monospace-driven brutalist minimalism -- a design system that feels like it was built by engineers who understand that restraint is the ultimate form o...",category:"AI & Machine Learning",theme:"dark",colors:["#ffffff","#1f2228","#000000"],fonts:{heading:"GeistMono",body:"universalSans"},tags:["dark","ai-machine-learning","minimal","elegant","data-dense","gradient"]},cursor:{description:"Cursor's website is a study in warm minimalism meets code-editor elegance. The entire experience is built on a warm off-white canvas (`#f2f1ed`) with dark warm-brown text (`#26251e`) -- not pure bl...",category:"Developer Tools",theme:"light",colors:["#26251e","#f2f1ed","#e6e5e0","#ffffff","#000000","#f54e00"],fonts:{heading:"CursorGothic",body:"jjannon"},tags:["light","developer-tools","minimal"]},expo:{description:"Expo's interface is a luminous, confidence-radiating developer platform built on the premise that tools for building apps should feel as polished as the apps themselves. The entire experience lives...",category:"Developer Tools",theme:"dark",colors:["#000000","#1c2024","#0d74ce","#476cff","#47c2ff","#8145b5"],fonts:{heading:"Inter",body:"Inter"},tags:["dark","developer-tools","playful"]},linear:{description:"Linear's website is a masterclass in dark-mode-first product design \u2014 a near-black canvas (`#08090a`) where content emerges from darkness like starlight. The overall impression is one of extreme pr...",category:"Developer Tools",theme:"dark",colors:["#010102","#08090a","#0f1011","#191a1b","#28282c","#f7f8f8"],fonts:{heading:"Inter Variable",body:"Inter Variable"},tags:["dark","developer-tools","minimal","bold"]},lovable:{description:"Lovable's website radiates warmth through restraint. The entire page sits on a creamy, parchment-toned background (`#f7f4ed`) that immediately separates it from the cold-white conventions of most d...",category:"Developer Tools",theme:"light",colors:["#f7f4ed","#1c1c1c","#fcfbf8","#5f5f5d","#eceae4","#3b82f6"],fonts:{heading:"Camera Plain Variable",body:"Camera Plain Variable"},tags:["light","developer-tools","minimal"]},mintlify:{description:"Mintlify's website is a study in documentation-as-product design \u2014 a white, airy, information-rich surface that treats clarity as its highest aesthetic value. The page opens with a luminous white (...",category:"Developer Tools",theme:"light",colors:["#0d0d0d","#ffffff","#18e299","#d4fae8","#0fa76e","#c37d0d"],fonts:{heading:"Inter",body:"Inter"},tags:["light","developer-tools","minimal","bold","gradient"]},posthog:{description:"PostHog's website feels like a startup's internal wiki that escaped into the wild \u2014 warm, irreverent, and deliberately anti-corporate. The background isn't the expected crisp white or dark void of ...",category:"Developer Tools",theme:"light",colors:["#4d4f46","#23251d","#f54e00","#f7a501","#b17816","#3b82f6"],fonts:{heading:"IBM Plex Sans Variable",body:"IBM Plex Sans Variable"},tags:["light","developer-tools","bold","playful","modern","gradient"]},raycast:{description:"Raycast's marketing site feels like the dark interior of a precision instrument \u2014 a Swiss watch case carved from obsidian. The background isn't just dark, it's an almost-black blue-tint (`#07080a`)...",category:"Developer Tools",theme:"dark",colors:["#07080a","#ffffff","#ff6363","#55b3ff","#5fc992","#ffbc33"],fonts:{heading:"Inter",body:"16px"},tags:["dark","developer-tools","minimal","data-dense","gradient"]},resend:{description:"Resend's website is a dark, cinematic canvas that treats email infrastructure like a luxury product. The entire page is draped in pure black (`#000000`) with text that glows in near-white (`#f0f0f0...",category:"Developer Tools",theme:"dark",colors:["#000000","#f0f0f0","#ffffff","#ff5900","#ff801f","#ffa057"],fonts:{heading:"domaine",body:"inter"},tags:["dark","developer-tools","minimal","elegant"]},sentry:{description:"Sentry's website is a dark-mode-first developer tool interface that speaks the language of code editors and terminal windows. The entire aesthetic is rooted in deep purple-black backgrounds (`#1f16...",category:"Developer Tools",theme:"dark",colors:["#1f1633","#150f23","#362d59","#6a5fc1","#79628c","#422082"],fonts:{heading:"Dammit Sans",body:"Rubik"},tags:["dark","developer-tools","bold"]},supabase:{description:"Supabase's website is a dark-mode-native developer platform that channels the aesthetic of a premium code editor \u2014 deep black backgrounds (`#0f0f0f`, `#171717`) with emerald green accents (`#3ecf8e...",category:"Developer Tools",theme:"dark",colors:["#3ecf8e","#00c573","#0f0f0f","#171717","#242424","#2e2e2e"],fonts:{heading:"DM Sans",body:"DM Sans"},tags:["dark","developer-tools","minimal","data-dense"]},superhuman:{description:"Superhuman's website feels like opening a luxury envelope \u2014 predominantly white, immaculately clean, with a single dramatic gesture of color that commands attention. The hero section is a cinematic...",category:"Developer Tools",theme:"light",colors:["#1b1938","#cbb7fb","#292827","#714cb6","#ffffff","#e9e5dd"],fonts:{heading:"Super Sans VF",body:"Super Sans VF"},tags:["light","developer-tools","minimal","bold","elegant","data-dense","gradient"]},vercel:{description:"Vercel's website is the visual thesis of developer infrastructure made invisible \u2014 a design system so restrained it borders on philosophical. The page is overwhelmingly white (`#ffffff`) with near-...",category:"Developer Tools",theme:"light",colors:["#171717","#ffffff","#000000","#ff5b4f","#de1d8d","#0a72ef"],fonts:{heading:"Geist",body:"Geist"},tags:["light","developer-tools","minimal"]},warp:{description:"Warp's website feels like sitting at a campfire in a deep forest \u2014 warm, dark, and alive with quiet confidence. Unlike the cold, blue-tinted blacks favored by most developer tools, Warp wraps every...",category:"Developer Tools",theme:"light",colors:["#faf9f6","#353534","#868584","#afaeac","#666469","#454545"],fonts:{heading:"Matter Regular",body:"Matter Regular"},tags:["light","developer-tools","minimal","bold"]},zapier:{description:"Zapier's website radiates warm, approachable professionalism. It rejects the cold monochrome minimalism of developer tools in favor of a cream-tinted canvas (`#fffefb`) that feels like unbleached p...",category:"Developer Tools",theme:"light",colors:["#201515","#fffefb","#fffdf9","#ff4f00","#36342e","#939084"],fonts:{heading:"Degular Display",body:"Inter"},tags:["light","developer-tools","minimal","bold","enterprise","modern","elegant"]},clickhouse:{description:`ClickHouse's interface is a high-performance cockpit rendered in acid yellow-green on obsidian black \u2014 a design that screams "speed" before you read a single word. The entire experience lives in da...`,category:"Infrastructure",theme:"dark",colors:["#faff69","#166534","#14572f","#f4f692","#4f5100","#161600"],fonts:{heading:"Inter",body:"Basier"},tags:["dark","infrastructure"]},composio:{description:"Composio's interface is a nocturnal command center \u2014 a dense, developer-focused darkness punctuated by electric cyan and deep cobalt signals. The entire experience is built on an almost-pure-black ...",category:"Infrastructure",theme:"dark",colors:["#0007cd","#00ffff","#0089ff","#0096ff","#0f0f0f","#000000"],fonts:{heading:"abcDiatype",body:"Inter"},tags:["dark","infrastructure","minimal","data-dense","gradient"]},hashicorp:{description:"HashiCorp's website is enterprise infrastructure made tangible \u2014 a design system that must communicate the complexity of cloud infrastructure management while remaining approachable. The visual lan...",category:"Infrastructure",theme:"dark",colors:["#000000","#15181e","#0d0e12","#f1f2f3","#d5d7db","#b2b6bd"],fonts:{heading:"__hashicorpSans_96f0ca",body:"system-ui"},tags:["dark","infrastructure","minimal","bold","enterprise","data-dense"]},mongodb:{description:"MongoDB's website is a deep-forest-meets-terminal experience \u2014 a design system rooted in the darkest teal-black (`#001e2b`) that evokes both the density of a database and the depth of a forest cano...",category:"Infrastructure",theme:"dark",colors:["#001e2b","#00ed64","#00684a","#006cfa","#3860be","#1eaedb"],fonts:{heading:"MongoDB Value Serif",body:"Euclid Circular A"},tags:["dark","infrastructure","bold","enterprise"]},sanity:{description:"Sanity's website is a developer-content platform rendered as a nocturnal command center -- dark, precise, and deeply structured. The entire experience sits on a near-black canvas (`#0b0b0b`) that r...",category:"Infrastructure",theme:"dark",colors:["#0b0b0b","#000000","#f36458","#0052ef","#55beff","#afe3ff"],fonts:{heading:"waldenburgNormal",body:"waldenburgNormal"},tags:["dark","infrastructure","playful"]},stripe:{description:"Stripe's website is the gold standard of fintech design -- a system that manages to feel simultaneously technical and luxurious, precise and warm. The page opens on a clean white canvas (`#ffffff`)...",category:"Infrastructure",theme:"light",colors:["#533afd","#061b31","#ffffff","#1c1e54","#0d253d","#ea2261"],fonts:{heading:"Inter",body:"Inter"},tags:["light","infrastructure","minimal","bold","enterprise","modern","data-dense","gradient"]},airtable:{description:'Airtable\'s website is a clean, enterprise-friendly platform that communicates "sophisticated simplicity" through a white canvas with deep navy text (`#181d26`) and Airtable Blue (`#1b61c9`) as the ...',category:"Design & Productivity",theme:"light",colors:["#181d26","#1b61c9","#ffffff","#006400","#333333","#254fad"],fonts:{heading:"Haas",body:"Haas"},tags:["light","design-productivity","minimal","playful","enterprise"]},cal:{description:"Cal.com's website is a masterclass in monochromatic restraint \u2014 a grayscale world where boldness comes not from color but from the sheer confidence of black text on white space. Inspired by Uber's ...",category:"Design & Productivity",theme:"light",colors:["#242424","#111111","#ffffff","#0099ff","#3b82f6","#0000ee"],fonts:{heading:"Cal Sans",body:"Inter"},tags:["light","design-productivity","minimal","bold","modern","data-dense"]},clay:{description:"Clay's website is a warm, playful celebration of color that treats B2B data enrichment like a craft rather than an enterprise chore. The design language is built on a foundation of warm cream backg...",category:"Design & Productivity",theme:"light",colors:["#000000","#ffffff","#faf9f7","#84e7a5","#078a52","#02492a"],fonts:{heading:"DM Sans",body:"DM Sans"},tags:["light","design-productivity","playful","enterprise"]},figma:{description:"Figma's interface is the design tool that designed itself \u2014 a masterclass in typographic sophistication where a custom variable font (figmaSans) modulates between razor-thin (weight 320) and bold (...",category:"Design & Productivity",theme:"light",colors:["#000000","#ffffff"],fonts:{heading:"figmaSans",body:"Inter"},tags:["light","design-productivity","bold","gradient"]},framer:{description:"Framer's website is a cinematic, tool-obsessed dark canvas that radiates the confidence of a design tool built by designers who worship craft. The entire experience is drenched in pure black \u2014 not ...",category:"Design & Productivity",theme:"dark",colors:["#000000","#ffffff","#0099ff","#a6a6a6","#090909","#0000ee"],fonts:{heading:"GT Walsheim Framer Medium",body:"Inter Variable"},tags:["dark","design-productivity"]},intercom:{description:'Intercom\'s website is a warm, confident customer service platform that communicates "AI-first helpdesk" through a clean, editorial design language. The page operates on a warm off-white canvas (`#f...',category:"Design & Productivity",theme:"light",colors:["#111111","#ffffff","#faf9f6","#ff5600","#fe4c02","#65b5ff"],fonts:{heading:"Saans",body:"MediumLL"},tags:["light","design-productivity","minimal"]},miro:{description:`Miro's website is a clean, collaborative-tool-forward platform that communicates "visual thinking" through generous whitespace, pastel accent colors, and a confident geometric font. The design uses...`,category:"Design & Productivity",theme:"light",colors:["#1c1c1e","#ffffff","#5b76fe","#2a41b6","#ffc6c6","#600000"],fonts:{heading:"Roobert PRO Medium",body:"Noto Sans"},tags:["light","design-productivity","minimal","modern"]},notion:{description:"Notion's website embodies the philosophy of the tool itself: a blank canvas that gets out of your way. The design system is built on warm neutrals rather than cold grays, creating a distinctly appr...",category:"Design & Productivity",theme:"light",colors:["#ffffff","#0075de","#213183","#005bab","#f6f5f4","#31302e"],fonts:{heading:"NotionInter",body:"NotionInter"},tags:["light","design-productivity","minimal","bold"]},pinterest:{description:"Pinterest's website is a warm, inspiration-driven canvas that treats visual discovery like a lifestyle magazine. The design operates on a soft, slightly warm white background with Pinterest Red (`#...",category:"Design & Productivity",theme:"light",colors:["#e60023","#103c25","#0b2819","#211922","#000000","#62625b"],fonts:{heading:"Pin Sans",body:"Pin Sans"},tags:["light","design-productivity","bold"]},webflow:{description:'Webflow\'s website is a visually rich, tool-forward platform that communicates "design without code" through clean white surfaces, the signature Webflow Blue (`#146ef5`), and a rich secondary color ...',category:"Design & Productivity",theme:"light",colors:["#080808","#146ef5","#3b89ff","#006acc","#0055d4","#7a3dff"],fonts:{heading:"Inter",body:"20px"},tags:["light","design-productivity","minimal"]},coinbase:{description:"Coinbase's website is a clean, trustworthy crypto platform that communicates financial reliability through a blue-and-white binary palette. The design uses Coinbase Blue (`#0052ff`) \u2014 a deep, satur...",category:"Fintech",theme:"light",colors:["#0052ff","#ffffff","#0a0b0d","#eef0f3","#578bfa","#0667d0"],fonts:{heading:"CoinbaseDisplay",body:"CoinbaseSans"},tags:["light","fintech","minimal","enterprise"]},kraken:{description:"Kraken's website is a clean, trustworthy crypto exchange that uses purple as its commanding brand color. The design operates on white backgrounds with Kraken Purple (`#7132f5`, `#5741d8`, `#5b1ecf`...",category:"Fintech",theme:"light",colors:["#7132f5","#5741d8","#5b1ecf","#101114","#686b82","#9497a9"],fonts:{heading:"Kraken-Brand",body:"Kraken-Product"},tags:["light","fintech","minimal","bold","enterprise"]},revolut:{description:`Revolut's website is fintech confidence distilled into pixels \u2014 a design system that communicates "your money is in capable hands" through massive typography, generous whitespace, and a disciplined...`,category:"Fintech",theme:"light",colors:["#191c1f","#ffffff","#f4f4f4","#494fdf","#4f55f1","#376cd5"],fonts:{heading:"Aeonik Pro",body:"Inter"},tags:["light","fintech","modern"]},wise:{description:`Wise's website is a bold, confident fintech platform that communicates "money without borders" through massive typography and a distinctive lime-green accent. The design operates on a warm off-whit...`,category:"Fintech",theme:"light",colors:["#0e0f0c","#9fe870","#163300","#e2f6d5","#cdffad","#054d28"],fonts:{heading:"Wise Sans",body:"Inter"},tags:["light","fintech","minimal","bold","data-dense"]},airbnb:{description:"Airbnb's website is a warm, photography-forward marketplace that feels like flipping through a travel magazine where every page invites you to book. The design operates on a foundation of pure whit...",category:"Enterprise & Consumer",theme:"light",colors:["#ff385c","#e00b41","#c13515","#b32505","#460479","#92174d"],fonts:{heading:"Nunito Sans",body:"Inter"},tags:["light","enterprise-consumer","minimal","bold"]},apple:{description:"Apple's website is a masterclass in controlled drama \u2014 vast expanses of pure black and near-white serve as cinematic backdrops for products that are photographed as if they were sculptures in a gal...",category:"Enterprise & Consumer",theme:"dark",colors:["#000000","#f5f5f7","#1d1d1f","#0071e3","#0066cc","#2997ff"],fonts:{heading:"Inter",body:"Inter"},tags:["dark","enterprise-consumer","minimal","gradient"]},bmw:{description:"BMW's website is automotive engineering made visual \u2014 a design system that communicates precision, performance, and German industrial confidence. The page alternates between deep dark hero sections...",category:"Enterprise & Consumer",theme:"light",colors:["#ffffff","#1c69d4","#0653b6","#262626","#757575","#bbbbbb"],fonts:{heading:"BMWTypeNextLatin Light",body:"BMWTypeNextLatin"},tags:["light","enterprise-consumer","minimal","elegant"]},ibm:{description:"IBM's website is the digital embodiment of enterprise authority built on the Carbon Design System \u2014 a design language so methodically structured it reads like an engineering specification rendered ...",category:"Enterprise & Consumer",theme:"dark",colors:["#0f62fe","#ffffff","#161616","#262626","#393939","#525252"],fonts:{heading:"IBM Plex Sans",body:"Inter"},tags:["dark","enterprise-consumer","minimal","playful","enterprise"]},nvidia:{description:"NVIDIA's website is a high-contrast, technology-forward experience that communicates raw computational power through design restraint. The page is built on a stark black (`#000000`) and white (`#ff...",category:"Enterprise & Consumer",theme:"dark",colors:["#76b900","#000000","#ffffff","#bff230","#df6500","#ef9100"],fonts:{heading:"NVIDIA-EMEA",body:"NVIDIA-EMEA"},tags:["dark","enterprise-consumer","minimal","bold","playful","data-dense"]},spacex:{description:"SpaceX's website is a full-screen cinematic experience that treats aerospace engineering like a film \u2014 every section is a scene, every photograph is a frame, and the interface disappears entirely b...",category:"Enterprise & Consumer",theme:"dark",colors:["#000000","#f0f0fa"],fonts:{heading:"DM Sans",body:"DM Sans"},tags:["dark","enterprise-consumer","minimal","bold"]},spotify:{description:"Spotify's web interface is a dark, immersive music player that wraps listeners in a near-black cocoon (`#121212`, `#181818`, `#1f1f1f`) where album art and content become the primary source of colo...",category:"Enterprise & Consumer",theme:"dark",colors:["#1ed760","#121212","#181818","#1f1f1f","#ffffff","#b3b3b3"],fonts:{heading:"Inter",body:"SpotifyMixUI"},tags:["dark","enterprise-consumer","bold"]},uber:{description:"Uber's design language is a masterclass in confident minimalism -- a black-and-white universe where every pixel serves a purpose and nothing decorates without earning its place. The entire experien...",category:"Enterprise & Consumer",theme:"dark",colors:["#000000","#ffffff","#e2e2e2","#f3f3f3","#efefef","#4b4b4b"],fonts:{heading:"Inter",body:"UberMoveText"},tags:["dark","enterprise-consumer","minimal","bold","playful","data-dense"]}};function It(r){return r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function me(r){let e=r.toLowerCase().replace(/[^a-z0-9]/g,"");return At.find(t=>t.id===r||t.id.toLowerCase().replace(/[^a-z0-9]/g,"")===e||t.name.toLowerCase().replace(/[^a-z0-9]/g,"")===e)}function Ie(r){return ca[r]}function pa(r){return!r||r==="All"?At:At.filter(e=>e.category.toLowerCase()===r.toLowerCase())}function ut(r){return pa(r).map(t=>{let a=ca[t.id];return{id:t.id,slug:It(t.name),name:t.name,category:t.category,description:a?.description??"",theme:a?.theme??"light",colors:a?.colors??[],fonts:a?.fonts??{heading:"Inter",body:"Inter"},tags:a?.tags??[]}})}function Tr(r){let e=r??At,t={};for(let i of e)(t[i.category]??=[]).push(i);let a=[];for(let[i,n]of Object.entries(t)){a.push(`**${i}**`);for(let o of n){let s=ca[o.id];a.push(` - ${o.name} (${o.id}) \u2014 ${s?.theme??"light"}, ${s?.description?.slice(0,60)??""}`)}}return a.join(`
|
|
8798
|
-
`)}function Pr(r,e){let t=
|
|
8797
|
+
8. Pair black CTAs with white secondaries for balanced dual-action layouts`}]}],ca={cohere:{description:"Cohere's interface is a polished enterprise command deck \u2014 confident, clean, and designed to make AI feel like serious infrastructure rather than a consumer toy. The experience lives on a bright wh...",category:"AI & Machine Learning",theme:"light",colors:["#000000","#212121","#17171c","#1863dc","#4c6ee6","#9b60aa"],fonts:{heading:"CohereText",body:"Unica77 Cohere Web"},tags:["light","ai-machine-learning","minimal","bold","enterprise","gradient"]},elevenlabs:{description:"ElevenLabs' website is a study in restrained elegance \u2014 a near-white canvas (`#ffffff`, `#f5f5f5`) where typography and subtle shadows do all the heavy lifting. The design feels like a premium audi...",category:"AI & Machine Learning",theme:"light",colors:["#ffffff","#f5f5f5","#f5f2ef","#000000","#4e4e4e","#777169"],fonts:{heading:"Waldenburg",body:"Inter"},tags:["light","ai-machine-learning","minimal","bold"]},minimax:{description:"MiniMax's website is a clean, product-showcase platform for a Chinese AI technology company that bridges consumer-friendly appeal with technical credibility. The design language is predominantly wh...",category:"AI & Machine Learning",theme:"light",colors:["#1456f0","#3daeff","#ea5ec1","#bfdbfe","#60a5fa","#3b82f6"],fonts:{heading:"DM Sans",body:"DM Sans"},tags:["light","ai-machine-learning","minimal","bold","playful","gradient"]},mistral:{description:"Mistral AI's interface is a sun-drenched landscape rendered in code \u2014 a warm, bold, unapologetically European design that trades the typical blue-screen AI aesthetic for golden amber, burnt orange,...",category:"AI & Machine Learning",theme:"light",colors:["#fa520f","#fb6424","#ff8105","#ff8a00","#ffa110","#ffb83e"],fonts:{heading:"Arial",body:"Inter"},tags:["light","ai-machine-learning","minimal","bold","elegant","gradient"]},ollama:{description:"Ollama's interface is radical minimalism taken to its logical conclusion \u2014 a pure-white void where content floats without decoration, shadow, or color. The design philosophy mirrors the product its...",category:"AI & Machine Learning",theme:"light",colors:["#000000","#262626","#090909","#ffffff","#fafafa","#e5e5e5"],fonts:{heading:"SF Pro Rounded",body:"ui-sans-serif"},tags:["light","ai-machine-learning","minimal","playful"]},opencode:{description:"OpenCode's website embodies a terminal-native, monospace-first aesthetic that reflects its identity as an open source AI coding agent. The entire visual system is built on a stark dark-on-light con...",category:"AI & Machine Learning",theme:"light",colors:["#201d1d","#fdfcfc","#9a9898","#302c2c","#646262","#f1eeee"],fonts:{heading:"Inter",body:"16px (1.00rem)"},tags:["light","ai-machine-learning","minimal","bold"]},replicate:{description:"Replicate's interface is a developer playground crackling with creative energy \u2014 a bold, high-contrast design that feels more like a music festival poster than a typical API platform. The hero sect...",category:"AI & Machine Learning",theme:"dark",colors:["#202020","#ea2804","#dd4425","#2b9a66","#24292e","#ffffff"],fonts:{heading:"rb-freigeist-neue",body:"basier-square"},tags:["dark","ai-machine-learning","minimal","bold","playful","gradient"]},runwayml:{description:"Runway's interface is a cinematic reel brought to life as a website \u2014 a dark, editorial, film-production-grade design where full-bleed photography and video ARE the primary UI elements. This is not...",category:"AI & Machine Learning",theme:"dark",colors:["#000000","#030303","#1a1a1a","#ffffff","#fefefe","#e9ecf2"],fonts:{heading:"Inter",body:"Inter"},tags:["dark","ai-machine-learning","minimal","bold"]},together:{description:"Together AI's interface is a pastel-gradient dreamscape built for enterprise AI infrastructure \u2014 a design that somehow makes GPU clusters and model inference feel light, airy, and optimistic. The h...",category:"AI & Machine Learning",theme:"light",colors:["#ef2cc1","#fc4c02","#010120","#bdbbff","#ffffff","#000000"],fonts:{heading:"The Future",body:"Inter"},tags:["light","ai-machine-learning","minimal","playful","enterprise","modern","elegant","data-dense","gradient"]},voltagent:{description:"VoltAgent's interface is a deep-space command terminal for the AI age \u2014 a developer-facing darkness built on near-pure-black surfaces (`#050507`) where the only interruption is the electric pulse o...",category:"AI & Machine Learning",theme:"dark",colors:["#00d992","#2fd6a1","#10b981","#818cf8","#306cce","#2554a0"],fonts:{heading:"system-ui",body:"Inter"},tags:["dark","ai-machine-learning","playful","data-dense"]},x:{description:"xAI's website is a masterclass in dark-first, monospace-driven brutalist minimalism -- a design system that feels like it was built by engineers who understand that restraint is the ultimate form o...",category:"AI & Machine Learning",theme:"dark",colors:["#ffffff","#1f2228","#000000"],fonts:{heading:"GeistMono",body:"universalSans"},tags:["dark","ai-machine-learning","minimal","elegant","data-dense","gradient"]},cursor:{description:"Cursor's website is a study in warm minimalism meets code-editor elegance. The entire experience is built on a warm off-white canvas (`#f2f1ed`) with dark warm-brown text (`#26251e`) -- not pure bl...",category:"Developer Tools",theme:"light",colors:["#26251e","#f2f1ed","#e6e5e0","#ffffff","#000000","#f54e00"],fonts:{heading:"CursorGothic",body:"jjannon"},tags:["light","developer-tools","minimal"]},expo:{description:"Expo's interface is a luminous, confidence-radiating developer platform built on the premise that tools for building apps should feel as polished as the apps themselves. The entire experience lives...",category:"Developer Tools",theme:"dark",colors:["#000000","#1c2024","#0d74ce","#476cff","#47c2ff","#8145b5"],fonts:{heading:"Inter",body:"Inter"},tags:["dark","developer-tools","playful"]},linear:{description:"Linear's website is a masterclass in dark-mode-first product design \u2014 a near-black canvas (`#08090a`) where content emerges from darkness like starlight. The overall impression is one of extreme pr...",category:"Developer Tools",theme:"dark",colors:["#010102","#08090a","#0f1011","#191a1b","#28282c","#f7f8f8"],fonts:{heading:"Inter Variable",body:"Inter Variable"},tags:["dark","developer-tools","minimal","bold"]},lovable:{description:"Lovable's website radiates warmth through restraint. The entire page sits on a creamy, parchment-toned background (`#f7f4ed`) that immediately separates it from the cold-white conventions of most d...",category:"Developer Tools",theme:"light",colors:["#f7f4ed","#1c1c1c","#fcfbf8","#5f5f5d","#eceae4","#3b82f6"],fonts:{heading:"Camera Plain Variable",body:"Camera Plain Variable"},tags:["light","developer-tools","minimal"]},mintlify:{description:"Mintlify's website is a study in documentation-as-product design \u2014 a white, airy, information-rich surface that treats clarity as its highest aesthetic value. The page opens with a luminous white (...",category:"Developer Tools",theme:"light",colors:["#0d0d0d","#ffffff","#18e299","#d4fae8","#0fa76e","#c37d0d"],fonts:{heading:"Inter",body:"Inter"},tags:["light","developer-tools","minimal","bold","gradient"]},posthog:{description:"PostHog's website feels like a startup's internal wiki that escaped into the wild \u2014 warm, irreverent, and deliberately anti-corporate. The background isn't the expected crisp white or dark void of ...",category:"Developer Tools",theme:"light",colors:["#4d4f46","#23251d","#f54e00","#f7a501","#b17816","#3b82f6"],fonts:{heading:"IBM Plex Sans Variable",body:"IBM Plex Sans Variable"},tags:["light","developer-tools","bold","playful","modern","gradient"]},raycast:{description:"Raycast's marketing site feels like the dark interior of a precision instrument \u2014 a Swiss watch case carved from obsidian. The background isn't just dark, it's an almost-black blue-tint (`#07080a`)...",category:"Developer Tools",theme:"dark",colors:["#07080a","#ffffff","#ff6363","#55b3ff","#5fc992","#ffbc33"],fonts:{heading:"Inter",body:"16px"},tags:["dark","developer-tools","minimal","data-dense","gradient"]},resend:{description:"Resend's website is a dark, cinematic canvas that treats email infrastructure like a luxury product. The entire page is draped in pure black (`#000000`) with text that glows in near-white (`#f0f0f0...",category:"Developer Tools",theme:"dark",colors:["#000000","#f0f0f0","#ffffff","#ff5900","#ff801f","#ffa057"],fonts:{heading:"domaine",body:"inter"},tags:["dark","developer-tools","minimal","elegant"]},sentry:{description:"Sentry's website is a dark-mode-first developer tool interface that speaks the language of code editors and terminal windows. The entire aesthetic is rooted in deep purple-black backgrounds (`#1f16...",category:"Developer Tools",theme:"dark",colors:["#1f1633","#150f23","#362d59","#6a5fc1","#79628c","#422082"],fonts:{heading:"Dammit Sans",body:"Rubik"},tags:["dark","developer-tools","bold"]},supabase:{description:"Supabase's website is a dark-mode-native developer platform that channels the aesthetic of a premium code editor \u2014 deep black backgrounds (`#0f0f0f`, `#171717`) with emerald green accents (`#3ecf8e...",category:"Developer Tools",theme:"dark",colors:["#3ecf8e","#00c573","#0f0f0f","#171717","#242424","#2e2e2e"],fonts:{heading:"DM Sans",body:"DM Sans"},tags:["dark","developer-tools","minimal","data-dense"]},superhuman:{description:"Superhuman's website feels like opening a luxury envelope \u2014 predominantly white, immaculately clean, with a single dramatic gesture of color that commands attention. The hero section is a cinematic...",category:"Developer Tools",theme:"light",colors:["#1b1938","#cbb7fb","#292827","#714cb6","#ffffff","#e9e5dd"],fonts:{heading:"Super Sans VF",body:"Super Sans VF"},tags:["light","developer-tools","minimal","bold","elegant","data-dense","gradient"]},vercel:{description:"Vercel's website is the visual thesis of developer infrastructure made invisible \u2014 a design system so restrained it borders on philosophical. The page is overwhelmingly white (`#ffffff`) with near-...",category:"Developer Tools",theme:"light",colors:["#171717","#ffffff","#000000","#ff5b4f","#de1d8d","#0a72ef"],fonts:{heading:"Geist",body:"Geist"},tags:["light","developer-tools","minimal"]},warp:{description:"Warp's website feels like sitting at a campfire in a deep forest \u2014 warm, dark, and alive with quiet confidence. Unlike the cold, blue-tinted blacks favored by most developer tools, Warp wraps every...",category:"Developer Tools",theme:"light",colors:["#faf9f6","#353534","#868584","#afaeac","#666469","#454545"],fonts:{heading:"Matter Regular",body:"Matter Regular"},tags:["light","developer-tools","minimal","bold"]},zapier:{description:"Zapier's website radiates warm, approachable professionalism. It rejects the cold monochrome minimalism of developer tools in favor of a cream-tinted canvas (`#fffefb`) that feels like unbleached p...",category:"Developer Tools",theme:"light",colors:["#201515","#fffefb","#fffdf9","#ff4f00","#36342e","#939084"],fonts:{heading:"Degular Display",body:"Inter"},tags:["light","developer-tools","minimal","bold","enterprise","modern","elegant"]},clickhouse:{description:`ClickHouse's interface is a high-performance cockpit rendered in acid yellow-green on obsidian black \u2014 a design that screams "speed" before you read a single word. The entire experience lives in da...`,category:"Infrastructure",theme:"dark",colors:["#faff69","#166534","#14572f","#f4f692","#4f5100","#161600"],fonts:{heading:"Inter",body:"Basier"},tags:["dark","infrastructure"]},composio:{description:"Composio's interface is a nocturnal command center \u2014 a dense, developer-focused darkness punctuated by electric cyan and deep cobalt signals. The entire experience is built on an almost-pure-black ...",category:"Infrastructure",theme:"dark",colors:["#0007cd","#00ffff","#0089ff","#0096ff","#0f0f0f","#000000"],fonts:{heading:"abcDiatype",body:"Inter"},tags:["dark","infrastructure","minimal","data-dense","gradient"]},hashicorp:{description:"HashiCorp's website is enterprise infrastructure made tangible \u2014 a design system that must communicate the complexity of cloud infrastructure management while remaining approachable. The visual lan...",category:"Infrastructure",theme:"dark",colors:["#000000","#15181e","#0d0e12","#f1f2f3","#d5d7db","#b2b6bd"],fonts:{heading:"__hashicorpSans_96f0ca",body:"system-ui"},tags:["dark","infrastructure","minimal","bold","enterprise","data-dense"]},mongodb:{description:"MongoDB's website is a deep-forest-meets-terminal experience \u2014 a design system rooted in the darkest teal-black (`#001e2b`) that evokes both the density of a database and the depth of a forest cano...",category:"Infrastructure",theme:"dark",colors:["#001e2b","#00ed64","#00684a","#006cfa","#3860be","#1eaedb"],fonts:{heading:"MongoDB Value Serif",body:"Euclid Circular A"},tags:["dark","infrastructure","bold","enterprise"]},sanity:{description:"Sanity's website is a developer-content platform rendered as a nocturnal command center -- dark, precise, and deeply structured. The entire experience sits on a near-black canvas (`#0b0b0b`) that r...",category:"Infrastructure",theme:"dark",colors:["#0b0b0b","#000000","#f36458","#0052ef","#55beff","#afe3ff"],fonts:{heading:"waldenburgNormal",body:"waldenburgNormal"},tags:["dark","infrastructure","playful"]},stripe:{description:"Stripe's website is the gold standard of fintech design -- a system that manages to feel simultaneously technical and luxurious, precise and warm. The page opens on a clean white canvas (`#ffffff`)...",category:"Infrastructure",theme:"light",colors:["#533afd","#061b31","#ffffff","#1c1e54","#0d253d","#ea2261"],fonts:{heading:"Inter",body:"Inter"},tags:["light","infrastructure","minimal","bold","enterprise","modern","data-dense","gradient"]},airtable:{description:'Airtable\'s website is a clean, enterprise-friendly platform that communicates "sophisticated simplicity" through a white canvas with deep navy text (`#181d26`) and Airtable Blue (`#1b61c9`) as the ...',category:"Design & Productivity",theme:"light",colors:["#181d26","#1b61c9","#ffffff","#006400","#333333","#254fad"],fonts:{heading:"Haas",body:"Haas"},tags:["light","design-productivity","minimal","playful","enterprise"]},cal:{description:"Cal.com's website is a masterclass in monochromatic restraint \u2014 a grayscale world where boldness comes not from color but from the sheer confidence of black text on white space. Inspired by Uber's ...",category:"Design & Productivity",theme:"light",colors:["#242424","#111111","#ffffff","#0099ff","#3b82f6","#0000ee"],fonts:{heading:"Cal Sans",body:"Inter"},tags:["light","design-productivity","minimal","bold","modern","data-dense"]},clay:{description:"Clay's website is a warm, playful celebration of color that treats B2B data enrichment like a craft rather than an enterprise chore. The design language is built on a foundation of warm cream backg...",category:"Design & Productivity",theme:"light",colors:["#000000","#ffffff","#faf9f7","#84e7a5","#078a52","#02492a"],fonts:{heading:"DM Sans",body:"DM Sans"},tags:["light","design-productivity","playful","enterprise"]},figma:{description:"Figma's interface is the design tool that designed itself \u2014 a masterclass in typographic sophistication where a custom variable font (figmaSans) modulates between razor-thin (weight 320) and bold (...",category:"Design & Productivity",theme:"light",colors:["#000000","#ffffff"],fonts:{heading:"figmaSans",body:"Inter"},tags:["light","design-productivity","bold","gradient"]},framer:{description:"Framer's website is a cinematic, tool-obsessed dark canvas that radiates the confidence of a design tool built by designers who worship craft. The entire experience is drenched in pure black \u2014 not ...",category:"Design & Productivity",theme:"dark",colors:["#000000","#ffffff","#0099ff","#a6a6a6","#090909","#0000ee"],fonts:{heading:"GT Walsheim Framer Medium",body:"Inter Variable"},tags:["dark","design-productivity"]},intercom:{description:'Intercom\'s website is a warm, confident customer service platform that communicates "AI-first helpdesk" through a clean, editorial design language. The page operates on a warm off-white canvas (`#f...',category:"Design & Productivity",theme:"light",colors:["#111111","#ffffff","#faf9f6","#ff5600","#fe4c02","#65b5ff"],fonts:{heading:"Saans",body:"MediumLL"},tags:["light","design-productivity","minimal"]},miro:{description:`Miro's website is a clean, collaborative-tool-forward platform that communicates "visual thinking" through generous whitespace, pastel accent colors, and a confident geometric font. The design uses...`,category:"Design & Productivity",theme:"light",colors:["#1c1c1e","#ffffff","#5b76fe","#2a41b6","#ffc6c6","#600000"],fonts:{heading:"Roobert PRO Medium",body:"Noto Sans"},tags:["light","design-productivity","minimal","modern"]},notion:{description:"Notion's website embodies the philosophy of the tool itself: a blank canvas that gets out of your way. The design system is built on warm neutrals rather than cold grays, creating a distinctly appr...",category:"Design & Productivity",theme:"light",colors:["#ffffff","#0075de","#213183","#005bab","#f6f5f4","#31302e"],fonts:{heading:"NotionInter",body:"NotionInter"},tags:["light","design-productivity","minimal","bold"]},pinterest:{description:"Pinterest's website is a warm, inspiration-driven canvas that treats visual discovery like a lifestyle magazine. The design operates on a soft, slightly warm white background with Pinterest Red (`#...",category:"Design & Productivity",theme:"light",colors:["#e60023","#103c25","#0b2819","#211922","#000000","#62625b"],fonts:{heading:"Pin Sans",body:"Pin Sans"},tags:["light","design-productivity","bold"]},webflow:{description:'Webflow\'s website is a visually rich, tool-forward platform that communicates "design without code" through clean white surfaces, the signature Webflow Blue (`#146ef5`), and a rich secondary color ...',category:"Design & Productivity",theme:"light",colors:["#080808","#146ef5","#3b89ff","#006acc","#0055d4","#7a3dff"],fonts:{heading:"Inter",body:"20px"},tags:["light","design-productivity","minimal"]},coinbase:{description:"Coinbase's website is a clean, trustworthy crypto platform that communicates financial reliability through a blue-and-white binary palette. The design uses Coinbase Blue (`#0052ff`) \u2014 a deep, satur...",category:"Fintech",theme:"light",colors:["#0052ff","#ffffff","#0a0b0d","#eef0f3","#578bfa","#0667d0"],fonts:{heading:"CoinbaseDisplay",body:"CoinbaseSans"},tags:["light","fintech","minimal","enterprise"]},kraken:{description:"Kraken's website is a clean, trustworthy crypto exchange that uses purple as its commanding brand color. The design operates on white backgrounds with Kraken Purple (`#7132f5`, `#5741d8`, `#5b1ecf`...",category:"Fintech",theme:"light",colors:["#7132f5","#5741d8","#5b1ecf","#101114","#686b82","#9497a9"],fonts:{heading:"Kraken-Brand",body:"Kraken-Product"},tags:["light","fintech","minimal","bold","enterprise"]},revolut:{description:`Revolut's website is fintech confidence distilled into pixels \u2014 a design system that communicates "your money is in capable hands" through massive typography, generous whitespace, and a disciplined...`,category:"Fintech",theme:"light",colors:["#191c1f","#ffffff","#f4f4f4","#494fdf","#4f55f1","#376cd5"],fonts:{heading:"Aeonik Pro",body:"Inter"},tags:["light","fintech","modern"]},wise:{description:`Wise's website is a bold, confident fintech platform that communicates "money without borders" through massive typography and a distinctive lime-green accent. The design operates on a warm off-whit...`,category:"Fintech",theme:"light",colors:["#0e0f0c","#9fe870","#163300","#e2f6d5","#cdffad","#054d28"],fonts:{heading:"Wise Sans",body:"Inter"},tags:["light","fintech","minimal","bold","data-dense"]},airbnb:{description:"Airbnb's website is a warm, photography-forward marketplace that feels like flipping through a travel magazine where every page invites you to book. The design operates on a foundation of pure whit...",category:"Enterprise & Consumer",theme:"light",colors:["#ff385c","#e00b41","#c13515","#b32505","#460479","#92174d"],fonts:{heading:"Nunito Sans",body:"Inter"},tags:["light","enterprise-consumer","minimal","bold"]},apple:{description:"Apple's website is a masterclass in controlled drama \u2014 vast expanses of pure black and near-white serve as cinematic backdrops for products that are photographed as if they were sculptures in a gal...",category:"Enterprise & Consumer",theme:"dark",colors:["#000000","#f5f5f7","#1d1d1f","#0071e3","#0066cc","#2997ff"],fonts:{heading:"Inter",body:"Inter"},tags:["dark","enterprise-consumer","minimal","gradient"]},bmw:{description:"BMW's website is automotive engineering made visual \u2014 a design system that communicates precision, performance, and German industrial confidence. The page alternates between deep dark hero sections...",category:"Enterprise & Consumer",theme:"light",colors:["#ffffff","#1c69d4","#0653b6","#262626","#757575","#bbbbbb"],fonts:{heading:"BMWTypeNextLatin Light",body:"BMWTypeNextLatin"},tags:["light","enterprise-consumer","minimal","elegant"]},ibm:{description:"IBM's website is the digital embodiment of enterprise authority built on the Carbon Design System \u2014 a design language so methodically structured it reads like an engineering specification rendered ...",category:"Enterprise & Consumer",theme:"dark",colors:["#0f62fe","#ffffff","#161616","#262626","#393939","#525252"],fonts:{heading:"IBM Plex Sans",body:"Inter"},tags:["dark","enterprise-consumer","minimal","playful","enterprise"]},nvidia:{description:"NVIDIA's website is a high-contrast, technology-forward experience that communicates raw computational power through design restraint. The page is built on a stark black (`#000000`) and white (`#ff...",category:"Enterprise & Consumer",theme:"dark",colors:["#76b900","#000000","#ffffff","#bff230","#df6500","#ef9100"],fonts:{heading:"NVIDIA-EMEA",body:"NVIDIA-EMEA"},tags:["dark","enterprise-consumer","minimal","bold","playful","data-dense"]},spacex:{description:"SpaceX's website is a full-screen cinematic experience that treats aerospace engineering like a film \u2014 every section is a scene, every photograph is a frame, and the interface disappears entirely b...",category:"Enterprise & Consumer",theme:"dark",colors:["#000000","#f0f0fa"],fonts:{heading:"DM Sans",body:"DM Sans"},tags:["dark","enterprise-consumer","minimal","bold"]},spotify:{description:"Spotify's web interface is a dark, immersive music player that wraps listeners in a near-black cocoon (`#121212`, `#181818`, `#1f1f1f`) where album art and content become the primary source of colo...",category:"Enterprise & Consumer",theme:"dark",colors:["#1ed760","#121212","#181818","#1f1f1f","#ffffff","#b3b3b3"],fonts:{heading:"Inter",body:"SpotifyMixUI"},tags:["dark","enterprise-consumer","bold"]},uber:{description:"Uber's design language is a masterclass in confident minimalism -- a black-and-white universe where every pixel serves a purpose and nothing decorates without earning its place. The entire experien...",category:"Enterprise & Consumer",theme:"dark",colors:["#000000","#ffffff","#e2e2e2","#f3f3f3","#efefef","#4b4b4b"],fonts:{heading:"Inter",body:"UberMoveText"},tags:["dark","enterprise-consumer","minimal","bold","playful","data-dense"]}};function It(r){return r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function fe(r){let e=r.toLowerCase().replace(/[^a-z0-9]/g,"");return At.find(t=>t.id===r||t.id.toLowerCase().replace(/[^a-z0-9]/g,"")===e||t.name.toLowerCase().replace(/[^a-z0-9]/g,"")===e)}function Ie(r){return ca[r]}function pa(r){return!r||r==="All"?At:At.filter(e=>e.category.toLowerCase()===r.toLowerCase())}function ut(r){return pa(r).map(t=>{let a=ca[t.id];return{id:t.id,slug:It(t.name),name:t.name,category:t.category,description:a?.description??"",theme:a?.theme??"light",colors:a?.colors??[],fonts:a?.fonts??{heading:"Inter",body:"Inter"},tags:a?.tags??[]}})}function Tr(r){let e=r??At,t={};for(let i of e)(t[i.category]??=[]).push(i);let a=[];for(let[i,n]of Object.entries(t)){a.push(`**${i}**`);for(let o of n){let s=ca[o.id];a.push(` - ${o.name} (${o.id}) \u2014 ${s?.theme??"light"}, ${s?.description?.slice(0,60)??""}`)}}return a.join(`
|
|
8798
|
+
`)}function Pr(r,e){let t=fe(r);if(!t)return null;let a=Sr[e]??Sr.general;if(!a)return null;let i=t.sections.filter(n=>a.some(o=>n.title.toLowerCase().includes(o)));return i.length===0?null:i.map(n=>`## ${n.title}
|
|
8799
8799
|
|
|
8800
8800
|
${n.content}`).join(`
|
|
8801
8801
|
|
|
@@ -10226,26 +10226,26 @@ ${n.map(o=>` - ${o}`).join(`
|
|
|
10226
10226
|
`)}`);return a.join(`
|
|
10227
10227
|
|
|
10228
10228
|
`)}function Ar(r){return(r?ha(r):tt).map(t=>{let a=ua[t.id];return{id:t.id,slug:Ti(t.name),name:t.name,category:t.category,description:a?.description??"",tags:a?.tags??[],envVars:a?.envVars??[],docsUrl:a?.docsUrl??"",packages:a?.packages??[],difficulty:a?.difficulty??"medium"}})}var Pi=[{name:"Dashboard",description:"Overview with key stats and today's activity",condition:r=>r.surfaceType==="internal-tool"||r.surfaceType==="customer-app",keywords:/\b(dashboard|overview|home.?page|stats)\b/i},{name:"Landing Page",description:"Public page explaining what this does",condition:r=>r.publicLanding===!0,keywords:/\b(landing|marketing|hero|homepage)\b/i},{name:"Scheduling / Booking",description:"Calendar, time slots, reservations",condition:r=>r.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:r=>r.multiRole===!0||r.primaryActor==="both",keywords:/\b(admin|panel|manage.?user|moderat)\b/i},{name:"User Profiles",description:"Account pages, settings, preferences",condition:r=>r.primaryActor==="customers"||r.primaryActor==="both",keywords:/\b(profile|account|settings|preferences)\b/i},{name:"Search / Browse",description:"Find and filter content or listings",condition:r=>r.surfaceType==="marketplace",keywords:/\b(search|browse|filter|discover|explore)\b/i},{name:"Email Notifications",description:"Welcome emails, alerts, reminders",condition:r=>r.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:r=>r.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:r=>r.integrations?.includes("ai")===!0,keywords:/\b(ai|chatbot|gpt|llm|generat|assistant)\b/i},{name:"Maps / Location",description:"Google Maps, location search, geolocation",condition:r=>r.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:r=>r.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:r=>r.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:r=>r.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:r=>r.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 Ir(r,e,t){let a=t?.suggestedName||Bi(r),i=e.primaryActor==="both"?"Staff + Customers":e.primaryActor==="staff"?"Staff / Admin":e.primaryActor==="customers"?"End Users":"Users",n=e.audienceType??(e.surfaceType==="internal-tool"?"internal":(e.primaryActor==="customers"||e.primaryActor==="both","b2c")),o=e.surfaceType==="internal-tool"?"Internal tool":e.surfaceType==="marketplace"?"Marketplace":e.surfaceType==="content-site"?"Content site":e.surfaceType==="game"?"Game":"App",s;if(t?.suggestedFeatures&&t.suggestedFeatures.length>0)s=t.suggestedFeatures.map(l=>({name:l.name,description:l.description,checked:l.recommended,source:l.recommended?"explicit":"suggested"}));else{let l=`${r} ${e.primaryAction||""}`;s=[];for(let d of Pi){let u=d.keywords.test(l),h=d.condition(e);(u||h)&&s.push({name:d.name,description:d.description,checked:u,source:u?"explicit":"suggested"})}}return{name:a,audience:i,audienceType:n,surfaceType:o,primaryAction:e.primaryAction||"manage items",features:s,publicLanding:e.publicLanding??!0,authModel:e.authModel??"email",dbProvider:e.dbProvider??"neon",integrations:e.integrations??[],language:t?.language||"English"}}function Mr(r){let e=r.features.filter(s=>s.checked),t=r.features.filter(s=>!s.checked),a={email:"Email sign-up",none:"No login (public)",social:"Social login","invite-only":"Invite-only"},i={neon:"Postgres",turso:"SQLite (legacy)"},n={b2c:"Your customers use this app (business-to-customer)",b2b:"Other businesses sign up for this (SaaS platform)",internal:"Internal team tool (staff only)"},o=[`**${r.name}** \u2014 ${r.surfaceType} for ${r.audience}`,`Audience: ${n[r.audienceType]??r.audienceType}`,`Primary action: ${r.primaryAction}`,`Access: ${a[r.authModel]??r.authModel} | Database: ${i[r.dbProvider]??r.dbProvider}${r.publicLanding?" | Landing page: Yes":""}${r.language&&r.language!=="English"?` | Language: ${r.language}`:""}`,""];if(e.length>0){o.push("**Included:**");for(let s of e)o.push(` \u2713 ${s.name} \u2014 ${s.description}`)}if(r.integrations.length>0&&(o.push(""),o.push(`**Integrations:** ${r.integrations.join(", ")}`)),t.length>0){o.push(""),o.push("**Available to add:**");for(let s of t)o.push(` \u25CB ${s.name} \u2014 ${s.description}`)}return o.join(`
|
|
10229
|
-
`)}function Bi(r){let e=r.match(/\b(?:called|named)\s+["']?([A-Za-z][A-Za-z0-9 ]{1,30})["']?/i);if(e)return ga(e[1]);let t=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"]),i=r.toLowerCase().replace(/[^a-z0-9\s]/g,"").split(/\s+/).filter(n=>n.length>2&&!t.has(n)).slice(0,3);return i.length===0?"my-app":i.join("-")}function ga(r){return r.toLowerCase().replace(/[^a-z0-9\s]/g,"").trim().replace(/\s+/g,"-")}var Mt="__mistflow_url_choice__",Ui=600*1e3;function Fr(){let r=
|
|
10229
|
+
`)}function Bi(r){let e=r.match(/\b(?:called|named)\s+["']?([A-Za-z][A-Za-z0-9 ]{1,30})["']?/i);if(e)return ga(e[1]);let t=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"]),i=r.toLowerCase().replace(/[^a-z0-9\s]/g,"").split(/\s+/).filter(n=>n.length>2&&!t.has(n)).slice(0,3);return i.length===0?"my-app":i.join("-")}function ga(r){return r.toLowerCase().replace(/[^a-z0-9\s]/g,"").trim().replace(/\s+/g,"-")}var Mt="__mistflow_url_choice__",Ui=600*1e3;function Fr(){let r=be(He(),".mistflow","confirm-secret");if(ht(r))try{return Buffer.from(Lr(r,"utf-8").trim(),"hex")}catch{}let e=Ni(32);return ma(be(He(),".mistflow"),{recursive:!0}),fa(r,e.toString("hex"),{mode:384}),e}function Ur(r){return Li("sha256").update(r.trim().toLowerCase()).digest("hex").slice(0,16)}function Ei(r,e){let t={cwd:r,d:Ur(e),exp:Date.now()+Ui},a=Buffer.from(JSON.stringify(t)).toString("base64url"),i=Nr("sha256",Fr()).update(a).digest("base64url");return`${a}.${i}`}function Hi(r,e,t){let a=r.split(".");if(a.length!==2)return!1;let[i,n]=a,o=Nr("sha256",Fr()).update(i).digest("base64url"),s=Buffer.from(n),l=Buffer.from(o);if(s.length!==l.length||!Fi(s,l))return!1;try{let d=JSON.parse(Buffer.from(i,"base64url").toString("utf-8"));return!(typeof d.exp!="number"||Date.now()>d.exp||d.cwd!==e||d.d!==Ur(t))}catch{return!1}}function Oi(r){let e=r,t=He(),a=!1;for(let i=0;i<64;i++){if(ht(be(e,"mistflow.json")))return"mistflow";if(!a&&ht(be(e,"package.json"))&&(a=!0),e===t)break;let n=Mi(e);if(n===e)break;e=n}return a?"foreign":"none"}function Gi(r){let e=He(),t=r.replace(/\/+$/,"");if(t===e||t==="/"||t===""||t==="/tmp"||t==="/private/tmp")return!0;let a=["Desktop","Documents","Downloads"];for(let i of a)if(t===be(e,i))return!0;return!1}var Wi=te.object({description:te.string().min(1,"App description or modification request"),projectPath:te.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:te.string().optional().describe("Returned by a previous mist_plan call with status 'clarify'. Pass it back to continue the conversation."),answers:te.record(te.string()).optional().describe("User's answers to the clarifying questions from the previous round. Keys are the questions, values are the answers."),existingPlan:te.record(te.unknown()).optional().describe("If provided, modifies this existing plan instead of creating a new one. Pass the current plan object from mistflow.json."),existingPlanId:te.string().optional().describe("Alternative to existingPlan \u2014 pass the planId from a previous mist_plan call to modify that plan."),templateToken:te.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:te.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:te.boolean().optional().describe("Skip clarifying questions and generate the plan immediately"),landingDesign:te.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:te.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:te.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:te.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:te.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:te.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.")});function _i(r){let e=[[/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[a,i]of e)if(a.test(r))return i;return r.replace(/[?.,!]/g,"").split(/\s+/).filter(a=>!["what","how","do","does","is","are","the","a","an","would","should","you","your","for","this","that","to","of","or","and","want","like","prefer"].includes(a.toLowerCase())).slice(0,2).join(" ").slice(0,12)||"Option"}function ji(r){let e=be(He(),".mistflow","plans",`${r}.json`);if(!ht(e))return null;try{return JSON.parse(Lr(e,"utf-8")).plan??null}catch{return null}}async function zi(r){let{description:e,projectPath:t,conversationId:a,answers:i,existingPlan:n,existingPlanId:o,templateToken:s,remixDescription:l,autonomous:d,language:u,landingDesign:h,appStyle:c,brandMentioned:g,confirmToken:b,urlChoice:y}=r,f=n;if(!f&&o&&(f=ji(o)??void 0,!f))return p("Your previous plan is no longer available. Please describe your app again to generate a new plan.",!0);let v=a;if(!ce())return p("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let C;if(!v&&!f&&!s){if(!Ri(t))return p(`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 k=Oi(t);if(k!=="mistflow"&&Gi(t))return p(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(`
|
|
10230
10230
|
`)}),!0);if(k==="foreign"&&!g){if(!(b?Hi(b,t,e):!1)){let x=Ei(t,e);return p(JSON.stringify({status:"confirm_new_project",projectPath:t,description:e,confirmToken:x,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.",b?"The previous confirmToken was invalid, expired, or did not match the current directory/description. Use the fresh token above.":""].filter(Boolean).join(`
|
|
10231
|
-
`)}))}C="Note: You're inside an existing project. Mistflow will create the new app in a subdirectory. It won't modify this codebase."}else k==="foreign"&&g&&(C="Note: You're inside an existing project. Mistflow will create the new app in a subdirectory. It won't modify this codebase.")}if(s)try{if(!(await cr(s)).plan)return p("This template has no plan to fork. Try a different template.",!0);let m=await pr(s),x=m.plan,S="";if(l&&m.has_source)try{let
|
|
10231
|
+
`)}))}C="Note: You're inside an existing project. Mistflow will create the new app in a subdirectory. It won't modify this codebase."}else k==="foreign"&&g&&(C="Note: You're inside an existing project. Mistflow will create the new app in a subdirectory. It won't modify this codebase.")}if(s)try{if(!(await cr(s)).plan)return p("This template has no plan to fork. Try a different template.",!0);let m=await pr(s),x=m.plan,S="";if(l&&m.has_source)try{let ke=await ra(m.plan,l),Se=ke.plan??ke,kt=ke.diff,ee=Se?.steps??[],ta=new Set([...(kt?.added??[]).map(Ce=>Ce.number),...(kt?.modified??[]).map(Ce=>Ce.number)]),Ne=ee.map(Ce=>{let fi=Ce.number;return ta.has(fi)?{...Ce,status:"pending"}:{...Ce,status:"completed",source:"forked"}});Se.steps=Ne,x=Se;let $e=Ne.filter(Ce=>Ce.status==="pending").length;S=` Remixed: ${Ne.filter(Ce=>Ce.status==="completed").length} steps unchanged, ${$e} steps need re-implementation.`}catch(ke){console.error("[plan] Remix failed, using original plan:",ke),S=" (Remix failed \u2014 using original plan. You can modify it later.)"}let G=Rr(),D=be(He(),".mistflow","plans");ma(D,{recursive:!0}),fa(be(D,`${G}.json`),JSON.stringify({plan:x,projectId:m.id,sourceDeploymentId:m.source_deployment_id,forkToken:m.fork_token,requiredEnvVars:m.required_env_vars,dbProvider:m.db_provider}));let j=x?.name??"forked-app",ue=m.has_source,ve=ue?"Source code will be restored during init. Run init promptly \u2014 the download token expires in 1 hour.":"",Xe=m.deploy_url?` Instant deploy started \u2014 your app will be live at ${m.deploy_url} in under a minute.`:"";return p(JSON.stringify({planId:G,forkedFrom:m.forked_from,projectId:m.id,hasSource:ue,deployUrl:m.deploy_url,message:`Forked "${m.forked_from}" into your workspace.${S}${Xe} ${ve} NEXT: Call mist_build with action='init', name='${j}', and planId='${G}' to create the project now.`}))}catch(k){let m=k instanceof Error?k.message:"Failed to fork template";return p(m,!0)}if(f){let k;try{k=await ra(f,e)}catch(D){let j=D instanceof Error?D.message:"Failed to modify plan";return p(j,!0)}let m=k.plan,x=k.diff,S=[];if(x?.added?.length){let D=x.added.map(j=>j.title);S.push(`Added ${D.length} step(s): ${D.join(", ")}`)}if(x?.removed?.length){let D=x.removed.map(j=>j.title);S.push(`Removed ${D.length} step(s): ${D.join(", ")}`)}if(x?.modified?.length){let D=x.modified.map(j=>j.title);S.push(`Modified ${D.length} step(s): ${D.join(", ")}`)}let G=S.length>0?S.join(". "):"No changes detected.";return p(JSON.stringify({plan:m,diff:x,message:`Plan modified. ${G}. Update mistflow.json with the new plan, then continue with mist_build (action: 'implement').`}))}let P=y?.trim()||void 0,A=i;if(!P&&i&&Mt in i&&(P=i[Mt]),i&&Mt in i){let{[Mt]:k,...m}=i;A=Object.keys(m).length>0?m:void 0}if(P&&(P=P.replace(/^Keep\s+/i,"").replace(/\s*\(Recommended\)\s*$/i,"").replace(/\.mistflow\.app.*$/i,"").trim()||void 0),P){let k=P.toLowerCase().replace(/\s+/g,"-");/^[a-z0-9][a-z0-9-]{1,30}[a-z0-9]$/.test(k)?P=k:(console.error(`[mist_plan] Discarding urlChoice '${P}' \u2014 does not look like a subdomain. Backend will auto-generate.`),P=void 0)}let B;try{B=await qa(e,{conversationId:v,answers:A,autonomous:d,language:u})}catch(k){let m=k instanceof Error?k.message:"Failed to generate plan";return p(m,!0)}if(B.status==="clarify"){let k=B.reflection||"",m=B.suggestedName||"",x=B.suggestedFeatures??[],S=B.questions??[],G=S.some(ee=>Array.isArray(ee.options)&&typeof ee.options[0]=="object"&&ee.options[0]?.label),D={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"},j=S.map(ee=>{let ta=ee.decisionKey&&D[ee.decisionKey]||_i(ee.question),Ne;return G&&Array.isArray(ee.options)?Ne=ee.options.map($e=>({label:$e.label,description:$e.description??""})):Array.isArray(ee.options)?Ne=ee.options.map(($e,Ha)=>({label:Ha===0?`${$e} (Recommended)`:String($e),description:ee.why??""})):Ne=[{label:"Yes (Recommended)",description:ee.why??""},{label:"No",description:""}],{question:ee.question,header:ta,options:Ne,multiSelect:!1}}),ve=B.decisions?.audienceType??null,Xe=x.length>0?Ir(e,{primaryActor:null,primaryAction:null,surfaceType:null,audienceType:ve,multiRole:null,publicLanding:null,realMoney:null,scheduling:null,authModel:null,dbProvider:null,integrations:null},{suggestedName:m,suggestedFeatures:x,language:u}):null,ke=Xe?Mr(Xe):"",Se=ga(m||"my-app").slice(0,32);try{let ee=await $a(Se);!ee.available&&ee.suggestion&&(Se=ee.suggestion)}catch{}ke&&(ke+=`
|
|
10232
10232
|
|
|
10233
|
-
**Your app URL:** https://${
|
|
10234
|
-
`:"",
|
|
10233
|
+
**Your app URL:** https://${Se}.mistflow.app`);let kt={question:`Your app will be at ${Se}.mistflow.app \u2014 want to customize the URL?`,header:"URL",options:[{label:`Keep ${Se}.mistflow.app (Recommended)`,description:"This URL is available"},{label:"Choose a different URL",description:"Type your preferred subdomain"}],multiSelect:!1};return j.push(kt),p(JSON.stringify({status:"clarify",conversation_id:B.conversation_id,questions:S,questionCount:S.length,suggestedFeatures:x,suggestedName:m,suggestedSubdomain:Se,reflection:k,briefText:ke,askUserQuestions:j,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:[...C?[C,""]:[],k?`${k}
|
|
10234
|
+
`:"",ke?`Here's what I'd build:
|
|
10235
10235
|
|
|
10236
|
-
${
|
|
10237
|
-
`:"",`I have ${S.length} quick question${S.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: "${B.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: "${
|
|
10238
|
-
`)}))}let I=B.plan,M=I.name??"Untitled App",G=B.methodology,H=I.steps;if(!Array.isArray(H)||H.length===0)return p("Plan generation incomplete \u2014 the plan is missing implementation steps. Please call mist_plan again with the same description to retry.",!0);let O=I.publicPages;if(!O||Array.isArray(O)&&O.length===0){let k=I.pages,m=H.some(S=>typeof S.name=="string"&&S.name.toLowerCase().includes("landing")||typeof S.title=="string"&&S.title.toLowerCase().includes("landing")),x=Array.isArray(k)&&k.some(S=>S.path==="/"||S.route==="/");m||x?O=["/","/pricing"]:O=["/"]}let re=I.primaryAction;if(!re){let k=I.features;if(Array.isArray(k)&&k.length>0){let x=k.find(D=>typeof D.priority=="string"&&D.priority.toLowerCase()==="must-have")??k[0];re={entity:x.name??x.title??"item",action:"create",fromPage:"/dashboard"}}}let j=I.nonNegotiables;(!j||Array.isArray(j)&&j.length===0)&&(j=["Landing page renders correctly at / with content (not a redirect)","Core user action works end-to-end (create entity, see it in list)"]);let q=Rr(),E=fe(He(),".mistflow","plans");ma(E,{recursive:!0});try{let m=Date.now();for(let x of[E,fe(He(),".mistflow","mockup-state")])if(ht(x))for(let S of Di(x))try{let D=fe(x,S),U=Ai(D).mtimeMs;m-U>6048e5&&Ii(D)}catch{}}catch{}let _;if(h){let k=et(h);k?_=k.id:console.error(`Landing design '${h}' not found \u2014 ignoring. Use mist_project action='landing-designs' to browse available landing designs.`)}let F;if(c){let k=me(c);k?F=k.id:console.error(`App style '${c}' not found \u2014 ignoring. Use mist_project action='app-styles' to browse available app styles.`)}let J=!!_,le=H.some(k=>{let m=`${k.name??k.title} ${k.description??""}`.toLowerCase();return m.includes("landing")||m.includes("hero")||m.includes("marketing")||m.includes("homepage")}),T=!J&&le?kr(e,{maxResults:2}):[];T.length>0&&(_=T[0].id,console.error(`Auto-assigned landing layout preset (default): ${T[0].title} (${_})`));let R={name:I.name,summary:I.summary,dataModel:I.dataModel,pages:I.pages,features:I.features,steps:H.map(k=>({...k,name:k.name??k.title})),design:I.design,landingDesign:_,appStyle:F,dbProvider:I.dbProvider??"neon",authModel:I.authModel,audienceType:I.audienceType??"b2c",roles:I.roles,defaultRole:I.defaultRole,publicPages:O,navStyle:I.navStyle,multiTenant:I.multiTenant,primaryAction:re,nonNegotiables:j,requestedSubdomain:P,...u&&u.toLowerCase()!=="english"?{language:u}:{}};fa(fe(E,`${q}.json`),JSON.stringify({plan:R,methodology:G}));let L=H.map(k=>`${k.number}. ${k.name??k.title}`),oe="",ie=[],w;!J&&T.length>0&&(ie=T.map(m=>({id:m.id,slug:m.slug,title:m.title,description:m.description,url:`${Ae()}/designs?tab=landing-designs`})),w={question:"What landing page style fits this app?",header:"Landing Design",options:[...T.map((m,x)=>({label:x===0?`${m.title} (Recommended)`:m.title,description:m.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 ${Ae()}/designs?tab=landing-designs and pass the ID back.`}],multiSelect:!1},oe=` Also ask the user about landing design using the AskUserQuestion tool with the 'landingDesignQuestion' object. Recommended: ${T.map(m=>m.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 (or don't answer), '${T[0].id}' is already set as the plan default \u2014 no action needed.`);let N="",V=[],ge;F||(V=Br(e,{maxResults:3}).map(x=>({id:x.id,slug:It(x.name),name:x.name,description:x.description,theme:x.theme,url:`${Ae()}/designs/app-styles/${It(x.name)}`})),ge={question:"What design style should your app have? Choose a design system for consistent, brand-quality UI across all pages.",header:"App Design",options:[...V.map((x,S)=>({label:S===0?`${x.name} (Recommended)`:x.name,description:`${x.theme} theme \u2014 ${x.description} Preview: ${x.url}`})),{label:"See more app styles",description:`Not sure? Browse all 53 app styles at ${Ae()}/designs?tab=app-styles and pick one.`},{label:"Skip \u2014 use default styling",description:"Proceed without a design system"}],multiSelect:!1},N=` Ask the user which app style they want using the AskUserQuestion tool with the 'appStyleQuestion' object provided. Recommended: ${V.map(x=>`[${x.name}](${x.url})`).join(", ")}. In your message, say these are top picks based on their description and that if none feel right they can browse all 53 app styles at ${Ae()}/designs?tab=app-styles (include this link verbatim). Once the user picks, pass appStyle='<id>' to the mist_build init call. If user says "skip", proceed without one.`);let Z=(I.audienceType??"b2c")==="b2c",ye={question:"Include a lifestyle photo in your landing page hero? Photos add warmth and human context; pure CSS stays cleaner.",header:"Hero",options:[{label:Z?"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:Z?"No, CSS only":"No, CSS only (Recommended)",description:"Animated gradients + glassmorphism, no photo \u2014 cleaner and more technical (like Stripe, Linear, Vercel)."}],multiSelect:!1},xe=" 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.",de="",z=[];for(let k of H){let m=k.name??k.title,x=k.integrationId;if(x){let S=at(x);if(S){let D=rt(S.id);z.push({step:m,presetId:S.id,presetName:S.name,envVars:D?.envVars??[]})}}}if(z.length>0){let k=z.flatMap(S=>S.envVars),m=[...new Set(k.map(S=>S.key))];de=` This plan uses integrations (${z.map(S=>S.presetName).join(", ")}). Detailed blueprints will be auto-injected during each integration step.${m.length>0?` The user will need these API keys: ${m.join(", ")}.`:""}`}return p(JSON.stringify({planId:q,name:I.name,summary:I.summary,stepCount:H.length,steps:L,design:I.design,..._?{landingDesign:_}:{},...F?{appStyle:F}:{},...V.length>0?{recommendedAppStyles:V}:{},...ge?{appStyleQuestion:ge}:{},...ie.length>0?{recommendedLandingDesigns:ie}:{},...w?{landingDesignQuestion:w}:{},heroPhotoQuestion:ye,...z.length>0?{integrations:z.map(k=>({step:k.step,preset:k.presetId,name:k.presetName,envVars:k.envVars}))}:{},message:`Plan generated for "${M}" (${H.length} steps).${_?` Landing layout "${_}" set as default.`:""}${F?` App style "${F}" will be applied across all pages.`:""}${de}${N}${oe}${xe}`,timingContext:`Planning took ~90 seconds. Building will take roughly ${Math.max(15,H.length*3)}\u2013${H.length*5} minutes total across ${H.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='${q}'. If the user says skip or "just build it", call mist_build with action='init', name='${M}', and planId='${q}' immediately.`,...C?{warning:C}:{}}))}var Er={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.","","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(`
|
|
10236
|
+
${ke}
|
|
10237
|
+
`:"",`I have ${S.length} quick question${S.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: "${B.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: "${Se}".`,'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(`
|
|
10238
|
+
`)}))}let I=B.plan,M=I.name??"Untitled App",O=B.methodology,E=I.steps;if(!Array.isArray(E)||E.length===0)return p("Plan generation incomplete \u2014 the plan is missing implementation steps. Please call mist_plan again with the same description to retry.",!0);let H=I.publicPages;if(!H||Array.isArray(H)&&H.length===0){let k=I.pages,m=E.some(S=>typeof S.name=="string"&&S.name.toLowerCase().includes("landing")||typeof S.title=="string"&&S.title.toLowerCase().includes("landing")),x=Array.isArray(k)&&k.some(S=>S.path==="/"||S.route==="/");m||x?H=["/","/pricing"]:H=["/"]}let re=I.primaryAction;if(!re){let k=I.features;if(Array.isArray(k)&&k.length>0){let x=k.find(G=>typeof G.priority=="string"&&G.priority.toLowerCase()==="must-have")??k[0];re={entity:x.name??x.title??"item",action:"create",fromPage:"/dashboard"}}}let z=I.nonNegotiables;(!z||Array.isArray(z)&&z.length===0)&&(z=["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=Rr(),U=be(He(),".mistflow","plans");ma(U,{recursive:!0});try{let m=Date.now();for(let x of[U,be(He(),".mistflow","mockup-state")])if(ht(x))for(let S of Di(x))try{let G=be(x,S),D=Ai(G).mtimeMs;m-D>6048e5&&Ii(G)}catch{}}catch{}let _;if(h){let k=et(h);k?_=k.id:console.error(`Landing design '${h}' not found \u2014 ignoring. Use mist_project action='landing-designs' to browse available landing designs.`)}let F;if(c){let k=fe(c);k?F=k.id:console.error(`App style '${c}' not found \u2014 ignoring. Use mist_project action='app-styles' to browse available app styles.`)}let Q=!!_,le=E.some(k=>{let m=`${k.name??k.title} ${k.description??""}`.toLowerCase();return m.includes("landing")||m.includes("hero")||m.includes("marketing")||m.includes("homepage")}),T=!Q&&le?kr(e,{maxResults:2}):[];T.length>0&&(_=T[0].id,console.error(`Auto-assigned landing layout preset (default): ${T[0].title} (${_})`));let R={name:I.name,summary:I.summary,dataModel:I.dataModel,pages:I.pages,features:I.features,steps:E.map(k=>({...k,name:k.name??k.title})),design:I.design,landingDesign:_,appStyle:F,dbProvider:I.dbProvider??"neon",authModel:I.authModel,audienceType:I.audienceType??"b2c",roles:I.roles,defaultRole:I.defaultRole,publicPages:H,navStyle:I.navStyle,multiTenant:I.multiTenant,primaryAction:re,nonNegotiables:z,requestedSubdomain:P,...u&&u.toLowerCase()!=="english"?{language:u}:{}};fa(be(U,`${K}.json`),JSON.stringify({plan:R,methodology:O}));let L=E.map(k=>`${k.number}. ${k.name??k.title}`),oe="",ie=[],w;!Q&&T.length>0&&(ie=T.map(m=>({id:m.id,slug:m.slug,title:m.title,description:m.description,url:`${Ae()}/designs?tab=landing-designs`})),w={question:"What landing page style fits this app?",header:"Landing Design",options:[...T.map((m,x)=>({label:x===0?`${m.title} (Recommended)`:m.title,description:m.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 ${Ae()}/designs?tab=landing-designs and pass the ID back.`}],multiSelect:!1},oe=` Also ask the user about landing design using the AskUserQuestion tool with the 'landingDesignQuestion' object. Recommended: ${T.map(m=>m.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 (or don't answer), '${T[0].id}' is already set as the plan default \u2014 no action needed.`);let N="",q=[],me;F||(q=Br(e,{maxResults:3}).map(x=>({id:x.id,slug:It(x.name),name:x.name,description:x.description,theme:x.theme,url:`${Ae()}/designs/app-styles/${It(x.name)}`})),me={question:"What design style should your app have? Choose a design system for consistent, brand-quality UI across all pages.",header:"App Design",options:[...q.map((x,S)=>({label:S===0?`${x.name} (Recommended)`:x.name,description:`${x.theme} theme \u2014 ${x.description} Preview: ${x.url}`})),{label:"See more app styles",description:`Not sure? Browse all 53 app styles at ${Ae()}/designs?tab=app-styles and pick one.`},{label:"Skip \u2014 use default styling",description:"Proceed without a design system"}],multiSelect:!1},N=` Ask the user which app style they want using the AskUserQuestion tool with the 'appStyleQuestion' object provided. Recommended: ${q.map(x=>`[${x.name}](${x.url})`).join(", ")}. In your message, say these are top picks based on their description and that if none feel right they can browse all 53 app styles at ${Ae()}/designs?tab=app-styles (include this link verbatim). Once the user picks, pass appStyle='<id>' to the mist_build init call. If user says "skip", proceed without one.`);let Z=(I.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:Z?"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:Z?"No, CSS only":"No, CSS only (Recommended)",description:"Animated gradients + glassmorphism, no photo \u2014 cleaner and more technical (like Stripe, Linear, Vercel)."}],multiSelect:!1},we=" 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.",de="",$=[];for(let k of E){let m=k.name??k.title,x=k.integrationId;if(x){let S=at(x);if(S){let G=rt(S.id);$.push({step:m,presetId:S.id,presetName:S.name,envVars:G?.envVars??[]})}}}if($.length>0){let k=$.flatMap(S=>S.envVars),m=[...new Set(k.map(S=>S.key))];de=` This plan uses integrations (${$.map(S=>S.presetName).join(", ")}). Detailed blueprints will be auto-injected during each integration step.${m.length>0?` The user will need these API keys: ${m.join(", ")}.`:""}`}return p(JSON.stringify({planId:K,name:I.name,summary:I.summary,stepCount:E.length,steps:L,design:I.design,..._?{landingDesign:_}:{},...F?{appStyle:F}:{},...q.length>0?{recommendedAppStyles:q}:{},...me?{appStyleQuestion:me}:{},...ie.length>0?{recommendedLandingDesigns:ie}:{},...w?{landingDesignQuestion:w}:{},heroPhotoQuestion:xe,...$.length>0?{integrations:$.map(k=>({step:k.step,preset:k.presetId,name:k.presetName,envVars:k.envVars}))}:{},message:`Plan generated for "${M}" (${E.length} steps).${_?` Landing layout "${_}" set as default.`:""}${F?` App style "${F}" will be applied across all pages.`:""}${de}${N}${oe}${we}`,timingContext:`Planning took ~90 seconds. Building will take roughly ${Math.max(15,E.length*3)}\u2013${E.length*5} minutes total across ${E.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='${M}', and planId='${K}' immediately.`,...C?{warning:C}:{}}))}var Er={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.","","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(`
|
|
10239
10239
|
`),inputSchema:Wi,handler:zi};import{z as ae}from"zod";import{existsSync as _t,readFileSync as os}from"fs";import{join as jt,resolve as is}from"path";import{homedir as ns}from"os";import{execFileSync as Pa}from"child_process";import{z as Rt}from"zod";import{existsSync as Me,mkdirSync as Nt,writeFileSync as Oe,readFileSync as Ft,readdirSync as $i,copyFileSync as Vi}from"fs";import{join as X,resolve as ya,dirname as gt,isAbsolute as _r}from"path";import{spawn as qi}from"child_process";import{randomBytes as Ki}from"crypto";import{simpleGit as jr}from"simple-git";function Yi(r){let e=gt(ya(r)),t=10,a=0;for(;a<t&&e!==gt(e);){if(Me(X(e,"pnpm-workspace.yaml"))||Me(X(e,"lerna.json")))return e;let i=X(e,"package.json");if(Me(i))try{if(JSON.parse(Ft(i,"utf-8")).workspaces)return e}catch{}e=gt(e),a++}return null}function Ge(r,e,t,a,i,n){return new Promise(o=>{let s=qi(r,e,{cwd:t,stdio:["pipe","pipe","pipe"],timeout:a,env:n?{...process.env,...n}:process.env}),l="",d="";s.stdout?.on("data",u=>{let h=u.toString();if(d+=h,i)for(let c of h.split(`
|
|
10240
10240
|
`).filter(Boolean))i(c)}),s.stderr?.on("data",u=>{let h=u.toString();if(l+=h,i)for(let c of h.split(`
|
|
10241
10241
|
`).filter(Boolean))i(c)}),s.on("close",u=>{if(u===0)o({success:!0});else{let h=l.split(`
|
|
10242
|
-
`).find(c=>c.startsWith("npm error"))??l.slice(0,300);o({success:!1,error:h})}}),s.on("error",u=>{o({success:!1,error:u.message})})})}var Dd=Rt.object({name:Rt.string().min(1),plan:Rt.any(),path:Rt.string().optional()});function W(r,e,t){let a=X(r,e);Nt(gt(a),{recursive:!0}),Oe(a,t)}var Hr={amber:{primary:"25 95% 53%",primaryForeground:"0 0% 100%"},emerald:{primary:"160 84% 39%",primaryForeground:"0 0% 100%"},indigo:{primary:"239 84% 67%",primaryForeground:"0 0% 100%"},rose:{primary:"347 77% 50%",primaryForeground:"0 0% 100%"},cyan:{primary:"189 94% 43%",primaryForeground:"0 0% 100%"},violet:{primary:"263 70% 50%",primaryForeground:"0 0% 100%"},orange:{primary:"21 90% 48%",primaryForeground:"0 0% 100%"},teal:{primary:"168 76% 42%",primaryForeground:"0 0% 100%"},sky:{primary:"199 89% 48%",primaryForeground:"0 0% 100%"}},Ji={sharp:"0.125rem",subtle:"0.375rem",rounded:"0.75rem",pill:"9999px"};function Ut(r){let e=r.replace("#","");if(e.length!==6&&e.length!==3)return null;let t=e.length===3?e[0]+e[0]+e[1]+e[1]+e[2]+e[2]:e,a=parseInt(t,16);return isNaN(a)?null:{r:a>>16&255,g:a>>8&255,b:a&255}}function Et(r,e,t){r/=255,e/=255,t/=255;let a=Math.max(r,e,t),i=Math.min(r,e,t),n=(a+i)/2;if(a===i)return{h:0,s:0,l:Math.round(n*100)};let o=a-i,s=n>.5?o/(2-a-i):o/(a+i),l=0;return a===r?l=((e-t)/o+(e<t?6:0))/6:a===e?l=((t-r)/o+2)/6:l=((r-e)/o+4)/6,{h:Math.round(l*360),s:Math.round(s*100),l:Math.round(n*100)}}function ot(r){let e=Ut(r);if(!e)return"0 0% 50%";let{h:t,s:a,l:i}=Et(e.r,e.g,e.b);return`${t} ${a}% ${i}%`}function zr(r){let e=Ut(r);return e?Et(e.r,e.g,e.b).l:50}function $r(r){let e=Ut(r);return e?Et(e.r,e.g,e.b).s:0}function Qi(r){let e=
|
|
10243
|
-
`);if(b===-1)continue;let y=g.slice(0,b).trim().toLowerCase();i[y]=g.slice(b)}let o=g=>g.match(/#[0-9a-fA-F]{6}\b/)?.[0],s,l=["interactive","accent","action","cta","brand"];for(let g of l){if(s)break;for(let b of Object.keys(i))if(b.includes(g)&&(s=o(i[b]),s))break}if(!s){for(let g of Object.keys(i))if(g.includes("secondary")&&(s=o(i[g]),s))break}let d;for(let g of Object.keys(i))if((g.includes("surface")||g.includes("background")||g.includes("canvas"))&&(d=o(i[g]),d))break;let u;for(let g of Object.keys(i))if((g==="primary"||g.includes("text")||g.includes("neutral"))&&(u=o(i[g]),u))break;let h;for(let g of Object.keys(i))if(g.includes("neutral")||g.includes("muted")||g.includes("tertiary")){let y=(i[g].match(/#[0-9a-fA-F]{6}\b/g)??[]).map(v=>({hex:v,l:zr(v)})).sort((v,C)=>v.l-C.l),f=y[Math.floor(y.length/2)];if(f&&(h=f.hex),h)break}let c;for(let g of Object.keys(i))if((g.includes("border")||g.includes("divider")||g.includes("separator"))&&(c=o(i[g]),c))break;if(!c){let g=a.match(/[Bb]order[^`]*`(#[0-9a-fA-F]{6})`/);g&&(c=g[1])}return s&&$r(s)<10&&(s=void 0),!s&&!d&&!u?null:{background:d,foreground:u,accent:s,muted:h,border:c}}function Xi(r,e){let t=Qi(e),a=t?.accent??r.colors.find(y=>$r(y)>20)??r.colors[0]??"#6366f1",i=ot(a),n=zr(a),o=t?.background??(r.theme==="light"?"#ffffff":"#0a0a0a"),s=Ut(o),l=s?Et(s.r,s.g,s.b):{h:0,s:0,l:100},d=l.s>3?l.h:0,u=Math.min(l.s,15),h=t?.foreground??"#0f172a",c=t?.muted,g=t?.border,b=Math.min(u,10);return{light:{background:`${d} ${u}% 99%`,foreground:ot(h),card:`${d} ${u}% 100%`,cardForeground:ot(h),muted:c?ot(c):`${d} ${Math.min(u,10)}% 96%`,mutedForeground:`${d} ${Math.min(u,8)}% 45%`,border:g?ot(g):`${d} ${Math.min(u,10)}% 90%`,input:g?ot(g):`${d} ${Math.min(u,10)}% 90%`,ring:i},dark:{background:`${d} ${b}% 4%`,foreground:"0 0% 95%",card:`${d} ${b}% 6%`,cardForeground:"0 0% 95%",muted:`${d} ${Math.min(b,6)}% 16%`,mutedForeground:`${d} ${Math.min(b,6)}% 65%`,border:`${d} ${Math.min(b,6)}% 16%`,input:`${d} ${Math.min(b,6)}% 16%`,ring:i},primary:i,primaryForeground:n>60?"0 0% 5%":"0 0% 100%"}}function
|
|
10242
|
+
`).find(c=>c.startsWith("npm error"))??l.slice(0,300);o({success:!1,error:h})}}),s.on("error",u=>{o({success:!1,error:u.message})})})}var Dd=Rt.object({name:Rt.string().min(1),plan:Rt.any(),path:Rt.string().optional()});function W(r,e,t){let a=X(r,e);Nt(gt(a),{recursive:!0}),Oe(a,t)}var Hr={amber:{primary:"25 95% 53%",primaryForeground:"0 0% 100%"},emerald:{primary:"160 84% 39%",primaryForeground:"0 0% 100%"},indigo:{primary:"239 84% 67%",primaryForeground:"0 0% 100%"},rose:{primary:"347 77% 50%",primaryForeground:"0 0% 100%"},cyan:{primary:"189 94% 43%",primaryForeground:"0 0% 100%"},violet:{primary:"263 70% 50%",primaryForeground:"0 0% 100%"},orange:{primary:"21 90% 48%",primaryForeground:"0 0% 100%"},teal:{primary:"168 76% 42%",primaryForeground:"0 0% 100%"},sky:{primary:"199 89% 48%",primaryForeground:"0 0% 100%"}},Ji={sharp:"0.125rem",subtle:"0.375rem",rounded:"0.75rem",pill:"9999px"};function Ut(r){let e=r.replace("#","");if(e.length!==6&&e.length!==3)return null;let t=e.length===3?e[0]+e[0]+e[1]+e[1]+e[2]+e[2]:e,a=parseInt(t,16);return isNaN(a)?null:{r:a>>16&255,g:a>>8&255,b:a&255}}function Et(r,e,t){r/=255,e/=255,t/=255;let a=Math.max(r,e,t),i=Math.min(r,e,t),n=(a+i)/2;if(a===i)return{h:0,s:0,l:Math.round(n*100)};let o=a-i,s=n>.5?o/(2-a-i):o/(a+i),l=0;return a===r?l=((e-t)/o+(e<t?6:0))/6:a===e?l=((t-r)/o+2)/6:l=((r-e)/o+4)/6,{h:Math.round(l*360),s:Math.round(s*100),l:Math.round(n*100)}}function ot(r){let e=Ut(r);if(!e)return"0 0% 50%";let{h:t,s:a,l:i}=Et(e.r,e.g,e.b);return`${t} ${a}% ${i}%`}function zr(r){let e=Ut(r);return e?Et(e.r,e.g,e.b).l:50}function $r(r){let e=Ut(r);return e?Et(e.r,e.g,e.b).s:0}function Qi(r){let e=fe(r);if(!e)return null;let t=e.sections.find(g=>g.title.toLowerCase().includes("color palette"));if(!t)return null;let a=t.content,i={},n=a.split(/^### /m);for(let g of n){if(!g.trim())continue;let b=g.indexOf(`
|
|
10243
|
+
`);if(b===-1)continue;let y=g.slice(0,b).trim().toLowerCase();i[y]=g.slice(b)}let o=g=>g.match(/#[0-9a-fA-F]{6}\b/)?.[0],s,l=["interactive","accent","action","cta","brand"];for(let g of l){if(s)break;for(let b of Object.keys(i))if(b.includes(g)&&(s=o(i[b]),s))break}if(!s){for(let g of Object.keys(i))if(g.includes("secondary")&&(s=o(i[g]),s))break}let d;for(let g of Object.keys(i))if((g.includes("surface")||g.includes("background")||g.includes("canvas"))&&(d=o(i[g]),d))break;let u;for(let g of Object.keys(i))if((g==="primary"||g.includes("text")||g.includes("neutral"))&&(u=o(i[g]),u))break;let h;for(let g of Object.keys(i))if(g.includes("neutral")||g.includes("muted")||g.includes("tertiary")){let y=(i[g].match(/#[0-9a-fA-F]{6}\b/g)??[]).map(v=>({hex:v,l:zr(v)})).sort((v,C)=>v.l-C.l),f=y[Math.floor(y.length/2)];if(f&&(h=f.hex),h)break}let c;for(let g of Object.keys(i))if((g.includes("border")||g.includes("divider")||g.includes("separator"))&&(c=o(i[g]),c))break;if(!c){let g=a.match(/[Bb]order[^`]*`(#[0-9a-fA-F]{6})`/);g&&(c=g[1])}return s&&$r(s)<10&&(s=void 0),!s&&!d&&!u?null:{background:d,foreground:u,accent:s,muted:h,border:c}}function Xi(r,e){let t=Qi(e),a=t?.accent??r.colors.find(y=>$r(y)>20)??r.colors[0]??"#6366f1",i=ot(a),n=zr(a),o=t?.background??(r.theme==="light"?"#ffffff":"#0a0a0a"),s=Ut(o),l=s?Et(s.r,s.g,s.b):{h:0,s:0,l:100},d=l.s>3?l.h:0,u=Math.min(l.s,15),h=t?.foreground??"#0f172a",c=t?.muted,g=t?.border,b=Math.min(u,10);return{light:{background:`${d} ${u}% 99%`,foreground:ot(h),card:`${d} ${u}% 100%`,cardForeground:ot(h),muted:c?ot(c):`${d} ${Math.min(u,10)}% 96%`,mutedForeground:`${d} ${Math.min(u,8)}% 45%`,border:g?ot(g):`${d} ${Math.min(u,10)}% 90%`,input:g?ot(g):`${d} ${Math.min(u,10)}% 90%`,ring:i},dark:{background:`${d} ${b}% 4%`,foreground:"0 0% 95%",card:`${d} ${b}% 6%`,cardForeground:"0 0% 95%",muted:`${d} ${Math.min(b,6)}% 16%`,mutedForeground:`${d} ${Math.min(b,6)}% 65%`,border:`${d} ${Math.min(b,6)}% 16%`,input:`${d} ${Math.min(b,6)}% 16%`,ring:i},primary:i,primaryForeground:n>60?"0 0% 5%":"0 0% 100%"}}function Y(r){let e=r.trim().split(/\s+/),t=parseFloat(e[0]),a=parseFloat(e[1])/100,i=parseFloat(e[2])/100,n=a*Math.min(i,1-i),o=E=>{let H=(E+t/30)%12;return i-n*Math.max(-1,Math.min(H-3,9-H,1))},s=o(0),l=o(8),d=o(4),u=E=>E<=.04045?E/12.92:Math.pow((E+.055)/1.055,2.4),h=u(s),c=u(l),g=u(d),b=Math.cbrt(.4122214708*h+.5363325363*c+.0514459929*g),y=Math.cbrt(.2119034982*h+.6806995451*c+.1073969566*g),f=Math.cbrt(.0883024619*h+.2817188376*c+.6299787005*g),v=.2104542553*b+.793617785*y-.0040720468*f,C=1.9779984951*b-2.428592205*y+.4505937099*f,P=.0259040371*b+.7827717662*y-.808675766*f,A=Math.sqrt(C*C+P*P),B=Math.atan2(P,C)*180/Math.PI;B<0&&(B+=360);let I=v.toFixed(4),M=A.toFixed(4),O=A<1e-4?"0":B.toFixed(2);return`${I} ${M} ${O}`}function Zi(r,e){let t=r?.borderRadius??"subtle",a=Ji[t]??"0.375rem",i,n,o,s,l=e?Ie(e):void 0,d=!1;if(l){let c=Xi(l,e);d=l.theme==="dark",i=d?c.dark:c.light,n=d?c.light:c.dark,o=c.primary,s=c.primaryForeground}else{let c=r?.accentColor??"indigo",g=Hr[c]??Hr.indigo;i={background:"0 0% 100%",foreground:"240 10% 4%",card:"0 0% 100%",cardForeground:"240 10% 4%",muted:"240 5% 96%",mutedForeground:"240 4% 46%",border:"240 6% 90%",input:"240 6% 90%",ring:"240 5% 65%"},n={background:"240 10% 4%",foreground:"0 0% 95%",card:"240 10% 6%",cardForeground:"0 0% 95%",muted:"240 4% 16%",mutedForeground:"240 5% 65%",border:"240 4% 16%",input:"240 4% 16%",ring:"240 5% 65%"},o=g.primary,s=g.primaryForeground}let u=[...Object.entries(i).map(([c,g])=>` --color-${Or(c)}: oklch(${Y(g)});`),` --color-primary: oklch(${Y(o)});`,` --color-primary-foreground: oklch(${Y(s)});`,` --color-secondary: oklch(${Y(i.muted)});`,` --color-secondary-foreground: oklch(${Y(i.foreground)});`,` --color-accent: oklch(${Y(i.muted)});`,` --color-accent-foreground: oklch(${Y(i.foreground)});`,` --color-destructive: oklch(${Y(d?"0 72% 51%":"0 84% 60%")});`,` --color-destructive-foreground: oklch(${Y("0 0% 100%")});`,` --color-popover: oklch(${Y(i.card)});`,` --color-popover-foreground: oklch(${Y(i.cardForeground)});`," --radius-sm: 0.25rem;",` --radius-md: ${a};`," --radius-lg: 0.5rem;"," --radius-xl: 0.75rem;"].join(`
|
|
10244
10244
|
`),h="";return l||(h=`
|
|
10245
10245
|
|
|
10246
10246
|
@media (prefers-color-scheme: dark) {
|
|
10247
10247
|
:root {
|
|
10248
|
-
${[...Object.entries(n).map(([g,b])=>` --color-${Or(g)}: oklch(${
|
|
10248
|
+
${[...Object.entries(n).map(([g,b])=>` --color-${Or(g)}: oklch(${Y(b)});`),` --color-primary: oklch(${Y(o)});`,` --color-primary-foreground: oklch(${Y(s)});`,` --color-secondary: oklch(${Y(n.muted)});`,` --color-secondary-foreground: oklch(${Y(n.foreground)});`,` --color-accent: oklch(${Y(n.muted)});`,` --color-accent-foreground: oklch(${Y(n.foreground)});`,` --color-destructive: oklch(${Y("0 72% 51%")});`,` --color-destructive-foreground: oklch(${Y("0 0% 100%")});`,` --color-popover: oklch(${Y(n.card)});`,` --color-popover-foreground: oklch(${Y(n.cardForeground)});`].join(`
|
|
10249
10249
|
`)}
|
|
10250
10250
|
}
|
|
10251
10251
|
}`),`@import "tailwindcss";
|
|
@@ -10365,7 +10365,7 @@ export default function RootLayout({ children }: { children: React.ReactNode })
|
|
|
10365
10365
|
</html>
|
|
10366
10366
|
);
|
|
10367
10367
|
}
|
|
10368
|
-
`}function Lt(r,...e){let t=JSON.stringify(r).toLowerCase();return e.some(a=>t.includes(a.toLowerCase()))}var rn={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 ba(r){let e=r.toLowerCase().replace(/[^a-z]/g,"");for(let[t,a]of Object.entries(rn))if(e.includes(t))return a;return"Circle"}function mt(r){return r.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function on(r){if(r.authModel==="none")return null;let e=["/login","/register","/api/auth","/api/health","/api/webhooks"];if(r.publicPages&&Array.isArray(r.publicPages))for(let n of r.publicPages){if(typeof n!="string"||n.length<1)continue;let o=n.replace(/[\u201C\u201D\u201E\u201F\u2018\u2019\u2033\u2036]/g,"").trim();if(!o)continue;let s=o.startsWith("/")?o:"/"+o;e.includes(s)||e.push(s)}let t=e.filter(n=>n==="/"),a=e.filter(n=>n!=="/"),i=[];i.push('import { NextRequest, NextResponse } from "next/server";'),i.push(""),i.push("const PUBLIC_PREFIXES = [");for(let n of a)i.push(' "'+n+'",');return i.push("];"),i.push(""),t.length>0&&(i.push('const PUBLIC_EXACT = ["'+t.join('", "')+'"];'),i.push("")),i.push("export function middleware(req: NextRequest) {"),i.push(" const { pathname } = req.nextUrl;"),i.push(""),t.length>0&&i.push(" if (PUBLIC_EXACT.includes(pathname)) return NextResponse.next();"),i.push(" if (PUBLIC_PREFIXES.some((p) => pathname.startsWith(p))) return NextResponse.next();"),i.push(""),i.push(' const token = req.cookies.get("better-auth.session_token")?.value || req.cookies.get("__Secure-better-auth.session_token")?.value;'),i.push(" if (!token) {"),i.push(' return NextResponse.redirect(new URL("/login", req.url));'),i.push(" }"),i.push(""),i.push(" return NextResponse.next();"),i.push("}"),i.push(""),i.push("export const config = {"),i.push(' matcher: ["/((?!_next|static|favicon\\\\.ico).*)"],'),i.push("};"),i.push(""),i.join(`
|
|
10368
|
+
`}function Lt(r,...e){let t=JSON.stringify(r).toLowerCase();return e.some(a=>t.includes(a.toLowerCase()))}var rn={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 ba(r){let e=r.toLowerCase().replace(/[^a-z]/g,"");for(let[t,a]of Object.entries(rn))if(e.includes(t))return a;return"Circle"}function mt(r){return r.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function on(r){if(r.authModel==="none")return null;let e=["/login","/register","/api/auth","/api/health","/api/webhooks","/api/admin/seed"];if(r.publicPages&&Array.isArray(r.publicPages))for(let n of r.publicPages){if(typeof n!="string"||n.length<1)continue;let o=n.replace(/[\u201C\u201D\u201E\u201F\u2018\u2019\u2033\u2036]/g,"").trim();if(!o)continue;let s=o.startsWith("/")?o:"/"+o;e.includes(s)||e.push(s)}let t=e.filter(n=>n==="/"),a=e.filter(n=>n!=="/"),i=[];i.push('import { NextRequest, NextResponse } from "next/server";'),i.push(""),i.push("const PUBLIC_PREFIXES = [");for(let n of a)i.push(' "'+n+'",');return i.push("];"),i.push(""),t.length>0&&(i.push('const PUBLIC_EXACT = ["'+t.join('", "')+'"];'),i.push("")),i.push("export function middleware(req: NextRequest) {"),i.push(" const { pathname } = req.nextUrl;"),i.push(""),t.length>0&&i.push(" if (PUBLIC_EXACT.includes(pathname)) return NextResponse.next();"),i.push(" if (PUBLIC_PREFIXES.some((p) => pathname.startsWith(p))) return NextResponse.next();"),i.push(""),i.push(' const token = req.cookies.get("better-auth.session_token")?.value || req.cookies.get("__Secure-better-auth.session_token")?.value;'),i.push(" if (!token) {"),i.push(' return NextResponse.redirect(new URL("/login", req.url));'),i.push(" }"),i.push(""),i.push(" return NextResponse.next();"),i.push("}"),i.push(""),i.push("export const config = {"),i.push(' matcher: ["/((?!_next|static|favicon\\\\.ico).*)"],'),i.push("};"),i.push(""),i.join(`
|
|
10369
10369
|
`)}function nn(r){if(r.navStyle==="none")return null;let e=["/api","/login","/register","/sign-in","/sign-up","/admin"],a=(r.pages??[]).filter(l=>{let d=l.path??l.route??"";return d==="/"||d===""||d.includes("[")||d.replace(/^\//,"").split("/").length>1?!1:!e.some(h=>d.startsWith(h))}).map(l=>{let d=l.path??l.route??"",u=d.startsWith("/")?d:"/"+d,h=l.name??mt(d.replace(/^\//,"")),c=ba(h);return{label:h,href:u,icon:c}});a.some(l=>l.href==="/dashboard")||a.unshift({label:"Dashboard",href:"/dashboard",icon:"Home"});let i=r.authModel==="none",n=[...new Set(a.map(l=>l.icon))];i||n.push("LogOut");let o=mt(r.name);if(r.navStyle==="topbar"){let l=[];l.push('"use client";'),l.push(""),l.push('import Link from "next/link";'),l.push('import { usePathname } from "next/navigation";'),i||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 { "+n.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 d of a)l.push(' { label: "'+d.label+'", href: "'+d.href+'", icon: '+d.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">'+o+"</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>"),i?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(`
|
|
10370
10370
|
`)}}let s=[];s.push('"use client";'),s.push(""),s.push('import { useState } from "react";'),s.push('import Link from "next/link";'),s.push('import { usePathname } from "next/navigation";'),i||s.push('import { authClient } from "@/lib/auth-client";'),s.push('import { Button } from "@/components/ui/button";'),s.push('import { Sheet, SheetContent, SheetTrigger, SheetTitle } from "@/components/ui/sheet";'),s.push('import { cn } from "@/lib/utils";'),s.push("import { Menu, "+n.join(", ")+' } from "lucide-react";'),s.push(""),s.push("interface SidebarProps {"),s.push(" user: { name: string | null; email: string; role?: string | undefined };"),s.push("}"),s.push(""),s.push("const NAV_ITEMS = [");for(let l of a)s.push(' { label: "'+l.label+'", href: "'+l.href+'", icon: '+l.icon+" },");return s.push("];"),s.push(""),s.push('function NavContent({ pathname, user, onNavigate }: { pathname: string; user: SidebarProps["user"]; onNavigate?: () => void }) {'),s.push(" return ("),s.push(" <>"),s.push(' <div className="flex h-14 items-center border-b px-4">'),s.push(' <span className="text-lg font-semibold">'+o+"</span>"),s.push(" </div>"),s.push(' <nav className="flex-1 space-y-1 p-2">'),s.push(" {NAV_ITEMS.map((item) => ("),s.push(" <Link"),s.push(" key={item.href}"),s.push(" href={item.href}"),s.push(" onClick={onNavigate}"),s.push(' aria-current={pathname === item.href ? "page" : undefined}'),s.push(" className={cn("),s.push(' "flex items-center gap-3 rounded-md px-3 py-2.5 text-sm font-medium transition-colors",'),s.push(' pathname === item.href ? "bg-primary/10 text-primary" : "text-muted-foreground hover:bg-muted hover:text-foreground"'),s.push(" )}"),s.push(" >"),s.push(' <item.icon className="h-4 w-4" />'),s.push(" {item.label}"),s.push(" </Link>"),s.push(" ))}"),s.push(" </nav>"),s.push(' <div className="border-t p-4">'),s.push(' <div className="flex items-center gap-3">'),s.push(' <div className="flex-1 truncate">'),s.push(' <p className="truncate text-sm font-medium">{user.name ?? "User"}</p>'),s.push(' <p className="truncate text-xs text-muted-foreground">{user.email}</p>'),s.push(" </div>"),i||(s.push(" <Button"),s.push(' variant="ghost"'),s.push(' size="icon"'),s.push(' onClick={() => authClient.signOut({ fetchOptions: { onSuccess: () => { window.location.href = "/login"; } } })}'),s.push(" >"),s.push(' <LogOut className="h-4 w-4" />'),s.push(" </Button>")),s.push(" </div>"),s.push(" </div>"),s.push(" </>"),s.push(" );"),s.push("}"),s.push(""),s.push("export default function Sidebar({ user }: SidebarProps) {"),s.push(" const pathname = usePathname();"),s.push(" const [open, setOpen] = useState(false);"),s.push(""),s.push(" return ("),s.push(" <>"),s.push(' <aside className="hidden md:flex h-screen w-64 flex-col border-r bg-card">'),s.push(" <NavContent pathname={pathname} user={user} />"),s.push(" </aside>"),s.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">'),s.push(" <Sheet open={open} onOpenChange={setOpen}>"),s.push(" <SheetTrigger asChild>"),s.push(' <Button variant="ghost" size="icon" className="-ml-2">'),s.push(' <Menu className="h-5 w-5" />'),s.push(" </Button>"),s.push(" </SheetTrigger>"),s.push(' <SheetContent side="left" className="w-64 p-0">'),s.push(' <SheetTitle className="sr-only">Navigation</SheetTitle>'),s.push(' <div className="flex h-full flex-col">'),s.push(" <NavContent pathname={pathname} user={user} onNavigate={() => setOpen(false)} />"),s.push(" </div>"),s.push(" </SheetContent>"),s.push(" </Sheet>"),s.push(' <span className="text-lg font-semibold">'+o+"</span>"),s.push(" </div>"),s.push(" </>"),s.push(" );"),s.push("}"),s.push(""),{path:"components/sidebar.tsx",content:s.join(`
|
|
10371
10371
|
`)}}function sn(r){if(!r.roles||r.roles.length===0)return null;let e=r.roles,t=r.defaultRole??e[0],a=[];a.push("export type Role = "+e.map(i=>'"'+i+'"').join(" | ")+";"),a.push(""),a.push("export const ROLES = ["+e.map(i=>'"'+i+'"').join(", ")+"] as const;"),a.push(""),a.push('export const DEFAULT_ROLE: Role = "'+t+'";'),a.push(""),a.push("export const ROLE_LABELS: Record<Role, string> = {");for(let i of e){let n=i.charAt(0).toUpperCase()+i.slice(1);a.push(' "'+i+'": "'+n+'",')}return a.push("};"),a.push(""),a.push("export function getUserRole(user: Record<string, unknown>): Role {"),a.push(" const role = (user.role as string) ?? DEFAULT_ROLE;"),a.push(" if (ROLES.includes(role as Role)) return role as Role;"),a.push(" return DEFAULT_ROLE;"),a.push("}"),a.push(""),a.push("export function hasRole(userRole: string | undefined, required: Role | Role[]): boolean {"),a.push(" if (!userRole) return false;"),a.push(" const allowed = Array.isArray(required) ? required : [required];"),a.push(" return allowed.includes(userRole as Role);"),a.push("}"),a.push(""),a.join(`
|
|
@@ -10379,50 +10379,50 @@ export default function RootLayout({ children }: { children: React.ReactNode })
|
|
|
10379
10379
|
`)}function un(r){if(!r.multiTenant)return null;let e=[];return e.push('import { db } from "./db";'),e.push('import { organization, orgMember } from "@/db/schema/organization";'),e.push('import { eq } from "drizzle-orm";'),e.push(""),e.push("export async function getCurrentOrg(userId: string) {"),e.push(" const membership = await db"),e.push(" .select()"),e.push(" .from(orgMember)"),e.push(" .where(eq(orgMember.userId, userId))"),e.push(" .limit(1);"),e.push(" if (membership.length === 0) return null;"),e.push(" const org = await db"),e.push(" .select()"),e.push(" .from(organization)"),e.push(" .where(eq(organization.id, membership[0].orgId))"),e.push(" .limit(1);"),e.push(" return org[0] ?? null;"),e.push("}"),e.push(""),e.push("export async function getOrgMembers(orgId: string) {"),e.push(" return db"),e.push(" .select()"),e.push(" .from(orgMember)"),e.push(" .where(eq(orgMember.orgId, orgId));"),e.push("}"),e.push(""),e.push("export async function inviteToOrg(orgId: string, email: string, role: string) {"),e.push(" const id = crypto.randomUUID();"),e.push(" await db.insert(orgMember).values({"),e.push(" id,"),e.push(" orgId,"),e.push(" userId: email,"),e.push(" role,"),e.push(" });"),e.push(" return { id, orgId, email, role };"),e.push("}"),e.push(""),e.join(`
|
|
10380
10380
|
`)}function hn(r){if(!r.multiTenant)return null;let e=[];return e.push('"use client";'),e.push(""),e.push("import {"),e.push(" DropdownMenu,"),e.push(" DropdownMenuContent,"),e.push(" DropdownMenuItem,"),e.push(" DropdownMenuTrigger,"),e.push('} from "@/components/ui/dropdown-menu";'),e.push('import { Button } from "@/components/ui/button";'),e.push('import { ChevronsUpDown } from "lucide-react";'),e.push(""),e.push("interface OrgSwitcherProps {"),e.push(" orgs: Array<{ id: string; name: string }>;"),e.push(" currentOrgId: string;"),e.push("}"),e.push(""),e.push("export default function OrgSwitcher({ orgs, currentOrgId }: OrgSwitcherProps) {"),e.push(" const currentOrg = orgs.find((o) => o.id === currentOrgId);"),e.push(""),e.push(" return ("),e.push(" <DropdownMenu>"),e.push(" <DropdownMenuTrigger asChild>"),e.push(' <Button variant="outline" className="w-full justify-between">'),e.push(' <span className="truncate">{currentOrg?.name ?? "Select org"}</span>'),e.push(' <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />'),e.push(" </Button>"),e.push(" </DropdownMenuTrigger>"),e.push(' <DropdownMenuContent className="w-56">'),e.push(" {orgs.map((org) => ("),e.push(" <DropdownMenuItem key={org.id}>"),e.push(" {org.name}"),e.push(" </DropdownMenuItem>"),e.push(" ))}"),e.push(" </DropdownMenuContent>"),e.push(" </DropdownMenu>"),e.push(" );"),e.push("}"),e.push(""),e.join(`
|
|
10381
10381
|
`)}function gn(r,e,t){let a=[],i=r.split("-").map(l=>l.charAt(0).toUpperCase()+l.slice(1)).join(" ");a.push(`# ${i}`),a.push(""),e?.summary&&(a.push(e.summary),a.push(""));let n=e?.features??[];if(n.length>0){a.push("## Features"),a.push("");for(let l of n){let d=l.description?` \u2014 ${l.description}`:"";a.push(`- **${l.name}**${d}`)}a.push("")}a.push("## Tech Stack"),a.push(""),a.push("| Layer | Technology |"),a.push("|-------|------------|"),a.push("| Framework | Next.js 15 (App Router) |"),a.push("| Database | Mistflow Cloud (Postgres) + Drizzle ORM |"),a.push("| Auth | Better Auth (email/password, social login) |"),a.push("| Styling | Tailwind CSS + shadcn/ui |"),a.push("| Deployment | Mistflow Cloud |"),t.hasStripe&&a.push("| Payments | Stripe |"),t.hasResend&&a.push("| Email | Resend + React Email |"),t.hasStorage&&a.push("| File Storage | Mistflow Cloud (managed blob storage) |"),t.hasAdmin&&a.push("| Admin | Better Auth admin plugin |"),t.hasAI&&a.push("| AI | Vercel AI SDK + OpenAI |"),a.push("");let o=e?.pages??[];if(o.length>0){a.push("## Pages"),a.push(""),a.push("| Route | Description |"),a.push("|-------|-------------|");for(let l of o){let d=l.path??l.route??l.name??"",u=l.description??"";a.push(`| \`${d.startsWith("/")?d:"/"+d}\` | ${u} |`)}a.push("")}let s=e?.dataModel??[];if(s.length>0){a.push("## Data Model"),a.push("");for(let l of s){let d=l.entity??l.name??"Unknown";if(a.push(`### ${d}`),a.push(""),l.fields.length>0){if(typeof l.fields[0]=="string")a.push(`Fields: ${l.fields.join(", ")}`);else{a.push("| Field | Type |"),a.push("|-------|------|");for(let u of l.fields)a.push(`| ${u.name} | ${u.type} |`)}a.push("")}}}return a.push("## Getting Started"),a.push(""),a.push("### Prerequisites"),a.push(""),a.push("- Node.js 20+"),a.push("- npm"),a.push(""),a.push("### Install"),a.push(""),a.push("```bash"),a.push("npm install"),a.push("```"),a.push(""),a.push("### Set up environment"),a.push(""),a.push("Copy `.env.example` to `.env.local` and fill in the values:"),a.push(""),a.push("```bash"),a.push("cp .env.example .env.local"),a.push("```"),a.push(""),a.push("| Variable | Description | Required |"),a.push("|----------|-------------|----------|"),t.isNeon?a.push("| `DATABASE_URL` | Postgres connection URL | Yes |"):(a.push("| `TURSO_URL` | Database connection URL | Yes |"),a.push("| `TURSO_AUTH_TOKEN` | Database auth token | Yes |")),a.push("| `AUTH_SECRET` | Auth encryption secret (auto-generated) | Yes |"),t.hasStripe&&(a.push("| `STRIPE_SECRET_KEY` | Stripe secret key | Yes |"),a.push("| `STRIPE_WEBHOOK_SECRET` | Stripe webhook signing secret | Yes |"),a.push("| `NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY` | Stripe publishable key | Yes |")),t.hasResend&&(a.push("| `RESEND_API_KEY` | Resend API key | Yes |"),a.push("| `EMAIL_FROM` | Sender email address | Yes (production) |")),t.hasStorage&&(a.push("| `MISTFLOW_API_KEY` | Mistflow API key for file storage | Yes |"),a.push("| `MISTFLOW_PROJECT_ID` | Mistflow project ID | Yes |")),t.hasAI&&a.push("| `OPENAI_API_KEY` | OpenAI API key | Yes |"),a.push(""),a.push("### Local database"),a.push(""),t.isNeon?(a.push("For local development, start a local Postgres server:"),a.push(""),a.push("```bash"),a.push("# Using Docker:"),a.push("docker run -d --name postgres -e POSTGRES_PASSWORD=postgres -p 5432:5432 postgres:17"),a.push("# Or install via Homebrew: brew install postgresql@17 && brew services start postgresql@17"),a.push("```")):(a.push("For local development, start a local Turso server:"),a.push(""),a.push("```bash"),a.push("npx turso dev"),a.push("```")),a.push(""),a.push("Then set up the database:"),a.push(""),a.push("```bash"),a.push("npm run db:push"),a.push("```"),a.push(""),a.push("### Run"),a.push(""),a.push("```bash"),a.push("npm run dev"),a.push("```"),a.push(""),a.push("Open [http://localhost:3000](http://localhost:3000)."),a.push(""),a.push("## Project Structure"),a.push(""),a.push("```"),a.push("app/"),a.push(" (auth)/ Login and registration pages"),a.push(" (dashboard)/ Authenticated app pages"),t.hasAdmin&&a.push(" (admin)/ Admin panel pages"),a.push(" api/ API routes (auth, health, webhooks)"),a.push(" layout.tsx Root layout with fonts and providers"),a.push(" globals.css Design tokens and Tailwind config"),a.push("components/ Reusable UI components"),a.push("db/"),a.push(" schema/ Database table definitions"),a.push(" index.ts Schema exports"),a.push("lib/"),a.push(" auth.ts Better Auth server config"),a.push(" auth-client.ts Better Auth client config"),a.push(` db.ts ${t.isNeon?"Postgres":"SQLite"} database connection`),t.hasStripe&&a.push(" stripe.ts Stripe client"),t.hasResend&&(a.push(" resend.ts Resend client"),a.push(" email.ts Email send helpers")),t.hasStorage&&a.push(" storage.ts File upload/download helpers"),t.hasAI&&a.push(" ai.ts AI client (Vercel AI SDK + OpenAI)"),t.hasResend&&a.push("emails/ React Email templates"),a.push("```"),a.push(""),a.push("## Deploy"),a.push(""),a.push("Deploy to production with Mistflow:"),a.push(""),a.push("```"),a.push("# In your AI editor (Claude Code, Cursor, etc.):"),a.push("mist_deploy action='deploy'"),a.push("```"),a.push(""),a.push("Your app will be live at `https://<app-name>.mistflow.app`."),a.push(""),e?.design&&(a.push("## Design"),a.push(""),e.design.tone&&a.push(`- **Tone**: ${e.design.tone}`),e.design.fonts&&(a.push(`- **Heading font**: ${e.design.fonts.heading}`),a.push(`- **Body font**: ${e.design.fonts.body}`)),e.design.accentColor&&a.push(`- **Accent color**: ${e.design.accentColor}`),e.design.borderRadius&&a.push(`- **Border radius**: ${e.design.borderRadius}`),a.push("")),a.push("---"),a.push(""),a.push("Built with [Mistflow](https://mistflow.ai)"),a.push(""),a.join(`
|
|
10382
|
-
`)}async function Vr(r){let{name:e,plan:t,path:a,planId:i}=r;if(!a)return p("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(!_r(a))return p(`mist_build init 'path' must be an absolute path \u2014 received '${a}'. Pass the full absolute path to the target directory.`,!0);let n=ya(a),o=t?.design,s=t?.appStyle;if(s&&o){let m=Ie(s);if(m?.fonts){let x=S=>Cr[S]??S;o.fonts={heading:x(m.fonts.heading),body:x(m.fonts.body)}}}let l=t?Lt(t,"stripe","payment","billing","subscription","checkout","pricing"):!1,d=!0,u=t?Lt(t,"upload","file storage","image upload","profile picture","attachment","gallery","media","blob"):!1,h=t?Lt(t,"admin panel","admin dashboard","admin management"):!1,c=t?Lt(t,"ai integration","openai","llm","ai chat","chatbot","gpt"):!1,g=t,b=!0;if(Me(n))return p(`A project already exists at this location (${n}). Choose a different name, or delete the existing folder first.`,!0);Nt(n,{recursive:!0});try{let m=X(gt(n),".mistflow","mockups");if(Me(m)){let x=$i(m).filter(S=>S.endsWith(".html"));if(x.length>0){let S=X(n,".mistflow","mockups");Nt(S,{recursive:!0});for(let
|
|
10382
|
+
`)}async function Vr(r){let{name:e,plan:t,path:a,planId:i}=r;if(!a)return p("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(!_r(a))return p(`mist_build init 'path' must be an absolute path \u2014 received '${a}'. Pass the full absolute path to the target directory.`,!0);let n=ya(a),o=t?.design,s=t?.appStyle;if(s&&o){let m=Ie(s);if(m?.fonts){let x=S=>Cr[S]??S;o.fonts={heading:x(m.fonts.heading),body:x(m.fonts.body)}}}let l=t?Lt(t,"stripe","payment","billing","subscription","checkout","pricing"):!1,d=!0,u=t?Lt(t,"upload","file storage","image upload","profile picture","attachment","gallery","media","blob"):!1,h=t?Lt(t,"admin panel","admin dashboard","admin management"):!1,c=t?Lt(t,"ai integration","openai","llm","ai chat","chatbot","gpt"):!1,g=t,b=!0;if(Me(n))return p(`A project already exists at this location (${n}). Choose a different name, or delete the existing folder first.`,!0);Nt(n,{recursive:!0});try{let m=X(gt(n),".mistflow","mockups");if(Me(m)){let x=$i(m).filter(S=>S.endsWith(".html"));if(x.length>0){let S=X(n,".mistflow","mockups");Nt(S,{recursive:!0});for(let G of x)Vi(X(m,G),X(S,G));console.error(`Copied ${x.length} mockup file(s) into project`)}}}catch(m){console.error("Could not copy mockup files:",m instanceof Error?m.message:m)}let y=null;try{y=await Dt("nextjs")}catch(m){console.error("Could not fetch scaffold from API, using minimal scaffold:",m instanceof Error?m.message:m)}if(y){let m=e.toLowerCase().replace(/[^a-z0-9-]/g,"-");for(let D of y.files){if(D.path==="package.json"||D.path==="middleware.ts"||D.path==="components/sidebar.tsx"||D.path==="components/topnav.tsx"||D.path==="app/(dashboard)/layout.tsx"||D.path==="app/(dashboard)/page.tsx"||D.path==="app/(dashboard)/dashboard/page.tsx"||!l&&(D.path.includes("stripe")||D.path.includes("webhook/stripe"))||!d&&(D.path.includes("resend")||D.path.includes("emails/"))||!h&&(D.path.includes("(admin)")||D.path.includes("admin-sidebar"))||b&&(D.path==="lib/db.ts"||D.path==="lib/auth.ts"||D.path==="drizzle.config.ts"||D.path==="db/schema/auth.ts"))continue;let j=D.content.replace(/\{\{APP_NAME\}\}/g,e).replace(/\{\{WORKER_NAME\}\}/g,m);if(b&&D.path==="next.config.ts"&&(j=j.replace(/serverExternalPackages:\s*\[[^\]]*\],?/g,'serverExternalPackages: ["@electric-sql/pglite"],')),D.path==="next.config.ts"){let ue=Yi(n);ue&&(console.error(`[init] Project is inside monorepo at ${ue} \u2014 adding outputFileTracingRoot`),j.includes("outputFileTracingRoot")||(j=j.replace('import type { NextConfig } from "next";',`import type { NextConfig } from "next";
|
|
10383
10383
|
import { dirname } from "path";
|
|
10384
10384
|
import { fileURLToPath } from "url";
|
|
10385
10385
|
|
|
10386
|
-
const __dirname = dirname(fileURLToPath(import.meta.url));`),
|
|
10387
|
-
images: {`)))}!h&&D.path.includes("sidebar")&&(
|
|
10386
|
+
const __dirname = dirname(fileURLToPath(import.meta.url));`),j=j.replace("images: {",`outputFileTracingRoot: __dirname,
|
|
10387
|
+
images: {`)))}!h&&D.path.includes("sidebar")&&(j=j.replace(/\{user\.role === "admin"[\s\S]*?<\/Link>\s*\)\}/m,""),j=j.replace(/, Shield/g,"")),W(n,D.path,j)}let x={...y.dependencies};b&&(delete x["@libsql/client"],x["@neondatabase/serverless"]="^0.10.0",x["@electric-sql/pglite"]="^0.2.0"),l&&(x.stripe="^17.0.0"),d&&(x.resend="^4.0.0",x["@react-email/components"]="^0.0.31"),c&&(x.ai="^4.0.0",x["@ai-sdk/openai"]="^1.0.0",x.openai="^4.0.0");let S={"@noble/ciphers":"^1.3.0"},G={react:"19.1.0","react-dom":"19.1.0",punycode:"^2.3.1"};if(W(n,"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:x,devDependencies:y.devDependencies,optionalDependencies:S,overrides:G},null,2)),y.methodology){let D=y.methodology;b&&(D=D.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")),W(n,"AGENTS.md",D),W(n,"CLAUDE.md",D)}b&&(W(n,"lib/db.ts",['import { neon } from "@neondatabase/serverless";','import { drizzle as drizzleNeon } from "drizzle-orm/neon-http";','import { drizzle as drizzlePglite } from "drizzle-orm/pglite";',"","// 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)"," // eslint-disable-next-line @typescript-eslint/no-require-imports",' const { PGlite } = require("@electric-sql/pglite");',' const client = new PGlite("./local.pg");'," _db = drizzlePglite(client);"," }"," }"," 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(`
|
|
10388
10388
|
`)),W(n,"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(`
|
|
10389
10389
|
`)),W(n,"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(`
|
|
10390
|
-
`)),W(n,"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";',"",
|
|
10391
|
-
`)))}else W(n,"package.json",JSON.stringify({name:e,version:"0.1.0",private:!0},null,2));W(n,"app/globals.css",Zi(o,s)),W(n,"app/layout.tsx",an(e,o,g?.language)),W(n,"README.md",gn(e,t,{hasStripe:l,hasResend:d,hasStorage:u,hasAdmin:h,hasAI:c,isNeon:b}));let f=[],v=t?.publicPages;if(Array.isArray(v))f=v;else if(typeof v=="string"){try{f=JSON.parse(v)}catch{f=[]}Array.isArray(f)||(f=[])}if(!f.includes("/")){let m=t?.steps?.some(S=>{let
|
|
10390
|
+
`)),W(n,"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 }: { to: string; subject: string; html: string }) {"," const apiKey = process.env.RESEND_API_KEY;"," if (!apiKey) {",' console.error("[auth] RESEND_API_KEY not set \u2014 skipping email send");'," return;"," }",' const from = process.env.EMAIL_FROM || "noreply@mail.mistflow.app";'," console.log(`[auth] Sending email to ${to} from ${from}`);",' 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}`);"," } else {"," console.log(`[auth] Email sent successfully to ${to}`);"," }","}","","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);"," if (!isLocal && !canSendEmail) {",' console.error("[auth] RESEND_API_KEY not set \u2014 disabling email verification to avoid telling users to check an inbox that will stay empty");'," }"," return betterAuth({"," baseURL,"," trustedOrigins: [baseURL],",' database: drizzleAdapter(db, { provider: "pg", schema }),'," emailAndPassword: {"," enabled: true,"," requireEmailVerification: !isLocal && canSendEmail,"," sendResetPassword: async ({ user, url }: { user: { email: string; name: string }; url: string }) => {"," 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="${url}">${url}</a></p>`,'," });"," },"," },"," emailVerification: {"," sendOnSignUp: canSendEmail,"," 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>`,'," });"," },"," },"," secret: process.env.AUTH_SECRET,",' plugins: [admin({ defaultRole: "user" }), nextCookies()],'," 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(`
|
|
10391
|
+
`)))}else W(n,"package.json",JSON.stringify({name:e,version:"0.1.0",private:!0},null,2));W(n,"app/globals.css",Zi(o,s)),W(n,"app/layout.tsx",an(e,o,g?.language)),W(n,"README.md",gn(e,t,{hasStripe:l,hasResend:d,hasStorage:u,hasAdmin:h,hasAI:c,isNeon:b}));let f=[],v=t?.publicPages;if(Array.isArray(v))f=v;else if(typeof v=="string"){try{f=JSON.parse(v)}catch{f=[]}Array.isArray(f)||(f=[])}if(!f.includes("/")){let m=t?.steps?.some(S=>{let G=((S.name??"")+" "+(S.description??"")).toLowerCase();return G.includes("landing")||G.includes("marketing")||G.includes("homepage")}),x=t?.pages?.some(S=>S.path==="/");(m||x)&&(f=["/",...f])}let C={name:e,summary:t?.summary,authModel:t?.authModel,roles:t?.roles,defaultRole:t?.defaultRole,publicPages:f,navStyle:t?.navStyle,multiTenant:t?.multiTenant,pages:t?.pages,dataModel:t?.dataModel,design:t?.design},P=on(C);P&&W(n,"middleware.ts",P);let A=nn(C);A&&W(n,A.path,A.content);let B=sn(C);if(B&&W(n,"lib/roles.ts",B),W(n,"app/page.tsx",ln(C)),W(n,"app/(dashboard)/layout.tsx",dn(C,h)),W(n,"app/(dashboard)/dashboard/page.tsx",cn(C)),C.multiTenant){let m=pn(C,b);m&&W(n,"db/schema/organization.ts",m);let x=un(C);x&&W(n,"lib/org.ts",x);let S=hn(C);S&&W(n,"components/org-switcher.tsx",S)}W(n,"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)),l&&W(n,"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(`
|
|
10392
10392
|
`)),d&&(W(n,"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(`
|
|
10393
10393
|
`)),W(n,"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(`
|
|
10394
10394
|
`))),u&&(W(n,"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(`
|
|
10395
10395
|
`)),W(n,"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(`
|
|
10396
10396
|
`))),c&&(W(n,"lib/ai.ts",['import { createOpenAI } from "@ai-sdk/openai";',"","export const openai = createOpenAI({"," apiKey: process.env.OPENAI_API_KEY,","});",""].join(`
|
|
10397
10397
|
`)),W(n,"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(`
|
|
10398
|
-
`)));let I={name:e,methodologyVersion:y?.version??"1.0",createdAt:new Date().toISOString(),...i?{planId:i}:{},plan:Array.isArray(t?.steps)?{...t,steps:t.steps.map(m=>({number:m.number,name:m.name??m.title,description:m.description,entities:m.entities,pages:m.pages,features:m.features,status:"pending"}))}:t,dbProvider:"neon",env:{managed:{DATABASE_URL:{description:"Postgres connection URL",scope:"production"},AUTH_SECRET:{description:"Auth encryption secret",scope:"production"},...l?{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"}}:{},...d?{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"}}:{},...u?{MISTFLOW_API_KEY:{description:"Mistflow API key for file storage",scope:"production"},MISTFLOW_PROJECT_ID:{description:"Mistflow project ID",scope:"production"}}:{}},...c?{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:h,hasResend:d,hasStorage:u,hasAI:c,deploy:null};W(n,"mistflow.json",JSON.stringify(I,null,2));let M=Ki(32).toString("hex"),
|
|
10398
|
+
`)));let I={name:e,methodologyVersion:y?.version??"1.0",createdAt:new Date().toISOString(),...i?{planId:i}:{},plan:Array.isArray(t?.steps)?{...t,steps:t.steps.map(m=>({number:m.number,name:m.name??m.title,description:m.description,entities:m.entities,pages:m.pages,features:m.features,status:"pending"}))}:t,dbProvider:"neon",env:{managed:{DATABASE_URL:{description:"Postgres connection URL",scope:"production"},AUTH_SECRET:{description:"Auth encryption secret",scope:"production"},...l?{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"}}:{},...d?{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"}}:{},...u?{MISTFLOW_API_KEY:{description:"Mistflow API key for file storage",scope:"production"},MISTFLOW_PROJECT_ID:{description:"Mistflow project ID",scope:"production"}}:{}},...c?{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:h,hasResend:d,hasStorage:u,hasAI:c,deploy:null};W(n,"mistflow.json",JSON.stringify(I,null,2));let M=Ki(32).toString("hex"),O=l?`
|
|
10399
10399
|
# Stripe
|
|
10400
10400
|
STRIPE_SECRET_KEY=
|
|
10401
10401
|
STRIPE_WEBHOOK_SECRET=
|
|
10402
10402
|
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=
|
|
10403
10403
|
NEXT_PUBLIC_APP_URL=http://localhost:3000
|
|
10404
|
-
`:"",
|
|
10404
|
+
`:"",E=d?`
|
|
10405
10405
|
# Email (Resend)
|
|
10406
10406
|
RESEND_API_KEY=
|
|
10407
10407
|
EMAIL_FROM=onboarding@resend.dev
|
|
10408
|
-
`:"",
|
|
10408
|
+
`:"",H=u?`
|
|
10409
10409
|
# File Storage (Mistflow managed)
|
|
10410
10410
|
MISTFLOW_API_KEY=
|
|
10411
10411
|
MISTFLOW_PROJECT_ID=
|
|
10412
10412
|
`:"",re=c?`
|
|
10413
10413
|
# AI (get your key at https://platform.openai.com/api-keys)
|
|
10414
10414
|
OPENAI_API_KEY=
|
|
10415
|
-
`:"",
|
|
10415
|
+
`:"",z=`# Local dev: PGlite is used automatically (zero-install embedded Postgres)
|
|
10416
10416
|
# Set DATABASE_URL only for production or to use a remote Postgres
|
|
10417
|
-
# DATABASE_URL=postgresql://postgres:postgres@localhost:5432/devdb`,
|
|
10417
|
+
# DATABASE_URL=postgresql://postgres:postgres@localhost:5432/devdb`,K=`# Local dev: PGlite is used automatically (zero-install embedded Postgres)
|
|
10418
10418
|
# Set DATABASE_URL only for production or to use a remote Postgres
|
|
10419
|
-
# DATABASE_URL=postgresql://postgres:postgres@localhost:5432/devdb`;W(n,".env.local",`${
|
|
10419
|
+
# DATABASE_URL=postgresql://postgres:postgres@localhost:5432/devdb`;W(n,".env.local",`${z}
|
|
10420
10420
|
AUTH_SECRET=${M}
|
|
10421
|
-
${
|
|
10421
|
+
${O}${E}${H}${re}`),W(n,".env.example",`${K}
|
|
10422
10422
|
AUTH_SECRET=your-secret-here
|
|
10423
|
-
${
|
|
10424
|
-
${
|
|
10425
|
-
${w.key}=`});Oe(X(f,".env.local"),
|
|
10423
|
+
${O}${E}${H}${re}`);let U=[],_=(m,x)=>{U.push({phase:m,message:x})},F=(m,x)=>{let S=U.find(G=>G.phase===m&&!G.durationMs);S&&(S.durationMs=x)},Q={NPM_CONFIG_LEGACY_PEER_DEPS:"true"};_("install","Installing packages...");let le=Date.now(),T=0,R=await Ge("npm",["install"],n,12e4,m=>{let x=m.match(/added (\d+) packages/);x&&(T=parseInt(x[1],10))},Q);if(R.success||(console.error("[init] npm install failed, retrying..."),R=await Ge("npm",["install"],n,12e4,m=>{let x=m.match(/added (\d+) packages/);x&&(T=parseInt(x[1],10))},Q)),!R.success)return p(`Project files were created at ${n} but package installation failed after 2 attempts: ${R.error}. Run "npm install" manually to retry.`,!0);F("install",Date.now()-le),U[U.length-1].message=`Installed ${T||"all"} packages`;let L=y?.shadcnComponents??["button","card","input","label","form","dialog","table","dropdown-menu","badge","separator","skeleton","sheet","tabs","avatar","select","textarea","checkbox","switch","tooltip","popover","sonner"];_("ui",`Adding ${L.length} UI components...`);let oe=Date.now(),ie=await Ge("npx",["--yes","shadcn@latest","add","-y","-o",...L],n,12e4,void 0,Q);if(ie.success||(console.error("[init] shadcn install failed, retrying..."),ie=await Ge("npx",["--yes","shadcn@latest","add","-y","-o",...L],n,12e4,void 0,Q)),ie.success)U[U.length-1].message=`Added ${L.length} UI components (Button, Card, Dialog, Table, ...)`;else return p(`Project created at ${n} but UI component installation failed after 2 attempts: ${ie.error}. Run "npx shadcn@latest add -y -o ${L.join(" ")}" manually (set NPM_CONFIG_LEGACY_PEER_DEPS=true if npm complains about peer dependencies) to retry.`,!0);F("ui",Date.now()-oe),_("db","Setting up database...");let w=Date.now(),N,q=await Ge("npx",["drizzle-kit","push"],n,3e4);q.success?U[U.length-1].message="Database ready":(console.error("DB push failed:",q.error),N="Database setup failed \u2014 login won't work yet. Try deploying again. If it keeps failing, contact support.",U[U.length-1].message=b?"Database setup skipped (configure DATABASE_URL to enable)":"Database setup skipped (configure TURSO_URL to enable)"),F("db",Date.now()-w),_("git","Initializing git repository...");let me=Date.now();try{let m=jr(n);await m.init(),await m.add("."),await m.commit("Initial Mistflow project setup"),U[U.length-1].message="Git repository initialized"}catch{console.error("Git initialization failed, continuing without git."),U[U.length-1].message="Git init skipped"}F("git",Date.now()-me);let pe=g?.requestedSubdomain||void 0,Z,xe;try{let m=await Bt(e,void 0,"neon",pe);Z=m.id;let x=X(n,"mistflow.json"),S=JSON.parse(Ft(x,"utf-8"));if(S.projectId=Z,Oe(x,JSON.stringify(S,null,2)),ia(n,na(Z,e)),m.managed_env&&Object.keys(m.managed_env).length>0){let G=X(n,".env.local"),D=Me(G)?Ft(G,"utf-8"):"";for(let[j,ue]of Object.entries(m.managed_env)){let ve=new RegExp(`^${j}=.*$`,"m");ve.test(D)?D=D.replace(ve,`${j}=${ue}`):D+=`
|
|
10424
|
+
${j}=${ue}`}Oe(G,D)}if(Z)try{let{getBaseUrl:G,getAuthHeaders:D}=await import("./api-client-UL3OJVLP.js"),j=D(),ue=t?.features,ve={};Array.isArray(ue)&&ue.length>0&&(ve.features=ue.map(Xe=>Xe.name)),t&&(ve.plan=t),Object.keys(ve).length>0&&await fetch(`${G()}/api/projects/${encodeURIComponent(Z)}/state`,{method:"PUT",headers:{...j,"Content-Type":"application/json"},body:JSON.stringify(ve)})}catch{}}catch(m){let x=m instanceof Error?m.message:String(m);console.error("Could not register project on backend:",x),xe=`Project created locally but NOT registered on Mistflow servers (${x}). Deploy will auto-register it.`}let we=U.reduce((m,x)=>m+(x.durationMs??0),0),de={projectPath:n,projectId:Z},$=U.map(m=>{let x=m.durationMs?` (${(m.durationMs/1e3).toFixed(1)}s)`:"";return`${m.message}${x}`});de.progress=$,de.totalSetupTime=`${(we/1e3).toFixed(1)}s`;let k=[];return N&&k.push(N),Z||k.push("Project was not registered with Mistflow (not signed in). Run mist_setup to sign in BEFORE deploying \u2014 deploy will fail without it."),xe&&(de.registrationWarning=xe),k.length>0&&(de.warnings=k),Z?de.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.":de.nextAction="NEXT: Call mist_build with action='implement' to start building the first plan step. IMPORTANT: You MUST run mist_setup to sign in before deploying \u2014 the project could not be registered because auth is missing.",p(JSON.stringify(de))}async function qr(r){let{name:e,plan:t,projectId:a,sourceDeploymentId:i,forkToken:n,requiredEnvVars:o,dbProvider:s,planId:l}=r;if(!r.path)return p("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(!_r(r.path))return p(`mist_build init 'path' must be an absolute path \u2014 received '${r.path}'. Pass the full absolute path to the target directory.`,!0);let d=ya(r.path);if(Me(d))return p(`A project already exists at this location (${d}). Choose a different name, or delete the existing folder first.`,!0);let{mkdtempSync:u,renameSync:h,rmSync:c,cpSync:g}=await import("fs"),{tmpdir:b}=await import("os"),y=u(X(b(),"mistflow-fork-")),f=X(y,"project");Nt(f,{recursive:!0});let v=[],C=(A,B)=>v.push({phase:A,message:B}),P=(A,B)=>{let I=v.find(M=>M.phase===A);I&&(I.durationMs=B)};try{C("download","Downloading source code from template...");let A=Date.now(),B=X(y,"source.tar.gz");try{await ur(i,n,B)}catch(w){c(y,{recursive:!0,force:!0});let N=w instanceof Error?w.message:"Source download failed";return p(`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)}P("download",Date.now()-A),v[v.length-1].message="Source code downloaded",C("extract","Extracting source code...");let I=Date.now(),M=await Ge("tar",["-xzf",B,"-C",f,"--exclude","node_modules","--exclude",".git"],f,6e4);if(!M.success)return c(y,{recursive:!0,force:!0}),p(`Failed to extract source archive: ${M.error}`,!0);if(P("extract",Date.now()-I),!Me(X(f,"package.json")))return c(y,{recursive:!0,force:!0}),p("Source archive does not contain a package.json. The template may be corrupted.",!0);let O=[".mistflow",".env.local",".env.example","local.db","local.pg"];for(let w of O){let N=X(f,w);Me(N)&&c(N,{recursive:!0,force:!0})}let E={name:e,projectId:a,template:"nextjs",createdAt:new Date().toISOString(),planId:l??void 0,plan:t,dbProvider:s};Oe(X(f,"mistflow.json"),JSON.stringify(E,null,2));let H=o.map(w=>{let N=w.description?`# ${w.description}`:`# ${w.key}`,q=w.setup_url?` (${w.setup_url})`:"";return`${N}${q}
|
|
10425
|
+
${w.key}=`});Oe(X(f,".env.local"),H.join(`
|
|
10426
10426
|
|
|
10427
10427
|
`)+`
|
|
10428
10428
|
`);let re=o.map(w=>`${w.key}=`);Oe(X(f,".env.example"),re.join(`
|
|
@@ -10436,7 +10436,7 @@ Forked from a Mistflow template. Built with Next.js, Drizzle ORM, and Better Aut
|
|
|
10436
10436
|
1. Copy \`.env.example\` to \`.env.local\` and fill in your values
|
|
10437
10437
|
2. Run \`npm run dev\`
|
|
10438
10438
|
3. Deploy with \`mist_deploy\`
|
|
10439
|
-
`),C("setup","Setting up project directory...");let
|
|
10439
|
+
`),C("setup","Setting up project directory...");let z=Date.now();try{h(f,d)}catch(w){if(w.code==="EXDEV")g(f,d,{recursive:!0}),c(f,{recursive:!0,force:!0});else throw w}P("setup",Date.now()-z),C("install","Installing packages...");let K=Date.now(),U=0,_=await Ge("npm",["install"],d,12e4,w=>{let N=w.match(/added (\d+) packages/);N&&(U=parseInt(N[1],10))});if(_.success||(console.error("[initFromSource] npm install failed, retrying..."),_=await Ge("npm",["install"],d,12e4,w=>{let N=w.match(/added (\d+) packages/);N&&(U=parseInt(N[1],10))})),!_.success)return p(`Source code was restored at ${d} but package installation failed: ${_.error}. Run "npm install" manually.`,!0);P("install",Date.now()-K),v[v.length-1].message=`Installed ${U||"all"} packages`,C("git","Initializing git repository...");let F=Date.now();try{let w=jr(d);await w.init(),await w.add("."),await w.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"}P("git",Date.now()-F);try{let{markLocalSetupDone:w}=await import("./api-client-UL3OJVLP.js");await w(a)}catch{console.error("[initFromSource] Could not mark local_setup_done on backend, continuing.")}let Q=JSON.parse(Ft(X(d,"mistflow.json"),"utf-8"));Q.projectId=a,Oe(X(d,"mistflow.json"),JSON.stringify(Q,null,2)),ia(d,na(a,e));let le=t.steps,T=le?.filter(w=>w.status==="completed").length??0,R=le?.filter(w=>w.status==="pending").length??0,L=le?.length??0,oe=o.length>0?`
|
|
10440
10440
|
|
|
10441
10441
|
Environment variables needed:
|
|
10442
10442
|
`+o.map(w=>` \u2022 ${w.key}${w.description?` \u2014 ${w.description}`:""}`).join(`
|
|
@@ -12387,11 +12387,11 @@ Each section is a separate component file. The page.tsx simply imports and stack
|
|
|
12387
12387
|
`)}function Gt(r){return r.entity??r.name??"Unknown"}function jn(r){return r.length===0?"":typeof r[0]=="string"?r.join(", "):r.map(e=>`${e.name} (${e.type})`).join(", ")}function vo(r){return r.path??r.route??r.name??""}function zn(r){let e=(r||"text").toLowerCase();return e==="string"||e==="varchar"||e==="char"?"text":e==="integer"||e==="int"||e==="number"||e==="float"||e==="decimal"||e==="double"?"number":e==="boolean"||e==="bool"?"boolean":e==="date"||e==="datetime"||e==="timestamp"?"date":e==="email"?"email":e==="url"||e==="uri"?"url":e==="enum"||e==="select"?"select":e==="text"||e==="longtext"||e==="textarea"?"textarea":"text"}function ko(r,e){if(!r.entities||r.entities.length===0)return e;let t=r.entities.map(a=>a.toLowerCase());return e.filter(a=>{let i=Gt(a).toLowerCase();return t.some(n=>i.includes(n)||n.includes(i))})}function $n(r,e){if(!r.pages||r.pages.length===0)return[];let t=r.pages.map(a=>a.toLowerCase());return e.filter(a=>{let i=(a.name??"").toLowerCase(),n=vo(a).toLowerCase();return t.some(o=>i.includes(o)||o.includes(i)||n.includes(o))})}function Vn(r){if(r.integrationId)return"integration";let e=`${r.name} ${r.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 qn(r){switch(r){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 Kn(r,e){let t=[];if(t.push("### Design choices (decided at plan time \u2014 follow these exactly):"),r.tone&&t.push(`- **App tone**: ${r.tone}`),r.fonts&&(t.push(`- **Heading font**: ${r.fonts.heading} (load from Google Fonts)`),t.push(`- **Body font**: ${r.fonts.body} (load from Google Fonts)`)),r.accentColor&&t.push(`- **Accent color**: ${r.accentColor} (use for primary buttons, active states, highlights only)`),r.borderRadius){let a={sharp:"2px",subtle:"6px",rounded:"12px",pill:"9999px"};t.push(`- **Border radius**: ${r.borderRadius} (${a[r.borderRadius]??r.borderRadius}) \u2014 set as --radius in globals.css`)}if(r.shadowStyle){let a={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"};t.push(`- **Shadow style**: ${r.shadowStyle} \u2014 ${a[r.shadowStyle]??r.shadowStyle}`)}if(r.cardStyle){let a={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"};t.push(`- **Card style**: ${r.cardStyle} \u2014 ${a[r.cardStyle]??r.cardStyle}`)}if(r.landingTone&&t.push(`- **Landing page tone**: ${r.landingTone}`),r.visualStrategy){let a=r.visualStrategy,i=r.heroPhoto!==!1,n=i&&!!a.heroImages?.length;if(t.push(""),t.push("### Visual strategy:"),n&&a.heroImages&&a.heroImages.length>0){t.push("**Hero image** \u2014 use this Unsplash photo as the landing page hero BACKGROUND:");let o=a.heroImages[0];t.push(`- URL: ${o.url}`),t.push(`- Alt text for img tag: "${o.alt||"Hero image"} \u2014 Photo by ${o.photographer} on Unsplash"`),t.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 i&&!a.heroImages?.length?t.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.'"):i||t.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(a.sectionImages?.length){t.push("**Section images available** \u2014 use these for feature sections, about sections, or testimonial backgrounds (NOT the hero):");for(let o of a.sectionImages)t.push(`- ${o.url} \u2014 alt: "${o.alt||"section image"} \u2014 Photo by ${o.photographer} on Unsplash"`)}(n||a.sectionImages?.length)&&t.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."),t.push(""),t.push("**Hero layout \u2014 split hero with product UI mockup (follow this exactly):**"),t.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."),t.push(""),t.push("```"),t.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"),t.push("\u2502 [Logo] [Sign In] [CTA \u2192] \u2502 \u2190 transparent nav, NOT sticky"),t.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"),t.push("\u2502 \u2502"),t.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"),t.push("\u2502 \u2502 Glassmorphic \u2502 \u2502"),t.push("\u2502 Big bold headline, \u2502 product mockup \u2502 \u2502"),t.push("\u2502 accent color on key word \u2502 card showing \u2502 \u2502"),t.push("\u2502 \u2502 real app data \u2502 \u2502"),t.push("\u2502 Description paragraph \u2502 (stats, table, \u2502 \u2502"),t.push("\u2502 \u2502 chart, etc.) \u2502 \u2502"),t.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"),t.push("\u2502 \u2502"),t.push("\u2502 500+ 25K+ 99% \u2502"),t.push("\u2502 Label Label Label \u2502"),t.push("\u2502 \u2502"),n?t.push("\u2502 \u2190 full-bleed photo bg + dark overlay behind all \u2192 \u2502"):t.push("\u2502 \u2190 preset gradient / glass background behind all \u2192 \u2502"),t.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"),t.push("```"),t.push(""),t.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"),t.push("**Right side (~45%)**: A glassmorphic floating card that previews what the app looks like inside:"),t.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)"),t.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"),t.push("- Must be DOMAIN-SPECIFIC: a library app shows book catalog rows, a gym app shows check-in stats, a CRM shows pipeline cards"),t.push("- Add subtle inner elements with `bg-white/5` or `bg-white/10` for depth"),t.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 t.push(""),t.push(bo),t.join(`
|
|
12388
12388
|
`)}async function Yn(r){try{let e=await lr("nextjs",r);return{reminders:e.reminders,skill:e.skill}}catch{return{reminders:`### ${r} step
|
|
12389
12389
|
- Follow existing patterns in the codebase
|
|
12390
|
-
- Server Components by default, "use client" only when interactivity is needed`,skill:""}}}async function Jn(r,e,t,a,i,n){let o=[];o.push(`## Step ${r.number}: ${r.name}`),o.push(""),o.push("### What to build:"),o.push(r.description),o.push(""),e.primaryAction&&(o.push("### Primary user action (non-negotiable):"),o.push(`- **Core action**: ${e.primaryAction.action}`),o.push(`- **User flow**: ${e.primaryAction.flow}`),o.push(`- **Dashboard must show**: ${e.primaryAction.dashboardSurface}`),o.push(""),o.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."),o.push(""));let l=["landing","design","dashboard","crud","layout","admin","general","auth"].includes(i);if(e.design&&l?(o.push(Kn(e.design,{hasDesignPreset:!!e.landingDesign&&(i==="landing"||i==="design")})),o.push("")):e.design&&!l&&(o.push("### Design tokens (for reference only \u2014 this step is not UI-focused):"),e.design.accentColor&&o.push(`- Accent color: ${e.design.accentColor}`),e.design.fonts&&o.push(`- Fonts: ${e.design.fonts.heading} / ${e.design.fonts.body}`),o.push("")),n){let f=fo(n);if(f.length>0){o.push("### Approved wireframe (MUST READ before writing any files):"),o.push("The user approved a wireframe sketch before building. **Read these files NOW before writing any code for this step:**");for(let v of f){let C=v.replace(n,"").replace(/^\//,"");o.push(`- \`${C}\``)}o.push(""),o.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."),o.push(""),o.push("The wireframe is intentionally rough (grayscale, system fonts). Your job is to:"),o.push("1. **Keep the same layout structure** \u2014 same information hierarchy, same element placement, same sections in the same order"),o.push("2. **Apply the design tokens** \u2014 colors, fonts, shadows, radius from the plan design choices above"),o.push("3. **Elevate the visual quality** \u2014 make it feel designed for THIS specific app, not generic"),o.push("4. **Respect the HTML comments** \u2014 they explain WHY things are placed where they are"),o.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"),o.push("")}}e.roles&&Array.isArray(e.roles)&&e.roles.length>0&&(o.push("### Role system (from plan):"),o.push(`- Roles: ${e.roles.join(", ")}`),o.push(`- Default role for new signups: ${e.defaultRole??e.roles[0]}`),o.push("- Role helpers are in `lib/roles.ts` \u2014 use `getUserRole()` and `hasRole()` for access checks"),o.push("")),e.multiTenant&&(o.push("### Multi-tenant (from plan):"),o.push("- Organization tables are in `db/schema/organization.ts`"),o.push("- Org helpers are in `lib/org.ts` \u2014 use `getCurrentOrg()` to scope queries"),o.push("- All data queries MUST be scoped to the current org (filter by orgId)"),o.push("- Org switcher component is at `components/org-switcher.tsx`"),o.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."),o.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."),o.push("")),e.language&&(o.push(`### Language: ${e.language}`),o.push(`ALL user-facing text must be written in ${e.language}:`),o.push("- Page titles, headings, labels, button text, placeholder text"),o.push("- Navigation items, menu labels, footer text"),o.push("- Error messages, success messages, empty states"),o.push("- Landing page copy, marketing text, CTAs"),o.push("- Form labels and validation messages"),o.push("Code (variable names, comments, file names) stays in English."),o.push(`Set the HTML lang attribute to the appropriate locale code for ${e.language}.`),o.push(""));let d=["landing","design","auth","general","crud","dashboard"];e.audienceType&&d.includes(i)&&(e.audienceType==="b2c"?(o.push("### Audience: this app belongs to ONE business. The landing page talks TO their customers."),o.push("- Hero: what the customer gets ('Exceptional catering for your next event'), NOT what the tool does"),o.push("- CTAs: customer action ('Order Catering', 'Book Now'), NOT business action ('Get Started Free')"),o.push("- Testimonials: from customers ('They catered our wedding'), NOT from business owners"),o.push("- Features: customer benefits ('Specify your dietary needs'), NOT business benefits ('Track preferences')"),o.push("- Stats: social proof for customers ('2,400+ events served'), NOT internal metrics ('$48k revenue')"),o.push("- The business name IS the brand. Say it like a business homepage, not a SaaS onboarding."),o.push("")):e.audienceType==="b2b"?(o.push("### Audience: this is a SaaS platform. The landing page pitches TO business owners."),o.push("- Hero: the business pain + solution ('Catering orders managed in one place')"),o.push("- CTAs: business owner action ('Start Free Trial', 'Get Started')"),o.push("- Testimonials: from business owners who use the platform"),o.push("- Features: business benefits ('Track dietary preferences across all orders')"),o.push("- Stats: platform metrics ('500+ businesses', '50K+ orders processed')"),o.push("")):e.audienceType==="internal"&&(o.push("### Audience: internal staff tool. No marketing copy needed."),o.push("- No landing page. Auth page copy is functional: 'Sign in to continue'."),o.push("- Dashboard focuses on operational efficiency, not onboarding or sales."),o.push(""))),t.length>0&&(o.push("### Already completed:"),t.forEach(f=>o.push(`- ${f}`)),o.push(""));let u=e.dataModel?ko(r,e.dataModel):[];u.length>0&&(o.push("### Data model (from plan):"),u.forEach(f=>{let v=Gt(f),C=jn(f.fields);o.push(`- **${v}**: ${C}`),o.push(` Schema file: \`db/schema/${v.toLowerCase().replace(/\s+/g,"-")}.ts\``)}),o.push(""));let h=e.pages?$n(r,e.pages):[];h.length>0&&(o.push("### Pages to create/update:"),h.forEach(f=>{let v=f.description?` \u2014 ${f.description}`:"";o.push(`- \`${vo(f)}\`${v}`)}),o.push("")),i==="crud"&&u.length>0&&u.forEach(f=>{let v=Gt(f),C=v.toLowerCase().replace(/\s+/g,"-"),P=C.endsWith("s")?C:`${C}s`;o.push(`### Files for ${v} CRUD:`),o.push(`- List page: \`app/(dashboard)/${P}/page.tsx\` (Server Component)`),o.push(`- Detail page: \`app/(dashboard)/${P}/[id]/page.tsx\``),o.push(`- Create page: \`app/(dashboard)/${P}/new/page.tsx\``),o.push(`- Server Actions: \`app/(dashboard)/${P}/actions.ts\``),o.push(`- DataTable columns: \`components/${C}-table-columns.tsx\``),o.push(`- Form: \`components/${C}-form.tsx\``),o.push("")});let c=e.appStyle;if(c&&l){let f=Pr(c,i);if(f){let v=
|
|
12390
|
+
- Server Components by default, "use client" only when interactivity is needed`,skill:""}}}async function Jn(r,e,t,a,i,n){let o=[];o.push(`## Step ${r.number}: ${r.name}`),o.push(""),o.push("### What to build:"),o.push(r.description),o.push(""),e.primaryAction&&(o.push("### Primary user action (non-negotiable):"),o.push(`- **Core action**: ${e.primaryAction.action}`),o.push(`- **User flow**: ${e.primaryAction.flow}`),o.push(`- **Dashboard must show**: ${e.primaryAction.dashboardSurface}`),o.push(""),o.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."),o.push(""));let l=["landing","design","dashboard","crud","layout","admin","general","auth"].includes(i);if(e.design&&l?(o.push(Kn(e.design,{hasDesignPreset:!!e.landingDesign&&(i==="landing"||i==="design")})),o.push("")):e.design&&!l&&(o.push("### Design tokens (for reference only \u2014 this step is not UI-focused):"),e.design.accentColor&&o.push(`- Accent color: ${e.design.accentColor}`),e.design.fonts&&o.push(`- Fonts: ${e.design.fonts.heading} / ${e.design.fonts.body}`),o.push("")),n){let f=fo(n);if(f.length>0){o.push("### Approved wireframe (MUST READ before writing any files):"),o.push("The user approved a wireframe sketch before building. **Read these files NOW before writing any code for this step:**");for(let v of f){let C=v.replace(n,"").replace(/^\//,"");o.push(`- \`${C}\``)}o.push(""),o.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."),o.push(""),o.push("The wireframe is intentionally rough (grayscale, system fonts). Your job is to:"),o.push("1. **Keep the same layout structure** \u2014 same information hierarchy, same element placement, same sections in the same order"),o.push("2. **Apply the design tokens** \u2014 colors, fonts, shadows, radius from the plan design choices above"),o.push("3. **Elevate the visual quality** \u2014 make it feel designed for THIS specific app, not generic"),o.push("4. **Respect the HTML comments** \u2014 they explain WHY things are placed where they are"),o.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"),o.push("")}}e.roles&&Array.isArray(e.roles)&&e.roles.length>0&&(o.push("### Role system (from plan):"),o.push(`- Roles: ${e.roles.join(", ")}`),o.push(`- Default role for new signups: ${e.defaultRole??e.roles[0]}`),o.push("- Role helpers are in `lib/roles.ts` \u2014 use `getUserRole()` and `hasRole()` for access checks"),o.push("")),e.multiTenant&&(o.push("### Multi-tenant (from plan):"),o.push("- Organization tables are in `db/schema/organization.ts`"),o.push("- Org helpers are in `lib/org.ts` \u2014 use `getCurrentOrg()` to scope queries"),o.push("- All data queries MUST be scoped to the current org (filter by orgId)"),o.push("- Org switcher component is at `components/org-switcher.tsx`"),o.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."),o.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."),o.push("")),e.language&&(o.push(`### Language: ${e.language}`),o.push(`ALL user-facing text must be written in ${e.language}:`),o.push("- Page titles, headings, labels, button text, placeholder text"),o.push("- Navigation items, menu labels, footer text"),o.push("- Error messages, success messages, empty states"),o.push("- Landing page copy, marketing text, CTAs"),o.push("- Form labels and validation messages"),o.push("Code (variable names, comments, file names) stays in English."),o.push(`Set the HTML lang attribute to the appropriate locale code for ${e.language}.`),o.push(""));let d=["landing","design","auth","general","crud","dashboard"];e.audienceType&&d.includes(i)&&(e.audienceType==="b2c"?(o.push("### Audience: this app belongs to ONE business. The landing page talks TO their customers."),o.push("- Hero: what the customer gets ('Exceptional catering for your next event'), NOT what the tool does"),o.push("- CTAs: customer action ('Order Catering', 'Book Now'), NOT business action ('Get Started Free')"),o.push("- Testimonials: from customers ('They catered our wedding'), NOT from business owners"),o.push("- Features: customer benefits ('Specify your dietary needs'), NOT business benefits ('Track preferences')"),o.push("- Stats: social proof for customers ('2,400+ events served'), NOT internal metrics ('$48k revenue')"),o.push("- The business name IS the brand. Say it like a business homepage, not a SaaS onboarding."),o.push("")):e.audienceType==="b2b"?(o.push("### Audience: this is a SaaS platform. The landing page pitches TO business owners."),o.push("- Hero: the business pain + solution ('Catering orders managed in one place')"),o.push("- CTAs: business owner action ('Start Free Trial', 'Get Started')"),o.push("- Testimonials: from business owners who use the platform"),o.push("- Features: business benefits ('Track dietary preferences across all orders')"),o.push("- Stats: platform metrics ('500+ businesses', '50K+ orders processed')"),o.push("")):e.audienceType==="internal"&&(o.push("### Audience: internal staff tool. No marketing copy needed."),o.push("- No landing page. Auth page copy is functional: 'Sign in to continue'."),o.push("- Dashboard focuses on operational efficiency, not onboarding or sales."),o.push(""))),t.length>0&&(o.push("### Already completed:"),t.forEach(f=>o.push(`- ${f}`)),o.push(""));let u=e.dataModel?ko(r,e.dataModel):[];u.length>0&&(o.push("### Data model (from plan):"),u.forEach(f=>{let v=Gt(f),C=jn(f.fields);o.push(`- **${v}**: ${C}`),o.push(` Schema file: \`db/schema/${v.toLowerCase().replace(/\s+/g,"-")}.ts\``)}),o.push(""));let h=e.pages?$n(r,e.pages):[];h.length>0&&(o.push("### Pages to create/update:"),h.forEach(f=>{let v=f.description?` \u2014 ${f.description}`:"";o.push(`- \`${vo(f)}\`${v}`)}),o.push("")),i==="crud"&&u.length>0&&u.forEach(f=>{let v=Gt(f),C=v.toLowerCase().replace(/\s+/g,"-"),P=C.endsWith("s")?C:`${C}s`;o.push(`### Files for ${v} CRUD:`),o.push(`- List page: \`app/(dashboard)/${P}/page.tsx\` (Server Component)`),o.push(`- Detail page: \`app/(dashboard)/${P}/[id]/page.tsx\``),o.push(`- Create page: \`app/(dashboard)/${P}/new/page.tsx\``),o.push(`- Server Actions: \`app/(dashboard)/${P}/actions.ts\``),o.push(`- DataTable columns: \`components/${C}-table-columns.tsx\``),o.push(`- Form: \`components/${C}-form.tsx\``),o.push("")});let c=e.appStyle;if(c&&l){let f=Pr(c,i);if(f){let v=fe(c),C=Ie(c);o.push(`### App style: ${v?.name??c}`),o.push(""),o.push(`Applying the **${v?.name}** app style across this app. Follow these design specifications for consistent, brand-quality UI. The app style defines the visual identity (colors, fonts, spacing). All UI elements must use the project's CSS custom properties (--color-primary, --color-background, etc.) and the fonts configured in layout.tsx.`),C?.fonts&&o.push(`
|
|
12391
12391
|
**Fonts**: Use \`${C.fonts.heading}\` for headings and \`${C.fonts.body}\` for body text (Google Fonts equivalents if the originals are proprietary).`),o.push(""),o.push(f),o.push("")}}if(l){let f=lo(e.summary??e.name,{tone:e.design?.tone,audienceType:e.audienceType});if(f){let v=so(f);v&&(o.push(`### App archetype: ${f}`),o.push(""),o.push(`This app matches the **${f}** archetype. Follow these component-level patterns for page composition, cards, navigation, spacing, and motion. `+(c?`The app style (${c}) 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.")),o.push(""),o.push(v),o.push(""))}}if(i==="landing"||i==="design"){o.push(yo),o.push("");let f=e.design?.landingTone;if(f){let v=to(f);v&&(o.push(`### Landing tone: ${f}`),o.push(""),o.push(v),o.push(""))}}let g=r.integrationId?at(r.integrationId):void 0;if(g){let f=rt(g.id);if(o.push("### Integration blueprint (follow this closely):"),o.push(""),o.push(`Using integration: **${g.name}** (${g.category})`),f?.docsUrl&&o.push(`Official docs: ${f.docsUrl}`),f?.envVars?.length){o.push(""),o.push("**Required environment variables:**");for(let v of f.envVars)o.push(`- \`${v.key}\`: ${v.description} \u2014 Get it at ${v.setupUrl}`);o.push(""),o.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.")}f?.packages?.length&&(o.push(""),o.push(`**Packages to install:** \`npm install ${f.packages.join(" ")}\``)),o.push(""),o.push("---"),o.push(g.prompt),o.push("---"),o.push(""),o.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."),o.push("")}let{reminders:b,skill:y}=await Yn(i);return o.push(b),o.push(""),y&&!(i==="landing"&&e.landingDesign==="freeform")&&(o.push(`### ${i} reference:`),o.push(y),o.push("")),o.join(`
|
|
12392
|
-
`)}async function So(r){let{projectPath:e,step:t}=r,a=Hn(e??process.cwd()),i=_n(a);if(!i)return
|
|
12393
|
-
`+
|
|
12394
|
-
`)}
|
|
12392
|
+
`)}async function So(r){let{projectPath:e,step:t}=r,a=Hn(e??process.cwd()),i=_n(a);if(!i)return Te(a);let n=i.plan;if(!n||!n.steps||n.steps.length===0)return p("No project plan found. Start by describing your app idea first \u2014 the AI will create a plan for you.",!0);let o,s=n.steps.find(M=>M.status==="in_progress");if(s){let M=n.steps.findIndex(O=>O.number===s.number);M!==-1&&(n.steps[M].status="completed",o=`Auto-completed step ${s.number} (${s.name})`,xo(a,i))}let l;if(t!==void 0){if(l=n.steps.find(M=>M.number===t),!l)return p(`Step ${t} not found. The plan has ${n.steps.length} steps (numbered ${n.steps[0].number} to ${n.steps[n.steps.length-1].number}).`,!0)}else if(l=n.steps.find(M=>M.status!=="completed"),!l)return p(JSON.stringify({message:"All plan steps are completed!",completedSteps:n.steps.map(M=>M.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 d=n.steps.filter(M=>M.status==="completed").map(M=>`Step ${M.number}: ${M.name}`),{readLocalState:u}=await import("./state-manager-XY6GQEFE.js"),h=u(a),c=Vn(l),g=[];if((c==="crud"||c==="schema")&&n.dataModel&&l.entities&&l.entities.length>0){let M=ko(l,n.dataModel);for(let O of M){let E=Gt(O);try{let H=(O.fields||[]).map(F=>typeof F=="string"?{name:F,type:"text"}:{name:F.name,type:zn(F.type),required:F.required!==!1});if(H.length===0)continue;let re=i.dbProvider==="neon"?"nextjs-neon":"nextjs",z=await dr(re,E,H),K=0,U=0;for(let F of z.files){let Q=Ot(a,F.path);if(Sa(Q)){U++;continue}En(On(Q),{recursive:!0}),Ca(Q,F.content),K++}let _=Ot(a,"db","index.ts");if(Sa(_)){let F=wo(_,"utf-8");F.includes(z.dbExport)||Ca(_,F.trimEnd()+`
|
|
12393
|
+
`+z.dbExport+`
|
|
12394
|
+
`)}K>0?g.push(`${z.entityPascal} CRUD (${K} new files${U>0?`, ${U} existing skipped`:""})`):U>0&&g.push(`${z.entityPascal} CRUD (all ${U} files already exist \u2014 skipped)`)}catch(H){console.error(`Module generation failed for ${E} (non-fatal):`,H instanceof Error?H.message:H)}}}let b=await Jn(l,n,d,null,c,a),y=n.steps.findIndex(M=>M.number===l.number);if(y!==-1&&(i.plan.steps[y].status="in_progress",xo(a,i)),h&&i.projectId){let{syncRemoteState:M}=await import("./state-manager-XY6GQEFE.js");M(i.projectId,h).catch(()=>{})}let f=n.steps.every(M=>M.status==="completed"||M.number===l.number),v;if(f){let M=n.primaryAction?.action??"the core action",O=n.primaryAction?.flow??"sign up \u2192 reach dashboard \u2192 complete primary action";v=`THIS IS THE LAST STEP. Rules for speed:
|
|
12395
12395
|
|
|
12396
12396
|
1. Write ALL files using PARALLEL tool calls \u2014 batch multiple Write/Edit calls in a single message.
|
|
12397
12397
|
2. Do NOT read files you already know (AGENTS.md, CLAUDE.md, mistflow.json, middleware.ts, lib/auth.ts, lib/db.ts).
|
|
@@ -12408,9 +12408,9 @@ Each section is a separate component file. The page.tsx simply imports and stack
|
|
|
12408
12408
|
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).
|
|
12409
12409
|
5. After writing ALL files, call mist_build with action='implement' to move to the next step. The previous step is auto-marked complete \u2014 do NOT call implement twice.`;let C=qn(c),P={stepNumber:l.number,totalSteps:n.steps.length,estimatedMinutes:C,announcement:`Starting step ${l.number} of ${n.steps.length}: ${l.name}. This step usually takes ${C.min}\u2013${C.max} minutes.`},B=JSON.stringify({instruction:b,step:{number:l.number,name:l.name,description:l.description,status:"in_progress"},stepTiming:P,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.",...o?{autoCompleted:o}:{},...g.length>0?{generatedModules:g,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:`${d.length}/${n.steps.length} steps done`,nextAction:v});return await Wn(3e3)?Ee("http://localhost:3000",B):p(B)}import{z as Ta}from"zod";import{resolve as Qn}from"path";import{execFileSync as Xn}from"child_process";var Ic=Ta.object({projectPath:Ta.string().optional().describe("Path to the project directory (default: current working directory)"),buildOutput:Ta.string().optional().describe("Build output to parse (if not provided, runs npm run build)")});function ft(r){let e=[],t=/([^\s(]+)\((\d+),(\d+)\):\s*error\s+(TS\d+):\s*(.+)/g,a;for(;(a=t.exec(r))!==null;){let[,l,d,u,h,c]=a;e.push({file:l,line:parseInt(d,10),column:parseInt(u,10),message:`${h}: ${c}`,humanMessage:`There is a type error in ${l} on line ${d}: ${c}`,suggestion:`Check line ${d} in ${l}. ${h==="TS2345"?"The types of the arguments do not match.":`Fix the ${h} error.`}`})}let i=/(?:Error:\s*)?\.\/([^\s:]+):(\d+):(\d+)\s*\n\s*(.+)/g;for(;(a=i.exec(r))!==null;){let[,l,d,u,h]=a;e.some(c=>c.file===l&&c.line===parseInt(d,10))||e.push({file:l,line:parseInt(d,10),column:parseInt(u,10),message:h,humanMessage:`There is an error in ${l} on line ${d}: ${h.trim()}`,suggestion:`Check line ${d} in ${l} and fix the issue.`})}let n=/Module not found:\s*(?:Error:\s*)?Can't resolve ['"]([^'"]+)['"]\s*(?:in\s*['"]?([^'"]+)['"]?)?/g;for(;(a=n.exec(r))!==null;){let[,l,d]=a;e.push({file:d,message:`Module not found: ${l}`,humanMessage:`The file ${d??"your project"} is trying to import '${l}' which is not installed.`,suggestion:`Run npm install ${l}`})}let o=/Package subpath ['"]([^'"]+)['"] is not defined by "exports" in .*?node_modules\/([^/]+(?:\/[^/]+)?)\//g;for(;(a=o.exec(r))!==null;){let[,l,d]=a;e.push({message:`ERR_PACKAGE_PATH_NOT_EXPORTED: ${d}${l}`,humanMessage:`The package '${d}' does not export the subpath '${l}'. This is usually caused by a version conflict between packages that depend on different major versions of '${d}'.`,suggestion:`Add '${d}' 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 s=/SyntaxError:\s*([^\s:]+):\s*(.+?)\s*\((\d+):(\d+)\)/g;for(;(a=s.exec(r))!==null;){let[,l,d,u,h]=a;e.some(c=>c.file===l&&c.line===parseInt(u,10))||e.push({file:l,line:parseInt(u,10),column:parseInt(h,10),message:`SyntaxError: ${d}`,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 e}async function Co(r){let{projectPath:e,buildOutput:t}=r,a=Qn(e??process.cwd()),i=t??"";if(!t)try{return Xn("npm",["run","build"],{cwd:a,stdio:["pipe","pipe","pipe"],timeout:12e4}),p(JSON.stringify({errors:[],rawOutput:"",message:"Build succeeded with no errors."}))}catch(o){let s=o instanceof Error&&"stderr"in o?String(o.stderr):"",l=o instanceof Error&&"stdout"in o?String(o.stdout):"";i=s+`
|
|
12410
12410
|
`+l}let n=ft(i);return n.length===0?p(JSON.stringify({errors:[],rawOutput:i.slice(0,2e3),message:"Build failed but I could not extract specific errors. Here is the raw output."})):p(JSON.stringify({errors:n,rawOutput:i.slice(0,2e3),message:`Found ${n.length} error${n.length===1?"":"s"} in the build output.`}))}import{existsSync as Zn,readFileSync as es}from"fs";import{join as ts}from"path";function as(r){let e=ts(r,"mistflow.json");if(!Zn(e))return null;try{return JSON.parse(es(e,"utf-8"))}catch{return null}}async function To(r){try{let e=await fetch(r,{redirect:"follow",signal:AbortSignal.timeout(15e3)}),t=await e.text();return{status:e.status,body:t}}catch(e){return{status:0,body:String(e)}}}async function rs(r,e,t){try{let a=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",...t??{}},body:JSON.stringify(e),redirect:"follow",signal:AbortSignal.timeout(15e3)}),i=await a.text(),n;try{n=JSON.parse(i)}catch{}return{status:a.status,json:n}}catch{return{status:0}}}async function Po(r){try{let e=await r.screenshot({type:"png"});return Buffer.from(e).toString("base64")}catch{return}}async function st(r,e,t){let a=[],i=n=>{n.type()==="error"&&a.push(n.text())};r.on("console",i);try{let n=await t(),o=await Po(r);return{name:e,status:n.pass?"pass":"fail",detail:n.detail,fix:n.fix,screenshot:o,consoleErrors:a.length>0?a:void 0}}catch(n){let o=await Po(r);return{name:e,status:"fail",detail:`Unexpected error: ${n instanceof Error?n.message:String(n)}`,screenshot:o,consoleErrors:a.length>0?a:void 0}}finally{r.removeListener("console",i)}}async function Bo(r){let e=r.projectPath??process.cwd(),t=as(e),a=r.url;if(a||(a=t?.deploy?.url),!a)return p("No deploy URL found. Deploy the app first with mist_deploy, then call mist_build action='qa'.",!0);a.startsWith("http")||(a=`https://${a}`);let i=t?.projectId,n=[],o=await To(`${a}/api/health`);if(o.status!==200)return n.push({name:"Health endpoint",status:"fail",detail:`Returns ${o.status}`,fix:"The worker is not running or crashed on startup. Check app/api/health/route.ts exists and the build succeeded."}),Wt(a,n);n.push({name:"Health endpoint",status:"pass",detail:"Returns 200"});let s=await To(`${a}/api/auth/ok`);if(s.status!==200)return n.push({name:"Auth system",status:"fail",detail:`Auth endpoint returns ${s.status}`,fix:"Better Auth is not working. Check lib/auth.ts, lib/db.ts, and that your database env vars are set."}),Wt(a,n);n.push({name:"Auth system",status:"pass",detail:"Better Auth running"});let l,d,u;if(i){let g=await Qa(i);if(g){console.error("[qa] Calling seed endpoint for session token");let b=await rs(`${a}/api/admin/seed`,{token:g.seedToken,email:g.email,password:"QaTemp1!"});b.status===200&&b.json?(l=b.json.sessionToken,d=b.json.email,b.json.seeded?(u=b.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 ${b.status}`)}}if(!l)return n.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."}),Wt(a,n);let h,c;try{let{getIsolatedContext:g,takeScreenshot:b}=await import("./browser-manager-K5BT5YXO.js"),y=await g();h=y.context,c=y.page}catch(g){let b=g instanceof Error?g.message:String(g);return p(JSON.stringify({status:"cannot_verify",url:a,deployed:!0,reason:"App deployed successfully, but QA could not verify it via automated browser testing because Playwright is not installed locally.",detail:b,httpChecks:n.map(({screenshot:y,...f})=>f),fix:"Run: npx playwright install chromium",instruction:[`The app deployed and is live at ${a}. 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 ${a}. 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(`
|
|
12411
|
-
`)}),!1)}try{let g=await st(c,"Landing page",async()=>{await c.goto(a,{waitUntil:"domcontentloaded",timeout:3e4}),await c.waitForLoadState("networkidle").catch(()=>{});let y=await c.evaluate(()=>{let v=document.body;if(!v)return"";let C=document.createTreeWalker(v,NodeFilter.SHOW_TEXT),P="",A;for(;A=C.nextNode();){let B=A.parentElement;if(B){let I=window.getComputedStyle(B);I.display!=="none"&&I.visibility!=="hidden"&&parseFloat(I.opacity)>0&&(P+=A.textContent?.trim()+" ")}}return P.trim()});if(y.length<50)return{pass:!1,detail:`Landing page appears blank (${y.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 f=c.url();return f.includes("/login")||f.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 (${y.length} chars)`}});n.push(g);let b=!1;if(u){let y=await st(c,"Login",async()=>{await c.goto(`${a}/login`,{waitUntil:"domcontentloaded",timeout:15e3}),await c.waitForLoadState("networkidle").catch(()=>{});let f=c.locator('input[type="email"], input[name="email"], input[placeholder*="email" i]'),v=c.locator('input[type="password"], input[name="password"]');try{await f.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 f.first().fill(d),await v.first().fill(u),await c.locator('button[type="submit"], button:has-text("Sign in"), button:has-text("Log in"), button:has-text("Login")').first().click();try{await c.waitForURL(P=>!P.pathname.includes("/login"),{timeout:1e4})}catch{let P=await c.locator('[role="alert"], .text-red-500, .text-destructive, [data-error]').first().textContent().catch(()=>null);return{pass:!1,detail:P?`Login failed: ${P}`:"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 b=!0,{pass:!0,detail:`Logged in, redirected to ${c.url()}`}});n.push(y)}else n.push({name:"Login",status:"pass",detail:"Skipped form login (redeploy, password unavailable). Using session injection."});if(!b&&l){let y=new URL(a).hostname,f=a.startsWith("https");await h.addCookies([{name:f?"__Secure-better-auth.session_token":"better-auth.session_token",value:l,domain:y,path:"/",httpOnly:!0,secure:f,sameSite:"Lax"}]),console.error("[qa] Injected session cookie for dashboard checks")}{let y=await st(c,"Dashboard",async()=>{c.url().includes("/dashboard")||(await c.goto(`${a}/dashboard`,{waitUntil:"domcontentloaded",timeout:15e3}),await c.waitForLoadState("networkidle").catch(()=>{}));let P=await c.content();return P.length<1e3?{pass:!1,detail:`Dashboard page is very small (${P.length} bytes)`,fix:"Check app/(dashboard)/dashboard/page.tsx exists and the dashboard layout doesn't crash."}:await c.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 (${P.length} bytes)`}});n.push(y);let f=await c.evaluate(()=>{let C=[];return document.querySelectorAll("nav a[href], aside a[href]").forEach(A=>{let B=A.getAttribute("href");B&&B.startsWith("/")&&!B.startsWith("/api")&&!B.includes("[")&&B!=="/dashboard"&&B!=="/"&&!B.includes("/login")&&!B.includes("/sign")&&C.push(B)}),[...new Set(C)]});if(f.length>0){let C=0,P=[];for(let A of f.slice(0,8)){let B=await st(c,`Page: ${A}`,async()=>{await c.goto(`${a}${A}`,{waitUntil:"domcontentloaded",timeout:15e3}),await c.waitForLoadState("networkidle").catch(()=>{});let I=await c.title(),M=await c.content();return I.toLowerCase().includes("500")||I.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."}:I.toLowerCase().includes("404")||I.toLowerCase().includes("not found")?{pass:!1,detail:"Page returns 404",fix:`Page ${A} not found. Create the page or remove the nav link.`}:await c.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."}:M.length<500?{pass:!1,detail:`Page is very small (${M.length} bytes)`,fix:"Page may not have rendered. Check the page component."}:{pass:!0,detail:"Loads without errors"}});B.status==="fail"&&(C++,P.push(A)),n.push(B)}}let v=await st(c,"Design quality",async()=>{let C=c.url().includes("/dashboard")?c.url():`${a}/dashboard`;c.url().includes("/dashboard")||(await c.goto(C,{waitUntil:"domcontentloaded",timeout:15e3}),await c.waitForLoadState("networkidle").catch(()=>{}));let P=await c.evaluate(()=>{let A=[],B=document.querySelectorAll("h1, h2, h3, h4, h5, h6"),I=new Set;B.forEach(w=>{I.add(window.getComputedStyle(w).fontSize)}),B.length>=3&&I.size<2&&A.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 M=Array.from(B).map(w=>parseInt(w.tagName.charAt(1),10));for(let w=1;w<M.length;w++)if(M[w]-M[w-1]>1){A.push(`TYPOGRAPHY: Heading level skipped (h${M[w-1]} -> h${M[w]}). Use sequential heading levels for accessibility.`);break}let
|
|
12411
|
+
`)}),!1)}try{let g=await st(c,"Landing page",async()=>{await c.goto(a,{waitUntil:"domcontentloaded",timeout:3e4}),await c.waitForLoadState("networkidle").catch(()=>{});let y=await c.evaluate(()=>{let v=document.body;if(!v)return"";let C=document.createTreeWalker(v,NodeFilter.SHOW_TEXT),P="",A;for(;A=C.nextNode();){let B=A.parentElement;if(B){let I=window.getComputedStyle(B);I.display!=="none"&&I.visibility!=="hidden"&&parseFloat(I.opacity)>0&&(P+=A.textContent?.trim()+" ")}}return P.trim()});if(y.length<50)return{pass:!1,detail:`Landing page appears blank (${y.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 f=c.url();return f.includes("/login")||f.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 (${y.length} chars)`}});n.push(g);let b=!1;if(u){let y=await st(c,"Login",async()=>{await c.goto(`${a}/login`,{waitUntil:"domcontentloaded",timeout:15e3}),await c.waitForLoadState("networkidle").catch(()=>{});let f=c.locator('input[type="email"], input[name="email"], input[placeholder*="email" i]'),v=c.locator('input[type="password"], input[name="password"]');try{await f.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 f.first().fill(d),await v.first().fill(u),await c.locator('button[type="submit"], button:has-text("Sign in"), button:has-text("Log in"), button:has-text("Login")').first().click();try{await c.waitForURL(P=>!P.pathname.includes("/login"),{timeout:1e4})}catch{let P=await c.locator('[role="alert"], .text-red-500, .text-destructive, [data-error]').first().textContent().catch(()=>null);return{pass:!1,detail:P?`Login failed: ${P}`:"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 b=!0,{pass:!0,detail:`Logged in, redirected to ${c.url()}`}});n.push(y)}else n.push({name:"Login",status:"pass",detail:"Skipped form login (redeploy, password unavailable). Using session injection."});if(!b&&l){let y=new URL(a).hostname,f=a.startsWith("https");await h.addCookies([{name:f?"__Secure-better-auth.session_token":"better-auth.session_token",value:l,domain:y,path:"/",httpOnly:!0,secure:f,sameSite:"Lax"}]),console.error("[qa] Injected session cookie for dashboard checks")}{let y=await st(c,"Dashboard",async()=>{c.url().includes("/dashboard")||(await c.goto(`${a}/dashboard`,{waitUntil:"domcontentloaded",timeout:15e3}),await c.waitForLoadState("networkidle").catch(()=>{}));let P=await c.content();return P.length<1e3?{pass:!1,detail:`Dashboard page is very small (${P.length} bytes)`,fix:"Check app/(dashboard)/dashboard/page.tsx exists and the dashboard layout doesn't crash."}:await c.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 (${P.length} bytes)`}});n.push(y);let f=await c.evaluate(()=>{let C=[];return document.querySelectorAll("nav a[href], aside a[href]").forEach(A=>{let B=A.getAttribute("href");B&&B.startsWith("/")&&!B.startsWith("/api")&&!B.includes("[")&&B!=="/dashboard"&&B!=="/"&&!B.includes("/login")&&!B.includes("/sign")&&C.push(B)}),[...new Set(C)]});if(f.length>0){let C=0,P=[];for(let A of f.slice(0,8)){let B=await st(c,`Page: ${A}`,async()=>{await c.goto(`${a}${A}`,{waitUntil:"domcontentloaded",timeout:15e3}),await c.waitForLoadState("networkidle").catch(()=>{});let I=await c.title(),M=await c.content();return I.toLowerCase().includes("500")||I.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."}:I.toLowerCase().includes("404")||I.toLowerCase().includes("not found")?{pass:!1,detail:"Page returns 404",fix:`Page ${A} not found. Create the page or remove the nav link.`}:await c.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."}:M.length<500?{pass:!1,detail:`Page is very small (${M.length} bytes)`,fix:"Page may not have rendered. Check the page component."}:{pass:!0,detail:"Loads without errors"}});B.status==="fail"&&(C++,P.push(A)),n.push(B)}}let v=await st(c,"Design quality",async()=>{let C=c.url().includes("/dashboard")?c.url():`${a}/dashboard`;c.url().includes("/dashboard")||(await c.goto(C,{waitUntil:"domcontentloaded",timeout:15e3}),await c.waitForLoadState("networkidle").catch(()=>{}));let P=await c.evaluate(()=>{let A=[],B=document.querySelectorAll("h1, h2, h3, h4, h5, h6"),I=new Set;B.forEach(w=>{I.add(window.getComputedStyle(w).fontSize)}),B.length>=3&&I.size<2&&A.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 M=Array.from(B).map(w=>parseInt(w.tagName.charAt(1),10));for(let w=1;w<M.length;w++)if(M[w]-M[w-1]>1){A.push(`TYPOGRAPHY: Heading level skipped (h${M[w-1]} -> h${M[w]}). Use sequential heading levels for accessibility.`);break}let O=document.querySelectorAll("*"),E=!1,H=!1;O.forEach(w=>{let N=window.getComputedStyle(w);N.backgroundColor==="rgb(0, 0, 0)"&&w.clientHeight>100&&w.clientWidth>200&&(E=!0);let q=N.backgroundColor,me=N.color;if(q&&!q.includes("0, 0, 0")&&!q.includes("255, 255, 255")&&q!=="rgba(0, 0, 0, 0)"&&q!=="transparent"&&me.match(/rgb\((\d+), (\d+), (\d+)\)/)){let pe=me.match(/rgb\((\d+), (\d+), (\d+)\)/);if(pe){let[Z,xe,we]=[parseInt(pe[1]),parseInt(pe[2]),parseInt(pe[3])],de=Math.abs(Z-xe)<10&&Math.abs(xe-we)<10&&Z>80&&Z<180,$=q.match(/rgb\((\d+), (\d+), (\d+)\)/);if(de&&$){let[k,m,x]=[parseInt($[1]),parseInt($[2]),parseInt($[3])];!(Math.abs(k-m)<15&&Math.abs(m-x)<15)&&w.textContent&&w.textContent.trim().length>0&&(H=!0)}}}}),E&&A.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)."),H&&A.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 re=document.querySelectorAll('[class*="card"], [class*="Card"], [role="group"]'),z=!1;re.forEach(w=>{w.querySelectorAll('[class*="card"], [class*="Card"]').length>0&&(z=!0)}),z&&A.push("LAYOUT: Nested cards detected (card inside card). Flatten the hierarchy. Use spacing and background color to create separation instead.");let K=document.querySelectorAll("p, li, span, div"),U=0,_=0;K.forEach(w=>{w.textContent&&w.textContent.trim().length>20&&w.clientHeight>0&&(_++,window.getComputedStyle(w).textAlign==="center"&&U++)}),_>5&&U/_>.7&&A.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;O.forEach(w=>{let N=window.getComputedStyle(w);N.gap&&N.gap!=="normal"&&N.gap!=="0px"&&F.add(N.gap)}),F.size===1&&O.length>20&&A.push("LAYOUT: Same gap value used everywhere. Vary spacing to create hierarchy: tight within groups (8-12px), generous between sections (32-64px).");let Q=document.querySelectorAll("button, a, input, select, textarea"),le=!1;Q.forEach(w=>{let N=window.getComputedStyle(w);if(N.outline==="none"||N.outline==="0px none rgb(0, 0, 0)"){let q=w;(q.style.outline==="none"||q.style.outline==="0")&&(le=!0)}}),document.querySelectorAll("table, [role='table']").forEach(w=>{w.querySelectorAll("tbody tr").length===0&&(w.parentElement?.querySelector('[class*="empty"], [class*="Empty"], [class*="no-data"], [class*="placeholder"]')||A.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 R=document.querySelectorAll("style"),L=!1;R.forEach(w=>{let N=w.textContent||"";(N.includes("bounce")||N.includes("elastic")||N.match(/cubic-bezier\([^)]*[2-9]\.[0-9]/))&&(L=!0)}),L&&A.push("MOTION: Bounce or elastic easing detected. These feel dated. Use smooth deceleration curves (Quart out, Expo out) instead.");let oe=document.querySelectorAll("button, a, input, select, [role='button']"),ie=0;return oe.forEach(w=>{let N=w.getBoundingClientRect();N.width>0&&N.height>0&&(N.width<32||N.height<32)&&ie++}),ie>3&&A.push(`ACCESSIBILITY: ${ie} interactive elements are smaller than 32x32px. Minimum recommended touch target is 44x44px. Add padding to increase tap area.`),A});return P.length===0?{pass:!0,detail:"No design quality issues detected. Typography hierarchy, color usage, layout patterns, and accessibility basics look good."}:{pass:!1,detail:`${P.length} design quality issue(s) found:
|
|
12412
12412
|
${P.map((A,B)=>`${B+1}. ${A}`).join(`
|
|
12413
|
-
`)}`,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(n.push(v),n.find(C=>C.name==="Landing page"&&C.status==="pass")){let C=await st(c,"Landing design quality",async()=>{await c.goto(a,{waitUntil:"domcontentloaded",timeout:15e3}),await c.waitForLoadState("networkidle").catch(()=>{});let P=await c.evaluate(()=>{let A=[];document.querySelectorAll("*").forEach(
|
|
12413
|
+
`)}`,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(n.push(v),n.find(C=>C.name==="Landing page"&&C.status==="pass")){let C=await st(c,"Landing design quality",async()=>{await c.goto(a,{waitUntil:"domcontentloaded",timeout:15e3}),await c.waitForLoadState("networkidle").catch(()=>{});let P=await c.evaluate(()=>{let A=[];document.querySelectorAll("*").forEach(O=>{let E=window.getComputedStyle(O);(E.getPropertyValue("-webkit-background-clip")||E.getPropertyValue("background-clip"))==="text"&&O.textContent&&O.textContent.trim().length>0&&A.push("SLOP: Gradient text detected. This is a common AI design pattern. Use solid colors for text.")});let I=document.querySelector("section, [class*='hero'], [class*='Hero'], header + div, main > div:first-child");if(I){let O=(I.textContent||"").toLowerCase(),E=["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 H of E)if(O.match(new RegExp(H))){A.push(`COPY: Generic hero text detected ('${H}'). Write specific copy about what THIS app does for its users.`);break}}return document.querySelectorAll('[class*="grid"]').forEach(O=>{let H=window.getComputedStyle(O).gridTemplateColumns;if(H){let re=H.split(" ").filter(K=>K!=="").length,z=O.children;if(re===3&&z.length===3){let K=Array.from(z).map(F=>F.offsetHeight),U=K.every(F=>Math.abs(F-K[0])<5),_=Array.from(z).every(F=>{let Q=F.querySelectorAll("svg"),le=F.querySelectorAll("h2, h3, h4"),T=F.querySelectorAll("p");return Q.length>=1&&le.length>=1&&T.length>=1});U&&_&&A.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.")}}}),A});return P.length===0?{pass:!0,detail:"Landing page design looks intentional. No generic AI patterns detected."}:{pass:!1,detail:`${P.length} landing design issue(s):
|
|
12414
12414
|
${P.map((A,B)=>`${B+1}. ${A}`).join(`
|
|
12415
12415
|
`)}`,fix:"These patterns make the landing page look AI-generated. Fix them to create a more distinctive, professional design."}});n.push(C)}}}finally{h&&await h.close().catch(()=>{})}if(r.deploymentId){let g=n.filter(f=>f.status==="fail"),b=n.filter(f=>f.status==="pass"),y=Date.now();await Xa(r.deploymentId,{checks:n.map(({screenshot:f,...v})=>v),overall:g.length===0?"pass":"fail",passed:b.length,failed:g.length,duration_ms:Date.now()-y}).catch(()=>{})}return Wt(a,n)}function Wt(r,e){let t=e.filter(n=>n.status==="fail"),a=e.filter(n=>n.status==="pass"),i=[];if(t.length===0)i.push({type:"text",text:JSON.stringify({status:"pass",message:`QA passed. All ${e.length} checks OK. The app is working correctly.`,url:r,checks:e.map(({screenshot:n,...o})=>o)})});else{let n=t.map((o,s)=>`${s+1}. **${o.name}**: ${o.detail}
|
|
12416
12416
|
Fix: ${o.fix}`).join(`
|
|
@@ -12419,7 +12419,7 @@ ${P.map((A,B)=>`${B+1}. ${A}`).join(`
|
|
|
12419
12419
|
|
|
12420
12420
|
${n}
|
|
12421
12421
|
|
|
12422
|
-
Fix these issues in the source code, then call mist_deploy with action='deploy'${r.includes("-pv-")?" environment='preview'":""} to redeploy. After redeploying, call mist_build action='qa' again to verify the fixes.`})})}for(let n of e)n.screenshot&&i.push({type:"image",data:n.screenshot,mimeType:"image/png"});return{content:i}}function ss(r){let e=jt(ns(),".mistflow","plans",`${r}.json`);if(!_t(e))return null;try{let t=JSON.parse(os(e,"utf-8"));return t.plan?t:null}catch{return null}}var ls=ae.object({action:ae.enum(["init","implement","debug","build","qa","mockup"]).describe("'mockup' generates visual mockup HTML files from a plan for user preview and approval. 'init' creates and sets up a new project from your plan. 'implement' executes the next (or specific) plan step. 'debug' analyzes build or runtime errors \u2014 for runtime errors, call mist_project errors first then pass the output as buildOutput. 'build' runs the full production build locally (Mistflow Cloud edge runtime) without deploying. 'qa' tests the live deployed app \u2014 checks landing page, signup, login, dashboard, and nav links. Call after mist_deploy. If issues found, fix and redeploy, then call qa again."),name:ae.string().optional().describe("(init) Project name"),planId:ae.string().optional().describe("(init/mockup) Plan ID from mist_plan"),plan:ae.any().optional().describe("(init) Full plan object \u2014 use planId instead when available"),path:ae.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:ae.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:ae.string().optional().describe("(init) App style ID to apply across all pages (e.g. 'stripe', 'linear'). Can be set here if not set during mist_plan. Use mist_project action='app-styles' to browse."),confirmDarkTheme:ae.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:ae.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:ae.string().optional().describe("Path to the project directory (default: cwd)"),step:ae.number().optional().describe("(implement) Specific step number to implement"),buildOutput:ae.string().optional().describe("(debug) Build output to parse instead of running a build"),feedback:ae.string().optional().describe("(mockup) User feedback on the current mockup \u2014 describe what to change."),approved:ae.boolean().optional().describe("(mockup) Set to true when the user approves the mockup. Locks in the design direction."),url:ae.string().optional().describe("(qa) URL to test. Defaults to deploy URL from mistflow.json"),deploymentId:ae.string().optional().describe("(qa) Deployment ID to associate QA results with. Passed from mist_deploy output.")}),Do={name:"mist_build",description:"STEP 2-3 of the Mistflow workflow. Build and develop a Mistflow project. 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. Pass the planId returned by mist_plan \u2014 do NOT pass the full plan object. '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 implement (repeat) \u2192 mist_deploy \u2192 mist_build qa (loop until pass).",inputSchema:ls,handler:async r=>{let e=r;switch(e.action){case"init":{if(!e.name)return p("Project name is required for init.",!0);let t=e.plan,a=null;if(e.planId){if(a=ss(e.planId),!a)return p(`Plan not found for planId '${e.planId}'. The plan may have expired. Call mist_plan again to generate a new plan.`,!0);t=a.plan}if(!t)return p("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 p("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(a?.sourceDeploymentId&&a?.forkToken&&a?.projectId)return qr({name:e.name,plan:t,path:e.path,projectId:a.projectId,sourceDeploymentId:a.sourceDeploymentId,forkToken:a.forkToken,requiredEnvVars:a.requiredEnvVars??[],dbProvider:a.dbProvider??"neon",planId:e.planId});if(e.landingDesign){let d=et(e.landingDesign);d?t.landingDesign=d.id:console.error(`Landing design '${e.landingDesign}' not found \u2014 ignoring.`)}if(e.appStyle){let d=
|
|
12422
|
+
Fix these issues in the source code, then call mist_deploy with action='deploy'${r.includes("-pv-")?" environment='preview'":""} to redeploy. After redeploying, call mist_build action='qa' again to verify the fixes.`})})}for(let n of e)n.screenshot&&i.push({type:"image",data:n.screenshot,mimeType:"image/png"});return{content:i}}function ss(r){let e=jt(ns(),".mistflow","plans",`${r}.json`);if(!_t(e))return null;try{let t=JSON.parse(os(e,"utf-8"));return t.plan?t:null}catch{return null}}var ls=ae.object({action:ae.enum(["init","implement","debug","build","qa","mockup"]).describe("'mockup' generates visual mockup HTML files from a plan for user preview and approval. 'init' creates and sets up a new project from your plan. 'implement' executes the next (or specific) plan step. 'debug' analyzes build or runtime errors \u2014 for runtime errors, call mist_project errors first then pass the output as buildOutput. 'build' runs the full production build locally (Mistflow Cloud edge runtime) without deploying. 'qa' tests the live deployed app \u2014 checks landing page, signup, login, dashboard, and nav links. Call after mist_deploy. If issues found, fix and redeploy, then call qa again."),name:ae.string().optional().describe("(init) Project name"),planId:ae.string().optional().describe("(init/mockup) Plan ID from mist_plan"),plan:ae.any().optional().describe("(init) Full plan object \u2014 use planId instead when available"),path:ae.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:ae.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:ae.string().optional().describe("(init) App style ID to apply across all pages (e.g. 'stripe', 'linear'). Can be set here if not set during mist_plan. Use mist_project action='app-styles' to browse."),confirmDarkTheme:ae.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:ae.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:ae.string().optional().describe("Path to the project directory (default: cwd)"),step:ae.number().optional().describe("(implement) Specific step number to implement"),buildOutput:ae.string().optional().describe("(debug) Build output to parse instead of running a build"),feedback:ae.string().optional().describe("(mockup) User feedback on the current mockup \u2014 describe what to change."),approved:ae.boolean().optional().describe("(mockup) Set to true when the user approves the mockup. Locks in the design direction."),url:ae.string().optional().describe("(qa) URL to test. Defaults to deploy URL from mistflow.json"),deploymentId:ae.string().optional().describe("(qa) Deployment ID to associate QA results with. Passed from mist_deploy output.")}),Do={name:"mist_build",description:"STEP 2-3 of the Mistflow workflow. Build and develop a Mistflow project. 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. Pass the planId returned by mist_plan \u2014 do NOT pass the full plan object. '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 implement (repeat) \u2192 mist_deploy \u2192 mist_build qa (loop until pass).",inputSchema:ls,handler:async r=>{let e=r;switch(e.action){case"init":{if(!e.name)return p("Project name is required for init.",!0);let t=e.plan,a=null;if(e.planId){if(a=ss(e.planId),!a)return p(`Plan not found for planId '${e.planId}'. The plan may have expired. Call mist_plan again to generate a new plan.`,!0);t=a.plan}if(!t)return p("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 p("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(a?.sourceDeploymentId&&a?.forkToken&&a?.projectId)return qr({name:e.name,plan:t,path:e.path,projectId:a.projectId,sourceDeploymentId:a.sourceDeploymentId,forkToken:a.forkToken,requiredEnvVars:a.requiredEnvVars??[],dbProvider:a.dbProvider??"neon",planId:e.planId});if(e.landingDesign){let d=et(e.landingDesign);d?t.landingDesign=d.id:console.error(`Landing design '${e.landingDesign}' not found \u2014 ignoring.`)}if(e.appStyle){let d=fe(e.appStyle);d?t.appStyle=d.id:console.error(`App style '${e.appStyle}' not found \u2014 ignoring.`)}let i=t.design,o=t.audienceType==="b2c",s=e.heroPhoto??o;t.design={...i??{},heroPhoto:s};let l=t.appStyle;if(l&&!e.confirmDarkTheme){let d=fe(l),u=d?Ie(d.id):void 0,h=t.audienceType;if(d&&u?.theme==="dark"&&h==="b2c"){let c=ut(u.category).filter(b=>b.theme==="light"&&b.id!==d.id).slice(0,3),g=c.map(b=>`'${b.id}'`).join(", ");return p(JSON.stringify({status:"confirm_dark_theme",picked:{id:d.id,name:d.name,theme:"dark"},audience:"consumer app (b2c)",lightAlternatives:c.map(b=>({id:b.id,name:b.name,description:b.description})),askUserQuestion:{question:`You picked ${d.name}'s dark aesthetic. Dark themes tend to read as "developer tool" \u2014 for a consumer app, a light palette usually feels friendlier. Keep ${d.name} dark, or switch to a light style?`,header:"Theme",options:[{label:`Keep ${d.name} (dark)`,description:"I want the dark aesthetic. Proceed with the build."},...c.map(b=>({label:`Switch to ${b.name} (light)`,description:(b.description??"").slice(0,140)}))],multiSelect:!1},instruction:[`The user picked a dark-themed design system (${d.name}) for a consumer app.`,"MANDATORY: Use the AskUserQuestion tool with the askUserQuestion object above before calling mist_build init again.",`If the user keeps dark: call mist_build init with the SAME appStyle='${d.id}' AND confirmDarkTheme=true.`,g?`If the user picks a light alternative: call mist_build init with appStyle set to one of: ${g}.`:""].filter(Boolean).join(`
|
|
12423
12423
|
`)}))}}return Vr({name:e.name,plan:t,path:e.path,planId:e.planId})}case"implement":return So({projectPath:e.projectPath,step:e.step});case"debug":return Co({projectPath:e.projectPath,buildOutput:e.buildOutput});case"build":{let t=is(e.projectPath??process.cwd());if(!_t(jt(t,"mistflow.json")))return p("Not a Mistflow project \u2014 mistflow.json not found. Run mist_build init first.",!0);if(!_t(jt(t,"node_modules")))try{Pa("npm",["install"],{cwd:t,stdio:["pipe","pipe","pipe"],timeout:12e4})}catch{return p("npm install failed. Check package.json for issues.",!0)}let i=process.platform==="win32"?"npx.cmd":"npx",n=0,o=2;for(;;){n++;try{Pa(i,["@opennextjs/cloudflare","build"],{cwd:t,stdio:["pipe","pipe","pipe"],timeout:18e4});let s=_t(jt(t,".open-next"));return p(JSON.stringify({success:!0,buildDir:".open-next",message:s?"Production build succeeded. Ready to deploy with mist_deploy.":"Build completed but .open-next/ directory not found. Check your OpenNext config."}))}catch(s){let l=s instanceof Error&&"stderr"in s?String(s.stderr):"",d=s instanceof Error&&"stdout"in s?String(s.stdout):"",u=l+`
|
|
12424
12424
|
`+d;if(n<o){let c=[],g=/Module not found:\s*(?:Error:\s*)?Can't resolve ['"]([^'"]+)['"]/g,b;for(;(b=g.exec(u))!==null;){let y=b[1];if(!y.startsWith(".")&&!y.startsWith("@/")&&!y.startsWith("~/")){let f=y.startsWith("@")?y.split("/").slice(0,2).join("/"):y.split("/")[0];c.includes(f)||c.push(f)}}if(c.length>0){console.error(`[build] Auto-installing missing packages: ${c.join(", ")}`);try{Pa("npm",["install",...c],{cwd:t,stdio:["pipe","pipe","pipe"],timeout:6e4});continue}catch{console.error("[build] Auto-install failed, reporting build errors")}}}let h=ft(u);return p(JSON.stringify({success:!1,errors:h,rawOutput:u.slice(0,3e3),message:h.length>0?`Build failed with ${h.length} error${h.length===1?"":"s"}:
|
|
12425
12425
|
|
|
@@ -12428,12 +12428,12 @@ Fix these issues in the source code, then call mist_deploy with action='deploy'$
|
|
|
12428
12428
|
|
|
12429
12429
|
`)+`
|
|
12430
12430
|
|
|
12431
|
-
Fix these and run mist_build build again.`:"Build failed. Run mist_build with action='debug' for detailed analysis."}),!0)}}}case"qa":return Bo({projectPath:e.projectPath,url:e.url,deploymentId:e.deploymentId});case"mockup":return e.planId?mo({planId:e.planId,projectPath:e.projectPath,feedback:e.feedback,approved:e.approved}):p("planId is required for mockup. Pass the planId from mist_plan.",!0);default:return p(`Unknown action: ${e.action}. Use mockup, init, implement, build, debug, or qa.`,!0)}}};import{z as Je}from"zod";import{z as Vt}from"zod";import{resolve as Ho,join as
|
|
12431
|
+
Fix these and run mist_build build again.`:"Build failed. Run mist_build with action='debug' for detailed analysis."}),!0)}}}case"qa":return Bo({projectPath:e.projectPath,url:e.url,deploymentId:e.deploymentId});case"mockup":return e.planId?mo({planId:e.planId,projectPath:e.projectPath,feedback:e.feedback,approved:e.approved}):p("planId is required for mockup. Pass the planId from mist_plan.",!0);default:return p(`Unknown action: ${e.action}. Use mockup, init, implement, build, debug, or qa.`,!0)}}};import{z as Je}from"zod";import{z as Vt}from"zod";import{resolve as Ho,join as J,dirname as qt,basename as Bs}from"path";import{existsSync as ne,readFileSync as La,writeFileSync as Oo,unlinkSync as Ro,mkdirSync as Ds,cpSync as Ia,rmSync as Ma,readdirSync as As}from"fs";import{execFileSync as Is}from"child_process";import{spawn as Ms}from"child_process";import{tmpdir as Rs}from"os";function Ao(r,e){if(r instanceof he)switch(r.code){case"auth_missing":return p("No Mistflow credentials found. Run mist_setup to connect your account.",!0);case"auth_revoked":return p("Your Mistflow credentials were revoked. Run mist_setup to reconnect.",!0);case"auth_expired":case"auth_invalid":case"auth_org_not_found":return p("Your Mistflow session needs to be refreshed. Run mist_setup to reconnect.",!0);case"permission_denied":return p(r.message||"You don't have permission for that action.",!0);case"rate_limited":return p("You're hitting rate limits. Wait 30 seconds and try again.",!0);case"quota_exceeded":return p(`${r.message} Upgrade at https://app.mistflow.ai/pricing to lift limits.`,!0);case"validation_error":case"conflict":return p(r.message,!0);case"not_found":{let a=Pt(),i=a?.orgSlug?.replace(/^user_user_/,"")||void 0,n=a?.email||i;return n&&(r.message.toLowerCase().includes("project")||e.toLowerCase().includes("project"))?p(`Project not found. You are signed in as ${n}. This project may belong to a different account. Run mist_setup to sign in with the account that owns this project.`,!0):p(r.message,!0)}case"server_error":case"upstream_error":return p(`${e} failed: the Mistflow backend returned an error. Try again in 30 seconds.`,!0);case"network_error":return p(`${e} failed: cannot reach Mistflow servers. Check your network and try again.`,!0);default:return p(`${e} failed: ${r.message}`,!0)}let t=r instanceof Error?r.message:String(r);return p(`${e} failed: ${t}`,!0)}import{existsSync as We,readFileSync as bt,readdirSync as Ba,statSync as Da}from"fs";import{join as ye,relative as zt}from"path";import{execFileSync as ip}from"child_process";function ds(r){let e=ye(r,".env.local"),t=[];return We(e)?(bt(e,"utf-8").match(/^AUTH_SECRET=(.*)$/m)?.[1]?.trim()||t.push({check:"env",message:"AUTH_SECRET is missing from .env.local. Add a random secret for authentication.",file:".env.local"}),t):(t.push({check:"env",message:"Missing .env.local file. Create one with your local development environment variables (AUTH_SECRET, etc.).",file:".env.local"}),t)}function cs(r){let e=ye(r,"app","api","auth","[...all]","route.ts");return We(e)?[]:[{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 ps(r){let e=ye(r,"app","api","health","route.ts");return We(e)?[]:[{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 us(r){let e=ye(r,"mistflow.json");if(!We(e))return[];let t;try{t=JSON.parse(bt(e,"utf-8"))}catch{return[]}let a=t.env;if(!a?.required||typeof a.required!="object")return[];let i=[],n=ye(r,".env"),o="";try{We(n)&&(o=bt(n,"utf-8"))}catch{}for(let[s,l]of Object.entries(a.required)){let d=!!process.env[s],u=o.includes(`${s}=`);if(d||u)continue;let h=l?.description?` for '${l.description}'`:"";i.push({check:"required-env",message:`${s} is required${h}. Run mist_config to set it if you haven't already.`})}return i}function hs(r){let e=ye(r,"app");if(!We(e))return[];let t=[];function a(o){let s;try{s=Ba(o)}catch{return}for(let l of s){if(l==="node_modules"||l===".next"||l===".open-next"||l==="api")continue;let d=ye(o,l),u;try{u=Da(d)}catch{continue}if(u.isDirectory())a(d);else if(l==="page.tsx"||l==="page.ts"||l==="page.jsx"||l==="page.js"){let c="/"+zt(e,d).replace(/\\/g,"/").replace(/\([^)]+\)\//g,"").replace(/\/page\.(tsx?|jsx?)$/,"").replace(/^page\.(tsx?|jsx?)$/,"");t.push({file:zt(r,d),resolvedRoute:c||"/"})}}}a(e);let i=new Map;for(let o of t){let s=i.get(o.resolvedRoute)??[];s.push(o.file),i.set(o.resolvedRoute,s)}let n=[];for(let[o,s]of i)s.length>1&&n.push({check:"route-collision",message:`Route collision: ${s.join(" and ")} both resolve to "${o}". 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:s[1]});return n}function gs(r){let e=ye(r,"app");if(!We(e))return[];let t=[];function a(i){let n;try{n=Ba(i)}catch{return}for(let o of n){if(o==="node_modules"||o===".next"||o===".open-next")continue;let s=ye(i,o),l;try{l=Da(s)}catch{continue}if(l.isDirectory())a(s);else if(o==="actions.ts"||o==="actions.tsx"){let d=bt(s,"utf-8");d.includes("use server")&&d.includes("cookies()")&&d.includes(".set(")&&t.push(zt(r,s))}}}return a(e),t.length>0?[{check:"cookies-in-actions",message:`${t.length} server action(s) use cookies().set() which crashes on Mistflow Cloud's edge runtime: ${t.join(", ")}. Use a database field or form parameter instead.`,file:t[0]}]:[]}function ms(r){let e=/\b(useState|useEffect|useRef|useCallback|useMemo|useReducer|useContext|useLayoutEffect|useTransition)\s*\(/,t=[];function a(i){if(!We(i))return;let n;try{n=Ba(i)}catch{return}for(let o of n){if(o==="node_modules"||o===".next"||o===".open-next"||o==="ui")continue;let s=ye(i,o),l;try{l=Da(s)}catch{continue}if(l.isDirectory())a(s);else if(o.endsWith(".tsx")||o.endsWith(".jsx")){if(o==="layout.tsx"||o==="loading.tsx"||o==="error.tsx"||o==="not-found.tsx")continue;let d=bt(s,"utf-8");if(d.trimStart().startsWith('"use client"')||d.trimStart().startsWith("'use client'")||d.trimStart().startsWith('"use server"')||d.trimStart().startsWith("'use server'"))continue;if(e.test(d)){let u=zt(r,s);t.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 a(ye(r,"app")),a(ye(r,"components")),t}function Io(r){let e=[...ds(r),...cs(r),...ps(r),...hs(r),...gs(r),...ms(r)],t=[...us(r)];return{passed:e.length===0,errors:e,warnings:t}}import{existsSync as ge,readFileSync as Ye,readdirSync as $t,statSync as yt}from"fs";import{join as V}from"path";async function Mo(r,e){let t=[];t.push(fs(r)),t.push(bs(r)),t.push(ys(r)),t.push(xs(r)),t.push(ws(r)),t.push(Cs(r)),e?.plan&&t.push(...vs(r,e)),t.push(ks(r)),t.push(Ss(r)),t.push(...Ps(r)),t.push(Ts(r));let a=t.filter(d=>d.status==="fail"),i=t.filter(d=>d.status==="warn"),n=t.filter(d=>d.status==="pass"),o=a.length>0,s=!o,l;return s&&i.length===0?l=`All ${t.length} checks passed`:s?l=`${n.length}/${t.length} passed, ${i.length} warning(s)`:l=`${a.length} issue(s) found:
|
|
12432
12432
|
${a.map(d=>` - ${d.message}`).join(`
|
|
12433
|
-
`)}`,{passed:s,blocking:o,checksRun:t.length,checks:t,summary:l}}function fs(r){let e
|
|
12433
|
+
`)}`,{passed:s,blocking:o,checksRun:t.length,checks:t,summary:l}}function fs(r){let e=V(r,".open-next","worker.js");if(!ge(e))return{name:"worker-exists",status:"fail",message:"worker.js not found in build output. The build may have failed silently."};let t=Ye(e,"utf-8");return t.length<1e3?{name:"worker-exists",status:"warn",message:`worker.js is unusually small (${t.length} bytes). The build output may be incomplete.`}:{name:"worker-exists",status:"pass",message:"Worker bundle exists"}}function bs(r){let e=V(r,".open-next","assets");if(!ge(e))return{name:"assets-exist",status:"warn",message:"No static assets directory in build output. CSS and images may not load."};let t=0;function a(i){try{for(let n of $t(i)){let o=V(i,n);try{yt(o).isDirectory()?a(o):t++}catch{}}}catch{}}return a(e),t===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:`${t} static assets ready`}}function ys(r){let e=V(r,"app","api","health","route.ts");return ge(e)?{name:"health-route",status:"pass",message:"Health endpoint found"}:{name:"health-route",status:"warn",message:"No health endpoint found. Deployment verification may fail."}}function xs(r){let e=V(r,"app","api","auth","[...all]","route.ts");return ge(e)?{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 ws(r){let e=V(r,".open-next","worker.js");if(!ge(e))return{name:"worker-size",status:"pass",message:"Worker size check skipped"};let a=yt(e).size/(1024*1024);return a>60?{name:"worker-size",status:"fail",message:`Worker bundle is ${a.toFixed(1)}MB \u2014 exceeds Mistflow Cloud's 64MB worker bundle limit.`}:a>30?{name:"worker-size",status:"warn",message:`Worker bundle is ${a.toFixed(1)}MB \u2014 large but within Mistflow Cloud limits. May be slow to upload.`}:{name:"worker-size",status:"pass",message:`Worker bundle: ${a.toFixed(1)}MB`}}function vs(r,e){let t=[],a=new Set;if(e.plan?.pages)for(let o of e.plan.pages){let s=o.path??o.route??o.name;s&&a.add(s.replace(/^\//,""))}if(a.size===0)return[];let i=0,n=[];for(let o of a){if(o.startsWith("api/")||o==="login"||o==="register"||o==="sign-in"||o==="sign-up"){i++;continue}[V(r,"app","(dashboard)",o,"page.tsx"),V(r,"app","(dashboard)",o,"page.ts"),V(r,"app",o,"page.tsx"),V(r,"app",o,"page.ts"),V(r,"app","(admin)",o,"page.tsx")].some(l=>ge(l))?i++:n.push(`/${o}`)}return n.length===0?t.push({name:"plan-routes",status:"pass",message:`All ${a.size} planned pages found`}):n.length<=2?t.push({name:"plan-routes",status:"warn",message:`${i}/${a.size} planned pages found. Missing: ${n.join(", ")}`}):t.push({name:"plan-routes",status:"warn",message:`Only ${i}/${a.size} planned pages found. ${n.length} pages missing.`}),t}function ks(r){let e=V(r,"app");if(!ge(e))return{name:"empty-pages",status:"pass",message:"App directory check skipped"};let t=[];function a(i){try{for(let n of $t(i)){let o=V(i,n);try{if(yt(o).isDirectory())a(o);else if(n==="page.tsx"||n==="page.ts"){let l=Ye(o,"utf-8").trim();if(l.length<50||l.includes("export default function")&&l.includes("TODO")){let d=o.replace(r+"/","");t.push(d)}}}catch{}}}catch{}}return a(e),t.length>0?{name:"empty-pages",status:"warn",message:`${t.length} page(s) appear to be empty/placeholder: ${t.slice(0,3).join(", ")}`}:{name:"empty-pages",status:"pass",message:"No empty pages detected"}}function Ss(r){let e=V(r,"app","page.tsx");if(!ge(e))return{name:"landing-page",status:"warn",message:"No root page.tsx found"};let t=Ye(e,"utf-8");if(t.includes('redirect("/login")')||t.includes('redirect("/register")')){let a=V(r,"middleware.ts"),i=ge(a)?Ye(a,"utf-8"):"";if(!(i.includes('"/"')||i.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 t.length<200?{name:"landing-page",status:"warn",message:`Landing page is very small (${t.length} chars) \u2014 may be a placeholder.`}:{name:"landing-page",status:"pass",message:"Landing page has content"}}function Cs(r){let e=V(r,"app");if(!ge(e))return{name:"cookies-in-actions",status:"pass",message:"No app directory"};let t=[];function a(i){try{for(let n of $t(i)){if(n==="node_modules"||n===".next"||n===".open-next")continue;let o=V(i,n);try{if(yt(o).isDirectory())a(o);else if(n==="actions.ts"||n==="actions.tsx"){let l=Ye(o,"utf-8");l.includes("use server")&&l.includes("cookies()")&&l.includes(".set(")&&t.push(o.replace(r+"/",""))}}catch{}}}catch{}}return a(e),t.length>0?{name:"cookies-in-actions",status:"fail",message:`${t.length} server action(s) use cookies().set() which crashes on Mistflow Cloud's edge runtime: ${t.join(", ")}. Use a database field or form parameter instead.`}:{name:"cookies-in-actions",status:"pass",message:"No cookies().set() in server actions"}}function Ts(r){let e=V(r,"app");if(!ge(e))return{name:"fake-forms",status:"pass",message:"No app directory"};let t=[];function a(i){try{for(let n of $t(i)){if(n==="node_modules"||n===".next"||n===".open-next")continue;let o=V(i,n);try{if(yt(o).isDirectory())a(o);else if(n.endsWith(".tsx")||n.endsWith(".ts")){let l=Ye(o,"utf-8");if((l.includes("setTimeout")||l.includes("new Promise"))&&l.includes("Simulate")||l.includes("simulate")||l.includes("// TODO")&&l.includes("API")){let d=o.replace(r+"/","");t.push(d)}}}catch{}}}catch{}}return a(e),t.length>0?{name:"fake-forms",status:"fail",message:`${t.length} file(s) have fake/simulated API calls instead of real server actions: ${t.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 Ps(r){let t=[V(r,"components","sidebar.tsx"),V(r,"components","topnav.tsx"),V(r,"components","nav.tsx")].find(s=>ge(s));if(!t)return[];let n=(Ye(t,"utf-8").match(/href:\s*"([^"]+)"/g)??[]).map(s=>s.replace(/href:\s*"/,"").replace(/"$/,"")).filter(s=>!s.startsWith("/api")&&!s.includes("["));if(n.length===0)return[];let o=[];for(let s of n){let l=s.replace(/^\//,"");if(!l||l==="")continue;[V(r,"app","(dashboard)",l,"page.tsx"),V(r,"app","(dashboard)",l,"page.ts"),V(r,"app","(app)",l,"page.tsx"),V(r,"app",l,"page.tsx"),V(r,"app",l,"page.ts")].some(u=>ge(u))||o.push(s)}return o.length>0?[{name:"nav-links",status:"fail",message:`Sidebar/nav links to pages that don't exist: ${o.join(", ")}. These will 404.`}]:[{name:"nav-links",status:"pass",message:`All ${n.length} nav links have matching pages`}]}function Re(r,e){return Is("git",r,{cwd:e,encoding:"utf-8",timeout:3e4,stdio:["pipe","pipe","pipe"]}).trim()}function Aa(r){try{return Re(["rev-parse","--is-inside-work-tree"],r),!0}catch{return!1}}function Lo(r){try{return Re(["status","--porcelain"],r).length>0}catch{return!1}}function No(r,e){return Re(["add","-A"],r),Re(["commit","-m",e,"--allow-empty-message"],r),Re(["rev-parse","HEAD"],r)}function Ls(r){return Re(["rev-parse","HEAD"],r)}function Fo(r){try{return Re(["remote","get-url","origin"],r),!0}catch{return!1}}function Ns(r){try{let e=Re(["rev-parse","--abbrev-ref","HEAD"],r);return Re(["push","origin",e],r),{success:!0}}catch(e){return{success:!1,error:e instanceof Error?e.message:"push failed"}}}function Fs(r){let e=qt(Ho(r)),t=qt(e)===e?e:"/";for(;e!==t&&e!==qt(e);){if(ne(J(e,"pnpm-workspace.yaml"))||ne(J(e,"lerna.json")))return e;let a=J(e,"package.json");if(ne(a))try{if(JSON.parse(La(a,"utf-8")).workspaces)return e}catch{}e=qt(e)}return null}function Us(r){let e=J(Rs(),"mistflow-build");Ds(e,{recursive:!0});let t=J(e,`${Bs(r)}-${Date.now()}`);return Ia(r,t,{recursive:!0,filter:a=>{let i=a.slice(r.length);return!(i.startsWith("/.git")||i.startsWith("\\.git")||i==="/node_modules"||i.startsWith("/node_modules/")||i==="/.open-next"||i.startsWith("/.open-next/")||i==="/.next"||i.startsWith("/.next/"))}}),t}function Es(r,e){let t=J(r,".open-next"),a=J(r,".next");if(ne(t)){let i=J(e,".open-next");ne(i)&&Ma(i,{recursive:!0}),Ia(t,i,{recursive:!0})}if(ne(a)){let i=J(e,".next");ne(i)&&Ma(i,{recursive:!0}),Ia(a,i,{recursive:!0})}}function Hs(r){try{Ma(r,{recursive:!0,force:!0})}catch{console.error(`[deploy] Failed to clean up isolated build dir: ${r}`)}}function lt(r,e,t,a,i,n){return new Promise(o=>{let s=Ms(r,e,{cwd:t,stdio:["pipe","pipe","pipe"],timeout:a,...n?{env:n}:{}}),l="",d="";s.stdout?.on("data",u=>{let h=u.toString();if(d+=h,i)for(let c of h.split(`
|
|
12434
12434
|
`).filter(Boolean))i(c)}),s.stderr?.on("data",u=>{let h=u.toString();if(l+=h,i)for(let c of h.split(`
|
|
12435
|
-
`).filter(Boolean))i(c)}),s.on("close",(u,h)=>{o({success:u===0,stdout:d,stderr:l,signal:h})}),s.on("error",u=>{o({success:!1,stdout:d,stderr:l+u.message})})})}var Sp=Vt.object({projectPath:Vt.string().optional().describe("Path to the project directory (default: current working directory)"),message:Vt.string().optional().describe("Deploy message"),environment:Vt.enum(["production","preview"]).optional().default("production").describe("Target environment: 'production' (default) or 'preview' for a shareable URL")});function Os(r){return new Promise(e=>setTimeout(e,r))}function Uo(r){switch(r){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: ${r}`}}function Ra(r){let e=
|
|
12436
|
-
`)}async function Go(r,e){let a=process.platform==="win32"?"npx.cmd":"npx",i=0,n=
|
|
12435
|
+
`).filter(Boolean))i(c)}),s.on("close",(u,h)=>{o({success:u===0,stdout:d,stderr:l,signal:h})}),s.on("error",u=>{o({success:!1,stdout:d,stderr:l+u.message})})})}var Sp=Vt.object({projectPath:Vt.string().optional().describe("Path to the project directory (default: current working directory)"),message:Vt.string().optional().describe("Deploy message"),environment:Vt.enum(["production","preview"]).optional().default("production").describe("Target environment: 'production' (default) or 'preview' for a shareable URL")});function Os(r){return new Promise(e=>setTimeout(e,r))}function Uo(r){switch(r){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: ${r}`}}function Ra(r){let e=J(r,"mistflow.json");if(ne(e))try{return JSON.parse(La(e,"utf-8"))}catch{}return{}}function Gs(r,e){let t=J(r,"mistflow.json"),a=Ra(r),i=a.deploy?.count??a.deployCount??0;a.deploy={url:e,count:i+1,lastDeployedAt:new Date().toISOString()};let n=a.plan?.steps;if(Array.isArray(n))for(let o of n)o.status==="in_progress"&&(o.status="completed");delete a.deployUrl,delete a.deployCount,Oo(t,JSON.stringify(a,null,2)+`
|
|
12436
|
+
`)}async function Go(r,e){let a=process.platform==="win32"?"npx.cmd":"npx",i=0,n=J(r,"node_modules",".bin","opennextjs-cloudflare"),o=ne(n),s={...process.env,NODE_ENV:"production"},l=await lt(o?n:a,o?["build"]:["@opennextjs/cloudflare","build"],r,3e5,c=>{c.includes("Compiling")?e?.("Compiling your app..."):c.includes("Collecting page data")?e?.("Collecting page data..."):c.includes("Generating static pages")?e?.("Generating static pages..."):c.match(/^[○●◐λƒ]\s/)?i++:c.includes("Creating Cloudflare worker")?e?.("Packaging for Mistflow Cloud..."):c.includes("Build completed")&&e?.("Build completed!")},s);if(l.success)return{success:!0,buildStats:i>0?`${i} routes compiled`:"build complete"};let d=l.stderr+`
|
|
12437
12437
|
`+l.stdout;if(l.signal==="SIGKILL"||d.includes("SIGKILL")||d.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=ft(d);if(u.length>0){let c=u.map((g,b)=>{let y=`${b+1}. ${g.humanMessage}`;return g.suggestion&&(y+=`
|
|
12438
12438
|
Fix: ${g.suggestion}`),y}).join(`
|
|
12439
12439
|
|
|
@@ -12444,15 +12444,15 @@ ${c}`}}let h=d.split(`
|
|
|
12444
12444
|
${h.join(`
|
|
12445
12445
|
`)}`:`OpenNext build failed:
|
|
12446
12446
|
${d.slice(-500)}`}}async function Ws(r,e){let t=Fs(r);if(t)return console.error(`[deploy] Project is inside monorepo at ${t} \u2014 building in isolated temp directory`),e?.("Detected parent project folder \u2014 building in isolated directory..."),Eo(r,e);let a=await Go(r,e);return!a.success&&a.signal==="SIGKILL"?(console.error("[deploy] Build was OOM-killed \u2014 retrying in isolated temp directory"),e?.("Build ran out of memory \u2014 retrying with a fresh setup..."),Eo(r,e)):a}async function Eo(r,e){let t;try{e?.("Copying project to isolated build directory..."),t=Us(r),e?.("Installing dependencies...");let i=process.platform==="win32"?"npm.cmd":"npm",n=await lt(i,["install","--prefer-offline"],t,12e4);if(!n.success)return{success:!1,error:`Failed to install dependencies in isolated build:
|
|
12447
|
-
${n.stderr.slice(-300)}`};await lt(i,["dedupe"],t,6e4);let o=await Go(t,e);return o.success&&(e?.("Copying build artifacts..."),Es(t,r)),{...o,builtInIsolation:t}}finally{t&&Hs(t)}}async function _s(r,e,t){if(!ne(
|
|
12447
|
+
${n.stderr.slice(-300)}`};await lt(i,["dedupe"],t,6e4);let o=await Go(t,e);return o.success&&(e?.("Copying build artifacts..."),Es(t,r)),{...o,builtInIsolation:t}}finally{t&&Hs(t)}}async function _s(r,e,t){if(!ne(J(r,"db","schema")))return{success:!0,skipped:!0,skipReason:"No database structure found"};let a=J(r,"db","schema");try{if(As(a).filter(g=>g.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(!ne(J(r,"drizzle.config.ts")))return{success:!0,skipped:!0,skipReason:"No drizzle.config.ts found"};let i;try{i=await Ja(e)}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:n,credentials:o}=i;if(n==="neon"){if(!o.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(!o.TURSO_URL||!o.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 s={PATH:process.env.PATH??"",HOME:process.env.HOME??"",NODE_PATH:process.env.NODE_PATH??"",TMPDIR:process.env.TMPDIR??"",...o},d=process.platform==="win32"?"npx.cmd":"npx",h=await lt(d,t?["drizzle-kit","push","--force"]:["drizzle-kit","push"],r,6e4,c=>{let g=c.replace(/(?:TURSO_AUTH_TOKEN|DATABASE_URL|AUTH_SECRET)=[^\s&]*/gi,b=>b.split("=")[0]+"=REDACTED").replace(/postgresql:\/\/[^@]*@/g,"postgresql://REDACTED@").replace(/libsql:\/\/[^\s]*/g,"libsql://REDACTED");console.error(`[drizzle-kit] ${g}`)},s);if(!h.success){let c=(h.stderr+`
|
|
12448
12448
|
`+h.stdout).trim(),g=c.toLowerCase();if(g.includes("data-loss")||g.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 b=c.split(`
|
|
12449
12449
|
`).filter(f=>f.includes("error")||f.includes("Error")||f.includes("ERR")).slice(0,5);return{success:!1,error:`Database update failed:
|
|
12450
12450
|
${b.length>0?b.join(`
|
|
12451
12451
|
`):c.slice(-500)}`}}return{success:!0}}async function Wo(r){let{projectPath:e,message:t,environment:a="production",forceSchema:i}=r,n=a,o=Ho(e??process.cwd());if(!ce())return p("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let s=Io(o);if(!s.passed){let T=s.errors.map(R=>{let L=`[${R.check}] ${R.message}`;return R.file&&(L+=` (${R.file}${R.line?`:${R.line}`:""})`),L}).join(`
|
|
12452
12452
|
`);return p(`Deploy blocked \u2014 fix these issues first:
|
|
12453
12453
|
|
|
12454
|
-
${T}`,!0)}let l=s.warnings.map(T=>`[${T.check}] ${T.message}`),d;if(Aa(o))if(Lo(o))try{let T=Ra(o).deploy?.count??0,R=t?`Deploy v${T+1}: ${t}`:`Deploy v${T+1}`;d=No(o,R)}catch{console.error("[deploy] Pre-deploy git commit failed, continuing")}else try{d=Ls(o)}catch{}let u=De(o),h=u?.projectId;if(!h){let T=
|
|
12455
|
-
`)}catch(R){let L=R instanceof
|
|
12454
|
+
${T}`,!0)}let l=s.warnings.map(T=>`[${T.check}] ${T.message}`),d;if(Aa(o))if(Lo(o))try{let T=Ra(o).deploy?.count??0,R=t?`Deploy v${T+1}: ${t}`:`Deploy v${T+1}`;d=No(o,R)}catch{console.error("[deploy] Pre-deploy git commit failed, continuing")}else try{d=Ls(o)}catch{}let u=De(o),h=u?.projectId;if(!h){let T=J(o,"mistflow.json");if(!ne(T))return p("No mistflow.json found. Run mist_build (action: 'init') first to set up your project.",!0);try{let R=JSON.parse(La(T,"utf-8")),L=R.name;if(!L)return p("mistflow.json is missing a project name. Run mist_build (action: 'init') to set up your project.",!0);h=(await Bt(L)).id,R.projectId=h,Oo(T,JSON.stringify(R,null,2)+`
|
|
12455
|
+
`)}catch(R){let L=R instanceof he?R.message:"Check your internet connection.";return p(`Could not register project with Mistflow: ${L}
|
|
12456
12456
|
|
|
12457
12457
|
Try deploying again in a moment.`,!0)}}if(h&&n==="production")try{let T=await za(h),R=T,L=R.deploy_count??T.deployCount??0;(R.deploy_strategy??T.deploy_strategy)==="staging"&&L>0&&(n="preview",console.error("[deploy] Staging mode enabled \u2014 auto-redirecting to preview"))}catch{}let c=[],g=Date.now(),b=(T,R)=>{let L={phase:T,message:R};return c.push(L),L},y=(T,R)=>{T.durationMs=Date.now()-g,R&&(T.message=R)},f=!1;if(h&&n!=="preview"){let T=b("schema","Updating database structure..."),R=await _s(o,h,i);if(R.skipped)y(T,R.skipReason??"Database update skipped");else if(R.success)f=!0,y(T,"Database updated successfully");else return y(T,"Database update failed"),p(`Deploy blocked \u2014 database update failed:
|
|
12458
12458
|
|
|
@@ -12464,43 +12464,43 @@ ${P.error}`,!0);y(v,`Build complete \u2014 ${P.buildStats??"ready"} (${((Date.no
|
|
|
12464
12464
|
|
|
12465
12465
|
${B.summary}
|
|
12466
12466
|
|
|
12467
|
-
Fix these issues and try again.`,!0);let I=
|
|
12468
|
-
`)
|
|
12467
|
+
Fix these issues and try again.`,!0);let I=J(o,".open-next");if(!ne(I))return p("Build succeeded but .open-next/ directory not found. Check your OpenNext configuration.",!0);b("package","Packaging build artifacts...");let M=J(o,".open-next-build.tar.gz"),O=[".open-next"];if(ne(J(o,"db"))&&O.push("db"),ne(J(o,"drizzle.config.ts"))&&O.push("drizzle.config.ts"),ne(J(o,"package.json"))&&O.push("package.json"),!(await lt("tar",["-czf",M,"-C",o,...O],o,6e4)).success)return p("Failed to create build archive. Check disk space and permissions.",!0);let H;{let T=J(o,".mistflow-source.tar.gz");(await lt("tar",["-czf",T,"-C",o,"--exclude",".open-next","--exclude","node_modules","--exclude",".git","--exclude",".next","--exclude",".open-next-build.tar.gz","--exclude",".mistflow-source.tar.gz","."],o,6e4)).success?H=T:console.error("[deploy] Source archive creation failed, continuing without it")}b("upload","Uploading to Mistflow...");let re=Pt()?.email,z,K;try{let T=await Va(h,M,n,re,f,H,d);if(z=T.deployment_id??T.id,!z)return p("Upload succeeded but no deployment ID was returned. Check the Mistflow dashboard.",!0);K=T.status}catch(T){return Ao(T,"Deploy")}finally{try{Ro(M)}catch{}if(H)try{Ro(H)}catch{}}b("deploying","Deploying to the edge...");let U=Date.now(),_=24e4,F=3e3,Q=[Uo(K)],le=K;for(;Date.now()-U<_;){await Os(F);let T;try{T=await Ue(z)}catch{continue}if(T.status!==le&&(Q.push(Uo(T.status)),le=T.status),T.status==="live"){let R=((Date.now()-U)/1e3).toFixed(0),L=T.url??"";if(!L)return p("Deployment marked as live but no URL was returned. Check the Mistflow dashboard.",!0);let oe=n==="preview";if(!oe){Gs(o,L);try{let{readLocalState:m,syncRemoteState:x}=await import("./state-manager-XY6GQEFE.js"),S=m(o);S&&h&&(S.deployCount=(S.deployCount??0)+1,x(h,S).catch(()=>{}))}catch{}if(Aa(o)&&Fo(o))try{Lo(o)&&No(o,"Update deploy metadata"),Ns(o)}catch{}}let ie=oe?"Preview":"App",w=Ra(o),N=w.name,q=typeof N=="string"?N:"my app",me=w.features,pe=Array.isArray(me)?me.length:0,Z=w.plan,xe=Z&&typeof Z=="object"&&"steps"in Z?Z.steps:void 0,we=Array.isArray(xe)?xe.length:0,de=c.map(m=>m.message),$={url:L,time:`${R}s`,deploymentId:z,environment:n,statusLog:Q,deployTimeline:de,message:oe?`${ie} is live at ${L} \u2014 preview deployed in ${R}s. This URL expires in 72 hours.`:`Your app is live at ${L} \u2014 deployed in ${R}s.`};if(oe)$.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='"+L+"' 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(`
|
|
12468
|
+
`),$.nextAction=`MANDATORY: Call mist_build with action='qa' and url='${L}' to verify the preview. After QA passes, ask user to confirm, then call mist_deploy action='promote'.`,$.qaRequired=!0,$.qaUrl=L,$.previewDeploymentId=z,$.promoteAction=`mist_deploy action='promote' deploymentId='${z}'`;else{let m=encodeURIComponent(`Just built "${q}" with AI and deployed it live in ${R}s.
|
|
12469
12469
|
|
|
12470
|
-
${
|
|
12470
|
+
${we} steps, ${pe} features, zero config.
|
|
12471
12471
|
|
|
12472
12472
|
${L}
|
|
12473
12473
|
|
|
12474
12474
|
Built with @mistflow`),x=encodeURIComponent(`I just described an app idea and got a live, working URL in ${R} seconds.
|
|
12475
12475
|
|
|
12476
|
-
"${
|
|
12476
|
+
"${q}" \u2014 ${we} build steps, ${pe} features, fully deployed.
|
|
12477
12477
|
|
|
12478
12478
|
${L}
|
|
12479
12479
|
|
|
12480
|
-
Built with Mistflow (mistflow.ai)`)
|
|
12481
|
-
`)}
|
|
12482
|
-
`)
|
|
12483
|
-
Admin panel: ${L}/admin`:"",S=m?"Admin account created":"Test account created"
|
|
12480
|
+
Built with Mistflow (mistflow.ai)`);$.share={tweetUrl:`https://twitter.com/intent/tweet?text=${m}`,linkedInUrl:`https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(L)}`,celebration:["","================================================",` ${q} is LIVE!`,"================================================","",` ${L}`,"",` Deployed in ${R}s`,` ${pe>0?`${pe} features`:""}${pe>0&&we>0?" \xB7 ":""}${we>0?`${we} build steps`:""}`,""," Share it:",` Twitter \u2192 https://twitter.com/intent/tweet?text=${m}`,` LinkedIn \u2192 https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(L)}`,"","================================================"].join(`
|
|
12481
|
+
`)},$.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(`
|
|
12482
|
+
`),$.nextAction=`MANDATORY: Call mist_build with action='qa' and url='${L}' to verify the app works. Do NOT tell the user the app is ready until QA passes.`,$.qaRequired=!0,$.qaUrl=L}if(T.admin_credentials){let m=!!w.hasAdmin,x=m?`
|
|
12483
|
+
Admin panel: ${L}/admin`:"",S=m?"Admin account created":"Test account created";$.adminCredentials={message:`${S}. Save these credentials \u2014 they won't be shown again.
|
|
12484
12484
|
|
|
12485
12485
|
Email: ${T.admin_credentials.email}
|
|
12486
12486
|
Password: ${T.admin_credentials.password}
|
|
12487
|
-
Login: ${L}/login${x}`}}l.length>0&&(
|
|
12487
|
+
Login: ${L}/login${x}`}}l.length>0&&($.warnings=l);let k=[];if(!oe){let m=JSON.stringify(w).toLowerCase();k.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"}),Aa(o)&&!Fo(o)&&k.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 x=m.includes("user")||m.includes("account")||m.includes("member"),S=m.includes("stripe")||m.includes("payment")||m.includes("billing");x&&!S&&k.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"}),k.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"}),k.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"}),k.push({action:"See analytics",command:`Visit ${_a()} to see pageviews and visitors`,reason:"Track how people are using your app.",priority:"low"})}return k.length>0&&($.nextSteps=k),Ee(L,JSON.stringify($))}if(T.status==="failed")return p(T.error??"Deployment failed. Check the Mistflow dashboard for details.",!0)}return p(`Deploy is taking longer than expected. Your deploy ID is ${z} \u2014 check status later.`,!0)}import{z as Kt}from"zod";import{resolve as js,join as zs}from"path";import{execFileSync as $s}from"child_process";var Mp=Kt.object({projectPath:Kt.string().optional().describe("Path to the project directory (default: cwd)"),action:Kt.enum(["redeploy","rollback"]).describe("Action to perform: 'redeploy' re-deploys the latest build, 'rollback' reverts to a specific previous deployment"),deploymentId:Kt.string().optional().describe("Deployment ID to rollback to (required for 'rollback')")});function _e(r,e){return $s("git",r,{cwd:e,encoding:"utf-8",timeout:3e4,stdio:["pipe","pipe","pipe"]}).trim()}function _o(r){try{return _e(["rev-parse","--is-inside-work-tree"],r),!0}catch{return!1}}async function Vs(r,e,t,a){if(e&&_o(r))try{_e(["cat-file","-t",e],r);let i=!1;try{_e(["status","--porcelain"],r).length>0&&(_e(["stash","push","-m","mistflow-rollback-auto-stash"],r),i=!0)}catch{}return _e(["reset","--hard",e],r),_e(["commit","--allow-empty","-m","Rollback to previous deploy"],r),{method:"git",success:!0,...i?{warning:"Your uncommitted changes were saved to git stash. Run `git stash pop` to restore them."}:{}}}catch{}if(t&&a)try{let{existsSync:i,mkdirSync:n,rmSync:o}=await import("fs"),s=zs(r,".mistflow-rollback-source.tar.gz");await sr(a,s);let{spawn:l}=await import("child_process");await new Promise((d,u)=>{let h=l("tar",["-xzf",s,"-C",r,"--exclude","node_modules","--exclude",".git"],{cwd:r,stdio:"pipe"});h.on("close",c=>c===0?d():u(new Error(`tar exit ${c}`))),h.on("error",u)});try{o(s)}catch{}if(_o(r))try{_e(["add","-A"],r),_e(["commit","-m","Rollback to previous deploy (from source snapshot)"],r)}catch{}return{method:"r2",success:!0}}catch(i){return{method:"r2",success:!1,error:i instanceof Error?i.message:"Source download failed"}}return{method:"none",success:!1,error:"No source snapshot available for this deployment"}}function qs(r){return new Promise(e=>setTimeout(e,r))}function Ks(r){switch(r){case"pending":return"Provisioning...";case"building":return"Building...";case"deploying":return"Deploying to Mistflow Cloud...";case"verifying":return"Verifying deployment...";default:return`Status: ${r}`}}async function jo(r,e,t){let a=Date.now(),i=12e4,n=3e3,o=[],s="";for(;Date.now()-a<i;){await qs(n);let l;try{l=await Ue(r)}catch{continue}if(l.status!==s&&(o.push(Ks(l.status)),s=l.status),l.status==="live"){let d=((Date.now()-a)/1e3).toFixed(0),u=l.url??"";if(t)try{await t()}catch{}return p(JSON.stringify({url:u,time:`${d}s`,deploymentId:r,statusLog:o,message:u?`${e} complete \u2014 live at ${u} in ${d}s.`:`${e} complete in ${d}s.`}))}if(l.status==="failed")return p(l.error??`${e} failed. Check the Mistflow dashboard for details.`,!0)}return p(`${e} is taking longer than expected. Deployment ID: ${r} \u2014 check status later.`,!0)}async function Na(r){let{projectPath:e,action:t,deploymentId:a}=r,i=js(e??process.cwd());if(!ce())return p("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let o=De(i)?.projectId;if(!o)return p("No project ID found. Deploy your project first with mist_deploy, or initialize with mist_plan + mist_build.",!0);try{switch(t){case"redeploy":{let s=await or(o);return jo(s.deployment_id,"Redeploy")}case"rollback":{if(!a)return p("Deployment ID is required for rollback. Use mist_project (action: 'deployments') to see previous deployment IDs.",!0);let s=await nr(a);return jo(s.deployment_id,"Rollback",async()=>{let l=await Vs(i,s.git_commit_sha,s.source_artifact_key,a);l.success||console.error(`[rollback] Local source restore failed: ${l.error}`),l.warning&&console.error(`[rollback] ${l.warning}`)})}default:return p(`Unknown action: ${t}. Use redeploy or rollback.`,!0)}}catch(s){if(s instanceof he)return p(s.message,!0);let l=s instanceof Error?s.message:"An unexpected error occurred";return p(l,!0)}}import{resolve as Ys}from"path";function Js(r){return new Promise(e=>setTimeout(e,r))}async function zo(r){let e=Ys(r.projectPath??process.cwd());if(!ce())return p("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let a=De(e)?.projectId;if(!a)return p("No project ID found. Deploy the project first.",!0);let i=r.deploymentId;if(!i)try{let d=(await pt(a)).find(u=>u.environment==="preview"&&u.status==="live");if(!d)return p("No live preview found to promote. Deploy with staging mode first, then call promote after QA passes.",!0);i=d.id}catch{return p("Could not list deployments. Check your connection.",!0)}console.error(`[promote] Promoting preview ${i} to production...`);let n;try{n=(await ir(a,i)).deployment_id}catch(l){let d=l instanceof Error?l.message:"Promote failed";return p(`Promote failed: ${d}`,!0)}let o=Date.now(),s=12e4;for(;Date.now()-o<s;){await Js(3e3);try{let l=await Ue(n);if(l.status==="live"){let d=((Date.now()-o)/1e3).toFixed(0),u=l.url??"",h={url:u,time:`${d}s`,deploymentId:n,environment:"production",promoted:!0,message:`Promoted to production at ${u} in ${d}s. Same build that passed QA on preview.`};return h.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(`
|
|
12488
12488
|
`),h.nextAction=`MANDATORY: Call mist_build with action='qa' and url='${u}' to verify production.`,h.qaRequired=!0,h.qaUrl=u,u?Ee(u,JSON.stringify(h)):p(JSON.stringify(h))}if(l.status==="failed")return p(`Promote failed: ${l.error??"Check the Mistflow dashboard for details."}`,!0)}catch{}}return p(`Promote is taking longer than expected. Deployment ID: ${n}`,!0)}import{z as $o}from"zod";import{spawn as Zs,execFileSync as Vo}from"child_process";import{existsSync as Jt,readFileSync as qo,writeFileSync as el,mkdirSync as tl}from"fs";import{join as dt,resolve as al}from"path";import{homedir as Ko}from"os";import{createConnection as rl}from"net";import{existsSync as Qs,readFileSync as Xs}from"fs";function Yt(r){let e=new Set;if(!Qs(r))return e;let t=Xs(r,"utf-8");for(let a of t.split(`
|
|
12489
|
-
`)){let i=a.trim();if(!i||i.startsWith("#"))continue;let n=i.indexOf("=");if(n>0){let o=i.slice(0,n).trim(),s=i.slice(n+1).trim();s&&s!=='""'&&s!=="''"&&e.add(o)}}return e}var ol=$o.object({projectPath:$o.string().optional().describe("Path to the project directory (default: current working directory)")});function Yo(){return dt(Ko(),".mistflow","processes.json")}function Jo(){let r=Yo();if(!Jt(r))return[];try{return JSON.parse(qo(r,"utf-8"))}catch{return[]}}function Qo(r){let e=dt(Ko(),".mistflow");Jt(e)||tl(e,{recursive:!0}),el(Yo(),JSON.stringify(r,null,2))}function il(){let r=Jo(),e=[];for(let t of r)try{process.kill(t.pid,0),e.push(t)}catch{}Qo(e)}function Xo(r){return new Promise(e=>{let t=rl({port:r,host:"127.0.0.1"});t.on("connect",()=>{t.destroy(),e(!0)}),t.on("error",()=>{e(!1)})})}async function nl(r,e,t){let a=Date.now();for(;Date.now()-a<e;){if(await Xo(r))return!0;await new Promise(i=>setTimeout(i,t))}return!1}function sl(r){return Jt(dt(r,"mistflow.json"))}function ll(r){let e=dt(r,"mistflow.json");if(!Jt(e))return[];let t;try{t=JSON.parse(qo(e,"utf-8"))}catch{return[]}let a=t.env?.required;if(!a||typeof a!="object")return[];let i=Object.keys(a);if(i.length===0)return[];let n=Yt(dt(r,".env.local"));return i.filter(o=>!n.has(o))}var Zo={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:ol,handler:async r=>{let t=al(r.projectPath??process.cwd()),a=3e3;if(!sl(t))return
|
|
12489
|
+
`)){let i=a.trim();if(!i||i.startsWith("#"))continue;let n=i.indexOf("=");if(n>0){let o=i.slice(0,n).trim(),s=i.slice(n+1).trim();s&&s!=='""'&&s!=="''"&&e.add(o)}}return e}var ol=$o.object({projectPath:$o.string().optional().describe("Path to the project directory (default: current working directory)")});function Yo(){return dt(Ko(),".mistflow","processes.json")}function Jo(){let r=Yo();if(!Jt(r))return[];try{return JSON.parse(qo(r,"utf-8"))}catch{return[]}}function Qo(r){let e=dt(Ko(),".mistflow");Jt(e)||tl(e,{recursive:!0}),el(Yo(),JSON.stringify(r,null,2))}function il(){let r=Jo(),e=[];for(let t of r)try{process.kill(t.pid,0),e.push(t)}catch{}Qo(e)}function Xo(r){return new Promise(e=>{let t=rl({port:r,host:"127.0.0.1"});t.on("connect",()=>{t.destroy(),e(!0)}),t.on("error",()=>{e(!1)})})}async function nl(r,e,t){let a=Date.now();for(;Date.now()-a<e;){if(await Xo(r))return!0;await new Promise(i=>setTimeout(i,t))}return!1}function sl(r){return Jt(dt(r,"mistflow.json"))}function ll(r){let e=dt(r,"mistflow.json");if(!Jt(e))return[];let t;try{t=JSON.parse(qo(e,"utf-8"))}catch{return[]}let a=t.env?.required;if(!a||typeof a!="object")return[];let i=Object.keys(a);if(i.length===0)return[];let n=Yt(dt(r,".env.local"));return i.filter(o=>!n.has(o))}var Zo={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:ol,handler:async r=>{let t=al(r.projectPath??process.cwd()),a=3e3;if(!sl(t))return Te(t);let i=ll(t);if(i.length>0)return p(`Missing required environment variables in .env.local: ${i.join(", ")}. Add them to ${dt(t,".env.local")} before previewing.`,!0);il();let n=await Xo(a),o=Jo(),s=o.some(h=>h.type==="dev-server"&&h.port===a);if(n&&!s)return p(`Port ${a} is in use. Stop the other process or I will use a different port.`,!0);let l=[...o];if(!n){try{Vo("npx",["drizzle-kit","push"],{cwd:t,stdio:["pipe","pipe","pipe"],timeout:3e4})}catch{console.error("[preview] drizzle-kit push failed, continuing...")}try{Vo("npm",["run","build"],{cwd:t,stdio:["pipe","pipe","pipe"],timeout:18e4})}catch(b){let y=b instanceof Error&&"stderr"in b?String(b.stderr).slice(-1500):"",f=b instanceof Error&&"stdout"in b?String(b.stdout).slice(-1500):"",v=(y+`
|
|
12490
12490
|
`+f).trim();return p(`Build failed. Fix the errors before previewing:
|
|
12491
12491
|
|
|
12492
12492
|
${v}`,!0)}let h=Zs("npx",["next","start","-p",String(a)],{cwd:t,detached:!0,stdio:["ignore","pipe","pipe"]}),c="";if(h.stderr?.on("data",b=>{c+=b.toString()}),h.pid&&(h.unref(),l.push({pid:h.pid,type:"dev-server",port:a,startedAt:new Date().toISOString()}),Qo(l)),!await nl(a,15e3,500)){let b=c?`Server failed to start:
|
|
12493
12493
|
|
|
12494
|
-
${c.slice(-1e3)}`:"Server failed to start within 15s. Check for runtime errors.";return p(b,!0)}}let d=`http://localhost:${a}`,u=JSON.stringify({localUrl:d,message:`Preview is live at ${d}. Run mist_deploy to get your permanent URL on mistflow.app.`});return Ee(d,u)}};import{resolve as dl,join as cl}from"path";import{existsSync as pl,readFileSync as ul}from"fs";var Fa="test@mistflow.dev",ei="MistflowTest123!",hl="Test User";function ti(r){let e=cl(r,"mistflow.json");if(!pl(e))return null;try{return JSON.parse(ul(e,"utf-8"))}catch{return null}}function gl(r){let e=JSON.stringify(r).toLowerCase();return["auth","login","sign-in","sign-up","signin","signup"].some(t=>e.includes(t))}function ml(r){let e=r.plan;if(!e?.steps)return[];let t=new Set;for(let i of e.steps)if(i.pages)for(let n of i.pages)t.add(n);let a=new Set(["login","signup","sign-in","sign-up","signin","signout","sign-out","logout"]);return[...t].filter(i=>!a.has(i.toLowerCase())).slice(0,3)}function fl(r){let e=r.deploy;return e?.url?e.url:typeof r.deployUrl=="string"?r.deployUrl:null}async function ai(r){let e=dl(r.projectPath??process.cwd()),t=r.verifyUrl,a=null;if(t)a=ti(e);else{if(a=ti(e),!a)return p("No mistflow.json found. Run mist_deploy first, or pass verifyUrl explicitly.",!0);if(t=fl(a)??void 0,!t)return p("No deploy URL found in mistflow.json. Deploy your app first with mist_deploy.",!0)}t.startsWith("http")||(t=`https://${t}`);let i=a?gl(a):!1,n=a?ml(a):[],o;try{o=await Ct()}catch{return p("Browser not available. Install Playwright to use verify: npx playwright install chromium",!0)}let s={verified:!0,url:t,authTested:!1,testUser:null,pages:[],message:""},l=[];try{await o.goto(t,{waitUntil:"domcontentloaded",timeout:3e4}),await o.waitForLoadState("networkidle").catch(()=>{})}catch{return s.verified=!1,s.message=`Could not load ${t}. The app may not be deployed yet or the URL may be incorrect.`,p(JSON.stringify(s),!0)}let d=await o.title(),u=d.toLowerCase().includes("error")||d.toLowerCase().includes("404")?"error":"ok";s.pages.push({path:"/",status:u,title:d});try{let y=await Fe(o,!1);l.push({data:y.toString("base64"),mimeType:"image/png"})}catch{}if(u==="error"&&(s.verified=!1),i)try{(await o.evaluate(async f=>{let v=await fetch("/api/auth/sign-up/email",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(f)});return{status:v.status,ok:v.ok}},{email:Fa,password:ei,name:hl})).ok||await o.evaluate(async f=>{let v=await fetch("/api/auth/sign-in/email",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(f)});return{status:v.status,ok:v.ok}},{email:Fa,password:ei}),await o.reload({waitUntil:"domcontentloaded",timeout:15e3}),await o.waitForLoadState("networkidle").catch(()=>{}),s.authTested=!0,s.testUser={email:Fa};try{let f=await Fe(o,!1);l.push({data:f.toString("base64"),mimeType:"image/png"})}catch{}}catch{console.error("[verify] Auth test failed, continuing with public pages")}for(let y of n){let f=y.startsWith("/")?y:`/${y}`;try{await o.goto(`${t}${f}`,{waitUntil:"domcontentloaded",timeout:15e3}),await o.waitForLoadState("networkidle").catch(()=>{});let v=await o.title(),C=v.toLowerCase().includes("404")||v.toLowerCase().includes("not found")?"error":"ok";s.pages.push({path:f,status:C,title:v}),C==="error"&&(s.verified=!1);try{let P=await Fe(o,!1);l.push({data:P.toString("base64"),mimeType:"image/png"})}catch{}}catch{s.pages.push({path:f,status:"error",title:"Timeout"}),s.verified=!1}}let h=s.pages.filter(y=>y.status==="ok").length,c=s.pages.length,g=s.authTested?" Auth login successful.":"";s.message=s.verified?`Verified ${h}/${c} pages.${g} App looks good.`:`Verified ${h}/${c} pages \u2014 some issues found.${g} Check screenshots.`;let b=[{type:"text",text:JSON.stringify(s)}];for(let y of l)b.push({type:"image",data:y.data,mimeType:y.mimeType});return{content:b}}var bl=Je.object({action:Je.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:Je.string().optional().describe("Path to the project directory (default: cwd)"),environment:Je.enum(["production","preview"]).optional().describe("(deploy) Target environment. Defaults to 'production'. Projects with staging mode auto-redirect to preview."),forceSchema:Je.boolean().optional().describe("(deploy) Reset the database structure. Warning: this deletes existing data. Only use when the user confirms this is OK."),deploymentId:Je.string().optional().describe("(rollback/promote) Deployment ID to rollback to, or preview deployment ID to promote"),verifyUrl:Je.string().optional().describe("(verify) URL to verify. Defaults to deploy URL from mistflow.json")}),ri={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:bl,handler:async r=>{let e=r;switch(e.action){case"deploy":return Wo({projectPath:e.projectPath,environment:e.environment??"production",forceSchema:e.forceSchema});case"promote":return zo({projectPath:e.projectPath,deploymentId:e.deploymentId});case"preview":return Zo.handler({projectPath:e.projectPath});case"redeploy":return Na({projectPath:e.projectPath,action:"redeploy"});case"rollback":return Na({projectPath:e.projectPath,action:"rollback",deploymentId:e.deploymentId});case"verify":return ai({projectPath:e.projectPath,verifyUrl:e.verifyUrl});default:return p(`Unknown action: ${e.action}. Use deploy, promote, preview, redeploy, rollback, or verify.`,!0)}}};import{z as se}from"zod";import{resolve as Qt}from"path";import{existsSync as Xt,readFileSync as Zt}from"fs";import{join as ea}from"path";import{z as je}from"zod";import{resolve as yl,join as oi}from"path";import{existsSync as xl,readFileSync as wl,writeFileSync as vl}from"fs";var kl=je.object({action:je.enum(["get","update"]).default("get").describe("'get' reads current project state. 'update' modifies it."),projectPath:je.string().optional().describe("Path to the project directory (default: current working directory)"),completedStep:je.number().optional().describe("(update only) Mark a plan step as completed by step number"),addEnvVar:je.object({key:je.string(),description:je.string().optional(),setupUrl:je.string().optional()}).optional().describe("(update only) Add a required env var to the project manifest")}),ii={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:kl,handler:async r=>{let e=r,t=yl(e.projectPath??process.cwd()),a=oi(t,"mistflow.json");if(!xl(a))return
|
|
12494
|
+
${c.slice(-1e3)}`:"Server failed to start within 15s. Check for runtime errors.";return p(b,!0)}}let d=`http://localhost:${a}`,u=JSON.stringify({localUrl:d,message:`Preview is live at ${d}. Run mist_deploy to get your permanent URL on mistflow.app.`});return Ee(d,u)}};import{resolve as dl,join as cl}from"path";import{existsSync as pl,readFileSync as ul}from"fs";var Fa="test@mistflow.dev",ei="MistflowTest123!",hl="Test User";function ti(r){let e=cl(r,"mistflow.json");if(!pl(e))return null;try{return JSON.parse(ul(e,"utf-8"))}catch{return null}}function gl(r){let e=JSON.stringify(r).toLowerCase();return["auth","login","sign-in","sign-up","signin","signup"].some(t=>e.includes(t))}function ml(r){let e=r.plan;if(!e?.steps)return[];let t=new Set;for(let i of e.steps)if(i.pages)for(let n of i.pages)t.add(n);let a=new Set(["login","signup","sign-in","sign-up","signin","signout","sign-out","logout"]);return[...t].filter(i=>!a.has(i.toLowerCase())).slice(0,3)}function fl(r){let e=r.deploy;return e?.url?e.url:typeof r.deployUrl=="string"?r.deployUrl:null}async function ai(r){let e=dl(r.projectPath??process.cwd()),t=r.verifyUrl,a=null;if(t)a=ti(e);else{if(a=ti(e),!a)return p("No mistflow.json found. Run mist_deploy first, or pass verifyUrl explicitly.",!0);if(t=fl(a)??void 0,!t)return p("No deploy URL found in mistflow.json. Deploy your app first with mist_deploy.",!0)}t.startsWith("http")||(t=`https://${t}`);let i=a?gl(a):!1,n=a?ml(a):[],o;try{o=await Ct()}catch{return p("Browser not available. Install Playwright to use verify: npx playwright install chromium",!0)}let s={verified:!0,url:t,authTested:!1,testUser:null,pages:[],message:""},l=[];try{await o.goto(t,{waitUntil:"domcontentloaded",timeout:3e4}),await o.waitForLoadState("networkidle").catch(()=>{})}catch{return s.verified=!1,s.message=`Could not load ${t}. The app may not be deployed yet or the URL may be incorrect.`,p(JSON.stringify(s),!0)}let d=await o.title(),u=d.toLowerCase().includes("error")||d.toLowerCase().includes("404")?"error":"ok";s.pages.push({path:"/",status:u,title:d});try{let y=await Fe(o,!1);l.push({data:y.toString("base64"),mimeType:"image/png"})}catch{}if(u==="error"&&(s.verified=!1),i)try{(await o.evaluate(async f=>{let v=await fetch("/api/auth/sign-up/email",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(f)});return{status:v.status,ok:v.ok}},{email:Fa,password:ei,name:hl})).ok||await o.evaluate(async f=>{let v=await fetch("/api/auth/sign-in/email",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(f)});return{status:v.status,ok:v.ok}},{email:Fa,password:ei}),await o.reload({waitUntil:"domcontentloaded",timeout:15e3}),await o.waitForLoadState("networkidle").catch(()=>{}),s.authTested=!0,s.testUser={email:Fa};try{let f=await Fe(o,!1);l.push({data:f.toString("base64"),mimeType:"image/png"})}catch{}}catch{console.error("[verify] Auth test failed, continuing with public pages")}for(let y of n){let f=y.startsWith("/")?y:`/${y}`;try{await o.goto(`${t}${f}`,{waitUntil:"domcontentloaded",timeout:15e3}),await o.waitForLoadState("networkidle").catch(()=>{});let v=await o.title(),C=v.toLowerCase().includes("404")||v.toLowerCase().includes("not found")?"error":"ok";s.pages.push({path:f,status:C,title:v}),C==="error"&&(s.verified=!1);try{let P=await Fe(o,!1);l.push({data:P.toString("base64"),mimeType:"image/png"})}catch{}}catch{s.pages.push({path:f,status:"error",title:"Timeout"}),s.verified=!1}}let h=s.pages.filter(y=>y.status==="ok").length,c=s.pages.length,g=s.authTested?" Auth login successful.":"";s.message=s.verified?`Verified ${h}/${c} pages.${g} App looks good.`:`Verified ${h}/${c} pages \u2014 some issues found.${g} Check screenshots.`;let b=[{type:"text",text:JSON.stringify(s)}];for(let y of l)b.push({type:"image",data:y.data,mimeType:y.mimeType});return{content:b}}var bl=Je.object({action:Je.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:Je.string().optional().describe("Path to the project directory (default: cwd)"),environment:Je.enum(["production","preview"]).optional().describe("(deploy) Target environment. Defaults to 'production'. Projects with staging mode auto-redirect to preview."),forceSchema:Je.boolean().optional().describe("(deploy) Reset the database structure. Warning: this deletes existing data. Only use when the user confirms this is OK."),deploymentId:Je.string().optional().describe("(rollback/promote) Deployment ID to rollback to, or preview deployment ID to promote"),verifyUrl:Je.string().optional().describe("(verify) URL to verify. Defaults to deploy URL from mistflow.json")}),ri={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:bl,handler:async r=>{let e=r;switch(e.action){case"deploy":return Wo({projectPath:e.projectPath,environment:e.environment??"production",forceSchema:e.forceSchema});case"promote":return zo({projectPath:e.projectPath,deploymentId:e.deploymentId});case"preview":return Zo.handler({projectPath:e.projectPath});case"redeploy":return Na({projectPath:e.projectPath,action:"redeploy"});case"rollback":return Na({projectPath:e.projectPath,action:"rollback",deploymentId:e.deploymentId});case"verify":return ai({projectPath:e.projectPath,verifyUrl:e.verifyUrl});default:return p(`Unknown action: ${e.action}. Use deploy, promote, preview, redeploy, rollback, or verify.`,!0)}}};import{z as se}from"zod";import{resolve as Qt}from"path";import{existsSync as Xt,readFileSync as Zt}from"fs";import{join as ea}from"path";import{z as je}from"zod";import{resolve as yl,join as oi}from"path";import{existsSync as xl,readFileSync as wl,writeFileSync as vl}from"fs";var kl=je.object({action:je.enum(["get","update"]).default("get").describe("'get' reads current project state. 'update' modifies it."),projectPath:je.string().optional().describe("Path to the project directory (default: current working directory)"),completedStep:je.number().optional().describe("(update only) Mark a plan step as completed by step number"),addEnvVar:je.object({key:je.string(),description:je.string().optional(),setupUrl:je.string().optional()}).optional().describe("(update only) Add a required env var to the project manifest")}),ii={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:kl,handler:async r=>{let e=r,t=yl(e.projectPath??process.cwd()),a=oi(t,"mistflow.json");if(!xl(a))return Te(t);let i;try{i=JSON.parse(wl(a,"utf-8"))}catch{return p("Failed to parse mistflow.json.",!0)}if(e.action==="get"){let s=i.plan,l=s?.steps?.filter(f=>f.status==="completed").length??0,d=s?.steps?.length??0,u=Yt(oi(t,".env.local")),h=i.env?.required?Object.entries(i.env.required).map(([f,v])=>({name:f,description:v?.description,configured:u.has(f)})):[];i.projectId&&import("./state-manager-XY6GQEFE.js").then(({fetchRemoteState:f})=>f(i.projectId)).catch(()=>{});let c=[`Project: ${i.name}`];if(s){c.push(`Plan: ${s.summary??s.name??"unnamed"} \u2014 ${l}/${d} steps complete`);for(let f of s.steps){let v=f.status==="completed"?"\u2713":f.status==="in_progress"?"\u2192":" ";c.push(` [${v}] ${f.number}. ${f.name}`)}}let g=h.filter(f=>!f.configured);g.length>0&&c.push(`Missing env vars: ${g.map(f=>f.name).join(", ")}`),i.deploy?.url?c.push(`Deployed: ${i.deploy.url} (${i.deploy.count??0} deploys)`):c.push("Not deployed yet");let b=[],y=s?.steps?.find(f=>f.status!=="completed");return y?b.push(`NEXT: Call mist_build with action='implement' to work on step ${y.number} (${y.name}).`):s&&l===d&&(i.deploy?.url||b.push("NEXT: All steps complete! Call mist_deploy with action='deploy' to deploy the app now.")),g.length>0&&b.push(`Missing env vars in .env.local: ${g.map(f=>f.name).join(", ")}`),p(JSON.stringify({name:i.name,projectId:i.projectId,planProgress:s?{name:s.name,summary:s.summary,totalSteps:d,completedSteps:l,steps:s.steps}:null,envStatus:h,deploy:i.deploy??null,contextMessage:c.join(`
|
|
12495
12495
|
`),nextSteps:b}))}let n=[];if(e.completedStep!==void 0){let s=i.plan;if(s?.steps){let l=s.steps.findIndex(d=>d.number===e.completedStep);if(l===-1)return p(`Step ${e.completedStep} not found in the plan.`,!0);s.steps[l].status="completed",n.push(`Step ${e.completedStep} marked as completed`)}}e.addEnvVar&&(i.env||(i.env={required:{}}),i.env.required||(i.env.required={}),i.env.required[e.addEnvVar.key]={description:e.addEnvVar.description,setupUrl:e.addEnvVar.setupUrl},n.push(`Added required env var: ${e.addEnvVar.key}`)),vl(a,JSON.stringify(i,null,2)+`
|
|
12496
|
-
`),i.projectId&&import("./state-manager-XY6GQEFE.js").then(async({readLocalState:s,syncRemoteState:l})=>{let d=s(t);d&&await l(i.projectId,d)}).catch(()=>{});let o=[];if(e.completedStep!==void 0){let l=i.plan?.steps?.find(d=>d.status!=="completed");l?o.push(`NEXT: Call mist_build with action='implement' to work on step ${l.number} (${l.name}). Do this now.`):o.push("NEXT: All steps complete! Call mist_deploy with action='deploy' to deploy the app now. Do NOT suggest localhost.")}return e.addEnvVar&&(o.push(`Add ${e.addEnvVar.key} to your .env.local file`),e.addEnvVar.setupUrl&&o.push(`Get the value from: ${e.addEnvVar.setupUrl}`)),p(JSON.stringify({updated:!0,changes:n,message:n.length>0?`Project state saved. ${n.join(". ")}.`:"No changes made.",nextSteps:o.length>0?o:void 0}))}};var Sl=se.object({action:se.enum(["get","update","share","landing-designs","app-styles","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. 'app-styles' lists 54 full-app styles (Stripe, Linear, Vercel, etc.) for consistent brand-quality UI across all pages. '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:se.string().optional().describe("Path to the project directory (default: cwd)"),completedStep:se.number().optional().describe("(update) Mark a plan step as completed by step number"),addEnvVar:se.object({key:se.string(),description:se.string().optional(),setupUrl:se.string().optional()}).optional().describe("(update) Add a required env var to the project manifest"),templateDescription:se.string().optional().describe("(share) Short description of what this template builds"),category:se.string().optional().describe("(landing-designs / app-styles) Filter by category"),presetId:se.string().optional().describe("(landing-designs) Get full details for a specific landing design by ID"),appStyleId:se.string().optional().describe("(app-styles) Get full details for a specific app style by ID (e.g. 'stripe', 'linear')"),integrationId:se.string().optional().describe("(integrations) Get full details for a specific integration preset by ID (e.g. 'stripe-payments', 'resend-email', 'elevenlabs-voice')"),period:se.string().optional().describe("(errors) Time period for errors: '1h', '24h', '7d' (default: '7d')"),deploymentId:se.string().optional().describe("(logs) Deployment ID to fetch logs for. If omitted, fetches logs for the latest deployment.")}),ni={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. 'app-styles' lists 54 full-app styles from top companies (Stripe, Linear, Vercel, Notion, etc.) \u2014 pass an ID to mist_plan's appStyle field for consistent brand-quality design across ALL pages. '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:Sl,handler:async r=>{let e=r;if(["share","errors","logs","deployments"].includes(e.action)&&!ce())return p("You need to sign in first. Run mist_setup to connect your account.",!0);switch(e.action){case"get":case"update":return ii.handler({action:e.action,projectPath:e.projectPath,completedStep:e.completedStep,addEnvVar:e.addEnvVar});case"share":{let a=Qt(e.projectPath??process.cwd()),i=ea(a,"mistflow.json");if(!Xt(i))return
|
|
12496
|
+
`),i.projectId&&import("./state-manager-XY6GQEFE.js").then(async({readLocalState:s,syncRemoteState:l})=>{let d=s(t);d&&await l(i.projectId,d)}).catch(()=>{});let o=[];if(e.completedStep!==void 0){let l=i.plan?.steps?.find(d=>d.status!=="completed");l?o.push(`NEXT: Call mist_build with action='implement' to work on step ${l.number} (${l.name}). Do this now.`):o.push("NEXT: All steps complete! Call mist_deploy with action='deploy' to deploy the app now. Do NOT suggest localhost.")}return e.addEnvVar&&(o.push(`Add ${e.addEnvVar.key} to your .env.local file`),e.addEnvVar.setupUrl&&o.push(`Get the value from: ${e.addEnvVar.setupUrl}`)),p(JSON.stringify({updated:!0,changes:n,message:n.length>0?`Project state saved. ${n.join(". ")}.`:"No changes made.",nextSteps:o.length>0?o:void 0}))}};var Sl=se.object({action:se.enum(["get","update","share","landing-designs","app-styles","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. 'app-styles' lists 54 full-app styles (Stripe, Linear, Vercel, etc.) for consistent brand-quality UI across all pages. '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:se.string().optional().describe("Path to the project directory (default: cwd)"),completedStep:se.number().optional().describe("(update) Mark a plan step as completed by step number"),addEnvVar:se.object({key:se.string(),description:se.string().optional(),setupUrl:se.string().optional()}).optional().describe("(update) Add a required env var to the project manifest"),templateDescription:se.string().optional().describe("(share) Short description of what this template builds"),category:se.string().optional().describe("(landing-designs / app-styles) Filter by category"),presetId:se.string().optional().describe("(landing-designs) Get full details for a specific landing design by ID"),appStyleId:se.string().optional().describe("(app-styles) Get full details for a specific app style by ID (e.g. 'stripe', 'linear')"),integrationId:se.string().optional().describe("(integrations) Get full details for a specific integration preset by ID (e.g. 'stripe-payments', 'resend-email', 'elevenlabs-voice')"),period:se.string().optional().describe("(errors) Time period for errors: '1h', '24h', '7d' (default: '7d')"),deploymentId:se.string().optional().describe("(logs) Deployment ID to fetch logs for. If omitted, fetches logs for the latest deployment.")}),ni={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. 'app-styles' lists 54 full-app styles from top companies (Stripe, Linear, Vercel, Notion, etc.) \u2014 pass an ID to mist_plan's appStyle field for consistent brand-quality design across ALL pages. '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:Sl,handler:async r=>{let e=r;if(["share","errors","logs","deployments"].includes(e.action)&&!ce())return p("You need to sign in first. Run mist_setup to connect your account.",!0);switch(e.action){case"get":case"update":return ii.handler({action:e.action,projectPath:e.projectPath,completedStep:e.completedStep,addEnvVar:e.addEnvVar});case"share":{let a=Qt(e.projectPath??process.cwd()),i=ea(a,"mistflow.json");if(!Xt(i))return Te(a);let n;try{n=JSON.parse(Zt(i,"utf-8"))}catch{return p("Could not read mistflow.json.",!0)}let o=n.projectId;if(!o)return p("No project ID found. Deploy the project first to register it.",!0);try{let s=await hr(o,{isTemplate:!0,description:e.templateDescription});return p(JSON.stringify({shareUrl:s.share_url,shareToken:s.share_token,message:`Your project is now a shareable template!
|
|
12497
12497
|
|
|
12498
12498
|
Anyone can fork it: ${s.share_url}
|
|
12499
12499
|
|
|
12500
12500
|
Others can use it in their AI editor:
|
|
12501
|
-
"build me something like ${s.share_url}"`}))}catch(s){let l=s instanceof Error?s.message:"Failed to share project";return p(l,!0)}}case"landing-designs":{if(e.presetId){let o=et(e.presetId);if(!o)return p(`Preset '${e.presetId}' not found. Use mist_project action='presets' without presetId to list all available presets.`,!0);let s=xr(e.presetId);return p(JSON.stringify({preset:{id:o.id,title:o.title,category:o.category,description:s?.description??"",style:s?.style??"",theme:s?.theme??"dark",colors:s?.colors??[],tags:s?.tags??[],promptLength:o.prompt.length},message:`Landing design "${o.title}" (${o.category}) \u2014 ${s?.description??""}. To use it, pass landingDesign="${o.id}" when calling mist_plan.`}))}let a=vr(e.category??void 0),i=da(e.category),n=wr(i);return p(JSON.stringify({count:a.length,presets:a.map(o=>({id:o.id,title:o.title,category:o.category,description:o.description,style:o.style,theme:o.theme,colors:o.colors})),formatted:n,message:`${a.length} landing designs available.${e.category?` Filtered by: ${e.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 ${Ae()}/designs?tab=landing-designs.`}))}case"app-styles":{if(e.appStyleId){let o=me(e.appStyleId);if(!o)return p(`App style '${e.appStyleId}' not found. Use mist_project action='app-styles' without appStyleId to list all available app styles.`,!0);let s=Ie(o.id);return p(JSON.stringify({appStyle:{id:o.id,name:o.name,category:s?.category??o.category,description:s?.description??"",theme:s?.theme??"light",colors:s?.colors??[],fonts:s?.fonts??{heading:"Inter",body:"Inter"},tags:s?.tags??[],sectionCount:o.sections.length,sections:o.sections.map(l=>l.title)},message:`App style "${o.name}" (${o.category}) \u2014 ${s?.description??""}. To use it, pass appStyle="${o.id}" when calling mist_plan. The style's component specs, typography, color palette, and layout rules will be injected during ALL implementation steps for consistent brand-quality design.`}))}let a=ut(e.category??void 0),i=pa(e.category??void 0),n=Tr(i);return p(JSON.stringify({count:a.length,appStyles:a.map(o=>({id:o.id,name:o.name,category:o.category,description:o.description,theme:o.theme,colors:o.colors,fonts:o.fonts})),formatted:n,message:`${a.length} app styles available.${e.category?` Filtered by: ${e.category}.`:""} To use one, pass appStyle="<id>" when calling mist_plan. The style will be applied across ALL pages for consistent design. Browse them at ${Ae()}/designs?tab=app-styles.`}))}case"integrations":{if(e.integrationId){let o=at(e.integrationId);if(!o)return p(`Integration '${e.integrationId}' not found. Use mist_project action='integrations' without integrationId to list all available integrations.`,!0);let s=rt(o.id);return p(JSON.stringify({integration:{id:o.id,name:o.name,category:o.category,description:s?.description??"",packages:s?.packages??[],envVars:s?.envVars??[],docsUrl:s?.docsUrl??"",difficulty:s?.difficulty??"medium"},message:`Integration "${o.name}" (${o.category}) \u2014 ${s?.description??""}. This blueprint is auto-injected during implementation when your plan has a matching integration step. Required env vars: ${s?.envVars?.map(l=>l.key).join(", ")||"none"}. Docs: ${s?.docsUrl??"n/a"}.`}))}let a=Ar(e.category??void 0),i=ha(e.category??void 0),n=Dr(i);return p(JSON.stringify({count:a.length,integrations:a.map(o=>({id:o.id,name:o.name,category:o.category,description:o.description,packages:o.packages,difficulty:o.difficulty,envVars:o.envVars.map(s=>s.key)})),formatted:n,message:`${a.length} integration blueprints available.${e.category?` Filtered by: ${e.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 a=Qt(e.projectPath??process.cwd()),i=ea(a,"mistflow.json");if(!Xt(i))return Ce(a);let n;try{n=JSON.parse(Zt(i,"utf-8"))}catch{return p("Could not read mistflow.json.",!0)}let o=n.projectId;if(!o)return p("No project ID found. Deploy the project first.",!0);try{let s=await rr(o,e.period??"7d");return s.total===0?p(JSON.stringify({total:0,period:s.period,message:`No runtime errors in the last ${s.period}. The app is running clean.`})):p(JSON.stringify({total:s.total,period:s.period,errors:s.errors,message:`${s.total} runtime error(s) in the last ${s.period}. Review the errors above and use mist_build debug to investigate.`}))}catch(s){let l=s instanceof Error?s.message:"Failed to fetch errors";return p(l,!0)}}case"logs":{let a=Qt(e.projectPath??process.cwd()),i=ea(a,"mistflow.json");if(!Xt(i))return Ce(a);let n;try{n=JSON.parse(Zt(i,"utf-8"))}catch{return p("Could not read mistflow.json.",!0)}let o=n.projectId;if(!o)return p("No project ID found. Deploy the project first.",!0);let s=e.deploymentId;if(!s)try{let l=await pt(o);if(l.length===0)return p("No deployments found for this project.",!0);s=l[0].id}catch(l){let d=l instanceof Error?l.message:"Failed to fetch deployments";return p(d,!0)}try{let[l,d]=await Promise.all([ar(s),Ue(s)]),u=l.filter(c=>c.level==="error"),h=l.filter(c=>c.level==="warn");return p(JSON.stringify({deploymentId:s,status:d.status,errorMessage:d.error??null,totalLogs:l.length,errorCount:u.length,warnCount:h.length,logs:l.map(c=>({time:c.timestamp,level:c.level,phase:c.phase,message:c.message})),message:d.status==="failed"?`Deployment failed. ${u.length} error(s) found in logs. Review the logs above to diagnose the issue.`:`Deployment status: ${d.status}. ${l.length} log entries (${u.length} errors, ${h.length} warnings).`}))}catch(l){let d=l instanceof Error?l.message:"Failed to fetch deploy logs";return p(d,!0)}}case"deployments":{let a=Qt(e.projectPath??process.cwd()),i=ea(a,"mistflow.json");if(!Xt(i))return Ce(a);let n;try{n=JSON.parse(Zt(i,"utf-8"))}catch{return p("Could not read mistflow.json.",!0)}let o=n.projectId;if(!o)return p("No project ID found. Deploy the project first.",!0);try{let s=await pt(o);return p(JSON.stringify({total:s.length,deployments:s.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:`${s.length} deployment(s) found. Use mist_project action='logs' deploymentId='<id>' to see detailed logs for any deployment.`}))}catch(s){let l=s instanceof Error?s.message:"Failed to fetch deployments";return p(l,!0)}}case"version":{let a=St(),i=a.severity==="none",n={none:"up to date",patch:"patch update available",minor:"minor update available",major:"major update available",unsupported:"UNSUPPORTED \u2014 upgrade required"};return p(JSON.stringify({current:a.current,latest:a.latest||"unknown",minSupported:a.minSupported||"unknown",severity:a.severity,upToDate:i,upgradeCmd:a.upgradeCmd,changelogUrl:a.changelogUrl,backendSignalReceived:a.backendSignalReceived,message:a.backendSignalReceived?`Mistflow MCP ${a.current} (${n[a.severity]??a.severity}). Latest: ${a.latest}.${i?"":` Run \`${a.upgradeCmd}\` and restart your editor to upgrade.`}`:`Mistflow MCP ${a.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 p(`Unknown action: ${e.action}. Use get, update, share, landing-designs, app-styles, integrations, errors, logs, deployments, or version.`,!0)}}};import{z as Te}from"zod";import{z as ze}from"zod";import{resolve as Cl}from"path";var Ru=ze.object({projectPath:ze.string().optional().describe("Path to the project directory (default: cwd)"),action:ze.enum(["set","list","delete"]).describe("Action to perform"),key:ze.string().optional().describe("Environment variable name (required for 'set' and 'delete')"),value:ze.string().optional().describe("Environment variable value (required for 'set')"),category:ze.string().optional().describe("Category for the env var (default: 'custom')"),description:ze.string().optional().describe("Description of what this env var is for"),setupUrl:ze.string().optional().describe("URL where the user can obtain this value (e.g. Stripe dashboard)")});async function si(r){let{projectPath:e,action:t,key:a,value:i,category:n,description:o,setupUrl:s}=r,l=Cl(e??process.cwd());if(!ce())return p("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let u=De(l)?.projectId;if(!u)return p("No project ID found. Deploy your project first with mist_deploy, or initialize with mist_plan + mist_build.",!0);try{switch(t){case"set":return a?i?(await er(u,a,i,{category:n,description:o,setupUrl:s}),p(JSON.stringify({set:!0,key:a,message:`Environment variable '${a}' has been set. It will be available on your next deployment.`}))):p("Value is required. Provide the env var value.",!0):p("Key is required. Provide the env var name like 'STRIPE_SECRET_KEY'.",!0);case"list":{let h=await Za(u);return h.length===0?p(JSON.stringify({envVars:[],message:"No environment variables configured. Use action 'set' to add one."})):p(JSON.stringify({envVars:h.map(c=>({key:c.key,category:c.category,description:c.description,hasValue:c.has_value})),message:`${h.length} environment variable(s) configured.`}))}case"delete":return a?(await tr(u,a),p(JSON.stringify({deleted:!0,key:a,message:`Environment variable '${a}' has been removed.`}))):p("Key is required. Provide the env var name to delete.",!0);default:return p(`Unknown action: ${t}. Use set, list, or delete.`,!0)}}catch(h){if(h instanceof ue)return p(h.message,!0);let c=h instanceof Error?h.message:"An unexpected error occurred";return p(c,!0)}}import{z as xt}from"zod";import{resolve as Tl,join as Pl}from"path";import{existsSync as Bl,readFileSync as Dl,writeFileSync as Al}from"fs";var Gu=xt.object({projectPath:xt.string().optional().describe("Path to the project directory (default: cwd)"),action:xt.enum(["add","list","verify","remove"]).describe("Action to perform"),domain:xt.string().optional().describe("Domain name (required for 'add' and 'remove')"),domainId:xt.string().optional().describe("Domain ID (required for 'verify' and 'remove')")});function Ua(r,e){let t=Pl(r,"mistflow.json");if(!Bl(t))return;let a;try{a=JSON.parse(Dl(t,"utf-8"))}catch{return}a.domains=e,Al(t,JSON.stringify(a,null,2)+`
|
|
12502
|
-
`)}async function li(r){let{projectPath:e,action:t,domain:a,domainId:i}=r,n=Tl(e??process.cwd());if(!ce())return p("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let s=De(n)?.projectId;if(!s)return p("No project ID found. Deploy your project first with mist_deploy, or initialize with mist_plan + mist_build.",!0);try{switch(t){case"add":{if(!a)return p("Domain name is required. Provide the domain like 'myapp.com' or 'app.mycompany.com'.",!0);let l=await Ka(s,a),d=await qe(s);return Ua(n,d.map(u=>({domain:u.domain,status:u.status}))),p(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 qe(s);return l.length===0?p(JSON.stringify({domains:[],message:"No custom domains configured. Use action 'add' to add one."})):p(JSON.stringify({domains:l.map(d=>({id:d.id,domain:d.domain,status:d.status,ssl:d.ssl_status,error:d.error_message}))}))}case"verify":{if(!i){if(a){let h=(await qe(s)).find(c=>c.domain===a);if(h){let c=await oa(s,h.id);return p(JSON.stringify({domain:c.domain,status:c.status,ssl:c.ssl_status,error:c.error_message,message:c.status==="active"?`Domain '${c.domain}' is active and serving traffic.`:`Domain '${c.domain}' is ${c.status}. Make sure DNS records are configured correctly.`}))}return p(`Domain '${a}' not found. Use action 'list' to see configured domains.`,!0)}return p("Provide either domainId or domain name to verify.",!0)}let l=await oa(s,i),d=await qe(s);return Ua(n,d.map(u=>({domain:u.domain,status:u.status}))),p(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(!i&&!a)return p("Provide either domainId or domain name to remove.",!0);let l=i;if(!l&&a){let h=(await qe(s)).find(c=>c.domain===a);if(!h)return p(`Domain '${a}' not found.`,!0);l=h.id}await Ya(s,l);let d=await qe(s);return Ua(n,d.map(u=>({domain:u.domain,status:u.status}))),p(JSON.stringify({removed:!0,message:"Domain removed. It may take a few minutes for DNS changes to propagate."}))}default:return p(`Unknown action: ${t}. Use add, list, verify, or remove.`,!0)}}catch(l){if(l instanceof ue)return p(l.message,!0);let d=l instanceof Error?l.message:"An unexpected error occurred";return p(d,!0)}}var Il=Te.object({resource:Te.enum(["env","domain"]).describe("'env' manages app secrets and configuration values. 'domain' manages custom domains."),action:Te.string().describe("Action to perform. env: 'set', 'list', 'delete'. domain: 'add', 'list', 'verify', 'remove'."),projectPath:Te.string().optional().describe("Path to the project directory (default: cwd)"),key:Te.string().optional().describe("(env) Variable name"),value:Te.string().optional().describe("(env set) Variable value"),category:Te.string().optional().describe("(env set) Category"),description:Te.string().optional().describe("(env set) Description"),setupUrl:Te.string().optional().describe("(env set) URL to obtain the value"),domain:Te.string().optional().describe("(domain) Domain name"),domainId:Te.string().optional().describe("(domain) Domain ID")}),di={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:Il,handler:async r=>{let e=r;switch(e.resource){case"env":return si({projectPath:e.projectPath,action:e.action,key:e.key,value:e.value,category:e.category,description:e.description,setupUrl:e.setupUrl});case"domain":return li({projectPath:e.projectPath,action:e.action,domain:e.domain,domainId:e.domainId});default:return p(`Unknown resource: ${e.resource}. Use env or domain.`,!0)}}};import{z as Qe}from"zod";var Ml=Qe.object({action:Qe.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:Qe.string().optional().describe("URL to navigate to. Required for 'navigate'; optional for 'screenshot' (navigates before capturing)."),selector:Qe.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:Qe.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:Qe.boolean().default(!1).describe("For 'screenshot': capture the full scrollable page instead of just the viewport."),includeScreenshot:Qe.boolean().default(!1).describe("For navigate/interact actions: also return a screenshot alongside the accessibility snapshot.")}),ci={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:Ml,handler:async r=>{let e=r,t=await Ct();if(e.action==="navigate"){if(!e.url)return p("URL is required for 'navigate'.",!0);let n=[],o=d=>{d.type()==="error"&&n.push(d.text())};t.on("console",o),await t.goto(e.url,{waitUntil:"domcontentloaded",timeout:3e4}),await t.waitForLoadState("networkidle").catch(()=>{});let s=[],l=d=>s.push(d.message);if(t.on("pageerror",l),await t.waitForTimeout(500),t.removeListener("console",o),t.removeListener("pageerror",l),n.length>0||s.length>0){let d=await Tt(t),u=[{type:"text",text:JSON.stringify({url:t.url(),title:await t.title(),snapshot:d,consoleErrors:n,pageErrors:s,hasErrors:!0})}];if(e.includeScreenshot){let h=await Fe(t);u.push({type:"image",data:h.toString("base64"),mimeType:"image/png"})}return{content:u}}}else if(e.action==="go_back")await t.goBack({waitUntil:"domcontentloaded",timeout:1e4});else if(e.action==="go_forward")await t.goForward({waitUntil:"domcontentloaded",timeout:1e4});else if(e.action==="click"){if(!e.selector)return p("Selector is required for 'click'.",!0);await t.click(e.selector,{timeout:1e4}),await t.waitForLoadState("domcontentloaded").catch(()=>{}),await t.waitForTimeout(500)}else if(e.action==="type"){if(!e.selector)return p("Selector is required for 'type'.",!0);if(!e.value)return p("Value is required for 'type'.",!0);await t.type(e.selector,e.value,{delay:50})}else if(e.action==="fill"){if(!e.selector)return p("Selector is required for 'fill'.",!0);if(!e.value)return p("Value is required for 'fill'.",!0);await t.fill(e.selector,e.value)}else if(e.action==="select_option"){if(!e.selector)return p("Selector is required for 'select_option'.",!0);if(!e.value)return p("Value is required for 'select_option'.",!0);await t.selectOption(e.selector,e.value)}else if(e.action==="hover"){if(!e.selector)return p("Selector is required for 'hover'.",!0);await t.hover(e.selector,{timeout:1e4})}else if(e.action==="press_key"){if(!e.value)return p("Value is required for 'press_key' (e.g. 'Enter').",!0);await t.keyboard.press(e.value),await t.waitForLoadState("domcontentloaded").catch(()=>{}),await t.waitForTimeout(500)}else if(e.action==="screenshot"){e.url&&(await t.goto(e.url,{waitUntil:"domcontentloaded",timeout:3e4}),await t.waitForLoadState("networkidle").catch(()=>{}));let n;if(e.selector){let o=await t.$(e.selector);if(!o)return p(`Element not found: ${e.selector}`,!0);n=await o.screenshot({type:"png"})}else n=await Fe(t,e.fullPage);return{content:[{type:"text",text:JSON.stringify({url:t.url(),title:await t.title(),message:`Screenshot captured (${e.fullPage?"full page":"viewport"})`})},{type:"image",data:n.toString("base64"),mimeType:"image/png"}]}}else if(e.action==="snapshot"){let n=await Tt(t);return{content:[{type:"text",text:JSON.stringify({url:t.url(),title:await t.title(),snapshot:n})}]}}let a=await Tt(t),i=[{type:"text",text:JSON.stringify({url:t.url(),title:await t.title(),snapshot:a})}];if(e.includeScreenshot){let n=await Fe(t);i.push({type:"image",data:n.toString("base64"),mimeType:"image/png"})}return{content:i}}};import{existsSync as Le,readFileSync as vt,writeFileSync as ct}from"fs";import{join as Pe}from"path";import{z as wt}from"zod";function pi(r){let e=Pe(r,"mistflow.json");if(!Le(e))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 t;try{t=JSON.parse(vt(e,"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(!t.name||typeof t.name!="string")return{result:{name:"Project",status:"warn",message:"mistflow.json is missing the 'name' field."},config:t};let a=t.projectId,i=a?`, id: ${a}`:", no projectId";return{result:{name:"Project",status:"pass",message:`${t.name}${i}`},config:t}}async function Rl(){let r=Wa();if(!r.ok)return{result:{name:"Auth",status:"fail",message:r.reason==="missing"?"No credentials found.":"Credentials file is malformed.",fix:"Run mist_setup to log in."},creds:null,authValid:!1};try{let e=ja(),t=await fetch(`${Ve()}/api/org`,{headers:e,signal:AbortSignal.timeout(1e4)});try{Oa(t.headers)}catch{}if(!t.ok)return t.status===401?{result:{name:"Auth",status:"fail",message:"API key is invalid or revoked.",fix:"Run mist_setup to re-authenticate."},creds:r.creds,authValid:!1}:{result:{name:"Auth",status:"warn",message:`Server returned ${t.status}. Credentials may still be valid.`},creds:r.creds,authValid:!1};let a=await t.json(),i=a.slug??r.creds.orgSlug??"unknown",n=a.plan?`, plan: ${a.plan}`:"";return{result:{name:"Auth",status:"pass",message:`org: ${i}${n}`},creds:r.creds,authValid:!0}}catch(e){return e instanceof ue?{result:{name:"Auth",status:"fail",message:`Auth check failed: ${e.message}`,fix:"Run mist_setup to re-authenticate."},creds:r.creds,authValid:!1}:{result:{name:"Auth",status:"warn",message:"Could not reach API to validate credentials. Network issue?"},creds:r.creds,authValid:!1}}}async function Ll(){let r=Date.now();try{let e=await Dt("nextjs"),t=Date.now()-r;return{result:{name:"API",status:"pass",message:`${Ve()} reachable (${t}ms)`},scaffold:e}}catch(e){let t=Date.now()-r;return{result:{name:"API",status:"fail",message:e instanceof ue?e.message:`Timeout or network error after ${t}ms`,fix:"Check your network connection. If using --api-url, verify the backend is running."},scaffold:null}}}function Nl(){let r=St();if(!r.backendSignalReceived)return{name:"MCP version",status:"warn",message:`v${r.current} installed, but no backend signal received to compare against.`};let e={none:"up to date",patch:"patch update available",minor:"minor update available",major:"major update available",unsupported:"no longer supported"};return r.severity==="none"?{name:"MCP version",status:"pass",message:`v${r.current} (latest)`}:r.severity==="unsupported"?{name:"MCP version",status:"fail",message:`v${r.current} is ${e[r.severity]}. Minimum: v${r.minSupported}.`,fix:`Run \`${r.upgradeCmd}\` then restart your editor.`}:{name:"MCP version",status:"warn",message:`v${r.current} installed, v${r.latest} available (${e[r.severity]}).`,fix:`Run \`${r.upgradeCmd}\` then restart your editor.`}}function Fl(r,e,t,a){let i=Pe(r,"AGENTS.md"),n=Pe(r,"CLAUDE.md"),o=Le(i),s=e.methodologyVersion??"",l=t?.version??"";if(!o){if(!a||!t?.methodology)return{name:"AGENTS.md",status:"fail",message:"Missing. The host AI has no methodology context for this project.",fix:t?"Run mist_doctor without reportOnly to auto-restore it.":"Cannot restore: API unreachable. Fix connectivity first."};let d=ui(t.methodology,e);return ct(i,d),ct(n,d),{name:"AGENTS.md",status:"fix",message:`Restored from methodology v${l}.`}}if(a&&!Le(n)){let d=vt(i,"utf-8");ct(n,d)}if(l&&s&&l!==s){if(!a||!t?.methodology)return{name:"AGENTS.md",status:"warn",message:`Methodology v${s} installed, v${l} available.`,fix:"Run mist_doctor to update it."};let d=ui(t.methodology,e);ct(i,d),ct(n,d);try{let u=Pe(r,"mistflow.json"),h=JSON.parse(vt(u,"utf-8"));h.methodologyVersion=l,ct(u,JSON.stringify(h,null,2)+`
|
|
12503
|
-
`)}catch{}return{name:"AGENTS.md",status:"fix",message:`Updated methodology v${s} -> v${l}.`}}return{name:"AGENTS.md",status:"pass",message:s?`v${s}`:"present"}}async function Ul(r,e,t,a){let i=e.projectId;if(!i)return{name:"State sync",status:"skip",message:"No projectId. State sync not applicable without a linked project."};if(!t)return{name:"State sync",status:"skip",message:"Skipped (not authenticated)."};let n=gr(r),o=await mr(i);if(!n&&!o)return{name:"State sync",status:"warn",message:"No local or remote state found."};if(!n&&o){if(a){let{writeLocalState:s}=await import("./state-manager-XY6GQEFE.js");return s(r,o),{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 n&&!o?{name:"State sync",status:"warn",message:"Local state exists but no remote state found. Remote sync may have failed."}:n&&n.projectId!==i?{name:"State sync",status:"warn",message:`state.json projectId (${n.projectId}) doesn't match mistflow.json projectId (${i}).`}:{name:"State sync",status:"pass",message:`deployCount: ${n.deployCount}, features: ${n.features.length}`}}function El(r){let e=[],t=[];if(Le(
|
|
12501
|
+
"build me something like ${s.share_url}"`}))}catch(s){let l=s instanceof Error?s.message:"Failed to share project";return p(l,!0)}}case"landing-designs":{if(e.presetId){let o=et(e.presetId);if(!o)return p(`Preset '${e.presetId}' not found. Use mist_project action='presets' without presetId to list all available presets.`,!0);let s=xr(e.presetId);return p(JSON.stringify({preset:{id:o.id,title:o.title,category:o.category,description:s?.description??"",style:s?.style??"",theme:s?.theme??"dark",colors:s?.colors??[],tags:s?.tags??[],promptLength:o.prompt.length},message:`Landing design "${o.title}" (${o.category}) \u2014 ${s?.description??""}. To use it, pass landingDesign="${o.id}" when calling mist_plan.`}))}let a=vr(e.category??void 0),i=da(e.category),n=wr(i);return p(JSON.stringify({count:a.length,presets:a.map(o=>({id:o.id,title:o.title,category:o.category,description:o.description,style:o.style,theme:o.theme,colors:o.colors})),formatted:n,message:`${a.length} landing designs available.${e.category?` Filtered by: ${e.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 ${Ae()}/designs?tab=landing-designs.`}))}case"app-styles":{if(e.appStyleId){let o=fe(e.appStyleId);if(!o)return p(`App style '${e.appStyleId}' not found. Use mist_project action='app-styles' without appStyleId to list all available app styles.`,!0);let s=Ie(o.id);return p(JSON.stringify({appStyle:{id:o.id,name:o.name,category:s?.category??o.category,description:s?.description??"",theme:s?.theme??"light",colors:s?.colors??[],fonts:s?.fonts??{heading:"Inter",body:"Inter"},tags:s?.tags??[],sectionCount:o.sections.length,sections:o.sections.map(l=>l.title)},message:`App style "${o.name}" (${o.category}) \u2014 ${s?.description??""}. To use it, pass appStyle="${o.id}" when calling mist_plan. The style's component specs, typography, color palette, and layout rules will be injected during ALL implementation steps for consistent brand-quality design.`}))}let a=ut(e.category??void 0),i=pa(e.category??void 0),n=Tr(i);return p(JSON.stringify({count:a.length,appStyles:a.map(o=>({id:o.id,name:o.name,category:o.category,description:o.description,theme:o.theme,colors:o.colors,fonts:o.fonts})),formatted:n,message:`${a.length} app styles available.${e.category?` Filtered by: ${e.category}.`:""} To use one, pass appStyle="<id>" when calling mist_plan. The style will be applied across ALL pages for consistent design. Browse them at ${Ae()}/designs?tab=app-styles.`}))}case"integrations":{if(e.integrationId){let o=at(e.integrationId);if(!o)return p(`Integration '${e.integrationId}' not found. Use mist_project action='integrations' without integrationId to list all available integrations.`,!0);let s=rt(o.id);return p(JSON.stringify({integration:{id:o.id,name:o.name,category:o.category,description:s?.description??"",packages:s?.packages??[],envVars:s?.envVars??[],docsUrl:s?.docsUrl??"",difficulty:s?.difficulty??"medium"},message:`Integration "${o.name}" (${o.category}) \u2014 ${s?.description??""}. This blueprint is auto-injected during implementation when your plan has a matching integration step. Required env vars: ${s?.envVars?.map(l=>l.key).join(", ")||"none"}. Docs: ${s?.docsUrl??"n/a"}.`}))}let a=Ar(e.category??void 0),i=ha(e.category??void 0),n=Dr(i);return p(JSON.stringify({count:a.length,integrations:a.map(o=>({id:o.id,name:o.name,category:o.category,description:o.description,packages:o.packages,difficulty:o.difficulty,envVars:o.envVars.map(s=>s.key)})),formatted:n,message:`${a.length} integration blueprints available.${e.category?` Filtered by: ${e.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 a=Qt(e.projectPath??process.cwd()),i=ea(a,"mistflow.json");if(!Xt(i))return Te(a);let n;try{n=JSON.parse(Zt(i,"utf-8"))}catch{return p("Could not read mistflow.json.",!0)}let o=n.projectId;if(!o)return p("No project ID found. Deploy the project first.",!0);try{let s=await rr(o,e.period??"7d");return s.total===0?p(JSON.stringify({total:0,period:s.period,message:`No runtime errors in the last ${s.period}. The app is running clean.`})):p(JSON.stringify({total:s.total,period:s.period,errors:s.errors,message:`${s.total} runtime error(s) in the last ${s.period}. Review the errors above and use mist_build debug to investigate.`}))}catch(s){let l=s instanceof Error?s.message:"Failed to fetch errors";return p(l,!0)}}case"logs":{let a=Qt(e.projectPath??process.cwd()),i=ea(a,"mistflow.json");if(!Xt(i))return Te(a);let n;try{n=JSON.parse(Zt(i,"utf-8"))}catch{return p("Could not read mistflow.json.",!0)}let o=n.projectId;if(!o)return p("No project ID found. Deploy the project first.",!0);let s=e.deploymentId;if(!s)try{let l=await pt(o);if(l.length===0)return p("No deployments found for this project.",!0);s=l[0].id}catch(l){let d=l instanceof Error?l.message:"Failed to fetch deployments";return p(d,!0)}try{let[l,d]=await Promise.all([ar(s),Ue(s)]),u=l.filter(c=>c.level==="error"),h=l.filter(c=>c.level==="warn");return p(JSON.stringify({deploymentId:s,status:d.status,errorMessage:d.error??null,totalLogs:l.length,errorCount:u.length,warnCount:h.length,logs:l.map(c=>({time:c.timestamp,level:c.level,phase:c.phase,message:c.message})),message:d.status==="failed"?`Deployment failed. ${u.length} error(s) found in logs. Review the logs above to diagnose the issue.`:`Deployment status: ${d.status}. ${l.length} log entries (${u.length} errors, ${h.length} warnings).`}))}catch(l){let d=l instanceof Error?l.message:"Failed to fetch deploy logs";return p(d,!0)}}case"deployments":{let a=Qt(e.projectPath??process.cwd()),i=ea(a,"mistflow.json");if(!Xt(i))return Te(a);let n;try{n=JSON.parse(Zt(i,"utf-8"))}catch{return p("Could not read mistflow.json.",!0)}let o=n.projectId;if(!o)return p("No project ID found. Deploy the project first.",!0);try{let s=await pt(o);return p(JSON.stringify({total:s.length,deployments:s.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:`${s.length} deployment(s) found. Use mist_project action='logs' deploymentId='<id>' to see detailed logs for any deployment.`}))}catch(s){let l=s instanceof Error?s.message:"Failed to fetch deployments";return p(l,!0)}}case"version":{let a=St(),i=a.severity==="none",n={none:"up to date",patch:"patch update available",minor:"minor update available",major:"major update available",unsupported:"UNSUPPORTED \u2014 upgrade required"};return p(JSON.stringify({current:a.current,latest:a.latest||"unknown",minSupported:a.minSupported||"unknown",severity:a.severity,upToDate:i,upgradeCmd:a.upgradeCmd,changelogUrl:a.changelogUrl,backendSignalReceived:a.backendSignalReceived,message:a.backendSignalReceived?`Mistflow MCP ${a.current} (${n[a.severity]??a.severity}). Latest: ${a.latest}.${i?"":` Run \`${a.upgradeCmd}\` and restart your editor to upgrade.`}`:`Mistflow MCP ${a.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 p(`Unknown action: ${e.action}. Use get, update, share, landing-designs, app-styles, integrations, errors, logs, deployments, or version.`,!0)}}};import{z as Pe}from"zod";import{z as ze}from"zod";import{resolve as Cl}from"path";var Ru=ze.object({projectPath:ze.string().optional().describe("Path to the project directory (default: cwd)"),action:ze.enum(["set","list","delete"]).describe("Action to perform"),key:ze.string().optional().describe("Environment variable name (required for 'set' and 'delete')"),value:ze.string().optional().describe("Environment variable value (required for 'set')"),category:ze.string().optional().describe("Category for the env var (default: 'custom')"),description:ze.string().optional().describe("Description of what this env var is for"),setupUrl:ze.string().optional().describe("URL where the user can obtain this value (e.g. Stripe dashboard)")});async function si(r){let{projectPath:e,action:t,key:a,value:i,category:n,description:o,setupUrl:s}=r,l=Cl(e??process.cwd());if(!ce())return p("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let u=De(l)?.projectId;if(!u)return p("No project ID found. Deploy your project first with mist_deploy, or initialize with mist_plan + mist_build.",!0);try{switch(t){case"set":return a?i?(await er(u,a,i,{category:n,description:o,setupUrl:s}),p(JSON.stringify({set:!0,key:a,message:`Environment variable '${a}' has been set. It will be available on your next deployment.`}))):p("Value is required. Provide the env var value.",!0):p("Key is required. Provide the env var name like 'STRIPE_SECRET_KEY'.",!0);case"list":{let h=await Za(u);return h.length===0?p(JSON.stringify({envVars:[],message:"No environment variables configured. Use action 'set' to add one."})):p(JSON.stringify({envVars:h.map(c=>({key:c.key,category:c.category,description:c.description,hasValue:c.has_value})),message:`${h.length} environment variable(s) configured.`}))}case"delete":return a?(await tr(u,a),p(JSON.stringify({deleted:!0,key:a,message:`Environment variable '${a}' has been removed.`}))):p("Key is required. Provide the env var name to delete.",!0);default:return p(`Unknown action: ${t}. Use set, list, or delete.`,!0)}}catch(h){if(h instanceof he)return p(h.message,!0);let c=h instanceof Error?h.message:"An unexpected error occurred";return p(c,!0)}}import{z as xt}from"zod";import{resolve as Tl,join as Pl}from"path";import{existsSync as Bl,readFileSync as Dl,writeFileSync as Al}from"fs";var Gu=xt.object({projectPath:xt.string().optional().describe("Path to the project directory (default: cwd)"),action:xt.enum(["add","list","verify","remove"]).describe("Action to perform"),domain:xt.string().optional().describe("Domain name (required for 'add' and 'remove')"),domainId:xt.string().optional().describe("Domain ID (required for 'verify' and 'remove')")});function Ua(r,e){let t=Pl(r,"mistflow.json");if(!Bl(t))return;let a;try{a=JSON.parse(Dl(t,"utf-8"))}catch{return}a.domains=e,Al(t,JSON.stringify(a,null,2)+`
|
|
12502
|
+
`)}async function li(r){let{projectPath:e,action:t,domain:a,domainId:i}=r,n=Tl(e??process.cwd());if(!ce())return p("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let s=De(n)?.projectId;if(!s)return p("No project ID found. Deploy your project first with mist_deploy, or initialize with mist_plan + mist_build.",!0);try{switch(t){case"add":{if(!a)return p("Domain name is required. Provide the domain like 'myapp.com' or 'app.mycompany.com'.",!0);let l=await Ka(s,a),d=await qe(s);return Ua(n,d.map(u=>({domain:u.domain,status:u.status}))),p(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 qe(s);return l.length===0?p(JSON.stringify({domains:[],message:"No custom domains configured. Use action 'add' to add one."})):p(JSON.stringify({domains:l.map(d=>({id:d.id,domain:d.domain,status:d.status,ssl:d.ssl_status,error:d.error_message}))}))}case"verify":{if(!i){if(a){let h=(await qe(s)).find(c=>c.domain===a);if(h){let c=await oa(s,h.id);return p(JSON.stringify({domain:c.domain,status:c.status,ssl:c.ssl_status,error:c.error_message,message:c.status==="active"?`Domain '${c.domain}' is active and serving traffic.`:`Domain '${c.domain}' is ${c.status}. Make sure DNS records are configured correctly.`}))}return p(`Domain '${a}' not found. Use action 'list' to see configured domains.`,!0)}return p("Provide either domainId or domain name to verify.",!0)}let l=await oa(s,i),d=await qe(s);return Ua(n,d.map(u=>({domain:u.domain,status:u.status}))),p(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(!i&&!a)return p("Provide either domainId or domain name to remove.",!0);let l=i;if(!l&&a){let h=(await qe(s)).find(c=>c.domain===a);if(!h)return p(`Domain '${a}' not found.`,!0);l=h.id}await Ya(s,l);let d=await qe(s);return Ua(n,d.map(u=>({domain:u.domain,status:u.status}))),p(JSON.stringify({removed:!0,message:"Domain removed. It may take a few minutes for DNS changes to propagate."}))}default:return p(`Unknown action: ${t}. Use add, list, verify, or remove.`,!0)}}catch(l){if(l instanceof he)return p(l.message,!0);let d=l instanceof Error?l.message:"An unexpected error occurred";return p(d,!0)}}var Il=Pe.object({resource:Pe.enum(["env","domain"]).describe("'env' manages app secrets and configuration values. 'domain' manages custom domains."),action:Pe.string().describe("Action to perform. env: 'set', 'list', 'delete'. domain: 'add', 'list', 'verify', 'remove'."),projectPath:Pe.string().optional().describe("Path to the project directory (default: cwd)"),key:Pe.string().optional().describe("(env) Variable name"),value:Pe.string().optional().describe("(env set) Variable value"),category:Pe.string().optional().describe("(env set) Category"),description:Pe.string().optional().describe("(env set) Description"),setupUrl:Pe.string().optional().describe("(env set) URL to obtain the value"),domain:Pe.string().optional().describe("(domain) Domain name"),domainId:Pe.string().optional().describe("(domain) Domain ID")}),di={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:Il,handler:async r=>{let e=r;switch(e.resource){case"env":return si({projectPath:e.projectPath,action:e.action,key:e.key,value:e.value,category:e.category,description:e.description,setupUrl:e.setupUrl});case"domain":return li({projectPath:e.projectPath,action:e.action,domain:e.domain,domainId:e.domainId});default:return p(`Unknown resource: ${e.resource}. Use env or domain.`,!0)}}};import{z as Qe}from"zod";var Ml=Qe.object({action:Qe.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:Qe.string().optional().describe("URL to navigate to. Required for 'navigate'; optional for 'screenshot' (navigates before capturing)."),selector:Qe.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:Qe.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:Qe.boolean().default(!1).describe("For 'screenshot': capture the full scrollable page instead of just the viewport."),includeScreenshot:Qe.boolean().default(!1).describe("For navigate/interact actions: also return a screenshot alongside the accessibility snapshot.")}),ci={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:Ml,handler:async r=>{let e=r,t=await Ct();if(e.action==="navigate"){if(!e.url)return p("URL is required for 'navigate'.",!0);let n=[],o=d=>{d.type()==="error"&&n.push(d.text())};t.on("console",o),await t.goto(e.url,{waitUntil:"domcontentloaded",timeout:3e4}),await t.waitForLoadState("networkidle").catch(()=>{});let s=[],l=d=>s.push(d.message);if(t.on("pageerror",l),await t.waitForTimeout(500),t.removeListener("console",o),t.removeListener("pageerror",l),n.length>0||s.length>0){let d=await Tt(t),u=[{type:"text",text:JSON.stringify({url:t.url(),title:await t.title(),snapshot:d,consoleErrors:n,pageErrors:s,hasErrors:!0})}];if(e.includeScreenshot){let h=await Fe(t);u.push({type:"image",data:h.toString("base64"),mimeType:"image/png"})}return{content:u}}}else if(e.action==="go_back")await t.goBack({waitUntil:"domcontentloaded",timeout:1e4});else if(e.action==="go_forward")await t.goForward({waitUntil:"domcontentloaded",timeout:1e4});else if(e.action==="click"){if(!e.selector)return p("Selector is required for 'click'.",!0);await t.click(e.selector,{timeout:1e4}),await t.waitForLoadState("domcontentloaded").catch(()=>{}),await t.waitForTimeout(500)}else if(e.action==="type"){if(!e.selector)return p("Selector is required for 'type'.",!0);if(!e.value)return p("Value is required for 'type'.",!0);await t.type(e.selector,e.value,{delay:50})}else if(e.action==="fill"){if(!e.selector)return p("Selector is required for 'fill'.",!0);if(!e.value)return p("Value is required for 'fill'.",!0);await t.fill(e.selector,e.value)}else if(e.action==="select_option"){if(!e.selector)return p("Selector is required for 'select_option'.",!0);if(!e.value)return p("Value is required for 'select_option'.",!0);await t.selectOption(e.selector,e.value)}else if(e.action==="hover"){if(!e.selector)return p("Selector is required for 'hover'.",!0);await t.hover(e.selector,{timeout:1e4})}else if(e.action==="press_key"){if(!e.value)return p("Value is required for 'press_key' (e.g. 'Enter').",!0);await t.keyboard.press(e.value),await t.waitForLoadState("domcontentloaded").catch(()=>{}),await t.waitForTimeout(500)}else if(e.action==="screenshot"){e.url&&(await t.goto(e.url,{waitUntil:"domcontentloaded",timeout:3e4}),await t.waitForLoadState("networkidle").catch(()=>{}));let n;if(e.selector){let o=await t.$(e.selector);if(!o)return p(`Element not found: ${e.selector}`,!0);n=await o.screenshot({type:"png"})}else n=await Fe(t,e.fullPage);return{content:[{type:"text",text:JSON.stringify({url:t.url(),title:await t.title(),message:`Screenshot captured (${e.fullPage?"full page":"viewport"})`})},{type:"image",data:n.toString("base64"),mimeType:"image/png"}]}}else if(e.action==="snapshot"){let n=await Tt(t);return{content:[{type:"text",text:JSON.stringify({url:t.url(),title:await t.title(),snapshot:n})}]}}let a=await Tt(t),i=[{type:"text",text:JSON.stringify({url:t.url(),title:await t.title(),snapshot:a})}];if(e.includeScreenshot){let n=await Fe(t);i.push({type:"image",data:n.toString("base64"),mimeType:"image/png"})}return{content:i}}};import{existsSync as Le,readFileSync as vt,writeFileSync as ct}from"fs";import{join as Be}from"path";import{z as wt}from"zod";function pi(r){let e=Be(r,"mistflow.json");if(!Le(e))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 t;try{t=JSON.parse(vt(e,"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(!t.name||typeof t.name!="string")return{result:{name:"Project",status:"warn",message:"mistflow.json is missing the 'name' field."},config:t};let a=t.projectId,i=a?`, id: ${a}`:", no projectId";return{result:{name:"Project",status:"pass",message:`${t.name}${i}`},config:t}}async function Rl(){let r=Wa();if(!r.ok)return{result:{name:"Auth",status:"fail",message:r.reason==="missing"?"No credentials found.":"Credentials file is malformed.",fix:"Run mist_setup to log in."},creds:null,authValid:!1};try{let e=ja(),t=await fetch(`${Ve()}/api/org`,{headers:e,signal:AbortSignal.timeout(1e4)});try{Oa(t.headers)}catch{}if(!t.ok)return t.status===401?{result:{name:"Auth",status:"fail",message:"API key is invalid or revoked.",fix:"Run mist_setup to re-authenticate."},creds:r.creds,authValid:!1}:{result:{name:"Auth",status:"warn",message:`Server returned ${t.status}. Credentials may still be valid.`},creds:r.creds,authValid:!1};let a=await t.json(),i=a.slug??r.creds.orgSlug??"unknown",n=a.plan?`, plan: ${a.plan}`:"";return{result:{name:"Auth",status:"pass",message:`org: ${i}${n}`},creds:r.creds,authValid:!0}}catch(e){return e instanceof he?{result:{name:"Auth",status:"fail",message:`Auth check failed: ${e.message}`,fix:"Run mist_setup to re-authenticate."},creds:r.creds,authValid:!1}:{result:{name:"Auth",status:"warn",message:"Could not reach API to validate credentials. Network issue?"},creds:r.creds,authValid:!1}}}async function Ll(){let r=Date.now();try{let e=await Dt("nextjs"),t=Date.now()-r;return{result:{name:"API",status:"pass",message:`${Ve()} reachable (${t}ms)`},scaffold:e}}catch(e){let t=Date.now()-r;return{result:{name:"API",status:"fail",message:e instanceof he?e.message:`Timeout or network error after ${t}ms`,fix:"Check your network connection. If using --api-url, verify the backend is running."},scaffold:null}}}function Nl(){let r=St();if(!r.backendSignalReceived)return{name:"MCP version",status:"warn",message:`v${r.current} installed, but no backend signal received to compare against.`};let e={none:"up to date",patch:"patch update available",minor:"minor update available",major:"major update available",unsupported:"no longer supported"};return r.severity==="none"?{name:"MCP version",status:"pass",message:`v${r.current} (latest)`}:r.severity==="unsupported"?{name:"MCP version",status:"fail",message:`v${r.current} is ${e[r.severity]}. Minimum: v${r.minSupported}.`,fix:`Run \`${r.upgradeCmd}\` then restart your editor.`}:{name:"MCP version",status:"warn",message:`v${r.current} installed, v${r.latest} available (${e[r.severity]}).`,fix:`Run \`${r.upgradeCmd}\` then restart your editor.`}}function Fl(r,e,t,a){let i=Be(r,"AGENTS.md"),n=Be(r,"CLAUDE.md"),o=Le(i),s=e.methodologyVersion??"",l=t?.version??"";if(!o){if(!a||!t?.methodology)return{name:"AGENTS.md",status:"fail",message:"Missing. The host AI has no methodology context for this project.",fix:t?"Run mist_doctor without reportOnly to auto-restore it.":"Cannot restore: API unreachable. Fix connectivity first."};let d=ui(t.methodology,e);return ct(i,d),ct(n,d),{name:"AGENTS.md",status:"fix",message:`Restored from methodology v${l}.`}}if(a&&!Le(n)){let d=vt(i,"utf-8");ct(n,d)}if(l&&s&&l!==s){if(!a||!t?.methodology)return{name:"AGENTS.md",status:"warn",message:`Methodology v${s} installed, v${l} available.`,fix:"Run mist_doctor to update it."};let d=ui(t.methodology,e);ct(i,d),ct(n,d);try{let u=Be(r,"mistflow.json"),h=JSON.parse(vt(u,"utf-8"));h.methodologyVersion=l,ct(u,JSON.stringify(h,null,2)+`
|
|
12503
|
+
`)}catch{}return{name:"AGENTS.md",status:"fix",message:`Updated methodology v${s} -> v${l}.`}}return{name:"AGENTS.md",status:"pass",message:s?`v${s}`:"present"}}async function Ul(r,e,t,a){let i=e.projectId;if(!i)return{name:"State sync",status:"skip",message:"No projectId. State sync not applicable without a linked project."};if(!t)return{name:"State sync",status:"skip",message:"Skipped (not authenticated)."};let n=gr(r),o=await mr(i);if(!n&&!o)return{name:"State sync",status:"warn",message:"No local or remote state found."};if(!n&&o){if(a){let{writeLocalState:s}=await import("./state-manager-XY6GQEFE.js");return s(r,o),{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 n&&!o?{name:"State sync",status:"warn",message:"Local state exists but no remote state found. Remote sync may have failed."}:n&&n.projectId!==i?{name:"State sync",status:"warn",message:`state.json projectId (${n.projectId}) doesn't match mistflow.json projectId (${i}).`}:{name:"State sync",status:"pass",message:`deployCount: ${n.deployCount}, features: ${n.features.length}`}}function El(r){let e=[],t=[];if(Le(Be(r,"package.json"))?Le(Be(r,"node_modules"))||e.push("node_modules not installed (run npm install)"):e.push("missing package.json"),!Le(Be(r,".env.local")))e.push("missing .env.local");else try{vt(Be(r,".env.local"),"utf-8").match(/^AUTH_SECRET=(.+)$/m)||e.push("AUTH_SECRET not set in .env.local")}catch{e.push(".env.local exists but is not readable")}let a=Be(r,"app","api","auth","[...all]","route.ts");Le(a)||t.push("missing app/api/auth/[...all]/route.ts");let i=Be(r,"app","api","health","route.ts");return Le(i)||t.push("missing app/api/health/route.ts (needed for deploy verification)"),e.length>0?{name:"Structure",status:"fail",message:e.join("; "),fix:e.map(n=>n.includes("node_modules")?"Run `npm install` in the project directory.":n.includes(".env.local")?"Create .env.local with AUTH_SECRET=<random-secret>.":n.includes("AUTH_SECRET")?"Add AUTH_SECRET=<random-secret> to .env.local.":n.includes("package.json")?"This project is missing package.json. Was it scaffolded correctly?":"").filter(Boolean).join(" ")}:t.length>0?{name:"Structure",status:"warn",message:t.join("; ")}:{name:"Structure",status:"pass",message:"all required files present"}}function Hl(r,e){let t=e.env;if(!t?.required||typeof t.required!="object"||Object.keys(t.required).length===0)return{name:"Env vars",status:"pass",message:"no required env vars declared"};let a=[],i="";for(let n of[".env.local",".env"]){let o=Be(r,n);try{Le(o)&&(i+=`
|
|
12504
12504
|
`+vt(o,"utf-8"))}catch{}}for(let[n,o]of Object.entries(t.required)){let s=i.includes(`${n}=`),l=!!process.env[n];if(!s&&!l){let d=o?.description?` (${o.description})`:"";a.push(`${n}${d}`)}}return a.length>0?{name:"Env vars",status:"warn",message:`${a.length} required but not set: ${a.join(", ")}`,fix:"Set them via mist_config or add to .env.local."}:{name:"Env vars",status:"pass",message:`${Object.keys(t.required).length} required, all set`}}function Ol(r){let e=r.plan;if(!e?.steps||e.steps.length===0)return{name:"Plan",status:"skip",message:"No plan found in mistflow.json."};let t=e.steps.length,a=e.steps.filter(o=>o.status==="completed").length,i=e.steps.filter(o=>o.status==="in_progress").length,n=t-a-i;if(a===t)return{name:"Plan",status:"pass",message:`${a}/${t} steps completed`};if(i>0){let o=e.steps.find(s=>s.status==="in_progress");return{name:"Plan",status:"warn",message:`${a}/${t} completed, step ${o?.number} "${o?.name}" in progress`,fix:"Run mist_build implement to continue."}}return a===0?{name:"Plan",status:"warn",message:`${t} steps planned, none started.`,fix:"Run mist_build implement to start building."}:{name:"Plan",status:"warn",message:`${a}/${t} completed, ${n} remaining.`,fix:"Run mist_build implement to continue."}}function ui(r,e){let t=e.dbProvider;return t==="neon"||!t?r.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"):r}function Gl(r){let e={pass:"PASS",warn:"WARN",fail:"FAIL",fix:"FIXED",skip:"SKIP"},t=Math.max(...r.map(u=>u.name.length)),a=r.map(u=>{let h=".".repeat(t-u.name.length+4),c=e[u.status].padEnd(5);return` ${u.name} ${h} ${c} ${u.message}`}),i=r.filter(u=>u.status==="fix").length,n=r.filter(u=>u.status==="fail").length,o=r.filter(u=>u.status==="warn").length,s=[];i>0&&s.push(`${i} fixed`),n>0&&s.push(`${n} failure${n>1?"s":""}`),o>0&&s.push(`${o} warning${o>1?"s":""}`);let l=`mist_doctor results:
|
|
12505
12505
|
|
|
12506
12506
|
`+a.join(`
|