@mistflow-ai/mcp 0.7.5 → 1.0.1
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/cli.js +3369 -189
- package/dist/index.js +3364 -184
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,216 +1,3396 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
3
|
-
`)}var
|
|
4
|
-
`,{mode:384})}catch{}}function
|
|
5
|
-
What's new: ${
|
|
2
|
+
var yi=Object.defineProperty;var x=(t,e)=>()=>(t&&(e=t(t=0)),e);var Ot=(t,e)=>{for(var o in e)yi(t,o,{get:e[o],enumerable:!0})};function $o(){let t=[];return t.push("Mistflow is a full-stack app builder that creates and deploys web apps from natural language descriptions. When a user asks to build, create, or make a web app, website, landing page, dashboard, internal tool, marketplace, content site, or browser game, use Mistflow tools. Mistflow creates NEW apps from scratch. It does NOT modify existing non-Mistflow codebases."),t.push(""),t.push('Every capability is an MCP tool. There is no companion CLI. Long-running work (install, build, qa, deploy) uses the fire-and-poll pattern: the first call returns a jobId and `status: "running"`; subsequent calls with that jobId return fresh state. Each call responds in under a second \u2014 no 60s timeout risk.'),t.push(""),t.push(Ii),t.push(""),t.push(bi),t.push(""),t.push(wi),t.push(""),t.push(vi),t.push(""),t.push(xi),t.push(""),t.push(_i),t.push(""),t.push(Si),t.push(""),t.push("New app workflow:"),t.push("1. Choose destination: if the user didn't already give a path, ask whether to scaffold in the current folder or a new subfolder here. Resolve the absolute path before mist_init."),t.push('2. Plan: call mist_plan with the user\'s description EXACTLY as written \u2014 do NOT expand or add features. When the response has `status: "clarify"` with `questions[]`, render them via AskUserQuestion, collect the answers, and submit them back in the next mist_plan call with the `conversationId`. When `status: "design_clarify_pending"`, poll until directions are ready, present them to the user, submit the pick.'),t.push("3. Mockup (optional, recommended): call mist_mockup with the planId \u2014 returns a wireframe prompt. Write the HTML to the returned path, open it for the user, wait for approval. Iterate with { feedback }, lock with { approved: true }."),t.push("4. Scaffold: mist_init with { planId, path }. Transactional \u2014 if it fails before the final move, stop."),t.push("5. Install: mist_install { projectPath } starts; poll with { jobId } until complete. Typical 30\u201390s."),t.push("6. Implement: mist_implement runs one plan step at a time and auto-marks the prior step complete. Call repeatedly until all steps are done."),t.push("7. Build: mist_build { projectPath } starts; poll with { jobId }. On failure, the response has `missingModules[]` \u2014 chain mist_install with those modules then mist_build again without asking."),t.push("8. Deploy: mist_deploy { projectPath } starts tar + upload; poll with { action: 'status', deploymentId }. On complete, response has `qaRequired: true` and a `url` \u2014 do NOT surface the URL to the user until mist_qa passes. Subsequent actions: 'promote' (staging \u2192 prod), 'rollback' (revert to a specific deploymentId)."),t.push("9. QA: mist_qa { projectPath } starts Playwright; poll with { jobId }. Only surface the deploy URL to the user after QA exits 0."),t.push(""),t.push(ki),t.push(""),t.push(Pi),t.push(""),t.push("Updating an existing Mistflow app:"),t.push("- Cosmetic or single-file changes: edit files directly, then mist_build \u2192 mist_deploy."),t.push("- New page or feature (no new data model): mist_project action='get' for context, build it, then mist_build \u2192 mist_deploy."),t.push("- Feature needing new data model: ask product questions, call mist_project action='get' for context, call mist_plan with existingPlanId, then mist_implement, then mist_build \u2192 mist_deploy."),t.push("- Integration addition: ask product questions, mist_project action='get', mist_plan with existingPlanId, mist_implement, mist_config resource='env' for keys, mist_build \u2192 mist_deploy \u2192 mist_qa."),t.push("- Bug fix: mist_debug to extract structured errors, fix the code, mist_build \u2192 mist_deploy."),t.push(""),t.push("Tool summary:"),t.push("- mist_setup: authentication. Only call when the user has never signed in or a tool returned 'auth_missing'/'auth_revoked'. Do NOT call for 500s, 404s, or network errors. Also accepts an apiKey parameter for headless auth."),t.push("- mist_project: read/write project state (actions: 'get' / 'update'). Call 'get' before editing any existing Mistflow project to understand its shape."),t.push("- mist_browser: navigate, interact with, and screenshot the app during preview or after deploy. Returns screenshots inline in tool results."),t.push("- mist_help: returns the full tool reference. Call once per session."),t.push("- mist_plan / mist_mockup / mist_init / mist_implement / mist_debug / mist_config: core app-building workflow tools (see step-by-step above)."),t.push("- mist_install / mist_build / mist_qa / mist_deploy: fire-and-poll tools. Always check `status` in the response and keep polling while 'running'."),t.join(`
|
|
3
|
+
`)}var bi,wi,vi,xi,ki,Si,Pi,Ii,_i,No,jo,Do,Oo,Mo,Uo,Te=x(()=>{"use strict";bi="mist_plan uses the fire-and-poll shape: the first call returns quickly with status 'running' and a conversationId while the backend Sonnet ask_questions call runs in the background (that call alone can take 30-150s). Poll by calling mist_plan with just { conversationId } every ~10-15s until status is 'clarify' (questions arrived) or 'ready' (plan generated). Do NOT re-send description or answers while polling \u2014 the conversation is already tracked server-side.",wi='Treat the tool\'s returned JSON as authoritative. If `mist_plan` returns `status: "clarify"`, the planning call completed and is waiting on user answers. Do NOT rerun the same call or describe it as "still generating". Only poll again when `status: "design_clarify_pending"`.',vi="When submitting discovery answers back to `mist_plan` (conversationId + answers), prefer an array payload: `answers: [{question, decisionKey, answer}, ...]`. Do NOT collapse into a `{decisionKey: answer}` map \u2014 multiple discovery questions can share the same decision key.",xi="Before scaffolding a NEW app, resolve the destination path explicitly. If the user asked to create/build a new app and the current directory is not already that Mistflow project, ask whether to scaffold in the current folder or a new subfolder here (unless the user already gave a path). Do NOT inspect sibling directories and silently adopt one as the base just because it looks similar. Reuse an existing Mistflow project only when the user explicitly asks to continue/edit that project.",ki='Once the user approves the plan, the mist_init \u2192 mist_install \u2192 mist_implement (repeat) \u2192 mist_build \u2192 mist_deploy \u2192 mist_qa chain is expected. Do NOT pause between these calls to ask the user "should I continue?" or offer options like "full build vs step-by-step." A tool returns a status that requires user input when it genuinely needs one (e.g. confirm_new_project, awaiting promotion). Otherwise chain calls continuously. Brief one-line status updates are fine; permission requests are not.',Si="mist_init is all-or-nothing for normal users: it registers the cloud project first, scaffolds in a temp directory, then moves the finished app into place only after both steps succeed. If auth, quota, or network registration fails, stop before any app appears locally. Do NOT suggest reusing another app unless the user explicitly asks.",Pi="If mist_init fails, stop before any cloud command and explain why. Do NOT default to reusing some other existing app as recovery unless the user explicitly asked to continue that app.",Ii='Long-running tools (mist_install, mist_build, mist_qa, mist_deploy) use the fire-and-poll pattern. The first call returns `status: "running"` with a `jobId`. Every subsequent call with that `jobId` returns the current state \u2014 re-call whenever you see `status: "running"`. Each response is <1s so there is no 60s timeout risk. When `status: "complete"` or `"failed"` arrives, the tool is done. Never assume a job stalled because a single call took 20s \u2014 calls return fast, but the job itself keeps running in the background. Do not ask the user whether to keep polling; polling is how these tools work.',_i="When `mist_plan` returns a `questions[]` array (or `directions[]` for design picking), render each one via your native structured-question UI \u2014 `AskUserQuestion` in Claude Code, quick pick in Cursor, equivalents in other hosts. Do NOT just print them as plain numbered text; proper radio-button-style choices dramatically improve response quality. Each question has `id`/`decisionKey`/`question`/`options[]` (each option: `label`, `description`) plus an optional `recommended` hint. Collect answers, submit them back via `mist_plan` with the `conversationId` \u2014 don't ask the user to do that step.",No="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).",jo="Read or inspect Mistflow project state. 'get' (default) loads plan progress, env vars, and deploy info \u2014 call before editing. 'update' marks plan steps complete or adds env vars. 'share' creates a forkable template URL. 'landing-designs' / 'integrations' browse curated catalogs (pass presetId / integrationId for full details). 'errors' fetches runtime errors from the deployed app. 'logs' fetches deploy logs. 'deployments' lists history. 'version' reports the installed MCP version + any upgrade available.",Do="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.",Oo="Returns the full Mistflow MCP tool reference. Call ONCE at session start (or whenever unsure which tool to pick) to learn the 14-tool surface, the fire-and-poll pattern, and how to chain end-to-end from mist_plan through mist_qa. Static \u2014 no backend round-trip, safe to call frequently.",Mo="Analyze build errors from a Next.js / TypeScript project. Extracts structured errors with file, line, a human-readable message for the user, and an actionable suggestion. Call with { projectPath } to run `npm run build` and parse the failure; call with { buildOutput } to parse output captured elsewhere (e.g. from a failed mist_build job).",Uo="Generate a grayscale wireframe sketch of the planned app so the user can review layout + information hierarchy before any code is written. The server returns a structured spec + a wireframePrompt \u2014 the host AI writes the HTML file to .mistflow/mockups/mockup-<planId>.html and opens it. Pass { planId } for the first iteration, { planId, feedback: '...' } to iterate, { planId, approved: true } to lock the design before mist_init. Iterative by design \u2014 expect 1-3 rounds of feedback."});import{existsSync as vn,readFileSync as Bo,writeFileSync as Ti,mkdirSync as Ri}from"fs";import{join as bn,dirname as wn}from"path";import{homedir as Ai}from"os";import{fileURLToPath as Ci}from"url";function ue(){if(Mt)return Mt;try{let t=Ci(import.meta.url),e=wn(t);for(let o=0;o<6;o++){let n=bn(e,"package.json");if(vn(n)){let a=JSON.parse(Bo(n,"utf-8"));if(a.name==="@mistflow-ai/mcp"&&typeof a.version=="string")return Mt=a.version,a.version}let s=wn(e);if(s===e)break;e=s}}catch{}return Mt="0.0.0","0.0.0"}function Ut(t){let e=/^(\d+)\.(\d+)\.(\d+)/.exec(t.trim());return e?[parseInt(e[1],10),parseInt(e[2],10),parseInt(e[3],10)]:null}function Lo(t,e){let o=Ut(t),n=Ut(e);if(!o||!n)return 0;for(let s=0;s<3;s++){if(o[s]<n[s])return-1;if(o[s]>n[s])return 1}return 0}function zo(t,e,o){if(o&&Lo(t,o)<0)return"unsupported";if(!e||Lo(t,e)>=0)return"none";let s=Ut(t),a=Ut(e);return!s||!a?"none":s[0]<a[0]?"major":s[1]<a[1]?"minor":"patch"}function gt(t){let e=t.get("x-mistflow-mcp-latest")??"",o=t.get("x-mistflow-mcp-min-supported")??"",n=t.get("x-mistflow-mcp-changelog-url")??"";!e&&!o||(de={latest:e,minSupported:o,changelogUrl:n})}function Ho(){let t=process.env.MISTFLOW_STATE_DIR||bn(Ai(),".mistflow");return bn(t,"upgrade-state.json")}function Ei(){try{let t=Ho();return vn(t)?JSON.parse(Bo(t,"utf-8")):{}}catch{return{}}}function Ni(t){try{let e=Ho(),o=wn(e);vn(o)||Ri(o,{recursive:!0}),Ti(e,JSON.stringify(t,null,2)+`
|
|
4
|
+
`,{mode:384})}catch{}}function ji(t){return t==="patch"?7*864e5:t==="minor"?1*864e5:0}function Wo(){if(process.env.MISTFLOW_NO_UPGRADE_CHECK==="1"||!de)return null;let t=ue();if(t==="0.0.0")return null;let e=zo(t,de.latest,de.minSupported);if(e==="none")return null;if(e==="unsupported")return qo(e,t,de);if(Fo)return null;let o=Ei(),n=Date.now(),s=ji(e);return o.dismissedForVersion===de.latest&&e!=="major"||o.lastLatestSeen===de.latest&&o.lastShownMs&&n-o.lastShownMs<s?null:(Fo=!0,Ni({...o,lastShownMs:n,lastLatestSeen:de.latest}),qo(e,t,de))}function qo(t,e,o){let n="npx -y mistflow-ai install",s=o.changelogUrl?`
|
|
5
|
+
What's new: ${o.changelogUrl}`:"";return t==="unsupported"?`
|
|
6
6
|
|
|
7
7
|
---
|
|
8
|
-
Mistflow ${
|
|
9
|
-
You must upgrade to ${
|
|
8
|
+
Mistflow ${e} is no longer supported.
|
|
9
|
+
You must upgrade to ${o.latest} or newer to continue:
|
|
10
10
|
|
|
11
|
-
${
|
|
11
|
+
${n}
|
|
12
12
|
|
|
13
|
-
After upgrading, restart your AI editor.${
|
|
14
|
-
---`:
|
|
13
|
+
After upgrading, restart your AI editor.${s}
|
|
14
|
+
---`:t==="major"?`
|
|
15
15
|
|
|
16
16
|
---
|
|
17
|
-
Mistflow ${
|
|
18
|
-
This is a major update. Run \`${
|
|
19
|
-
---`:
|
|
17
|
+
Mistflow ${o.latest} is available (you have ${e}).
|
|
18
|
+
This is a major update. Run \`${n}\` and restart your editor.${s}
|
|
19
|
+
---`:t==="minor"?`
|
|
20
20
|
|
|
21
|
-
--- Mistflow update available: ${
|
|
22
|
-
Run \`${
|
|
21
|
+
--- Mistflow update available: ${e} -> ${o.latest} ---
|
|
22
|
+
Run \`${n}\` to upgrade, then restart your editor.${s}`:`
|
|
23
23
|
|
|
24
|
-
(Mistflow ${
|
|
24
|
+
(Mistflow ${o.latest} is out, you have ${e}. Run \`${n}\` when convenient.)`}function xn(){let t=ue(),e=de??{latest:"",minSupported:"",changelogUrl:""},o=zo(t,e.latest,e.minSupported);return{current:t,latest:e.latest,minSupported:e.minSupported,severity:o,upgradeCmd:"npx -y mistflow-ai install",changelogUrl:e.changelogUrl,backendSignalReceived:de!==null}}var Mt,de,Fo,ft=x(()=>{"use strict";Mt=null;de=null;Fo=!1});var Vo={};Ot(Vo,{closeBrowser:()=>Sn,getIsolatedContext:()=>Oi,getPage:()=>kn,getSnapshot:()=>yt,takeScreenshot:()=>bt});async function Go(){try{return await import("playwright")}catch{throw new Error("Playwright is not installed. Run: cd packages/mcp-server && pnpm add playwright && npx playwright install chromium")}}async function Di(){let t=await Go();return(!me||!me.isConnected())&&(me=await t.chromium.launch({headless:!0})),Re&&(await Re.close().catch(()=>{}),Re=null),Re=await me.newContext({viewport:{width:1280,height:720},deviceScaleFactor:1}),Se=await Re.newPage(),Se}async function kn(){return Se&&!Se.isClosed()?Se:($t||($t=Di().finally(()=>{$t=null})),$t)}async function Sn(){Se&&!Se.isClosed()&&await Se.close().catch(()=>{}),Re&&await Re.close().catch(()=>{}),me?.isConnected()&&await me.close().catch(()=>{}),Se=null,Re=null,me=null}async function Oi(){let t=await Go();(!me||!me.isConnected())&&(me=await t.chromium.launch({headless:!0}));let e=await me.newContext({viewport:{width:1280,height:720},deviceScaleFactor:1}),o=await e.newPage();return{context:e,page:o}}async function yt(t){return await t.locator("body").ariaSnapshot()}async function bt(t,e=!1){return await t.screenshot({fullPage:e,type:"png"})}var me,Re,Se,$t,Pn=x(()=>{"use strict";me=null,Re=null,Se=null,$t=null;process.once("SIGTERM",()=>{Sn().finally(()=>process.exit(0))});process.once("SIGINT",()=>{Sn().finally(()=>process.exit(0))})});function c(t,e=!1){let o=t;try{let n=Wo();n&&(o=t+n)}catch{}return{content:[{type:"text",text:o}],isError:e}}function Pe(t){return c(`This is not a Mistflow project (no mistflow.json found at ${t}).
|
|
25
25
|
|
|
26
26
|
Mistflow creates new projects from scratch \u2014 it doesn't work inside existing codebases.
|
|
27
27
|
|
|
28
28
|
To get started:
|
|
29
|
-
1.
|
|
30
|
-
2.
|
|
31
|
-
3.
|
|
29
|
+
1. Call mist_plan({ description: "<your app idea>" })
|
|
30
|
+
2. Call mist_init({ planId, path: "<absolute-path>" })
|
|
31
|
+
3. Call mist_install({ projectPath }), then mist_implement({ projectPath })
|
|
32
32
|
|
|
33
|
-
If you want to deploy an existing project, use your framework's deploy tools directly.`,!0)}var
|
|
34
|
-
`,{mode:384}),bt(s,t)}catch(i){try{vt(s)}catch{}throw i}}function Y(){return G().ok}var xt,X=u(()=>{"use strict";xt="https://api.mistflow.ai"});function f(){return A()}function j(){let e=G();if(!e.ok)throw new m("auth_missing","No Mistflow credentials found.",401);return Ct(e.creds)}function Ct(e){return{Authorization:`ApiKey ${e.apiKey}`,"Content-Type":"application/json","X-Mistflow-MCP-Version":R()}}function Rt(e){try{I(e.headers)}catch{}}async function Pt(e,t,n,r){for(let o=0;o<2;o++)try{return await fetch(e,{...t,signal:AbortSignal.timeout(n)})}catch(s){let i=s instanceof Error&&s.name==="TimeoutError",a=s instanceof TypeError;if(r&&o===0&&(i||a)){console.error(`[api] Retrying ${e} after ${i?"timeout":"network error"}`);continue}throw s}throw new Error("fetchWithRetry: exhausted retries")}async function jt(e){let t=null;try{t=await e.json()}catch{t=null}let n=t&&typeof t.code=="string"?t.code:void 0,r=t&&typeof t.message=="string"?t.message:t&&typeof t.detail=="string"?t.detail:e.statusText||"Request failed";if(n)return new m(n,r,e.status,t?.details);let o=e.status;return o===401?new m("auth_invalid",r,o):o===403?new m("permission_denied",r,o):o===404?new m("not_found",r,o):o===409?new m("conflict",r,o):o===422?new m("validation_error",r,o):o===429?new m("rate_limited",r,o):o>=500?new m("server_error",e.statusText||"Internal server error",o):new m("client_error",r,o)}async function It(e,t={}){let n=j(),{timeoutMs:r,idempotent:o,...s}=t,i=r??3e4,a=(s.method??"GET").toUpperCase(),p=o??(a==="GET"||a==="HEAD"),l;try{l=await Pt(`${f()}${e}`,{...s,headers:{...n,...s.headers}},i,p)}catch(_){throw _ instanceof Error&&_.name==="TimeoutError"?new m("network_error","Request timed out. Try again in a moment."):new m("network_error","Cannot reach Mistflow servers. Check your network.")}if(Rt(l),!l.ok)throw await jt(l);return l.json()}async function _e(e,t,n="neon",r){return It("/api/projects",{method:"POST",body:JSON.stringify({name:e,template:t,db_provider:n,requested_subdomain:r})})}var m,Mn,$=u(()=>{"use strict";X();L();m=class extends Error{constructor(n,r,o,s){super(r);this.code=n;this.statusCode=o;this.details=s;this.name="MistflowApiError"}get isAuth(){return this.code.startsWith("auth_")}get isTransient(){return this.code==="server_error"||this.code==="upstream_error"||this.code==="network_error"||this.code==="rate_limited"}};Mn=300*1e3});import{z as Z}from"zod";import{platform as Tt}from"os";import{execFile as ke}from"child_process";function Et(e){return"error"in e}function xe(e){return new Promise(t=>setTimeout(t,e))}function Dt(e){return new Promise(t=>{let n=Tt();n==="win32"?ke("cmd.exe",["/c","start","",e],r=>{r&&console.error("Could not open browser:",r.message),t(!r)}):ke(n==="darwin"?"open":"xdg-open",[e],o=>{o&&console.error("Could not open browser:",o.message),t(!o)}),setTimeout(()=>t(!1),5e3)})}async function Se(e,t,n,r){let o=n,s=r.sleep??xe;for(let i=0;i<t;i++){await s(o);let a;try{let l=await r.fetch(`${f()}/auth/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:e})});if(!l.ok)continue;a=await l.json()}catch{continue}if(Et(a))switch(a.error){case"authorization_pending":continue;case"slow_down":o+=5e3;continue;case"expired_token":return c("The sign-in link expired. Run mist_setup again to get a new code.",!0);case"access_denied":return c("Sign-in was cancelled. Run mist_setup again to try again.",!0);case"already_exchanged":return c("This sign-in link was already used. Run mist_setup again to get a new code.",!0)}let p=a.email||a.org_name||a.org_slug;return Q({apiKey:a.api_key,apiKeyId:a.api_key_id,apiKeyName:a.api_key_name,orgId:a.org_id,orgSlug:a.org_slug,email:a.email}),c(`Connected to Mistflow as ${p}. You are ready to build and deploy.`)}return null}async function Mt(e,t=Ot){let n=e;if(n?.apiKey)try{let i=await t.fetch(`${f()}/api/org`,{headers:{Authorization:`ApiKey ${n.apiKey}`}});if(!i.ok)return c("Invalid API key. Check the key and try again.",!0);let a=await i.json();return Q({apiKey:n.apiKey,orgId:a.id,orgSlug:a.slug}),c(`Connected to Mistflow as ${a.slug} via API key. You are ready to build and deploy.`)}catch{return c("Cannot reach Mistflow servers. Check your internet connection.",!0)}if(n?.deviceCode){let i=await Se(n.deviceCode,6,5e3,t);return i||c(JSON.stringify({status:"pending",deviceCode:n.deviceCode,instruction:"The user hasn't approved yet. Wait ~15 seconds and call mist_setup again with the same deviceCode."}))}let r;try{let i=await t.fetch(`${f()}/auth/device`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!i.ok)return c("Cannot reach Mistflow servers. Check your internet connection.",!0);r=await i.json()}catch{return c("Cannot reach Mistflow servers. Check your internet connection.",!0)}let o=`${r.verification_uri}?code=${r.user_code}`;console.error(`
|
|
35
|
-
Sign in at: ${
|
|
36
|
-
Your code: ${
|
|
37
|
-
`);try{await
|
|
38
|
-
`)){let
|
|
39
|
-
`)}function
|
|
40
|
-
`),nextSteps:
|
|
41
|
-
`),
|
|
33
|
+
If you want to deploy an existing project, use your framework's deploy tools directly.`,!0)}async function Jo(t,e){try{let{getPage:o,takeScreenshot:n}=await Promise.resolve().then(()=>(Pn(),Vo)),s=await o();await s.goto(t,{waitUntil:"domcontentloaded",timeout:15e3}),await s.waitForLoadState("networkidle").catch(()=>{});let a=await n(s,!1);return{content:[{type:"text",text:e},{type:"image",data:a.toString("base64"),mimeType:"image/png"}]}}catch{return c(e)}}var W=x(()=>{"use strict";ft()});import{readFileSync as Ko,existsSync as In,writeFileSync as Mi,mkdirSync as Ui,renameSync as $i,unlinkSync as Li}from"fs";import{join as _n,dirname as Fi}from"path";import{homedir as qi}from"os";import{randomBytes as Bi}from"crypto";function Yo(){return _n(qi(),".mistflow","credentials.json")}function Lt(){return(process.env.MISTFLOW_API_URL||"https://api.mistflow.ai").replace(/\/+$/,"")}function Qo(){let t=Yo();if(!In(t))return null;try{let e=JSON.parse(Ko(t,"utf-8"));return typeof e.apiKey=="string"?{[zi]:e}:e}catch{return null}}function Ve(){let t=process.env.MISTFLOW_API_KEY;if(t)return{ok:!0,creds:{apiKey:t,orgId:"",orgSlug:"env"}};let e=Qo();if(!e)return{ok:!1,reason:"missing"};let o=Lt(),n=e[o];return n&&typeof n.apiKey=="string"&&n.apiKey&&typeof n.orgId=="string"?{ok:!0,creds:n}:{ok:!1,reason:"missing"}}function Tn(t){let e=Yo(),o=Fi(e);In(o)||Ui(o,{recursive:!0});let n=Qo()??{},s=Lt();n[s]=t;let a=_n(o,`.credentials.tmp.${Bi(8).toString("hex")}`);try{Mi(a,JSON.stringify(n,null,2)+`
|
|
34
|
+
`,{mode:384}),$i(a,e)}catch(r){try{Li(a)}catch{}throw r}}function J(){return Ve().ok}function Ae(t){let e=_n(t,"mistflow.json");if(!In(e))return null;try{return JSON.parse(Ko(e,"utf-8"))}catch{return null}}var zi,Je=x(()=>{"use strict";zi="https://api.mistflow.ai"});var os={};Ot(os,{MistflowApiError:()=>C,addDomain:()=>jn,checkAuth:()=>Vi,checkAuthDetailed:()=>ts,checkSubdomain:()=>An,createDeployment:()=>Ki,createProject:()=>vt,deleteEnvVar:()=>Un,discoverDecisions:()=>Yi,downloadSource:()=>ta,downloadSourceWithToken:()=>ns,fetchDesignDirections:()=>En,fetchModule:()=>Hn,fetchPlanConversation:()=>qt,fetchScaffold:()=>Bn,fetchStepContext:()=>zn,forkTemplate:()=>Gn,generatePlan:()=>Nn,getAuthHeaders:()=>qe,getBaseUrl:()=>K,getDashboardUrl:()=>Hi,getDbCredentials:()=>Qi,getDeployLogs:()=>$n,getDeploymentStatus:()=>xt,getProject:()=>Ji,getProjectErrors:()=>Ln,getSeedInfo:()=>Xi,getSiteUrl:()=>Ke,getTemplate:()=>Wn,hasCredentialsOnDisk:()=>J,hasLocalCredentials:()=>es,listDeployments:()=>Qe,listDomains:()=>Ce,listEnvVars:()=>On,markLocalSetupDone:()=>na,modifyPlan:()=>Bt,pingBackend:()=>Rn,promotePreview:()=>Fn,redeployProject:()=>ea,removeDomain:()=>Dn,rollbackDeployment:()=>qn,shareProject:()=>Vn,uploadAndDeploy:()=>Cn,uploadQAResults:()=>Zi,upsertEnvVar:()=>Mn,verifyDomain:()=>zt});function K(){return Lt()}function Ke(){let t=process.env.MISTFLOW_API_URL;if(t){if(t.includes("mistflow.localhost"))return t.replace("api.mistflow","mistflow");if(t.includes("localhost:9100"))return t.replace(":9100",":9102")}return"https://mistflow.ai"}function Hi(){let t=process.env.MISTFLOW_API_URL;if(t){if(t.includes("mistflow.localhost"))return t.replace("api.mistflow","app.mistflow");if(t.includes("localhost:9100"))return t.replace(":9100",":9101")}return"https://app.mistflow.ai"}function qe(){let t=Ve();if(!t.ok)throw new C("auth_missing","No Mistflow credentials found.",401);return Wi(t.creds)}function Wi(t){return{Authorization:`ApiKey ${t.apiKey}`,"Content-Type":"application/json","X-Mistflow-MCP-Version":ue()}}function Ye(t){try{gt(t.headers)}catch{}}async function Rn(){try{let t=await fetch(`${K()}/health`,{method:"GET",signal:AbortSignal.timeout(5e3)});Ye(t)}catch{}}async function Zo(t,e,o,n){for(let s=0;s<2;s++)try{return await fetch(t,{...e,signal:AbortSignal.timeout(o)})}catch(a){let r=a instanceof Error&&a.name==="TimeoutError",i=a instanceof TypeError;if(n&&s===0&&(r||i)){console.error(`[api] Retrying ${t} after ${r?"timeout":"network error"}`);continue}throw a}throw new Error("fetchWithRetry: exhausted retries")}async function wt(t){let e=null;try{e=await t.json()}catch{e=null}let o=e&&typeof e.code=="string"?e.code:void 0,n=e&&typeof e.message=="string"?e.message:e&&typeof e.detail=="string"?e.detail:t.statusText||"Request failed";if(o)return new C(o,n,t.status,e?.details);let s=t.status;return s===401?new C("auth_invalid",n,s):s===403?new C("permission_denied",n,s):s===404?new C("not_found",n,s):s===409?new C("conflict",n,s):s===422?new C("validation_error",n,s):s===429?new C("rate_limited",n,s):s>=500?new C("server_error",t.statusText||"Internal server error",s):new C("client_error",n,s)}async function j(t,e={}){let o=qe(),{timeoutMs:n,idempotent:s,...a}=e,r=n??3e4,i=(a.method??"GET").toUpperCase(),l=s??(i==="GET"||i==="HEAD"),p;try{p=await Zo(`${K()}${t}`,{...a,headers:{...o,...a.headers}},r,l)}catch(m){throw m instanceof Error&&m.name==="TimeoutError"?new C("network_error","Request timed out. Try again in a moment."):new C("network_error","Cannot reach Mistflow servers. Check your network.")}if(Ye(p),!p.ok)throw await wt(p);return p.json()}function es(){return Ve().ok}async function Vi(){return(await ts()).ok}async function ts(){if(Ft!==null&&Date.now()<Xo)return Ft?{ok:!0}:{ok:!1,reason:"no_credentials"};if(!es())return{ok:!1,reason:"no_credentials"};try{return await j("/api/org"),Ft=!0,Xo=Date.now()+Gi,{ok:!0}}catch(t){if(Ft=null,!(t instanceof C))return{ok:!1,reason:"network_error"};switch(t.code){case"auth_missing":case"auth_revoked":return{ok:!1,reason:"no_credentials"};case"auth_expired":case"auth_invalid":case"auth_org_not_found":return{ok:!1,reason:"expired"};case"network_error":return{ok:!1,reason:"network_error"};case"rate_limited":case"server_error":case"upstream_error":return{ok:!1,reason:"server_error"};default:return{ok:!1,reason:"server_error"}}}}async function Ji(t){return j(`/api/projects/${encodeURIComponent(t)}`)}async function An(t){return j(`/api/projects/check-subdomain?name=${encodeURIComponent(t)}`)}async function vt(t,e,o="neon",n){return j("/api/projects",{method:"POST",body:JSON.stringify({name:t,template:e,db_provider:o,requested_subdomain:n})})}async function Ki(t,e){return j("/api/deploy",{method:"POST",body:JSON.stringify({project_id:t,build_output_url:e})})}async function Cn(t,e,o="production",n,s,a,r){let{readFileSync:i}=await import("fs"),{basename:l}=await import("path"),p=Ve();if(!p.ok)throw new C("auth_missing","No Mistflow credentials found.",401);let m=p.creds,u=i(e),d=new Blob([u],{type:"application/gzip"}),b=new FormData;if(b.append("project_id",t),b.append("build",d,l(e)),o!=="production"&&b.append("environment",o),n&&b.append("admin_email",n),s&&b.append("schema_pushed","true"),a){let{existsSync:y}=await import("fs");if(y(a)){let k=i(a),U=new Blob([k],{type:"application/gzip"});b.append("source",U,"source.tar.gz")}}r&&b.append("git_commit_sha",r);let R;try{R=await fetch(`${K()}/api/deploy/upload`,{method:"POST",headers:{Authorization:`ApiKey ${m.apiKey}`,"X-Mistflow-MCP-Version":ue()},body:b,signal:AbortSignal.timeout(3e5)})}catch{throw new C("network_error","Cannot reach Mistflow servers. Check your network.")}if(Ye(R),!R.ok)throw await wt(R);let w=await R.json();return{...w,id:w.deployment_id}}async function xt(t){return j(`/api/deploy/${encodeURIComponent(t)}/status`)}async function En(t){return j(`/api/plan/design-directions/${encodeURIComponent(t)}`,{timeoutMs:15e3})}async function qt(t){return j(`/api/plan/conversations/${encodeURIComponent(t)}`,{timeoutMs:15e3})}async function Nn(t,e){let o={description:t,conversation_id:e?.conversationId,answers:e?.answers};e?.autonomous&&(o.autonomous=!0),e?.language&&e.language.toLowerCase()!=="english"&&(o.language=e.language),e?.designConversationId&&(o.design_conversation_id=e.designConversationId),e?.designDirection&&(o.design_direction=e.designDirection);let n=e?.conversationId||e?.answers||e?.designConversationId?18e4:6e4;return j("/api/plan",{method:"POST",body:JSON.stringify(o),timeoutMs:n,idempotent:!1})}async function Bt(t,e){return j("/api/plan/modify",{method:"POST",body:JSON.stringify({existing_plan:t,modification:e})})}async function Yi(t){return j("/api/plan/discover",{method:"POST",body:JSON.stringify({description:t})})}async function jn(t,e){return j(`/api/projects/${encodeURIComponent(t)}/domains`,{method:"POST",body:JSON.stringify({domain:e})})}async function Ce(t){return j(`/api/projects/${encodeURIComponent(t)}/domains`)}async function zt(t,e){return j(`/api/projects/${encodeURIComponent(t)}/domains/${encodeURIComponent(e)}/verify`)}async function Dn(t,e){return j(`/api/projects/${encodeURIComponent(t)}/domains/${encodeURIComponent(e)}`,{method:"DELETE"})}async function Qi(t){return j(`/api/projects/${encodeURIComponent(t)}/db-credentials`)}async function Xi(t){try{return await j(`/api/projects/${encodeURIComponent(t)}/test-accounts`)}catch(e){return e instanceof C&&(e.statusCode===404||e.code==="not_found")||console.error("[api] Failed to fetch seed info:",e instanceof Error?e.message:e),null}}async function Zi(t,e){try{return await j(`/api/deploy/${encodeURIComponent(t)}/qa-results`,{method:"POST",body:JSON.stringify(e)})}catch(o){return console.error("[api] Failed to upload QA results:",o instanceof Error?o.message:o),null}}async function On(t){return j(`/api/projects/${encodeURIComponent(t)}/env`)}async function Mn(t,e,o,n){return j(`/api/projects/${encodeURIComponent(t)}/env`,{method:"PUT",body:JSON.stringify({key:e,value:o,category:n?.category??"custom",description:n?.description,setup_url:n?.setupUrl})})}async function Un(t,e){return j(`/api/projects/${encodeURIComponent(t)}/env/${encodeURIComponent(e)}`,{method:"DELETE"})}async function $n(t){return j(`/api/deploy/${encodeURIComponent(t)}/logs`)}async function Ln(t,e="7d"){return j(`/api/projects/${encodeURIComponent(t)}/errors?period=${encodeURIComponent(e)}`)}async function Qe(t){return j(`/api/projects/${encodeURIComponent(t)}/deployments`)}async function ea(t){return j(`/api/deploy/${encodeURIComponent(t)}/redeploy`,{method:"POST"})}async function Fn(t,e){let o=new URLSearchParams({preview_deployment_id:e});return j(`/api/deploy/${encodeURIComponent(t)}/promote`,{method:"POST",body:o.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"}})}async function qn(t){return j(`/api/deploy/${encodeURIComponent(t)}/rollback`,{method:"POST"})}async function ta(t,e){let o=Ve();if(!o.ok)throw new C("auth_missing","Not authenticated.",401);let n=o.creds,s=await fetch(`${K()}/api/deploy/${encodeURIComponent(t)}/source`,{headers:{Authorization:`ApiKey ${n.apiKey}`,"X-Mistflow-MCP-Version":ue()},signal:AbortSignal.timeout(12e4)});if(Ye(s),!s.ok)throw await wt(s);let{writeFileSync:a}=await import("fs"),r=Buffer.from(await s.arrayBuffer());a(e,r)}async function Ht(t,e){let{timeoutMs:o,idempotent:n,...s}=e??{},a=o??3e4,r=(s.method??"GET").toUpperCase(),i=n??(r==="GET"||r==="HEAD"),l;try{l=await Zo(`${K()}${t}`,{headers:{"Content-Type":"application/json","X-Mistflow-MCP-Version":ue()},...s},a,i)}catch(p){throw p instanceof Error&&p.name==="TimeoutError"?new C("network_error","Request timed out. Try again in a moment."):new C("network_error","Cannot reach Mistflow servers. Check your network.")}if(Ye(l),!l.ok)throw await wt(l);return l.json()}async function Bn(t="nextjs"){return Ht(`/api/scaffold/${encodeURIComponent(t)}`)}async function zn(t,e){return Ht(`/api/scaffold/${encodeURIComponent(t)}/context?step_type=${encodeURIComponent(e)}`)}async function Hn(t,e,o,n){return Ht(`/api/scaffold/${encodeURIComponent(t)}/module`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"crud",entity:e,fields:o,entity_plural:n})})}async function Wn(t){return Ht(`/api/templates/${encodeURIComponent(t)}`)}async function Gn(t){return j(`/api/templates/${encodeURIComponent(t)}/fork`,{method:"POST"})}async function ns(t,e,o){let n;try{n=await fetch(`${K()}/api/deploy/${encodeURIComponent(t)}/fork-source?fork_token=${encodeURIComponent(e)}`,{headers:{"X-Mistflow-MCP-Version":ue()},signal:AbortSignal.timeout(12e4)})}catch{throw new C("network_error","Cannot reach Mistflow servers. Check your network.")}if(Ye(n),!n.ok)throw n.status===401?new C("validation_error","Fork token expired or invalid. Re-open the project in the dashboard to get a fresh token.",n.status):await wt(n);let{writeFileSync:s}=await import("fs"),a=Buffer.from(await n.arrayBuffer());s(o,a)}async function na(t){await j(`/api/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify({local_setup_done:!0})})}async function Vn(t,e){return j(`/api/projects/${encodeURIComponent(t)}/share`,{method:"POST",body:JSON.stringify({is_template:e?.isTemplate??!1,template_description:e?.description})})}var C,Ft,Xo,Gi,le=x(()=>{"use strict";Je();ft();C=class extends Error{constructor(o,n,s,a){super(n);this.code=o;this.statusCode=s;this.details=a;this.name="MistflowApiError"}get isAuth(){return this.code.startsWith("auth_")}get isTransient(){return this.code==="server_error"||this.code==="upstream_error"||this.code==="network_error"||this.code==="rate_limited"}};Ft=null,Xo=0,Gi=300*1e3});import{z as Jn}from"zod";import{platform as oa}from"os";import{execFile as ss}from"child_process";function ra(t){return"error"in t}function is(t){return new Promise(e=>setTimeout(e,t))}function ia(t){return new Promise(e=>{let o=oa();o==="win32"?ss("cmd.exe",["/c","start","",t],n=>{n&&console.error("Could not open browser:",n.message),e(!n)}):ss(o==="darwin"?"open":"xdg-open",[t],s=>{s&&console.error("Could not open browser:",s.message),e(!s)}),setTimeout(()=>e(!1),5e3)})}async function rs(t,e,o,n){let s=o,a=n.sleep??is;for(let r=0;r<e;r++){await a(s);let i;try{let p=await n.fetch(`${K()}/auth/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:t})});if(!p.ok)continue;i=await p.json()}catch{continue}if(ra(i))switch(i.error){case"authorization_pending":continue;case"slow_down":s+=5e3;continue;case"expired_token":return c("The sign-in link expired. Run mist_setup again to get a new code.",!0);case"access_denied":return c("Sign-in was cancelled. Run mist_setup again to try again.",!0);case"already_exchanged":return c("This sign-in link was already used. Run mist_setup again to get a new code.",!0)}let l=i.email||i.org_name||i.org_slug;return Tn({apiKey:i.api_key,apiKeyId:i.api_key_id,apiKeyName:i.api_key_name,orgId:i.org_id,orgSlug:i.org_slug,email:i.email}),c(`Connected to Mistflow as ${l}. You are ready to build and deploy.`)}return null}async function la(t,e=aa){let o=t;if(o?.apiKey)try{let r=await e.fetch(`${K()}/api/org`,{headers:{Authorization:`ApiKey ${o.apiKey}`}});if(!r.ok)return c("Invalid API key. Check the key and try again.",!0);let i=await r.json();return Tn({apiKey:o.apiKey,orgId:i.id,orgSlug:i.slug}),c(`Connected to Mistflow as ${i.slug} via API key. You are ready to build and deploy.`)}catch{return c("Cannot reach Mistflow servers. Check your internet connection.",!0)}if(o?.deviceCode){let r=await rs(o.deviceCode,6,5e3,e);return r||c(JSON.stringify({status:"pending",deviceCode:o.deviceCode,instruction:"The user hasn't approved yet. Wait ~15 seconds and call mist_setup again with the same deviceCode."}))}let n;try{let r=await e.fetch(`${K()}/auth/device`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!r.ok)return c("Cannot reach Mistflow servers. Check your internet connection.",!0);n=await r.json()}catch{return c("Cannot reach Mistflow servers. Check your internet connection.",!0)}let s=`${n.verification_uri}?code=${n.user_code}`;console.error(`
|
|
35
|
+
Sign in at: ${s}
|
|
36
|
+
Your code: ${n.user_code}
|
|
37
|
+
`);try{await e.openBrowser(s)}catch{}let a=await rs(n.device_code,6,5e3,e);return a||c(JSON.stringify({status:"pending",deviceCode:n.device_code,signInUrl:s,userCode:n.user_code,instruction:"The user hasn't approved yet. Wait ~15 seconds, then call mist_setup again with deviceCode='"+n.device_code+"' to check if they approved."}))}var sa,aa,as,ls=x(()=>{"use strict";Te();W();le();Je();sa=Jn.object({apiKey:Jn.string().optional().describe("API key (mist_...) for headless auth. Skips the device code flow entirely. Generate one at app.mistflow.ai/mcp-keys."),deviceCode:Jn.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.")});aa={fetch:globalThis.fetch,openBrowser:ia,sleep:is};as={name:"mist_setup",description:No,inputSchema:sa,handler:t=>la(t)}});import{existsSync as ca,readFileSync as pa}from"fs";function cs(t){let e=new Set;if(!ca(t))return e;let o=pa(t,"utf-8");for(let n of o.split(`
|
|
38
|
+
`)){let s=n.trim();if(!s||s.startsWith("#"))continue;let a=s.indexOf("=");if(a>0){let r=s.slice(0,a).trim(),i=s.slice(a+1).trim();i&&i!=='""'&&i!=="''"&&e.add(r)}}return e}var ps=x(()=>{"use strict"});var Pt={};Ot(Pt,{emptyState:()=>St,fetchRemoteState:()=>ga,fuzzyMatch:()=>ya,getLocalStatePath:()=>Kn,readLocalState:()=>ha,syncRemoteState:()=>fa,writeLocalState:()=>kt});import{existsSync as ds,readFileSync as da,writeFileSync as ua,mkdirSync as ma}from"fs";import{join as us}from"path";function Kn(t){return us(t,".mistflow","state.json")}function ha(t){let e=Kn(t);if(!ds(e))return null;try{return JSON.parse(da(e,"utf-8"))}catch{return null}}function kt(t,e){let o=us(t,".mistflow");ds(o)||ma(o,{recursive:!0}),ua(Kn(t),JSON.stringify(e,null,2)+`
|
|
39
|
+
`)}function St(t,e){return{projectId:t,name:e,template:"",features:[],dbSchema:[],deployCount:0,decisions:[],provenance:[]}}async function ga(t){let e;try{e=qe()}catch{return null}try{let o=await fetch(`${K()}/api/projects/${encodeURIComponent(t)}/state`,{headers:{...e,"Content-Type":"application/json","X-Mistflow-MCP-Version":ue()}});try{gt(o.headers)}catch{}return o.ok?await o.json():null}catch{return null}}async function fa(t,e){let o;try{o=qe()}catch{return!1}try{let n=await fetch(`${K()}/api/projects/${encodeURIComponent(t)}/state`,{method:"PUT",headers:{...o,"Content-Type":"application/json","X-Mistflow-MCP-Version":ue()},body:JSON.stringify(e)});try{gt(n.headers)}catch{}return n.ok}catch{return!1}}function ya(t,e){let o=t.toLowerCase(),n=e.toLowerCase();return n.includes(o)||o.includes(n)?!0:o.split(/\s+/).some(a=>a.length>=3&&n.includes(a))}var Be=x(()=>{"use strict";le();ft()});var Yn={};Ot(Yn,{ensureBackendRegistered:()=>Pa,ensureShadcnComponents:()=>Ia});import{existsSync as hs,readFileSync as ba,writeFileSync as wa}from"fs";import{join as Wt}from"path";import{spawn as va}from"child_process";function xa(t,e,o,n,s){return new Promise(a=>{let r=va(t,e,{cwd:o,stdio:["pipe","pipe","pipe"],timeout:n,...s?{env:{...process.env,...s}}:{}}),i="",l="";r.stdout?.on("data",p=>{i+=p.toString()}),r.stderr?.on("data",p=>{l+=p.toString()}),r.on("close",p=>a({success:p===0,stdout:i,stderr:l})),r.on("error",p=>a({success:!1,stdout:i,stderr:l+p.message}))})}function ka(t){let e=Wt(t,"mistflow.json");if(!hs(e))return null;try{return JSON.parse(ba(e,"utf-8"))}catch{return null}}function Sa(t,e){wa(Wt(t,"mistflow.json"),JSON.stringify(e,null,2))}async function ms(t,e){try{let o=e.features,n=e.steps,s={plan:e};Array.isArray(o)&&o.length>0&&(s.features=o.map(a=>a.name)),Array.isArray(n)&&n.length>0&&(s.provenance=n.map(a=>({feature:a.name??a.title??`Step ${a.number??"?"}`,user_intent:(a.description??"").slice(0,500),decisions:"Seeded from plan",tradeoffs:"",files_affected:[]}))),await fetch(`${K()}/api/projects/${encodeURIComponent(t)}/state`,{method:"PUT",headers:{...qe(),"Content-Type":"application/json"},body:JSON.stringify(s)})}catch(o){console.error("[self-heal] state sync failed:",o instanceof Error?o.message:String(o))}}async function Pa(t,e={}){let o=ka(t);if(o){if(!J())return o.projectId;if(!o.projectId)try{let s=o.plan?.requestedSubdomain,a=await vt(o.name,void 0,o.dbProvider??"neon",s);return o.projectId=a.id,Sa(t,o),kt(t,St(a.id,o.name)),o.plan&&await ms(a.id,o.plan),console.error(`[self-heal] registered project ${a.id.slice(0,8)} with backend`),a.id}catch(n){console.error("[self-heal] createProject failed:",n instanceof Error?n.message:String(n));return}return e.forceSync&&o.plan&&o.projectId&&await ms(o.projectId,o.plan),o.projectId}}async function Ia(t,e){let o=["button","card","input","label","form","dialog","table","dropdown-menu","badge","separator","skeleton","sheet","tabs","avatar","select","textarea","checkbox","switch","tooltip","popover","sonner"],n=e&&e.length>0?e:o,s=Wt(t,"components","ui"),a=[],r=[];for(let p of n)hs(Wt(s,`${p}.tsx`))?a.push(p):r.push(p);if(r.length===0)return{installed:[],alreadyPresent:a};let i={NPM_CONFIG_LEGACY_PEER_DEPS:"true"},l=await xa("npx",["--yes","shadcn@latest","add","-y","-o",...r],t,18e4,i);return l.success?{installed:r,alreadyPresent:a}:{installed:[],alreadyPresent:a,failed:`shadcn add failed for: ${r.join(", ")}. ${l.stderr.slice(-300)}`.trim()}}var Qn=x(()=>{"use strict";le();Be()});import{z as Ee}from"zod";import{resolve as _a,join as gs}from"path";import{existsSync as Ta,readFileSync as fs,writeFileSync as Ra}from"fs";var Aa,ys,bs=x(()=>{"use strict";W();ps();Aa=Ee.object({action:Ee.enum(["get","update"]).default("get").describe("'get' reads current project state. 'update' modifies it."),projectPath:Ee.string().optional().describe("Path to the project directory (default: current working directory)"),completedStep:Ee.number().optional().describe("(update only) Mark a plan step as completed by step number"),addEnvVar:Ee.object({key:Ee.string(),description:Ee.string().optional(),setupUrl:Ee.string().optional()}).optional().describe("(update only) Add a required env var to the project manifest")}),ys={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. Called internally by mist_project; host AIs should use mist_project directly.",inputSchema:Aa,handler:async t=>{let e=t,o=_a(e.projectPath??process.cwd()),n=gs(o,"mistflow.json");if(!Ta(n))return Pe(o);let s;try{s=JSON.parse(fs(n,"utf-8"))}catch{return c("Failed to parse mistflow.json.",!0)}if(e.action==="get"){if(!s.projectId)try{let{ensureBackendRegistered:y}=await Promise.resolve().then(()=>(Qn(),Yn));await y(o)&&(s=JSON.parse(fs(n,"utf-8")))}catch{}let i=s.plan,l=i?.steps?.filter(y=>y.status==="completed").length??0,p=i?.steps?.length??0,m=cs(gs(o,".env.local")),u=s.env?.required?Object.entries(s.env.required).map(([y,k])=>({name:y,description:k?.description,configured:m.has(y)})):[];s.projectId&&Promise.resolve().then(()=>(Be(),Pt)).then(({fetchRemoteState:y})=>y(s.projectId)).catch(()=>{});let d=[`Project: ${s.name}`];if(i){d.push(`Plan: ${i.summary??i.name??"unnamed"} \u2014 ${l}/${p} steps complete`);for(let y of i.steps){let k=y.status==="completed"?"\u2713":y.status==="in_progress"?"\u2192":" ";d.push(` [${k}] ${y.number}. ${y.name}`)}}let b=u.filter(y=>!y.configured);b.length>0&&d.push(`Missing env vars: ${b.map(y=>y.name).join(", ")}`),s.deploy?.url?d.push(`Deployed: ${s.deploy.url} (${s.deploy.count??0} deploys)`):d.push("Not deployed yet");let R=[],w=i?.steps?.find(y=>y.status!=="completed");return w?R.push(`NEXT: Call mist_implement({ projectPath }) to work on step ${w.number} (${w.name}).`):i&&l===p&&(s.deploy?.url||R.push("NEXT: All steps complete. Call mist_build({ projectPath }) then mist_deploy({ action: 'deploy', projectPath }). Do NOT ask the user \u2014 chain straight through.")),b.length>0&&R.push(`Missing env vars in .env.local: ${b.map(y=>y.name).join(", ")}`),c(JSON.stringify({name:s.name,projectId:s.projectId,planProgress:i?{name:i.name,summary:i.summary,totalSteps:p,completedSteps:l,steps:i.steps}:null,envStatus:u,deploy:s.deploy??null,contextMessage:d.join(`
|
|
40
|
+
`),nextSteps:R}))}let a=[];if(e.completedStep!==void 0){let i=s.plan;if(i?.steps){let l=i.steps.findIndex(p=>p.number===e.completedStep);if(l===-1)return c(`Step ${e.completedStep} not found in the plan.`,!0);i.steps[l].status="completed",a.push(`Step ${e.completedStep} marked as completed`)}}e.addEnvVar&&(s.env||(s.env={required:{}}),s.env.required||(s.env.required={}),s.env.required[e.addEnvVar.key]={description:e.addEnvVar.description,setupUrl:e.addEnvVar.setupUrl},a.push(`Added required env var: ${e.addEnvVar.key}`)),Ra(n,JSON.stringify(s,null,2)+`
|
|
41
|
+
`),s.projectId&&Promise.resolve().then(()=>(Be(),Pt)).then(async({readLocalState:i,syncRemoteState:l})=>{let p=i(o);p&&await l(s.projectId,p)}).catch(()=>{});let r=[];if(e.completedStep!==void 0){let l=s.plan?.steps?.find(p=>p.status!=="completed");l?r.push(`NEXT: Call mist_implement({ projectPath }) to work on step ${l.number} (${l.name}). Do this now.`):r.push("NEXT: All steps complete. Call mist_build({ projectPath }) then mist_deploy({ action: 'deploy', projectPath }) to deploy the app. Do NOT suggest localhost.")}return e.addEnvVar&&(r.push(`Add ${e.addEnvVar.key} to your .env.local file`),e.addEnvVar.setupUrl&&r.push(`Get the value from: ${e.addEnvVar.setupUrl}`)),c(JSON.stringify({updated:!0,changes:a,message:a.length>0?`Project state saved. ${a.join(". ")}.`:"No changes made.",nextSteps:r.length>0?r:void 0}))}}});function Gt(t){let e=Xe.find(n=>n.id===t);if(e)return e;let o=t.toLowerCase().replace(/[^a-z0-9]/g,"");return Xe.find(n=>{let s=n.title.toLowerCase().replace(/[^a-z0-9]/g,"");return s===o||s.includes(o)||o.includes(s)})}function ws(t){return Xn[t]}function Zn(t){return t?Xe.filter(e=>e.category.toLowerCase()===t.toLowerCase()):Xe}function vs(t){let e=t??Xe;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 o={};for(let s of e){o[s.category]||(o[s.category]=[]);let a=Xn[s.id],r=a?` \u2014 ${a.description}`:"";o[s.category].push(`${s.id} \u2014 "${s.title}"${r}`)}let n=[];for(let[s,a]of Object.entries(o))n.push(`**${s}**:
|
|
42
|
+
${a.map(r=>` \u2022 ${r}`).join(`
|
|
43
|
+
`)}`);return n.join(`
|
|
42
44
|
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
45
|
+
`)}function Ca(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function xs(t){return(t?Zn(t):Xe).map(o=>{let n=Xn[o.id];return{id:o.id,slug:Ca(o.title),title:o.title,category:o.category,description:n?.description??"",tags:n?.tags??[],theme:n?.theme??"dark",colors:n?.colors??[],style:n?.style??""}})}function ks(t,e){return[]}var Xn,Xe,eo=x(()=>{"use strict";Xn={},Xe=[]});function Ea(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function et(t){let e=Ze.find(n=>n.id===t);if(e)return e;let o=t.toLowerCase().replace(/[^a-z0-9]/g,"");return Ze.find(n=>{let s=n.name.toLowerCase().replace(/[^a-z0-9]/g,"");return s===o||s.includes(o)||o.includes(s)})}function tt(t){return to[t]}function no(t){return t?Ze.filter(e=>e.category.toLowerCase()===t.toLowerCase()):Ze}function Ss(t){let e=t??Ze,o={};for(let s of e){o[s.category]||(o[s.category]=[]);let a=to[s.id],r=a?` \u2014 ${a.description}`:"",i=a?.packages.length?` (${a.packages.join(", ")})`:"";o[s.category].push(`${s.id} \u2014 "${s.name}"${r}${i}`)}let n=[];for(let[s,a]of Object.entries(o))n.push(`**${s}**:
|
|
46
|
+
${a.map(r=>` - ${r}`).join(`
|
|
47
|
+
`)}`);return n.join(`
|
|
46
48
|
|
|
47
|
-
|
|
49
|
+
`)}function Ps(t){return(t?no(t):Ze).map(o=>{let n=to[o.id];return{id:o.id,slug:Ea(o.name),name:o.name,category:o.category,description:n?.description??"",tags:n?.tags??[],envVars:n?.envVars??[],docsUrl:n?.docsUrl??"",packages:n?.packages??[],difficulty:n?.difficulty??"medium"}})}var to,Ze,Vt=x(()=>{"use strict";to={"resend-email":{description:"Transactional email with React Email templates and webhook handling.",tags:["email","transactional","welcome","notification","invite","alert"],envVars:[{key:"RESEND_API_KEY",description:"Resend API key for sending emails",setupUrl:"https://resend.com/api-keys"}],docsUrl:"https://resend.com/docs/send-with-nextjs",packages:["resend","@react-email/components"],difficulty:"easy"},"r2-storage":{description:"File uploads with drag-and-drop UI, stored in Mistflow Cloud.",tags:["storage","upload","file","image","media","attachment","avatar"],envVars:[],docsUrl:"https://developers.cloudflare.com/r2/",packages:[],difficulty:"easy"},"openai-ai":{description:"AI-powered features with OpenAI SDK, streaming chat, and content generation.",tags:["ai","openai","chatbot","gpt","llm","assistant","generation"],envVars:[{key:"OPENAI_API_KEY",description:"OpenAI API key for AI features",setupUrl:"https://platform.openai.com/api-keys"}],docsUrl:"https://platform.openai.com/docs/guides/text-generation",packages:["openai","ai"],difficulty:"medium"},"anthropic-ai":{description:"AI features with the Anthropic SDK, streaming Claude chat, and content generation.",tags:["ai","anthropic","claude","llm","assistant","generation"],envVars:[{key:"ANTHROPIC_API_KEY",description:"Anthropic API key for Claude",setupUrl:"https://console.anthropic.com/settings/keys"}],docsUrl:"https://docs.anthropic.com/en/docs/initial-setup",packages:["@anthropic-ai/sdk","ai"],difficulty:"medium"},"openrouter-ai":{description:"AI model router with access to 200+ models (GPT, Claude, Llama, Mistral, etc.) through one API.",tags:["ai","openrouter","llm","multi-model","claude","gpt","llama","mistral"],envVars:[{key:"OPENROUTER_API_KEY",description:"OpenRouter API key",setupUrl:"https://openrouter.ai/keys"}],docsUrl:"https://openrouter.ai/docs/quickstart",packages:["@openrouter/sdk"],difficulty:"easy"},"stripe-payments":{description:"Payment processing with Stripe Checkout, webhooks, and billing portal.",tags:["payments","stripe","billing","subscription","checkout","invoice"],envVars:[{key:"STRIPE_SECRET_KEY",description:"Stripe secret key",setupUrl:"https://dashboard.stripe.com/apikeys"},{key:"STRIPE_PUBLISHABLE_KEY",description:"Stripe publishable key (client-side)",setupUrl:"https://dashboard.stripe.com/apikeys"},{key:"STRIPE_WEBHOOK_SECRET",description:"Stripe webhook signing secret",setupUrl:"https://dashboard.stripe.com/webhooks"}],docsUrl:"https://docs.stripe.com/checkout/quickstart",packages:["stripe","@stripe/stripe-js"],difficulty:"advanced"},"elevenlabs-voice":{description:"Text-to-speech and voice generation with ElevenLabs API.",tags:["voice","tts","speech","audio","elevenlabs","narration","podcast"],envVars:[{key:"ELEVENLABS_API_KEY",description:"ElevenLabs API key for voice generation",setupUrl:"https://elevenlabs.io/app/settings/api-keys"}],docsUrl:"https://elevenlabs.io/docs/api-reference/text-to-speech",packages:["elevenlabs"],difficulty:"medium"},"google-maps":{description:"Google Maps embed, Places autocomplete, and geolocation features.",tags:["maps","location","google","places","geocoding","directions","nearby"],envVars:[{key:"NEXT_PUBLIC_GOOGLE_MAPS_API_KEY",description:"Google Maps API key (client-side)",setupUrl:"https://console.cloud.google.com/apis/credentials"}],docsUrl:"https://developers.google.com/maps/documentation/javascript",packages:["@googlemaps/js-api-loader"],difficulty:"medium"},"twilio-sms":{description:"SMS notifications, OTP verification, and phone number validation.",tags:["sms","twilio","otp","phone","verification","text-message"],envVars:[{key:"TWILIO_ACCOUNT_SID",description:"Twilio account SID",setupUrl:"https://console.twilio.com/"},{key:"TWILIO_AUTH_TOKEN",description:"Twilio auth token",setupUrl:"https://console.twilio.com/"},{key:"TWILIO_PHONE_NUMBER",description:"Twilio phone number for sending SMS",setupUrl:"https://console.twilio.com/us1/develop/phone-numbers/manage/incoming"}],docsUrl:"https://www.twilio.com/docs/messaging/quickstart/node",packages:["twilio"],difficulty:"medium"},"posthog-analytics":{description:"Product analytics with event tracking, feature flags, and session replay.",tags:["analytics","posthog","tracking","funnel","event","feature-flag"],envVars:[{key:"NEXT_PUBLIC_POSTHOG_KEY",description:"PostHog project API key",setupUrl:"https://app.posthog.com/project/settings"},{key:"NEXT_PUBLIC_POSTHOG_HOST",description:"PostHog instance URL (default: https://us.i.posthog.com)",setupUrl:"https://app.posthog.com/project/settings"}],docsUrl:"https://posthog.com/docs/libraries/next-js",packages:["posthog-js","posthog-node"],difficulty:"easy"},"firecrawl-scraping":{description:"Web scraping and crawling with markdown output, structured extraction, and async crawls.",tags:["scraping","crawl","firecrawl","web","extract","rag","markdown"],envVars:[{key:"FIRECRAWL_API_KEY",description:"Firecrawl API key",setupUrl:"https://firecrawl.dev"}],docsUrl:"https://docs.firecrawl.dev/sdks/node",packages:["@mendable/firecrawl-js"],difficulty:"easy"},"replicate-media":{description:"Image and video generation with 200+ AI models (Flux, Wan Video, Runway, SDXL, etc.) through one API.",tags:["image","video","replicate","flux","sdxl","generation","media","avatar","thumbnail"],envVars:[{key:"REPLICATE_API_TOKEN",description:"Replicate API token",setupUrl:"https://replicate.com/account/api-tokens"}],docsUrl:"https://replicate.com/docs/get-started/nodejs",packages:["replicate"],difficulty:"medium"}},Ze=[{id:"resend-email",name:"Resend Email",category:"communication",prompt:`## Resend Email Integration
|
|
48
50
|
|
|
49
|
-
|
|
51
|
+
### File Structure
|
|
52
|
+
\`\`\`
|
|
53
|
+
lib/resend.ts \u2014 Resend client singleton
|
|
54
|
+
lib/email.ts \u2014 Send helper functions (sendWelcomeEmail, sendNotification, etc.)
|
|
55
|
+
emails/ \u2014 React Email templates directory
|
|
56
|
+
welcome.tsx \u2014 Welcome email template
|
|
57
|
+
notification.tsx \u2014 Generic notification template
|
|
58
|
+
app/api/webhooks/resend/route.ts \u2014 Webhook handler for delivery events
|
|
59
|
+
\`\`\`
|
|
50
60
|
|
|
51
|
-
|
|
61
|
+
### Client Setup (lib/resend.ts)
|
|
62
|
+
\`\`\`typescript
|
|
63
|
+
import { Resend } from "resend";
|
|
52
64
|
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
\`node_modules/.bin/mist\` shims and can drift from the machine-level CLI.
|
|
65
|
+
export const resend = new Resend(process.env.RESEND_API_KEY);
|
|
66
|
+
\`\`\`
|
|
56
67
|
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
68
|
+
### Send Helper (lib/email.ts)
|
|
69
|
+
\`\`\`typescript
|
|
70
|
+
import { resend } from "./resend";
|
|
71
|
+
import WelcomeEmail from "@/emails/welcome";
|
|
72
|
+
|
|
73
|
+
export async function sendWelcomeEmail(to: string, name: string) {
|
|
74
|
+
const { data, error } = await resend.emails.send({
|
|
75
|
+
from: "App Name <noreply@yourdomain.com>",
|
|
76
|
+
to,
|
|
77
|
+
subject: "Welcome to App Name",
|
|
78
|
+
react: WelcomeEmail({ name }),
|
|
79
|
+
});
|
|
80
|
+
if (error) throw new Error(error.message);
|
|
81
|
+
return data;
|
|
82
|
+
}
|
|
83
|
+
\`\`\`
|
|
84
|
+
|
|
85
|
+
### React Email Template (emails/welcome.tsx)
|
|
86
|
+
\`\`\`tsx
|
|
87
|
+
import { Html, Head, Body, Container, Heading, Text, Button, Section } from "@react-email/components";
|
|
88
|
+
|
|
89
|
+
interface WelcomeEmailProps { name: string }
|
|
90
|
+
|
|
91
|
+
export default function WelcomeEmail({ name }: WelcomeEmailProps) {
|
|
92
|
+
return (
|
|
93
|
+
<Html>
|
|
94
|
+
<Head />
|
|
95
|
+
<Body style={{ backgroundColor: "#f6f9fc", fontFamily: "sans-serif" }}>
|
|
96
|
+
<Container style={{ maxWidth: 560, margin: "0 auto", padding: "20px 0" }}>
|
|
97
|
+
<Heading style={{ fontSize: 24, color: "#1a1a1a" }}>Welcome, {name}!</Heading>
|
|
98
|
+
<Text style={{ fontSize: 16, color: "#4a4a4a", lineHeight: 1.6 }}>
|
|
99
|
+
Thanks for signing up. Here's how to get started...
|
|
100
|
+
</Text>
|
|
101
|
+
<Section style={{ textAlign: "center", marginTop: 24 }}>
|
|
102
|
+
<Button href="https://yourapp.com/dashboard" style={{
|
|
103
|
+
backgroundColor: "#000", color: "#fff", padding: "12px 24px",
|
|
104
|
+
borderRadius: 6, fontSize: 14, fontWeight: 600,
|
|
105
|
+
}}>
|
|
106
|
+
Go to Dashboard
|
|
107
|
+
</Button>
|
|
108
|
+
</Section>
|
|
109
|
+
</Container>
|
|
110
|
+
</Body>
|
|
111
|
+
</Html>
|
|
112
|
+
);
|
|
113
|
+
}
|
|
114
|
+
\`\`\`
|
|
115
|
+
|
|
116
|
+
### Webhook Handler (app/api/webhooks/resend/route.ts)
|
|
117
|
+
\`\`\`typescript
|
|
118
|
+
import { NextRequest, NextResponse } from "next/server";
|
|
119
|
+
|
|
120
|
+
export async function POST(req: NextRequest) {
|
|
121
|
+
const body = await req.json();
|
|
122
|
+
const { type, data } = body;
|
|
123
|
+
// Handle: email.sent, email.delivered, email.bounced, email.complained
|
|
124
|
+
switch (type) {
|
|
125
|
+
case "email.bounced":
|
|
126
|
+
console.error("Email bounced:", data.to);
|
|
127
|
+
// Mark user email as invalid in your DB
|
|
128
|
+
break;
|
|
129
|
+
}
|
|
130
|
+
return NextResponse.json({ received: true });
|
|
131
|
+
}
|
|
132
|
+
\`\`\`
|
|
133
|
+
|
|
134
|
+
### Common Pitfalls
|
|
135
|
+
1. **Domain verification required for production.** Use Resend's free onboarding@resend.dev for dev, but production requires a verified domain.
|
|
136
|
+
2. **Rate limits.** Free tier: 100 emails/day, 3000/month. Queue emails for bulk sends.
|
|
137
|
+
3. **From address must match a verified domain** or use onboarding@resend.dev for testing.
|
|
138
|
+
4. **Webhooks need a public URL.** Use ngrok or similar for local webhook testing.
|
|
139
|
+
5. **React Email templates must be Server Components.** Do not add "use client" to email templates.
|
|
140
|
+
6. **Never ask the user to paste RESEND_API_KEY in chat.** Direct them to set it in the Mistflow dashboard (Project Settings > Environment Variables).`},{id:"r2-storage",name:"File Storage (R2)",category:"storage",prompt:`## File Storage Integration
|
|
141
|
+
|
|
142
|
+
Files are stored in Mistflow Cloud's managed blob storage. No extra setup needed for Mistflow-deployed apps.
|
|
143
|
+
|
|
144
|
+
### File Structure
|
|
145
|
+
\`\`\`
|
|
146
|
+
lib/storage.ts \u2014 Upload/download helpers
|
|
147
|
+
app/api/upload/route.ts \u2014 Upload API route (server-side)
|
|
148
|
+
components/file-upload.tsx \u2014 Drag-and-drop upload component
|
|
149
|
+
\`\`\`
|
|
150
|
+
|
|
151
|
+
### Upload API Route (app/api/upload/route.ts)
|
|
152
|
+
\`\`\`typescript
|
|
153
|
+
import { NextRequest, NextResponse } from "next/server";
|
|
154
|
+
|
|
155
|
+
export async function POST(req: NextRequest) {
|
|
156
|
+
const formData = await req.formData();
|
|
157
|
+
const file = formData.get("file") as File;
|
|
158
|
+
if (!file) return NextResponse.json({ error: "No file provided" }, { status: 400 });
|
|
159
|
+
|
|
160
|
+
// Validate file size (10MB max)
|
|
161
|
+
if (file.size > 10 * 1024 * 1024) {
|
|
162
|
+
return NextResponse.json({ error: "File too large (max 10MB)" }, { status: 400 });
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// Validate MIME type
|
|
166
|
+
const allowedTypes = ["image/jpeg", "image/png", "image/webp", "application/pdf"];
|
|
167
|
+
if (!allowedTypes.includes(file.type)) {
|
|
168
|
+
return NextResponse.json({ error: "File type not allowed" }, { status: 400 });
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
const bytes = await file.arrayBuffer();
|
|
172
|
+
const buffer = Buffer.from(bytes);
|
|
173
|
+
|
|
174
|
+
// Upload to R2 via Mistflow's storage endpoint
|
|
175
|
+
const key = \`uploads/\${Date.now()}-\${file.name.replace(/[^a-zA-Z0-9.-]/g, "_")}\`;
|
|
176
|
+
// Store buffer with key \u2014 implementation depends on R2 binding or S3-compatible client
|
|
177
|
+
// For Mistflow apps: the deploy pipeline auto-configures R2 bindings
|
|
178
|
+
|
|
179
|
+
return NextResponse.json({ url: \`/api/files/\${key}\`, key });
|
|
180
|
+
}
|
|
181
|
+
\`\`\`
|
|
182
|
+
|
|
183
|
+
### Drag-and-Drop Upload Component (components/file-upload.tsx)
|
|
184
|
+
\`\`\`tsx
|
|
185
|
+
"use client";
|
|
186
|
+
import { useState, useCallback } from "react";
|
|
187
|
+
|
|
188
|
+
interface FileUploadProps {
|
|
189
|
+
onUpload: (url: string) => void;
|
|
190
|
+
accept?: string;
|
|
191
|
+
maxSizeMB?: number;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
export function FileUpload({ onUpload, accept = "image/*", maxSizeMB = 10 }: FileUploadProps) {
|
|
195
|
+
const [isDragging, setIsDragging] = useState(false);
|
|
196
|
+
const [uploading, setUploading] = useState(false);
|
|
197
|
+
|
|
198
|
+
const handleUpload = useCallback(async (file: File) => {
|
|
199
|
+
setUploading(true);
|
|
200
|
+
try {
|
|
201
|
+
const formData = new FormData();
|
|
202
|
+
formData.append("file", file);
|
|
203
|
+
const res = await fetch("/api/upload", { method: "POST", body: formData });
|
|
204
|
+
if (!res.ok) throw new Error("Upload failed");
|
|
205
|
+
const { url } = await res.json();
|
|
206
|
+
onUpload(url);
|
|
207
|
+
} finally {
|
|
208
|
+
setUploading(false);
|
|
209
|
+
}
|
|
210
|
+
}, [onUpload]);
|
|
211
|
+
|
|
212
|
+
return (
|
|
213
|
+
<div
|
|
214
|
+
onDragOver={(e) => { e.preventDefault(); setIsDragging(true); }}
|
|
215
|
+
onDragLeave={() => setIsDragging(false)}
|
|
216
|
+
onDrop={(e) => {
|
|
217
|
+
e.preventDefault();
|
|
218
|
+
setIsDragging(false);
|
|
219
|
+
const file = e.dataTransfer.files[0];
|
|
220
|
+
if (file) handleUpload(file);
|
|
221
|
+
}}
|
|
222
|
+
className={\`border-2 border-dashed rounded-lg p-8 text-center cursor-pointer transition-colors \${
|
|
223
|
+
isDragging ? "border-primary bg-primary/5" : "border-muted-foreground/25 hover:border-primary/50"
|
|
224
|
+
}\`}
|
|
225
|
+
>
|
|
226
|
+
<input type="file" accept={accept} className="hidden" id="file-upload"
|
|
227
|
+
onChange={(e) => { const f = e.target.files?.[0]; if (f) handleUpload(f); }} />
|
|
228
|
+
<label htmlFor="file-upload" className="cursor-pointer">
|
|
229
|
+
{uploading ? "Uploading..." : "Drop a file here or click to browse"}
|
|
230
|
+
</label>
|
|
231
|
+
</div>
|
|
232
|
+
);
|
|
233
|
+
}
|
|
234
|
+
\`\`\`
|
|
235
|
+
|
|
236
|
+
### Common Pitfalls
|
|
237
|
+
1. **Always validate file type and size server-side.** Client-side validation can be bypassed.
|
|
238
|
+
2. **Sanitize filenames.** Strip special characters to avoid path traversal.
|
|
239
|
+
3. **Use unique keys.** Prefix with timestamp or UUID to avoid collisions.
|
|
240
|
+
4. **Set appropriate CORS headers** if the upload API is called from a different origin.
|
|
241
|
+
5. **For Mistflow apps, R2 bindings are auto-configured.** No env vars needed.`},{id:"openai-ai",name:"OpenAI / AI Integration",category:"ai",prompt:`## OpenAI / AI Integration
|
|
242
|
+
|
|
243
|
+
### File Structure
|
|
244
|
+
\`\`\`
|
|
245
|
+
lib/openai.ts \u2014 OpenAI client singleton
|
|
246
|
+
app/api/chat/route.ts \u2014 Streaming chat API route
|
|
247
|
+
components/chat.tsx \u2014 Chat UI component with streaming
|
|
248
|
+
\`\`\`
|
|
249
|
+
|
|
250
|
+
### Client Setup (lib/openai.ts)
|
|
251
|
+
\`\`\`typescript
|
|
252
|
+
import OpenAI from "openai";
|
|
253
|
+
|
|
254
|
+
export const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
|
|
255
|
+
\`\`\`
|
|
256
|
+
|
|
257
|
+
### Streaming Chat Route (app/api/chat/route.ts)
|
|
258
|
+
\`\`\`typescript
|
|
259
|
+
import { openai } from "@/lib/openai";
|
|
260
|
+
import { NextRequest } from "next/server";
|
|
261
|
+
|
|
262
|
+
export async function POST(req: NextRequest) {
|
|
263
|
+
const { messages, systemPrompt } = await req.json();
|
|
264
|
+
|
|
265
|
+
const stream = await openai.chat.completions.create({
|
|
266
|
+
model: "gpt-4o-mini",
|
|
267
|
+
messages: [
|
|
268
|
+
{ role: "system", content: systemPrompt || "You are a helpful assistant." },
|
|
269
|
+
...messages,
|
|
270
|
+
],
|
|
271
|
+
stream: true,
|
|
272
|
+
});
|
|
273
|
+
|
|
274
|
+
// Stream the response using ReadableStream
|
|
275
|
+
const encoder = new TextEncoder();
|
|
276
|
+
const readable = new ReadableStream({
|
|
277
|
+
async start(controller) {
|
|
278
|
+
for await (const chunk of stream) {
|
|
279
|
+
const text = chunk.choices[0]?.delta?.content || "";
|
|
280
|
+
if (text) controller.enqueue(encoder.encode(text));
|
|
281
|
+
}
|
|
282
|
+
controller.close();
|
|
283
|
+
},
|
|
284
|
+
});
|
|
285
|
+
|
|
286
|
+
return new Response(readable, {
|
|
287
|
+
headers: { "Content-Type": "text/plain; charset=utf-8" },
|
|
288
|
+
});
|
|
289
|
+
}
|
|
290
|
+
\`\`\`
|
|
291
|
+
|
|
292
|
+
### Chat UI Component (components/chat.tsx)
|
|
293
|
+
\`\`\`tsx
|
|
294
|
+
"use client";
|
|
295
|
+
import { useState, useRef, useEffect } from "react";
|
|
296
|
+
|
|
297
|
+
interface Message { role: "user" | "assistant"; content: string }
|
|
298
|
+
|
|
299
|
+
export function Chat() {
|
|
300
|
+
const [messages, setMessages] = useState<Message[]>([]);
|
|
301
|
+
const [input, setInput] = useState("");
|
|
302
|
+
const [streaming, setStreaming] = useState(false);
|
|
303
|
+
const scrollRef = useRef<HTMLDivElement>(null);
|
|
304
|
+
|
|
305
|
+
useEffect(() => {
|
|
306
|
+
scrollRef.current?.scrollIntoView({ behavior: "smooth" });
|
|
307
|
+
}, [messages]);
|
|
308
|
+
|
|
309
|
+
async function handleSend() {
|
|
310
|
+
if (!input.trim() || streaming) return;
|
|
311
|
+
const userMsg: Message = { role: "user", content: input };
|
|
312
|
+
setMessages((prev) => [...prev, userMsg]);
|
|
313
|
+
setInput("");
|
|
314
|
+
setStreaming(true);
|
|
315
|
+
|
|
316
|
+
const res = await fetch("/api/chat", {
|
|
317
|
+
method: "POST",
|
|
318
|
+
headers: { "Content-Type": "application/json" },
|
|
319
|
+
body: JSON.stringify({ messages: [...messages, userMsg] }),
|
|
320
|
+
});
|
|
321
|
+
|
|
322
|
+
const reader = res.body?.getReader();
|
|
323
|
+
const decoder = new TextDecoder();
|
|
324
|
+
let assistantContent = "";
|
|
325
|
+
|
|
326
|
+
setMessages((prev) => [...prev, { role: "assistant", content: "" }]);
|
|
327
|
+
|
|
328
|
+
while (reader) {
|
|
329
|
+
const { done, value } = await reader.read();
|
|
330
|
+
if (done) break;
|
|
331
|
+
assistantContent += decoder.decode(value);
|
|
332
|
+
setMessages((prev) => [
|
|
333
|
+
...prev.slice(0, -1),
|
|
334
|
+
{ role: "assistant", content: assistantContent },
|
|
335
|
+
]);
|
|
336
|
+
}
|
|
337
|
+
setStreaming(false);
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
return (
|
|
341
|
+
<div className="flex flex-col h-full">
|
|
342
|
+
<div className="flex-1 overflow-y-auto p-4 space-y-4">
|
|
343
|
+
{messages.map((m, i) => (
|
|
344
|
+
<div key={i} className={\`flex \${m.role === "user" ? "justify-end" : "justify-start"}\`}>
|
|
345
|
+
<div className={\`max-w-[80%] rounded-lg px-4 py-2 \${
|
|
346
|
+
m.role === "user" ? "bg-primary text-primary-foreground" : "bg-muted"
|
|
347
|
+
}\`}>
|
|
348
|
+
{m.content}
|
|
349
|
+
</div>
|
|
350
|
+
</div>
|
|
351
|
+
))}
|
|
352
|
+
<div ref={scrollRef} />
|
|
353
|
+
</div>
|
|
354
|
+
<div className="border-t p-4 flex gap-2">
|
|
355
|
+
<input value={input} onChange={(e) => setInput(e.target.value)}
|
|
356
|
+
onKeyDown={(e) => e.key === "Enter" && handleSend()}
|
|
357
|
+
placeholder="Type a message..." className="flex-1 rounded-md border px-3 py-2" />
|
|
358
|
+
<button onClick={handleSend} disabled={streaming}
|
|
359
|
+
className="rounded-md bg-primary px-4 py-2 text-primary-foreground disabled:opacity-50">
|
|
360
|
+
Send
|
|
361
|
+
</button>
|
|
362
|
+
</div>
|
|
363
|
+
</div>
|
|
364
|
+
);
|
|
365
|
+
}
|
|
366
|
+
\`\`\`
|
|
367
|
+
|
|
368
|
+
### Common Pitfalls
|
|
369
|
+
1. **Never expose OPENAI_API_KEY to the client.** Always call OpenAI from server-side API routes.
|
|
370
|
+
2. **Use gpt-4o-mini for most features** unless the user specifically asks for gpt-4o. Cost difference is 10x.
|
|
371
|
+
3. **Set max_tokens to prevent runaway costs.** Default to 1000 for chat, 2000 for content generation.
|
|
372
|
+
4. **Handle rate limits gracefully.** Return a user-friendly error, not a raw 429 response.
|
|
373
|
+
5. **Streaming is the default UX pattern.** Non-streaming feels broken for chat interfaces.
|
|
374
|
+
6. **Long streaming responses are fine on Mistflow Cloud.** Network I/O (waiting for OpenAI to generate tokens) does NOT count toward CPU time. A 2-minute streaming chat response uses only milliseconds of CPU.
|
|
375
|
+
7. **Never ask the user to paste OPENAI_API_KEY in chat.** Direct them to set it in the Mistflow dashboard (Project Settings > Environment Variables).`},{id:"anthropic-ai",name:"Anthropic / Claude",category:"ai",prompt:`## Anthropic / Claude Integration
|
|
376
|
+
|
|
377
|
+
### File Structure
|
|
378
|
+
\`\`\`
|
|
379
|
+
lib/anthropic.ts \u2014 Anthropic client singleton
|
|
380
|
+
app/api/chat/route.ts \u2014 Streaming chat API route
|
|
381
|
+
components/chat.tsx \u2014 Chat UI component with streaming
|
|
382
|
+
\`\`\`
|
|
383
|
+
|
|
384
|
+
### Client Setup (lib/anthropic.ts)
|
|
385
|
+
\`\`\`typescript
|
|
386
|
+
import Anthropic from "@anthropic-ai/sdk";
|
|
387
|
+
|
|
388
|
+
export const anthropic = new Anthropic({
|
|
389
|
+
apiKey: process.env.ANTHROPIC_API_KEY,
|
|
390
|
+
});
|
|
391
|
+
\`\`\`
|
|
392
|
+
|
|
393
|
+
### Streaming Chat Route (app/api/chat/route.ts)
|
|
394
|
+
\`\`\`typescript
|
|
395
|
+
import { anthropic } from "@/lib/anthropic";
|
|
396
|
+
import { NextRequest } from "next/server";
|
|
397
|
+
|
|
398
|
+
export async function POST(req: NextRequest) {
|
|
399
|
+
const { messages, systemPrompt } = await req.json();
|
|
400
|
+
|
|
401
|
+
const stream = anthropic.messages.stream({
|
|
402
|
+
model: "claude-sonnet-4-6",
|
|
403
|
+
max_tokens: 1024,
|
|
404
|
+
system: systemPrompt || "You are a helpful assistant.",
|
|
405
|
+
messages,
|
|
406
|
+
});
|
|
407
|
+
|
|
408
|
+
const encoder = new TextEncoder();
|
|
409
|
+
const readable = new ReadableStream({
|
|
410
|
+
async start(controller) {
|
|
411
|
+
for await (const event of stream) {
|
|
412
|
+
if (event.type === "content_block_delta" && event.delta.type === "text_delta") {
|
|
413
|
+
controller.enqueue(encoder.encode(event.delta.text));
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
controller.close();
|
|
417
|
+
},
|
|
418
|
+
});
|
|
419
|
+
|
|
420
|
+
return new Response(readable, {
|
|
421
|
+
headers: { "Content-Type": "text/plain; charset=utf-8" },
|
|
422
|
+
});
|
|
423
|
+
}
|
|
424
|
+
\`\`\`
|
|
425
|
+
|
|
426
|
+
### Chat UI Component (components/chat.tsx)
|
|
427
|
+
Use the same chat component pattern as the OpenAI integration. The client-side code is identical since both stream plain text. Only the API route differs.
|
|
428
|
+
|
|
429
|
+
### Common Pitfalls
|
|
430
|
+
1. **Never expose ANTHROPIC_API_KEY to the client.** Always call Anthropic from server-side API routes.
|
|
431
|
+
2. **Use claude-sonnet-4-6 for most features.** Use claude-haiku-4-5 for high-volume, cost-sensitive tasks. Claude opus is for complex reasoning.
|
|
432
|
+
3. **Anthropic uses a different message format than OpenAI.** Role is "user" or "assistant" (no "system" role in messages). System prompt is a separate top-level field.
|
|
433
|
+
4. **Set max_tokens explicitly.** Unlike OpenAI, Anthropic requires max_tokens on every request.
|
|
434
|
+
5. **Streaming is the default UX pattern.** Use \`anthropic.messages.stream()\` not \`anthropic.messages.create()\` for chat.
|
|
435
|
+
6. **Long streaming responses are fine on Mistflow Cloud.** Network I/O does NOT count toward CPU time.
|
|
436
|
+
7. **Never ask the user to paste ANTHROPIC_API_KEY in chat.** Direct them to set it in the Mistflow dashboard (Project Settings > Environment Variables).`},{id:"openrouter-ai",name:"OpenRouter",category:"ai",prompt:`## OpenRouter Integration
|
|
437
|
+
|
|
438
|
+
OpenRouter provides a single API for 200+ AI models (GPT-4o, Claude, Llama, Mistral, Gemini, etc.). It uses an OpenAI-compatible API, so you use the standard OpenAI SDK with a different base URL and API key.
|
|
439
|
+
|
|
440
|
+
### File Structure
|
|
441
|
+
\`\`\`
|
|
442
|
+
lib/openrouter.ts \u2014 OpenRouter client
|
|
443
|
+
app/api/chat/route.ts \u2014 Streaming chat API route
|
|
444
|
+
components/chat.tsx \u2014 Chat UI component with streaming
|
|
445
|
+
components/model-selector.tsx \u2014 Model picker dropdown
|
|
446
|
+
\`\`\`
|
|
447
|
+
|
|
448
|
+
### Client Setup (lib/openrouter.ts)
|
|
449
|
+
\`\`\`typescript
|
|
450
|
+
import { OpenRouter } from "@openrouter/sdk";
|
|
451
|
+
|
|
452
|
+
export const openrouter = new OpenRouter({
|
|
453
|
+
apiKey: process.env.OPENROUTER_API_KEY,
|
|
454
|
+
});
|
|
455
|
+
|
|
456
|
+
// Popular models \u2014 use these as defaults or in a model selector
|
|
457
|
+
export const MODELS = {
|
|
458
|
+
fast: "meta-llama/llama-3.1-8b-instruct",
|
|
459
|
+
balanced: "anthropic/claude-sonnet-4-6",
|
|
460
|
+
powerful: "openai/gpt-4o",
|
|
461
|
+
cheap: "meta-llama/llama-3.1-8b-instruct",
|
|
462
|
+
} as const;
|
|
463
|
+
\`\`\`
|
|
464
|
+
|
|
465
|
+
### Streaming Chat Route (app/api/chat/route.ts)
|
|
466
|
+
\`\`\`typescript
|
|
467
|
+
import { openrouter, MODELS } from "@/lib/openrouter";
|
|
468
|
+
import { NextRequest } from "next/server";
|
|
469
|
+
|
|
470
|
+
export async function POST(req: NextRequest) {
|
|
471
|
+
const { messages, systemPrompt, model } = await req.json();
|
|
472
|
+
|
|
473
|
+
const completion = await openrouter.chat.send({
|
|
474
|
+
model: model || MODELS.balanced,
|
|
475
|
+
messages: [
|
|
476
|
+
{ role: "system", content: systemPrompt || "You are a helpful assistant." },
|
|
477
|
+
...messages,
|
|
478
|
+
],
|
|
479
|
+
stream: true,
|
|
480
|
+
});
|
|
481
|
+
|
|
482
|
+
const encoder = new TextEncoder();
|
|
483
|
+
const readable = new ReadableStream({
|
|
484
|
+
async start(controller) {
|
|
485
|
+
for await (const chunk of completion) {
|
|
486
|
+
const text = chunk.choices?.[0]?.delta?.content || "";
|
|
487
|
+
if (text) controller.enqueue(encoder.encode(text));
|
|
488
|
+
}
|
|
489
|
+
controller.close();
|
|
490
|
+
},
|
|
491
|
+
});
|
|
492
|
+
|
|
493
|
+
return new Response(readable, {
|
|
494
|
+
headers: { "Content-Type": "text/plain; charset=utf-8" },
|
|
495
|
+
});
|
|
496
|
+
}
|
|
497
|
+
\`\`\`
|
|
498
|
+
|
|
499
|
+
### Model Selector Component (components/model-selector.tsx)
|
|
500
|
+
\`\`\`tsx
|
|
501
|
+
"use client";
|
|
502
|
+
|
|
503
|
+
const MODELS = [
|
|
504
|
+
{ id: "anthropic/claude-sonnet-4-6", label: "Claude Sonnet", tier: "Balanced" },
|
|
505
|
+
{ id: "openai/gpt-4o", label: "GPT-4o", tier: "Powerful" },
|
|
506
|
+
{ id: "openai/gpt-4o-mini", label: "GPT-4o Mini", tier: "Fast" },
|
|
507
|
+
{ id: "meta-llama/llama-3.1-70b-instruct", label: "Llama 3.1 70B", tier: "Open Source" },
|
|
508
|
+
{ id: "google/gemini-2.0-flash-001", label: "Gemini 2.0 Flash", tier: "Fast" },
|
|
509
|
+
];
|
|
510
|
+
|
|
511
|
+
interface ModelSelectorProps {
|
|
512
|
+
value: string;
|
|
513
|
+
onChange: (model: string) => void;
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
export function ModelSelector({ value, onChange }: ModelSelectorProps) {
|
|
517
|
+
return (
|
|
518
|
+
<select
|
|
519
|
+
value={value}
|
|
520
|
+
onChange={(e) => onChange(e.target.value)}
|
|
521
|
+
className="rounded-md border px-2 py-1 text-sm"
|
|
522
|
+
>
|
|
523
|
+
{MODELS.map((m) => (
|
|
524
|
+
<option key={m.id} value={m.id}>
|
|
525
|
+
{m.label} ({m.tier})
|
|
526
|
+
</option>
|
|
527
|
+
))}
|
|
528
|
+
</select>
|
|
529
|
+
);
|
|
530
|
+
}
|
|
531
|
+
\`\`\`
|
|
532
|
+
|
|
533
|
+
### Common Pitfalls
|
|
534
|
+
1. **Never expose OPENROUTER_API_KEY to the client.** Always call OpenRouter from server-side API routes.
|
|
535
|
+
2. **Model IDs use provider/model format.** E.g. "anthropic/claude-sonnet-4-6", not just "claude-sonnet".
|
|
536
|
+
3. **Use the \`@openrouter/sdk\` package.** It wraps the OpenRouter API with proper types and streaming support.
|
|
537
|
+
4. **Set max_tokens explicitly** for Anthropic models routed through OpenRouter. OpenAI models have defaults, Anthropic models don't.
|
|
538
|
+
5. **Check model pricing at openrouter.ai/models.** Costs vary 100x between models. Show users which model they're using.
|
|
539
|
+
6. **Long streaming responses are fine on Mistflow Cloud.** Network I/O does NOT count toward CPU time.
|
|
540
|
+
7. **Never ask the user to paste OPENROUTER_API_KEY in chat.** Direct them to set it in the Mistflow dashboard (Project Settings > Environment Variables).`},{id:"stripe-payments",name:"Stripe Payments",category:"payments",prompt:`## Stripe Payments Integration
|
|
541
|
+
|
|
542
|
+
### File Structure
|
|
543
|
+
\`\`\`
|
|
544
|
+
lib/stripe.ts \u2014 Stripe server client
|
|
545
|
+
db/schema/subscriptions.ts \u2014 Subscription-related DB schema
|
|
546
|
+
app/api/webhooks/stripe/route.ts \u2014 Webhook handler (critical path)
|
|
547
|
+
app/api/checkout/route.ts \u2014 Create Checkout Session
|
|
548
|
+
app/api/billing-portal/route.ts \u2014 Create Billing Portal session
|
|
549
|
+
app/(dashboard)/pricing/page.tsx \u2014 Pricing page
|
|
550
|
+
app/(dashboard)/billing/page.tsx \u2014 Billing/subscription management
|
|
551
|
+
\`\`\`
|
|
552
|
+
|
|
553
|
+
### Server Client (lib/stripe.ts)
|
|
554
|
+
\`\`\`typescript
|
|
555
|
+
import Stripe from "stripe";
|
|
556
|
+
|
|
557
|
+
export const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
|
|
558
|
+
\`\`\`
|
|
559
|
+
|
|
560
|
+
### Webhook Handler (app/api/webhooks/stripe/route.ts)
|
|
561
|
+
This is the most critical file. All subscription state changes flow through here.
|
|
562
|
+
\`\`\`typescript
|
|
563
|
+
import { NextRequest, NextResponse } from "next/server";
|
|
564
|
+
import { stripe } from "@/lib/stripe";
|
|
565
|
+
import { headers } from "next/headers";
|
|
566
|
+
|
|
567
|
+
export async function POST(req: NextRequest) {
|
|
568
|
+
const body = await req.text();
|
|
569
|
+
const headersList = await headers();
|
|
570
|
+
const signature = headersList.get("stripe-signature")!;
|
|
571
|
+
|
|
572
|
+
let event: Stripe.Event;
|
|
573
|
+
try {
|
|
574
|
+
event = stripe.webhooks.constructEvent(body, signature, process.env.STRIPE_WEBHOOK_SECRET!);
|
|
575
|
+
} catch (err) {
|
|
576
|
+
return NextResponse.json({ error: "Invalid signature" }, { status: 400 });
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
switch (event.type) {
|
|
580
|
+
case "checkout.session.completed": {
|
|
581
|
+
const session = event.data.object as Stripe.Checkout.Session;
|
|
582
|
+
// Create/update subscription record in DB
|
|
583
|
+
// Link session.customer to your user via session.metadata.userId
|
|
584
|
+
break;
|
|
585
|
+
}
|
|
586
|
+
case "customer.subscription.updated":
|
|
587
|
+
case "customer.subscription.deleted": {
|
|
588
|
+
const sub = event.data.object as Stripe.Subscription;
|
|
589
|
+
// Update subscription status in DB (active, canceled, past_due)
|
|
590
|
+
break;
|
|
591
|
+
}
|
|
592
|
+
case "invoice.payment_failed": {
|
|
593
|
+
// Notify user about failed payment
|
|
594
|
+
break;
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
return NextResponse.json({ received: true });
|
|
599
|
+
}
|
|
600
|
+
\`\`\`
|
|
601
|
+
|
|
602
|
+
### Checkout Route (app/api/checkout/route.ts)
|
|
603
|
+
\`\`\`typescript
|
|
604
|
+
import { stripe } from "@/lib/stripe";
|
|
605
|
+
import { NextRequest, NextResponse } from "next/server";
|
|
606
|
+
|
|
607
|
+
export async function POST(req: NextRequest) {
|
|
608
|
+
const { priceId, userId } = await req.json();
|
|
609
|
+
|
|
610
|
+
const session = await stripe.checkout.sessions.create({
|
|
611
|
+
mode: "subscription",
|
|
612
|
+
payment_method_types: ["card"],
|
|
613
|
+
line_items: [{ price: priceId, quantity: 1 }],
|
|
614
|
+
success_url: \`\${process.env.NEXT_PUBLIC_APP_URL}/billing?success=true\`,
|
|
615
|
+
cancel_url: \`\${process.env.NEXT_PUBLIC_APP_URL}/pricing\`,
|
|
616
|
+
metadata: { userId },
|
|
617
|
+
});
|
|
618
|
+
|
|
619
|
+
return NextResponse.json({ url: session.url });
|
|
620
|
+
}
|
|
621
|
+
\`\`\`
|
|
622
|
+
|
|
623
|
+
### Common Pitfalls
|
|
624
|
+
1. **Webhook handler must use raw body (req.text(), not req.json())** for signature verification.
|
|
625
|
+
2. **Always verify webhook signatures.** Never trust unverified payloads.
|
|
626
|
+
3. **Idempotency: webhooks can fire multiple times.** Use event.id to deduplicate.
|
|
627
|
+
4. **Store the Stripe customer ID in your user table.** Look up by metadata.userId in webhooks.
|
|
628
|
+
5. **Test with Stripe CLI locally:** \`stripe listen --forward-to localhost:3000/api/webhooks/stripe\`
|
|
629
|
+
6. **Price IDs come from Stripe Dashboard.** Do not hardcode amounts. Create Products + Prices in the dashboard and reference price IDs.
|
|
630
|
+
7. **Billing portal for self-service.** Use stripe.billingPortal.sessions.create() so users can manage their own subscriptions.
|
|
631
|
+
8. **Never ask the user to paste Stripe keys in chat.** Direct them to set STRIPE_SECRET_KEY, STRIPE_PUBLISHABLE_KEY, and STRIPE_WEBHOOK_SECRET in the Mistflow dashboard (Project Settings > Environment Variables).`},{id:"elevenlabs-voice",name:"ElevenLabs Voice",category:"media",prompt:`## ElevenLabs Voice Integration
|
|
632
|
+
|
|
633
|
+
### File Structure
|
|
634
|
+
\`\`\`
|
|
635
|
+
lib/elevenlabs.ts \u2014 ElevenLabs client + helpers
|
|
636
|
+
app/api/tts/route.ts \u2014 Text-to-speech API route (streaming)
|
|
637
|
+
app/api/voices/route.ts \u2014 List available voices
|
|
638
|
+
components/voice-player.tsx \u2014 Audio player with playback controls
|
|
639
|
+
components/voice-selector.tsx \u2014 Voice picker dropdown
|
|
640
|
+
\`\`\`
|
|
641
|
+
|
|
642
|
+
### Client Setup (lib/elevenlabs.ts)
|
|
643
|
+
\`\`\`typescript
|
|
644
|
+
import { ElevenLabsClient } from "elevenlabs";
|
|
645
|
+
|
|
646
|
+
export const elevenlabs = new ElevenLabsClient({
|
|
647
|
+
apiKey: process.env.ELEVENLABS_API_KEY,
|
|
648
|
+
});
|
|
649
|
+
|
|
650
|
+
// Default voice ID \u2014 "Rachel" is a good general-purpose voice
|
|
651
|
+
export const DEFAULT_VOICE_ID = "21m00Tcm4TlvDq8ikWAM";
|
|
652
|
+
\`\`\`
|
|
653
|
+
|
|
654
|
+
### Text-to-Speech Route (app/api/tts/route.ts)
|
|
655
|
+
\`\`\`typescript
|
|
656
|
+
import { elevenlabs, DEFAULT_VOICE_ID } from "@/lib/elevenlabs";
|
|
657
|
+
import { NextRequest, NextResponse } from "next/server";
|
|
658
|
+
|
|
659
|
+
export async function POST(req: NextRequest) {
|
|
660
|
+
const { text, voiceId } = await req.json();
|
|
661
|
+
|
|
662
|
+
if (!text || text.length > 5000) {
|
|
663
|
+
return NextResponse.json({ error: "Text is required (max 5000 chars)" }, { status: 400 });
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
const audioStream = await elevenlabs.textToSpeech.stream(
|
|
667
|
+
voiceId || DEFAULT_VOICE_ID,
|
|
668
|
+
{
|
|
669
|
+
text,
|
|
670
|
+
modelId: "eleven_multilingual_v2",
|
|
671
|
+
}
|
|
672
|
+
);
|
|
673
|
+
|
|
674
|
+
// Pipe the ElevenLabs stream directly to the client response.
|
|
675
|
+
// Network wait (ElevenLabs generating audio) does NOT count as CPU time
|
|
676
|
+
// on Mistflow Cloud, so even long text is fine.
|
|
677
|
+
const readable = new ReadableStream({
|
|
678
|
+
async start(controller) {
|
|
679
|
+
for await (const chunk of audioStream) {
|
|
680
|
+
controller.enqueue(new Uint8Array(chunk));
|
|
681
|
+
}
|
|
682
|
+
controller.close();
|
|
683
|
+
},
|
|
684
|
+
});
|
|
685
|
+
|
|
686
|
+
return new NextResponse(readable, {
|
|
687
|
+
headers: {
|
|
688
|
+
"Content-Type": "audio/mpeg",
|
|
689
|
+
"Transfer-Encoding": "chunked",
|
|
690
|
+
},
|
|
691
|
+
});
|
|
692
|
+
}
|
|
693
|
+
\`\`\`
|
|
694
|
+
|
|
695
|
+
### Voice Player Component (components/voice-player.tsx)
|
|
696
|
+
\`\`\`tsx
|
|
697
|
+
"use client";
|
|
698
|
+
import { useState, useRef } from "react";
|
|
699
|
+
|
|
700
|
+
interface VoicePlayerProps {
|
|
701
|
+
text: string;
|
|
702
|
+
voiceId?: string;
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
export function VoicePlayer({ text, voiceId }: VoicePlayerProps) {
|
|
706
|
+
const [loading, setLoading] = useState(false);
|
|
707
|
+
const [playing, setPlaying] = useState(false);
|
|
708
|
+
const audioRef = useRef<HTMLAudioElement | null>(null);
|
|
709
|
+
|
|
710
|
+
async function handlePlay() {
|
|
711
|
+
if (playing && audioRef.current) {
|
|
712
|
+
audioRef.current.pause();
|
|
713
|
+
setPlaying(false);
|
|
714
|
+
return;
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
setLoading(true);
|
|
718
|
+
try {
|
|
719
|
+
const res = await fetch("/api/tts", {
|
|
720
|
+
method: "POST",
|
|
721
|
+
headers: { "Content-Type": "application/json" },
|
|
722
|
+
body: JSON.stringify({ text, voiceId }),
|
|
723
|
+
});
|
|
724
|
+
const blob = await res.blob();
|
|
725
|
+
const url = URL.createObjectURL(blob);
|
|
726
|
+
const audio = new Audio(url);
|
|
727
|
+
audioRef.current = audio;
|
|
728
|
+
audio.onended = () => setPlaying(false);
|
|
729
|
+
audio.play();
|
|
730
|
+
setPlaying(true);
|
|
731
|
+
} finally {
|
|
732
|
+
setLoading(false);
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
return (
|
|
737
|
+
<button onClick={handlePlay} disabled={loading}
|
|
738
|
+
className="inline-flex items-center gap-2 rounded-md bg-primary px-3 py-1.5 text-sm text-primary-foreground disabled:opacity-50">
|
|
739
|
+
{loading ? "Generating..." : playing ? "Pause" : "Listen"}
|
|
740
|
+
</button>
|
|
741
|
+
);
|
|
742
|
+
}
|
|
743
|
+
\`\`\`
|
|
744
|
+
|
|
745
|
+
### Voice Listing Route (app/api/voices/route.ts)
|
|
746
|
+
\`\`\`typescript
|
|
747
|
+
import { elevenlabs } from "@/lib/elevenlabs";
|
|
748
|
+
import { NextResponse } from "next/server";
|
|
749
|
+
|
|
750
|
+
export async function GET() {
|
|
751
|
+
const voices = await elevenlabs.voices.getAll();
|
|
752
|
+
return NextResponse.json(
|
|
753
|
+
voices.voices.map((v) => ({ id: v.voice_id, name: v.name, category: v.category }))
|
|
754
|
+
);
|
|
755
|
+
}
|
|
756
|
+
\`\`\`
|
|
757
|
+
|
|
758
|
+
### Common Pitfalls
|
|
759
|
+
1. **Never expose ELEVENLABS_API_KEY to the client.** All TTS calls go through your API route.
|
|
760
|
+
2. **Character limits matter for cost.** ElevenLabs charges per character. Show character count in UI and enforce limits.
|
|
761
|
+
3. **Use eleven_multilingual_v2 model** for best quality across languages. Use eleven_flash_v2_5 for ultra-low latency.
|
|
762
|
+
4. **Cache generated audio** when the same text + voice combination is requested multiple times. Store in Mistflow Cloud storage or local cache.
|
|
763
|
+
5. **Voice cloning requires explicit user consent.** If building a voice cloning feature, add consent UI.
|
|
764
|
+
6. **Free tier: 10,000 characters/month.** Display remaining quota to users to avoid surprise failures.
|
|
765
|
+
7. **Long text is fine on Mistflow Cloud.** Network I/O (waiting for ElevenLabs to generate audio) does NOT count toward CPU time. Stream the response directly to the client for instant playback start.
|
|
766
|
+
8. **Never ask the user to paste ELEVENLABS_API_KEY in chat.** Direct them to set it in the Mistflow dashboard (Project Settings > Environment Variables).`},{id:"google-maps",name:"Google Maps",category:"location",prompt:`## Google Maps Integration
|
|
767
|
+
|
|
768
|
+
### File Structure
|
|
769
|
+
\`\`\`
|
|
770
|
+
lib/maps.ts \u2014 Maps loader + helper functions
|
|
771
|
+
components/map.tsx \u2014 Map embed component
|
|
772
|
+
components/places-autocomplete.tsx \u2014 Address search with autocomplete
|
|
773
|
+
\`\`\`
|
|
774
|
+
|
|
775
|
+
### Map Component (components/map.tsx)
|
|
776
|
+
\`\`\`tsx
|
|
777
|
+
"use client";
|
|
778
|
+
import { useEffect, useRef, useState } from "react";
|
|
779
|
+
import { Loader } from "@googlemaps/js-api-loader";
|
|
780
|
+
|
|
781
|
+
interface MapProps {
|
|
782
|
+
center?: { lat: number; lng: number };
|
|
783
|
+
zoom?: number;
|
|
784
|
+
markers?: { lat: number; lng: number; title?: string }[];
|
|
785
|
+
className?: string;
|
|
786
|
+
onMarkerClick?: (marker: { lat: number; lng: number }) => void;
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
export function Map({ center = { lat: 40.7128, lng: -74.006 }, zoom = 12, markers = [], className, onMarkerClick }: MapProps) {
|
|
790
|
+
const mapRef = useRef<HTMLDivElement>(null);
|
|
791
|
+
const [map, setMap] = useState<google.maps.Map | null>(null);
|
|
792
|
+
|
|
793
|
+
useEffect(() => {
|
|
794
|
+
const loader = new Loader({
|
|
795
|
+
apiKey: process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY!,
|
|
796
|
+
version: "weekly",
|
|
797
|
+
libraries: ["places"],
|
|
798
|
+
});
|
|
799
|
+
|
|
800
|
+
loader.load().then(() => {
|
|
801
|
+
if (!mapRef.current) return;
|
|
802
|
+
const m = new google.maps.Map(mapRef.current, { center, zoom, mapId: "DEMO_MAP_ID" });
|
|
803
|
+
setMap(m);
|
|
804
|
+
|
|
805
|
+
for (const marker of markers) {
|
|
806
|
+
const m2 = new google.maps.marker.AdvancedMarkerElement({
|
|
807
|
+
map: m, position: marker, title: marker.title,
|
|
808
|
+
});
|
|
809
|
+
if (onMarkerClick) {
|
|
810
|
+
m2.addListener("click", () => onMarkerClick(marker));
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
});
|
|
814
|
+
}, []);
|
|
815
|
+
|
|
816
|
+
return <div ref={mapRef} className={className ?? "w-full h-[400px] rounded-lg"} />;
|
|
817
|
+
}
|
|
818
|
+
\`\`\`
|
|
819
|
+
|
|
820
|
+
### Places Autocomplete (components/places-autocomplete.tsx)
|
|
821
|
+
\`\`\`tsx
|
|
822
|
+
"use client";
|
|
823
|
+
import { useEffect, useRef, useState } from "react";
|
|
824
|
+
import { Loader } from "@googlemaps/js-api-loader";
|
|
825
|
+
|
|
826
|
+
interface PlacesAutocompleteProps {
|
|
827
|
+
onSelect: (place: { address: string; lat: number; lng: number }) => void;
|
|
828
|
+
placeholder?: string;
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
export function PlacesAutocomplete({ onSelect, placeholder = "Search for an address..." }: PlacesAutocompleteProps) {
|
|
832
|
+
const inputRef = useRef<HTMLInputElement>(null);
|
|
833
|
+
|
|
834
|
+
useEffect(() => {
|
|
835
|
+
const loader = new Loader({
|
|
836
|
+
apiKey: process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY!,
|
|
837
|
+
version: "weekly",
|
|
838
|
+
libraries: ["places"],
|
|
839
|
+
});
|
|
840
|
+
|
|
841
|
+
loader.load().then(() => {
|
|
842
|
+
if (!inputRef.current) return;
|
|
843
|
+
const autocomplete = new google.maps.places.Autocomplete(inputRef.current, {
|
|
844
|
+
fields: ["formatted_address", "geometry"],
|
|
845
|
+
});
|
|
846
|
+
autocomplete.addListener("place_changed", () => {
|
|
847
|
+
const place = autocomplete.getPlace();
|
|
848
|
+
if (place.geometry?.location) {
|
|
849
|
+
onSelect({
|
|
850
|
+
address: place.formatted_address ?? "",
|
|
851
|
+
lat: place.geometry.location.lat(),
|
|
852
|
+
lng: place.geometry.location.lng(),
|
|
853
|
+
});
|
|
854
|
+
}
|
|
855
|
+
});
|
|
856
|
+
});
|
|
857
|
+
}, [onSelect]);
|
|
858
|
+
|
|
859
|
+
return <input ref={inputRef} placeholder={placeholder}
|
|
860
|
+
className="w-full rounded-md border px-3 py-2" />;
|
|
861
|
+
}
|
|
862
|
+
\`\`\`
|
|
863
|
+
|
|
864
|
+
### Common Pitfalls
|
|
865
|
+
1. **API key must be restricted in Google Cloud Console.** Restrict to your domain and specific APIs (Maps JS, Places).
|
|
866
|
+
2. **Use NEXT_PUBLIC_ prefix** so the key is available client-side. This is expected for Maps JS API.
|
|
867
|
+
3. **Enable the Maps JavaScript API AND Places API** in Google Cloud Console. Both are separate.
|
|
868
|
+
4. **AdvancedMarkerElement requires a mapId.** Create one in Cloud Console or use "DEMO_MAP_ID" for development.
|
|
869
|
+
5. **Billing is required.** Google Maps gives $200/month free credit (~28,000 map loads). Add billing alerts.
|
|
870
|
+
6. **Never ask the user to paste NEXT_PUBLIC_GOOGLE_MAPS_API_KEY in chat.** Direct them to set it in the Mistflow dashboard (Project Settings > Environment Variables).`},{id:"twilio-sms",name:"Twilio SMS",category:"communication",prompt:`## Twilio SMS Integration
|
|
871
|
+
|
|
872
|
+
### File Structure
|
|
873
|
+
\`\`\`
|
|
874
|
+
lib/twilio.ts \u2014 Twilio client singleton
|
|
875
|
+
lib/sms.ts \u2014 Send helper functions
|
|
876
|
+
app/api/sms/send/route.ts \u2014 Send SMS API route
|
|
877
|
+
app/api/webhooks/twilio/route.ts \u2014 Incoming SMS + delivery webhooks
|
|
878
|
+
\`\`\`
|
|
879
|
+
|
|
880
|
+
### Client Setup (lib/twilio.ts)
|
|
881
|
+
\`\`\`typescript
|
|
882
|
+
import twilio from "twilio";
|
|
883
|
+
|
|
884
|
+
export const twilioClient = twilio(
|
|
885
|
+
process.env.TWILIO_ACCOUNT_SID,
|
|
886
|
+
process.env.TWILIO_AUTH_TOKEN
|
|
887
|
+
);
|
|
888
|
+
\`\`\`
|
|
889
|
+
|
|
890
|
+
### Send Helpers (lib/sms.ts)
|
|
891
|
+
\`\`\`typescript
|
|
892
|
+
import { twilioClient } from "./twilio";
|
|
893
|
+
|
|
894
|
+
export async function sendSMS(to: string, body: string) {
|
|
895
|
+
return twilioClient.messages.create({
|
|
896
|
+
to,
|
|
897
|
+
from: process.env.TWILIO_PHONE_NUMBER,
|
|
898
|
+
body,
|
|
899
|
+
});
|
|
900
|
+
}
|
|
901
|
+
|
|
902
|
+
export async function sendOTP(to: string, code: string) {
|
|
903
|
+
return sendSMS(to, \`Your verification code is: \${code}. It expires in 10 minutes.\`);
|
|
904
|
+
}
|
|
905
|
+
\`\`\`
|
|
906
|
+
|
|
907
|
+
### Send Route (app/api/sms/send/route.ts)
|
|
908
|
+
\`\`\`typescript
|
|
909
|
+
import { sendSMS } from "@/lib/sms";
|
|
910
|
+
import { NextRequest, NextResponse } from "next/server";
|
|
911
|
+
|
|
912
|
+
export async function POST(req: NextRequest) {
|
|
913
|
+
const { to, message } = await req.json();
|
|
914
|
+
|
|
915
|
+
// Validate phone number format (E.164)
|
|
916
|
+
if (!/^\\+[1-9]\\d{1,14}$/.test(to)) {
|
|
917
|
+
return NextResponse.json({ error: "Invalid phone number. Use E.164 format (+1234567890)" }, { status: 400 });
|
|
918
|
+
}
|
|
919
|
+
|
|
920
|
+
const result = await sendSMS(to, message);
|
|
921
|
+
return NextResponse.json({ sid: result.sid, status: result.status });
|
|
922
|
+
}
|
|
923
|
+
\`\`\`
|
|
924
|
+
|
|
925
|
+
### Webhook Handler (app/api/webhooks/twilio/route.ts)
|
|
926
|
+
\`\`\`typescript
|
|
927
|
+
import { NextRequest, NextResponse } from "next/server";
|
|
928
|
+
|
|
929
|
+
export async function POST(req: NextRequest) {
|
|
930
|
+
const formData = await req.formData();
|
|
931
|
+
const from = formData.get("From") as string;
|
|
932
|
+
const body = formData.get("Body") as string;
|
|
933
|
+
const status = formData.get("MessageStatus") as string;
|
|
934
|
+
|
|
935
|
+
if (body) {
|
|
936
|
+
// Incoming SMS \u2014 handle auto-replies, keyword routing, etc.
|
|
937
|
+
console.log(\`SMS from \${from}: \${body}\`);
|
|
938
|
+
} else if (status) {
|
|
939
|
+
// Delivery status update \u2014 delivered, failed, undelivered
|
|
940
|
+
console.log(\`Message status: \${status}\`);
|
|
941
|
+
}
|
|
942
|
+
|
|
943
|
+
// Return TwiML response (empty = no auto-reply)
|
|
944
|
+
return new NextResponse('<?xml version="1.0" encoding="UTF-8"?><Response></Response>', {
|
|
945
|
+
headers: { "Content-Type": "text/xml" },
|
|
946
|
+
});
|
|
947
|
+
}
|
|
948
|
+
\`\`\`
|
|
949
|
+
|
|
950
|
+
### Common Pitfalls
|
|
951
|
+
1. **Phone numbers must be in E.164 format** (+1234567890). Validate before sending.
|
|
952
|
+
2. **Trial accounts can only send to verified numbers.** Upgrade for production use.
|
|
953
|
+
3. **Twilio webhook validation.** Use twilio.webhook() middleware to verify webhook signatures in production.
|
|
954
|
+
4. **SMS rate limits vary by country.** US: 1 SMS/second per number. Use Messaging Services for higher throughput.
|
|
955
|
+
5. **Never log full phone numbers.** Mask them in logs (e.g., +1***567890).
|
|
956
|
+
6. **Never ask the user to paste Twilio credentials in chat.** Direct them to set TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN, and TWILIO_PHONE_NUMBER in the Mistflow dashboard (Project Settings > Environment Variables).`},{id:"posthog-analytics",name:"PostHog Analytics",category:"analytics",prompt:`## PostHog Analytics Integration
|
|
957
|
+
|
|
958
|
+
### File Structure
|
|
959
|
+
\`\`\`
|
|
960
|
+
lib/posthog.ts \u2014 PostHog provider setup
|
|
961
|
+
app/providers.tsx \u2014 Client-side providers wrapper
|
|
962
|
+
components/posthog-pageview.tsx \u2014 Page view tracker component
|
|
963
|
+
lib/posthog-server.ts \u2014 Server-side PostHog client
|
|
964
|
+
\`\`\`
|
|
965
|
+
|
|
966
|
+
### Client Provider (lib/posthog.ts)
|
|
967
|
+
\`\`\`typescript
|
|
968
|
+
"use client";
|
|
969
|
+
import posthog from "posthog-js";
|
|
970
|
+
import { PostHogProvider as PHProvider } from "posthog-js/react";
|
|
971
|
+
import { useEffect } from "react";
|
|
972
|
+
|
|
973
|
+
export function PostHogProvider({ children }: { children: React.ReactNode }) {
|
|
974
|
+
useEffect(() => {
|
|
975
|
+
posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY!, {
|
|
976
|
+
api_host: process.env.NEXT_PUBLIC_POSTHOG_HOST || "https://us.i.posthog.com",
|
|
977
|
+
person_profiles: "identified_only",
|
|
978
|
+
capture_pageview: false, // We handle this manually for Next.js
|
|
979
|
+
});
|
|
980
|
+
}, []);
|
|
981
|
+
|
|
982
|
+
return <PHProvider client={posthog}>{children}</PHProvider>;
|
|
983
|
+
}
|
|
984
|
+
\`\`\`
|
|
985
|
+
|
|
986
|
+
### Page View Tracker (components/posthog-pageview.tsx)
|
|
987
|
+
\`\`\`tsx
|
|
988
|
+
"use client";
|
|
989
|
+
import { usePathname, useSearchParams } from "next/navigation";
|
|
990
|
+
import { useEffect } from "react";
|
|
991
|
+
import { usePostHog } from "posthog-js/react";
|
|
992
|
+
|
|
993
|
+
export function PostHogPageview() {
|
|
994
|
+
const pathname = usePathname();
|
|
995
|
+
const searchParams = useSearchParams();
|
|
996
|
+
const posthog = usePostHog();
|
|
997
|
+
|
|
998
|
+
useEffect(() => {
|
|
999
|
+
if (pathname && posthog) {
|
|
1000
|
+
let url = window.origin + pathname;
|
|
1001
|
+
if (searchParams.toString()) url += "?" + searchParams.toString();
|
|
1002
|
+
posthog.capture("$pageview", { "$current_url": url });
|
|
1003
|
+
}
|
|
1004
|
+
}, [pathname, searchParams, posthog]);
|
|
1005
|
+
|
|
1006
|
+
return null;
|
|
1007
|
+
}
|
|
1008
|
+
\`\`\`
|
|
1009
|
+
|
|
1010
|
+
### App Providers (app/providers.tsx)
|
|
1011
|
+
\`\`\`tsx
|
|
1012
|
+
"use client";
|
|
1013
|
+
import { PostHogProvider } from "@/lib/posthog";
|
|
1014
|
+
import { PostHogPageview } from "@/components/posthog-pageview";
|
|
1015
|
+
import { Suspense } from "react";
|
|
1016
|
+
|
|
1017
|
+
export function Providers({ children }: { children: React.ReactNode }) {
|
|
1018
|
+
return (
|
|
1019
|
+
<PostHogProvider>
|
|
1020
|
+
<Suspense fallback={null}>
|
|
1021
|
+
<PostHogPageview />
|
|
1022
|
+
</Suspense>
|
|
1023
|
+
{children}
|
|
1024
|
+
</PostHogProvider>
|
|
1025
|
+
);
|
|
1026
|
+
}
|
|
1027
|
+
\`\`\`
|
|
1028
|
+
|
|
1029
|
+
### Server-side Client (lib/posthog-server.ts)
|
|
1030
|
+
\`\`\`typescript
|
|
1031
|
+
import { PostHog } from "posthog-node";
|
|
1032
|
+
|
|
1033
|
+
export const posthogServer = new PostHog(process.env.NEXT_PUBLIC_POSTHOG_KEY!, {
|
|
1034
|
+
host: process.env.NEXT_PUBLIC_POSTHOG_HOST || "https://us.i.posthog.com",
|
|
1035
|
+
});
|
|
1036
|
+
|
|
1037
|
+
// Identify user after auth
|
|
1038
|
+
export function identifyUser(userId: string, properties?: Record<string, unknown>) {
|
|
1039
|
+
posthogServer.identify({ distinctId: userId, properties });
|
|
1040
|
+
}
|
|
1041
|
+
|
|
1042
|
+
// Track server-side events
|
|
1043
|
+
export function trackEvent(userId: string, event: string, properties?: Record<string, unknown>) {
|
|
1044
|
+
posthogServer.capture({ distinctId: userId, event, properties });
|
|
1045
|
+
}
|
|
1046
|
+
\`\`\`
|
|
1047
|
+
|
|
1048
|
+
### Feature Flags Usage
|
|
1049
|
+
\`\`\`tsx
|
|
1050
|
+
"use client";
|
|
1051
|
+
import { useFeatureFlagEnabled } from "posthog-js/react";
|
|
1052
|
+
|
|
1053
|
+
export function NewFeature() {
|
|
1054
|
+
const isEnabled = useFeatureFlagEnabled("new-dashboard");
|
|
1055
|
+
if (!isEnabled) return null;
|
|
1056
|
+
return <div>New Dashboard Feature</div>;
|
|
1057
|
+
}
|
|
1058
|
+
\`\`\`
|
|
1059
|
+
|
|
1060
|
+
### Common Pitfalls
|
|
1061
|
+
1. **Wrap PostHogPageview in Suspense.** useSearchParams() requires a Suspense boundary in Next.js App Router.
|
|
1062
|
+
2. **Set capture_pageview: false in init.** Next.js client-side navigation needs manual pageview tracking.
|
|
1063
|
+
3. **Use person_profiles: "identified_only"** to save on events. Anonymous events are cheaper.
|
|
1064
|
+
4. **Call posthog.identify() after login** with the user's ID to link sessions.
|
|
1065
|
+
5. **Server-side: always call posthogServer.shutdown()** in serverless environments, or events may be lost.
|
|
1066
|
+
6. **Never ask the user to paste PostHog keys in chat.** Direct them to set NEXT_PUBLIC_POSTHOG_KEY and NEXT_PUBLIC_POSTHOG_HOST in the Mistflow dashboard (Project Settings > Environment Variables).`},{id:"firecrawl-scraping",name:"Firecrawl Web Scraping",category:"scraping",prompt:`## Firecrawl Web Scraping Integration
|
|
1067
|
+
|
|
1068
|
+
Firecrawl handles all scraping on their servers. Your Worker just makes HTTP API calls. Single scrapes complete in 1-5 seconds. For multi-page crawls, use async mode with webhooks.
|
|
1069
|
+
|
|
1070
|
+
### File Structure
|
|
1071
|
+
\`\`\`
|
|
1072
|
+
lib/firecrawl.ts \u2014 Firecrawl client singleton
|
|
1073
|
+
app/api/scrape/route.ts \u2014 Single URL scrape endpoint
|
|
1074
|
+
app/api/crawl/start/route.ts \u2014 Start async crawl (returns job ID)
|
|
1075
|
+
app/api/crawl/[id]/route.ts \u2014 Poll crawl status
|
|
1076
|
+
app/api/firecrawl-webhook/route.ts \u2014 Webhook for async crawl results
|
|
1077
|
+
\`\`\`
|
|
1078
|
+
|
|
1079
|
+
### Client Setup (lib/firecrawl.ts)
|
|
1080
|
+
\`\`\`typescript
|
|
1081
|
+
import FirecrawlApp from "@mendable/firecrawl-js";
|
|
1082
|
+
|
|
1083
|
+
export const firecrawl = new FirecrawlApp({
|
|
1084
|
+
apiKey: process.env.FIRECRAWL_API_KEY!,
|
|
1085
|
+
});
|
|
1086
|
+
\`\`\`
|
|
1087
|
+
|
|
1088
|
+
### Scrape Single URL (app/api/scrape/route.ts)
|
|
1089
|
+
Single scrapes complete in 1-5 seconds. Network I/O does NOT count as CPU time on Workers, so this is safe.
|
|
1090
|
+
\`\`\`typescript
|
|
1091
|
+
import { firecrawl } from "@/lib/firecrawl";
|
|
1092
|
+
import { NextRequest, NextResponse } from "next/server";
|
|
1093
|
+
|
|
1094
|
+
export async function POST(req: NextRequest) {
|
|
1095
|
+
const { url } = await req.json();
|
|
1096
|
+
|
|
1097
|
+
if (!url || typeof url !== "string") {
|
|
1098
|
+
return NextResponse.json({ error: "URL is required" }, { status: 400 });
|
|
1099
|
+
}
|
|
1100
|
+
|
|
1101
|
+
const result = await firecrawl.scrapeUrl(url, {
|
|
1102
|
+
formats: ["markdown"],
|
|
1103
|
+
onlyMainContent: true,
|
|
1104
|
+
timeout: 20000,
|
|
1105
|
+
});
|
|
1106
|
+
|
|
1107
|
+
if (!result.success) {
|
|
1108
|
+
return NextResponse.json({ error: "Scrape failed" }, { status: 500 });
|
|
1109
|
+
}
|
|
1110
|
+
|
|
1111
|
+
return NextResponse.json({
|
|
1112
|
+
markdown: result.markdown,
|
|
1113
|
+
title: result.metadata?.title,
|
|
1114
|
+
description: result.metadata?.description,
|
|
1115
|
+
sourceUrl: result.metadata?.sourceURL,
|
|
1116
|
+
});
|
|
1117
|
+
}
|
|
1118
|
+
\`\`\`
|
|
1119
|
+
|
|
1120
|
+
### Start Async Crawl (app/api/crawl/start/route.ts)
|
|
1121
|
+
For multi-page crawls, ALWAYS use async mode with a webhook. Never use synchronous crawlUrl().
|
|
1122
|
+
\`\`\`typescript
|
|
1123
|
+
import { firecrawl } from "@/lib/firecrawl";
|
|
1124
|
+
import { NextRequest, NextResponse } from "next/server";
|
|
1125
|
+
|
|
1126
|
+
export async function POST(req: NextRequest) {
|
|
1127
|
+
const { url, maxPages = 50 } = await req.json();
|
|
1128
|
+
|
|
1129
|
+
const result = await firecrawl.asyncCrawlUrl(url, {
|
|
1130
|
+
limit: maxPages,
|
|
1131
|
+
maxDepth: 3,
|
|
1132
|
+
scrapeOptions: { formats: ["markdown"], onlyMainContent: true },
|
|
1133
|
+
webhook: {
|
|
1134
|
+
url: \`\${process.env.NEXT_PUBLIC_APP_URL}/api/firecrawl-webhook\`,
|
|
1135
|
+
},
|
|
1136
|
+
});
|
|
1137
|
+
|
|
1138
|
+
// Store crawl job ID in your DB for status tracking
|
|
1139
|
+
return NextResponse.json({ crawlId: result.id, status: "started" });
|
|
1140
|
+
}
|
|
1141
|
+
\`\`\`
|
|
1142
|
+
|
|
1143
|
+
### Poll Crawl Status (app/api/crawl/[id]/route.ts)
|
|
1144
|
+
\`\`\`typescript
|
|
1145
|
+
import { firecrawl } from "@/lib/firecrawl";
|
|
1146
|
+
import { NextRequest, NextResponse } from "next/server";
|
|
1147
|
+
|
|
1148
|
+
export async function GET(
|
|
1149
|
+
req: NextRequest,
|
|
1150
|
+
{ params }: { params: Promise<{ id: string }> }
|
|
1151
|
+
) {
|
|
1152
|
+
const { id } = await params;
|
|
1153
|
+
const status = await firecrawl.checkCrawlStatus(id);
|
|
1154
|
+
|
|
1155
|
+
return NextResponse.json({
|
|
1156
|
+
status: status.status,
|
|
1157
|
+
completed: status.completed,
|
|
1158
|
+
total: status.total,
|
|
1159
|
+
creditsUsed: status.creditsUsed,
|
|
1160
|
+
pages: status.data?.map((page: { markdown?: string; metadata?: { title?: string; sourceURL?: string } }) => ({
|
|
1161
|
+
title: page.metadata?.title,
|
|
1162
|
+
url: page.metadata?.sourceURL,
|
|
1163
|
+
markdownLength: page.markdown?.length ?? 0,
|
|
1164
|
+
})),
|
|
1165
|
+
});
|
|
1166
|
+
}
|
|
1167
|
+
\`\`\`
|
|
1168
|
+
|
|
1169
|
+
### Webhook Handler (app/api/firecrawl-webhook/route.ts)
|
|
1170
|
+
\`\`\`typescript
|
|
1171
|
+
import { NextRequest, NextResponse } from "next/server";
|
|
1172
|
+
|
|
1173
|
+
interface FirecrawlWebhookPayload {
|
|
1174
|
+
success: boolean;
|
|
1175
|
+
type: "crawl.started" | "crawl.page" | "crawl.completed" | "crawl.failed";
|
|
1176
|
+
id: string;
|
|
1177
|
+
data?: { markdown?: string; metadata?: { title?: string; sourceURL?: string } }[];
|
|
1178
|
+
error?: string;
|
|
1179
|
+
}
|
|
1180
|
+
|
|
1181
|
+
export async function POST(req: NextRequest) {
|
|
1182
|
+
const payload: FirecrawlWebhookPayload = await req.json();
|
|
1183
|
+
|
|
1184
|
+
switch (payload.type) {
|
|
1185
|
+
case "crawl.page":
|
|
1186
|
+
if (payload.data) {
|
|
1187
|
+
for (const page of payload.data) {
|
|
1188
|
+
// Store page in your database or vector store
|
|
1189
|
+
// page.markdown is clean, LLM-ready content
|
|
1190
|
+
// page.metadata.title, page.metadata.sourceURL for reference
|
|
1191
|
+
await storePage({
|
|
1192
|
+
crawlId: payload.id,
|
|
1193
|
+
url: page.metadata?.sourceURL ?? "",
|
|
1194
|
+
title: page.metadata?.title ?? "",
|
|
1195
|
+
markdown: page.markdown ?? "",
|
|
1196
|
+
});
|
|
1197
|
+
}
|
|
1198
|
+
}
|
|
1199
|
+
break;
|
|
1200
|
+
case "crawl.completed":
|
|
1201
|
+
// Mark crawl as done in your DB
|
|
1202
|
+
break;
|
|
1203
|
+
case "crawl.failed":
|
|
1204
|
+
// Log error: payload.error
|
|
1205
|
+
break;
|
|
1206
|
+
}
|
|
1207
|
+
|
|
1208
|
+
return NextResponse.json({ received: true });
|
|
1209
|
+
}
|
|
1210
|
+
|
|
1211
|
+
async function storePage(page: { crawlId: string; url: string; title: string; markdown: string }) {
|
|
1212
|
+
// TODO: Insert into your database
|
|
1213
|
+
// For RAG pipelines: chunk the markdown and generate embeddings
|
|
1214
|
+
}
|
|
1215
|
+
\`\`\`
|
|
1216
|
+
|
|
1217
|
+
### Extract Structured Data (with Zod schema)
|
|
1218
|
+
\`\`\`typescript
|
|
1219
|
+
import { z } from "zod";
|
|
1220
|
+
import { firecrawl } from "@/lib/firecrawl";
|
|
1221
|
+
|
|
1222
|
+
const ProductSchema = z.object({
|
|
1223
|
+
name: z.string(),
|
|
1224
|
+
price: z.number(),
|
|
1225
|
+
description: z.string(),
|
|
1226
|
+
inStock: z.boolean(),
|
|
1227
|
+
});
|
|
1228
|
+
|
|
1229
|
+
const result = await firecrawl.extract(
|
|
1230
|
+
["https://shop.example.com/products/*"],
|
|
1231
|
+
{
|
|
1232
|
+
schema: ProductSchema,
|
|
1233
|
+
prompt: "Extract product details from each product page",
|
|
1234
|
+
}
|
|
1235
|
+
);
|
|
1236
|
+
// result.data is typed as { name: string, price: number, ... }
|
|
1237
|
+
\`\`\`
|
|
1238
|
+
|
|
1239
|
+
### Map a Website (discover URLs before crawling)
|
|
1240
|
+
\`\`\`typescript
|
|
1241
|
+
import { firecrawl } from "@/lib/firecrawl";
|
|
1242
|
+
|
|
1243
|
+
// Discover all URLs on a site (1 credit flat, regardless of URL count)
|
|
1244
|
+
const map = await firecrawl.mapUrl("https://docs.example.com", {
|
|
1245
|
+
search: "API reference",
|
|
1246
|
+
limit: 200,
|
|
1247
|
+
});
|
|
1248
|
+
// map.links: Array<{ url: string, title?: string }>
|
|
1249
|
+
|
|
1250
|
+
// Then selectively scrape only relevant URLs
|
|
1251
|
+
const relevantUrls = map.links.slice(0, 20).map((l: { url: string }) => l.url);
|
|
1252
|
+
\`\`\`
|
|
1253
|
+
|
|
1254
|
+
### RAG Pipeline Pattern (Scrape -> Chunk -> Embed)
|
|
1255
|
+
Firecrawl's markdown output is already chunking-friendly. Headings are natural semantic boundaries.
|
|
1256
|
+
\`\`\`typescript
|
|
1257
|
+
function chunkMarkdown(markdown: string, maxSize = 1500): string[] {
|
|
1258
|
+
const sections = markdown.split(/\\n(?=#{1,3} )/);
|
|
1259
|
+
const chunks: string[] = [];
|
|
1260
|
+
|
|
1261
|
+
for (const section of sections) {
|
|
1262
|
+
if (section.length <= maxSize) {
|
|
1263
|
+
chunks.push(section.trim());
|
|
1264
|
+
} else {
|
|
1265
|
+
const paragraphs = section.split(/\\n\\n+/);
|
|
1266
|
+
let current = "";
|
|
1267
|
+
for (const para of paragraphs) {
|
|
1268
|
+
if (current.length + para.length > maxSize) {
|
|
1269
|
+
if (current) chunks.push(current.trim());
|
|
1270
|
+
current = para;
|
|
1271
|
+
} else {
|
|
1272
|
+
current += "\\n\\n" + para;
|
|
1273
|
+
}
|
|
1274
|
+
}
|
|
1275
|
+
if (current) chunks.push(current.trim());
|
|
1276
|
+
}
|
|
1277
|
+
}
|
|
1278
|
+
|
|
1279
|
+
return chunks.filter((c) => c.length > 50);
|
|
1280
|
+
}
|
|
1281
|
+
|
|
1282
|
+
// Usage: scrape a URL and prepare chunks for embedding
|
|
1283
|
+
const result = await firecrawl.scrapeUrl("https://docs.example.com/guide", {
|
|
1284
|
+
formats: ["markdown"],
|
|
1285
|
+
onlyMainContent: true,
|
|
1286
|
+
});
|
|
1287
|
+
const chunks = chunkMarkdown(result.markdown ?? "");
|
|
1288
|
+
// Now embed each chunk with OpenAI embeddings and store in your vector DB
|
|
1289
|
+
\`\`\`
|
|
1290
|
+
|
|
1291
|
+
### Common Pitfalls
|
|
1292
|
+
1. **Always use asyncCrawlUrl() for multi-page crawls, never crawlUrl().** The synchronous version polls until completion and will hold your Worker request open unnecessarily.
|
|
1293
|
+
2. **Map first, crawl selectively.** mapUrl() costs 1 credit flat. Do not waste credits crawling irrelevant pages.
|
|
1294
|
+
3. **onlyMainContent: true is the default.** It strips nav, footer, and ads. Set to false only if you need the full page structure.
|
|
1295
|
+
4. **Crawl results expire in 24 hours.** Store them in your database before the expiry.
|
|
1296
|
+
5. **Extract mode costs 5 credits per page** (1 scrape + 4 for JSON extraction). Use sparingly.
|
|
1297
|
+
6. **Markdown is the right format for AI apps.** It strips boilerplate, preserves structure, and is what LLMs expect.
|
|
1298
|
+
7. **Free tier: 500 credits (one-time).** Hobby plan is $16/month for 3,000 credits.
|
|
1299
|
+
8. **Network I/O does NOT count as CPU time.** Single scrapes (1-5s of network wait) are safe on Workers.
|
|
1300
|
+
9. **Never ask the user to paste FIRECRAWL_API_KEY in chat.** Direct them to set it in the Mistflow dashboard (Project Settings > Environment Variables).`},{id:"replicate-media",name:"Replicate (Image/Video Gen)",category:"media",prompt:`## Replicate Integration (Image and Video Generation)
|
|
1301
|
+
|
|
1302
|
+
Replicate is a model marketplace. One API key, 200+ models. Use it for image generation (Flux, SDXL), video generation (Wan, Runway), and other media tasks. All heavy computation runs on Replicate's GPUs. Your Worker just makes API calls.
|
|
1303
|
+
|
|
1304
|
+
### File Structure
|
|
1305
|
+
\`\`\`
|
|
1306
|
+
lib/replicate.ts \u2014 Replicate client singleton + model helpers
|
|
1307
|
+
app/api/generate-image/route.ts \u2014 Image generation endpoint
|
|
1308
|
+
app/api/generate-video/route.ts \u2014 Video generation endpoint (async with polling)
|
|
1309
|
+
components/image-generator.tsx \u2014 Image generation UI
|
|
1310
|
+
\`\`\`
|
|
1311
|
+
|
|
1312
|
+
### Client Setup (lib/replicate.ts)
|
|
1313
|
+
\`\`\`typescript
|
|
1314
|
+
import Replicate from "replicate";
|
|
1315
|
+
|
|
1316
|
+
export const replicate = new Replicate({
|
|
1317
|
+
auth: process.env.REPLICATE_API_TOKEN,
|
|
1318
|
+
});
|
|
1319
|
+
|
|
1320
|
+
// Recommended models \u2014 change these to use different models
|
|
1321
|
+
export const MODELS = {
|
|
1322
|
+
imageFast: "black-forest-labs/flux-schnell" as const,
|
|
1323
|
+
imageQuality: "black-forest-labs/flux-1.1-pro" as const,
|
|
1324
|
+
videoFast: "wan-video/wan-2.2-i2v-fast" as const,
|
|
1325
|
+
} as const;
|
|
1326
|
+
\`\`\`
|
|
1327
|
+
|
|
1328
|
+
### Image Generation Route (app/api/generate-image/route.ts)
|
|
1329
|
+
Image generation typically completes in 2-10 seconds. Safe for Workers.
|
|
1330
|
+
\`\`\`typescript
|
|
1331
|
+
import { replicate, MODELS } from "@/lib/replicate";
|
|
1332
|
+
import { NextRequest, NextResponse } from "next/server";
|
|
1333
|
+
|
|
1334
|
+
export async function POST(req: NextRequest) {
|
|
1335
|
+
const { prompt, model } = await req.json();
|
|
1336
|
+
|
|
1337
|
+
if (!prompt || typeof prompt !== "string") {
|
|
1338
|
+
return NextResponse.json({ error: "Prompt is required" }, { status: 400 });
|
|
1339
|
+
}
|
|
1340
|
+
|
|
1341
|
+
const output = await replicate.run(model || MODELS.imageQuality, {
|
|
1342
|
+
input: {
|
|
1343
|
+
prompt,
|
|
1344
|
+
aspect_ratio: "1:1",
|
|
1345
|
+
output_format: "webp",
|
|
1346
|
+
},
|
|
1347
|
+
});
|
|
1348
|
+
|
|
1349
|
+
// Output shape depends on the model. Most image models return a URL string or array of URLs.
|
|
1350
|
+
const imageUrl = Array.isArray(output) ? output[0] : output;
|
|
1351
|
+
|
|
1352
|
+
return NextResponse.json({ imageUrl });
|
|
1353
|
+
}
|
|
1354
|
+
\`\`\`
|
|
1355
|
+
|
|
1356
|
+
### Video Generation Route (app/api/generate-video/route.ts)
|
|
1357
|
+
Video generation takes 30s-5min. Use async predictions with polling.
|
|
1358
|
+
\`\`\`typescript
|
|
1359
|
+
import { replicate, MODELS } from "@/lib/replicate";
|
|
1360
|
+
import { NextRequest, NextResponse } from "next/server";
|
|
1361
|
+
|
|
1362
|
+
// Start video generation (returns immediately with prediction ID)
|
|
1363
|
+
export async function POST(req: NextRequest) {
|
|
1364
|
+
const { prompt, imageUrl } = await req.json();
|
|
1365
|
+
|
|
1366
|
+
const prediction = await replicate.predictions.create({
|
|
1367
|
+
model: MODELS.videoFast,
|
|
1368
|
+
input: {
|
|
1369
|
+
prompt,
|
|
1370
|
+
...(imageUrl ? { image: imageUrl } : {}),
|
|
1371
|
+
},
|
|
1372
|
+
});
|
|
1373
|
+
|
|
1374
|
+
return NextResponse.json({
|
|
1375
|
+
predictionId: prediction.id,
|
|
1376
|
+
status: prediction.status,
|
|
1377
|
+
});
|
|
1378
|
+
}
|
|
1379
|
+
|
|
1380
|
+
// Poll for completion (call from client on interval)
|
|
1381
|
+
export async function GET(req: NextRequest) {
|
|
1382
|
+
const id = req.nextUrl.searchParams.get("id");
|
|
1383
|
+
if (!id) return NextResponse.json({ error: "Missing prediction ID" }, { status: 400 });
|
|
1384
|
+
|
|
1385
|
+
const prediction = await replicate.predictions.get(id);
|
|
1386
|
+
|
|
1387
|
+
return NextResponse.json({
|
|
1388
|
+
status: prediction.status,
|
|
1389
|
+
output: prediction.output,
|
|
1390
|
+
error: prediction.error,
|
|
1391
|
+
});
|
|
1392
|
+
}
|
|
1393
|
+
\`\`\`
|
|
1394
|
+
|
|
1395
|
+
### Image Generator Component (components/image-generator.tsx)
|
|
1396
|
+
\`\`\`tsx
|
|
1397
|
+
"use client";
|
|
1398
|
+
import { useState } from "react";
|
|
1399
|
+
|
|
1400
|
+
export function ImageGenerator() {
|
|
1401
|
+
const [prompt, setPrompt] = useState("");
|
|
1402
|
+
const [imageUrl, setImageUrl] = useState<string | null>(null);
|
|
1403
|
+
const [loading, setLoading] = useState(false);
|
|
1404
|
+
|
|
1405
|
+
async function handleGenerate() {
|
|
1406
|
+
if (!prompt.trim() || loading) return;
|
|
1407
|
+
setLoading(true);
|
|
1408
|
+
setImageUrl(null);
|
|
1409
|
+
|
|
1410
|
+
try {
|
|
1411
|
+
const res = await fetch("/api/generate-image", {
|
|
1412
|
+
method: "POST",
|
|
1413
|
+
headers: { "Content-Type": "application/json" },
|
|
1414
|
+
body: JSON.stringify({ prompt }),
|
|
1415
|
+
});
|
|
1416
|
+
const { imageUrl: url } = await res.json();
|
|
1417
|
+
setImageUrl(url);
|
|
1418
|
+
} finally {
|
|
1419
|
+
setLoading(false);
|
|
1420
|
+
}
|
|
1421
|
+
}
|
|
1422
|
+
|
|
1423
|
+
return (
|
|
1424
|
+
<div className="space-y-4">
|
|
1425
|
+
<div className="flex gap-2">
|
|
1426
|
+
<input
|
|
1427
|
+
value={prompt}
|
|
1428
|
+
onChange={(e) => setPrompt(e.target.value)}
|
|
1429
|
+
onKeyDown={(e) => e.key === "Enter" && handleGenerate()}
|
|
1430
|
+
placeholder="Describe the image you want..."
|
|
1431
|
+
className="flex-1 rounded-md border px-3 py-2"
|
|
1432
|
+
/>
|
|
1433
|
+
<button
|
|
1434
|
+
onClick={handleGenerate}
|
|
1435
|
+
disabled={loading || !prompt.trim()}
|
|
1436
|
+
className="rounded-md bg-primary px-4 py-2 text-primary-foreground disabled:opacity-50"
|
|
1437
|
+
>
|
|
1438
|
+
{loading ? "Generating..." : "Generate"}
|
|
1439
|
+
</button>
|
|
1440
|
+
</div>
|
|
1441
|
+
{imageUrl && (
|
|
1442
|
+
<img src={imageUrl} alt={prompt} className="max-w-md rounded-lg shadow-md" />
|
|
1443
|
+
)}
|
|
1444
|
+
</div>
|
|
1445
|
+
);
|
|
1446
|
+
}
|
|
1447
|
+
\`\`\`
|
|
1448
|
+
|
|
1449
|
+
### Popular Models Reference
|
|
1450
|
+
**Image generation:**
|
|
1451
|
+
- \`black-forest-labs/flux-schnell\` \u2014 fast, good quality, cheapest
|
|
1452
|
+
- \`black-forest-labs/flux-1.1-pro\` \u2014 best quality, slower
|
|
1453
|
+
- \`black-forest-labs/flux-2-pro\` \u2014 highest fidelity, product photography, character consistency
|
|
1454
|
+
- \`google/nano-banana-pro\` \u2014 Google's model, strong prompt following, multilingual text rendering
|
|
1455
|
+
|
|
1456
|
+
**Video generation:**
|
|
1457
|
+
- \`wan-video/wan-2.2-i2v-fast\` \u2014 image-to-video, fast and affordable (10M+ runs)
|
|
1458
|
+
- \`google/veo-3.1-fast\` \u2014 high fidelity with audio
|
|
1459
|
+
- \`kwaivgi/kling-v3-video\` \u2014 multi-shot storytelling with native audio
|
|
1460
|
+
|
|
1461
|
+
### Common Pitfalls
|
|
1462
|
+
1. **Never expose REPLICATE_API_TOKEN to the client.** All generation calls go through your API routes.
|
|
1463
|
+
2. **Image gen is synchronous, video gen is async.** Image models return in 2-10s (safe for Workers). Video models take 30s-5min. Use \`replicate.predictions.create()\` + polling for video.
|
|
1464
|
+
3. **Output format varies by model.** Some return a URL string, some an array of URLs, some an object. Check the model's documentation on replicate.com.
|
|
1465
|
+
4. **Model IDs use owner/name format.** E.g. \`black-forest-labs/flux-schnell\`, not just \`flux-schnell\`.
|
|
1466
|
+
5. **Replicate charges per prediction.** Flux Schnell is ~$0.003/image. Flux Pro is ~$0.05/image. Video models are $0.05-$0.50/generation. Show generation cost to users.
|
|
1467
|
+
6. **Cache generated images.** Store output URLs in your database. Replicate URLs expire after a few hours. Download and re-host on R2 for permanent storage.
|
|
1468
|
+
7. **Network I/O does NOT count as CPU time on Workers.** Image generation wait time is all network I/O.
|
|
1469
|
+
8. **Never ask the user to paste REPLICATE_API_TOKEN in chat.** Direct them to set it in the Mistflow dashboard (Project Settings > Environment Variables).`}]});import{z as te}from"zod";import{resolve as Jt}from"path";import{existsSync as Kt,readFileSync as Yt}from"fs";import{join as Qt}from"path";var Na,Is,_s=x(()=>{"use strict";W();Te();bs();le();eo();ft();Vt();Na=te.object({action:te.enum(["get","update","share","landing-designs","integrations","errors","logs","deployments","version"]).default("get").describe("'get' reads current project state. 'update' marks steps complete or adds env vars. 'share' makes the project a shareable template. 'landing-designs' lists curated landing page hero designs. 'integrations' lists third-party service integration blueprints (Stripe, Resend, ElevenLabs, etc.) with setup guides. 'errors' fetches runtime errors from the deployed app. 'logs' fetches deploy logs for a specific deployment. 'deployments' lists deployment history. 'version' reports the installed @mistflow-ai/mcp version and whether an upgrade is available."),projectPath:te.string().optional().describe("Path to the project directory (default: cwd)"),completedStep:te.number().optional().describe("(update) Mark a plan step as completed by step number"),addEnvVar:te.object({key:te.string(),description:te.string().optional(),setupUrl:te.string().optional()}).optional().describe("(update) Add a required env var to the project manifest"),templateDescription:te.string().optional().describe("(share) Short description of what this template builds"),category:te.string().optional().describe("(landing-designs) Filter by category"),presetId:te.string().optional().describe("(landing-designs) Get full details for a specific landing design by ID"),integrationId:te.string().optional().describe("(integrations) Get full details for a specific integration preset by ID (e.g. 'stripe-payments', 'resend-email', 'elevenlabs-voice')"),period:te.string().optional().describe("(errors) Time period for errors: '1h', '24h', '7d' (default: '7d')"),deploymentId:te.string().optional().describe("(logs) Deployment ID to fetch logs for. If omitted, fetches logs for the latest deployment.")}),Is={name:"mist_project",description:jo,inputSchema:Na,handler:async t=>{let e=t;if(["share","errors","logs","deployments"].includes(e.action)&&!J())return c("You need to sign in first. Run mist_setup to connect your account.",!0);switch(e.action){case"get":case"update":return ys.handler({action:e.action,projectPath:e.projectPath,completedStep:e.completedStep,addEnvVar:e.addEnvVar});case"share":{let n=Jt(e.projectPath??process.cwd()),s=Qt(n,"mistflow.json");if(!Kt(s))return Pe(n);let a;try{a=JSON.parse(Yt(s,"utf-8"))}catch{return c("Could not read mistflow.json.",!0)}let r=a.projectId;if(!r)return c("No project ID found. Deploy the project first to register it.",!0);try{let i=await Vn(r,{isTemplate:!0,description:e.templateDescription});return c(JSON.stringify({shareUrl:i.share_url,shareToken:i.share_token,message:`Your project is now a shareable template!
|
|
1470
|
+
|
|
1471
|
+
Anyone can fork it: ${i.share_url}
|
|
1472
|
+
|
|
1473
|
+
Others can use it in their AI editor:
|
|
1474
|
+
"build me something like ${i.share_url}"`}))}catch(i){let l=i instanceof Error?i.message:"Failed to share project";return c(l,!0)}}case"landing-designs":{if(e.presetId){let r=Gt(e.presetId);if(!r)return c(`Preset '${e.presetId}' not found. Use mist_project action='presets' without presetId to list all available presets.`,!0);let i=ws(e.presetId);return c(JSON.stringify({preset:{id:r.id,title:r.title,category:r.category,description:i?.description??"",style:i?.style??"",theme:i?.theme??"dark",colors:i?.colors??[],tags:i?.tags??[],promptLength:r.prompt.length},message:`Landing design "${r.title}" (${r.category}) \u2014 ${i?.description??""}. To use it, pass landingDesign="${r.id}" when calling mist_plan.`}))}let n=xs(e.category??void 0),s=Zn(e.category),a=vs(s);return c(JSON.stringify({count:n.length,presets:n.map(r=>({id:r.id,title:r.title,category:r.category,description:r.description,style:r.style,theme:r.theme,colors:r.colors})),formatted:a,message:`${n.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 ${Ke()}/designs?tab=landing-designs.`}))}case"integrations":{if(e.integrationId){let r=et(e.integrationId);if(!r)return c(`Integration '${e.integrationId}' not found. Use mist_project action='integrations' without integrationId to list all available integrations.`,!0);let i=tt(r.id);return c(JSON.stringify({integration:{id:r.id,name:r.name,category:r.category,description:i?.description??"",packages:i?.packages??[],envVars:i?.envVars??[],docsUrl:i?.docsUrl??"",difficulty:i?.difficulty??"medium"},message:`Integration "${r.name}" (${r.category}) \u2014 ${i?.description??""}. This blueprint is auto-injected during implementation when your plan has a matching integration step. Required env vars: ${i?.envVars?.map(l=>l.key).join(", ")||"none"}. Docs: ${i?.docsUrl??"n/a"}.`}))}let n=Ps(e.category??void 0),s=no(e.category??void 0),a=Ss(s);return c(JSON.stringify({count:n.length,integrations:n.map(r=>({id:r.id,name:r.name,category:r.category,description:r.description,packages:r.packages,difficulty:r.difficulty,envVars:r.envVars.map(i=>i.key)})),formatted:a,message:`${n.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 n=Jt(e.projectPath??process.cwd()),s=Qt(n,"mistflow.json");if(!Kt(s))return Pe(n);let a;try{a=JSON.parse(Yt(s,"utf-8"))}catch{return c("Could not read mistflow.json.",!0)}let r=a.projectId;if(!r)return c("No project ID found. Deploy the project first.",!0);try{let i=await Ln(r,e.period??"7d");return i.total===0?c(JSON.stringify({total:0,period:i.period,message:`No runtime errors in the last ${i.period}. The app is running clean.`})):c(JSON.stringify({total:i.total,period:i.period,errors:i.errors,message:`${i.total} runtime error(s) in the last ${i.period}. Review the errors above and use mist_debug to investigate.`}))}catch(i){let l=i instanceof Error?i.message:"Failed to fetch errors";return c(l,!0)}}case"logs":{let n=Jt(e.projectPath??process.cwd()),s=Qt(n,"mistflow.json");if(!Kt(s))return Pe(n);let a;try{a=JSON.parse(Yt(s,"utf-8"))}catch{return c("Could not read mistflow.json.",!0)}let r=a.projectId;if(!r)return c("No project ID found. Deploy the project first.",!0);let i=e.deploymentId;if(!i)try{let l=await Qe(r);if(l.length===0)return c("No deployments found for this project.",!0);i=l[0].id}catch(l){let p=l instanceof Error?l.message:"Failed to fetch deployments";return c(p,!0)}try{let[l,p]=await Promise.all([$n(i),xt(i)]),m=l.filter(d=>d.level==="error"),u=l.filter(d=>d.level==="warn");return c(JSON.stringify({deploymentId:i,status:p.status,errorMessage:p.error??null,totalLogs:l.length,errorCount:m.length,warnCount:u.length,logs:l.map(d=>({time:d.timestamp,level:d.level,phase:d.phase,message:d.message})),message:p.status==="failed"?`Deployment failed. ${m.length} error(s) found in logs. Review the logs above to diagnose the issue.`:`Deployment status: ${p.status}. ${l.length} log entries (${m.length} errors, ${u.length} warnings).`}))}catch(l){let p=l instanceof Error?l.message:"Failed to fetch deploy logs";return c(p,!0)}}case"deployments":{let n=Jt(e.projectPath??process.cwd()),s=Qt(n,"mistflow.json");if(!Kt(s))return Pe(n);let a;try{a=JSON.parse(Yt(s,"utf-8"))}catch{return c("Could not read mistflow.json.",!0)}let r=a.projectId;if(!r)return c("No project ID found. Deploy the project first.",!0);try{let i=await Qe(r);return c(JSON.stringify({total:i.length,deployments:i.map(l=>({id:l.id,status:l.status,errorMessage:l.error_message,durationSeconds:l.duration_seconds,isRollback:!!l.rollback_from_id,createdAt:l.created_at})),message:`${i.length} deployment(s) found. Use mist_project action='logs' deploymentId='<id>' to see detailed logs for any deployment.`}))}catch(i){let l=i instanceof Error?i.message:"Failed to fetch deployments";return c(l,!0)}}case"version":{xn().backendSignalReceived||await Rn();let n=xn(),s=n.severity==="none",a={none:"up to date",patch:"patch update available",minor:"minor update available",major:"major update available",unsupported:"UNSUPPORTED \u2014 upgrade required"};return c(JSON.stringify({current:n.current,latest:n.latest||"unknown",minSupported:n.minSupported||"unknown",severity:n.severity,upToDate:s,upgradeCmd:n.upgradeCmd,changelogUrl:n.changelogUrl,backendSignalReceived:n.backendSignalReceived,message:n.backendSignalReceived?`Mistflow MCP ${n.current} (${a[n.severity]??n.severity}). Latest: ${n.latest}.${s?"":` Run \`${n.upgradeCmd}\` and restart your editor to upgrade.`}`:`Mistflow MCP ${n.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 c(`Unknown action: ${e.action}. Use get, update, share, landing-designs, integrations, errors, logs, deployments, or version.`,!0)}}}});import{z as ze}from"zod";var ja,Ts,Rs=x(()=>{"use strict";Te();W();Pn();ja=ze.object({action:ze.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:ze.string().optional().describe("URL to navigate to. Required for 'navigate'; optional for 'screenshot' (navigates before capturing)."),selector:ze.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:ze.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:ze.boolean().default(!1).describe("For 'screenshot': capture the full scrollable page instead of just the viewport."),includeScreenshot:ze.boolean().default(!1).describe("For navigate/interact actions: also return a screenshot alongside the accessibility snapshot.")}),Ts={name:"mist_browser",description:Do,inputSchema:ja,handler:async t=>{let e=t,o=await kn();if(e.action==="navigate"){if(!e.url)return c("URL is required for 'navigate'.",!0);let a=[],r=p=>{p.type()==="error"&&a.push(p.text())};o.on("console",r),await o.goto(e.url,{waitUntil:"domcontentloaded",timeout:3e4}),await o.waitForLoadState("networkidle").catch(()=>{});let i=[],l=p=>i.push(p.message);if(o.on("pageerror",l),await o.waitForTimeout(500),o.removeListener("console",r),o.removeListener("pageerror",l),a.length>0||i.length>0){let p=await yt(o),m=[{type:"text",text:JSON.stringify({url:o.url(),title:await o.title(),snapshot:p,consoleErrors:a,pageErrors:i,hasErrors:!0})}];if(e.includeScreenshot){let u=await bt(o);m.push({type:"image",data:u.toString("base64"),mimeType:"image/png"})}return{content:m}}}else if(e.action==="go_back")await o.goBack({waitUntil:"domcontentloaded",timeout:1e4});else if(e.action==="go_forward")await o.goForward({waitUntil:"domcontentloaded",timeout:1e4});else if(e.action==="click"){if(!e.selector)return c("Selector is required for 'click'.",!0);await o.click(e.selector,{timeout:1e4}),await o.waitForLoadState("domcontentloaded").catch(()=>{}),await o.waitForTimeout(500)}else if(e.action==="type"){if(!e.selector)return c("Selector is required for 'type'.",!0);if(!e.value)return c("Value is required for 'type'.",!0);await o.type(e.selector,e.value,{delay:50})}else if(e.action==="fill"){if(!e.selector)return c("Selector is required for 'fill'.",!0);if(!e.value)return c("Value is required for 'fill'.",!0);await o.fill(e.selector,e.value)}else if(e.action==="select_option"){if(!e.selector)return c("Selector is required for 'select_option'.",!0);if(!e.value)return c("Value is required for 'select_option'.",!0);await o.selectOption(e.selector,e.value)}else if(e.action==="hover"){if(!e.selector)return c("Selector is required for 'hover'.",!0);await o.hover(e.selector,{timeout:1e4})}else if(e.action==="press_key"){if(!e.value)return c("Value is required for 'press_key' (e.g. 'Enter').",!0);await o.keyboard.press(e.value),await o.waitForLoadState("domcontentloaded").catch(()=>{}),await o.waitForTimeout(500)}else if(e.action==="screenshot"){e.url&&(await o.goto(e.url,{waitUntil:"domcontentloaded",timeout:3e4}),await o.waitForLoadState("networkidle").catch(()=>{}));let a;if(e.selector){let r=await o.$(e.selector);if(!r)return c(`Element not found: ${e.selector}`,!0);a=await r.screenshot({type:"png"})}else a=await bt(o,e.fullPage);return{content:[{type:"text",text:JSON.stringify({url:o.url(),title:await o.title(),message:`Screenshot captured (${e.fullPage?"full page":"viewport"})`})},{type:"image",data:a.toString("base64"),mimeType:"image/png"}]}}else if(e.action==="snapshot"){let a=await yt(o);return{content:[{type:"text",text:JSON.stringify({url:o.url(),title:await o.title(),snapshot:a})}]}}let n=await yt(o),s=[{type:"text",text:JSON.stringify({url:o.url(),title:await o.title(),snapshot:n})}];if(e.includeScreenshot){let a=await bt(o);s.push({type:"image",data:a.toString("base64"),mimeType:"image/png"})}return{content:s}}}});import{z as As}from"zod";var Cs,Es,Ns=x(()=>{"use strict";Te();W();Cs=`# Mistflow MCP tool reference
|
|
1475
|
+
|
|
1476
|
+
Every capability is an MCP tool. There is no companion CLI. Long-running tools
|
|
1477
|
+
(install, build, qa, deploy) use the fire-and-poll pattern \u2014 the first call
|
|
1478
|
+
returns a \`jobId\` with \`status: "running"\`; subsequent calls with that
|
|
1479
|
+
\`jobId\` return fresh state in <1s each. Never the 60s MCP timeout ceiling.
|
|
60
1480
|
|
|
61
1481
|
## Host AI execution rules
|
|
62
1482
|
|
|
63
|
-
When
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
1483
|
+
When a tool returns \`status: "running"\`, call it again with the returned
|
|
1484
|
+
\`jobId\` in ~15-30s. Do NOT narrate "still generating" or ask the user if
|
|
1485
|
+
they want to keep waiting \u2014 polling is how these tools work. Each poll
|
|
1486
|
+
responds in under a second; the underlying work continues detached.
|
|
67
1487
|
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
1488
|
+
When \`mist_plan\` returns \`status: "clarify"\`, the first planning pass is
|
|
1489
|
+
complete and waiting on user answers. Render the \`questions[]\` via your
|
|
1490
|
+
native structured-question UI (AskUserQuestion in Claude Code, quick pick in
|
|
1491
|
+
Cursor). Do NOT re-call mist_plan or describe it as "still generating".
|
|
1492
|
+
Only re-call to submit the answers, or to poll when status is
|
|
1493
|
+
\`"design_clarify_pending"\`.
|
|
74
1494
|
|
|
75
1495
|
Before scaffolding a NEW app, resolve the destination path explicitly. If
|
|
76
1496
|
the user asked to create/build a new app and the current directory is not
|
|
77
|
-
already that Mistflow project, ask whether to scaffold in the current
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
answers
|
|
109
|
-
\`decisionKey\`
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
### \`
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
### \`
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
#
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
#
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
1497
|
+
already that Mistflow project, ask whether to scaffold in the current folder
|
|
1498
|
+
or a new subfolder here (unless the user already gave a path). Do NOT inspect
|
|
1499
|
+
sibling directories and silently adopt one. Reuse an existing Mistflow
|
|
1500
|
+
project only when the user explicitly asks to continue/edit that project.
|
|
1501
|
+
|
|
1502
|
+
\`mist_init\` is transactional: it registers the cloud project first,
|
|
1503
|
+
scaffolds in a temp directory, then moves the app into place only after both
|
|
1504
|
+
succeed. If auth, quota, or network registration fails, stop before any app
|
|
1505
|
+
appears locally. Do NOT default to reusing some other existing app as
|
|
1506
|
+
recovery unless the user explicitly asked.
|
|
1507
|
+
|
|
1508
|
+
## Tools
|
|
1509
|
+
|
|
1510
|
+
### \`mist_setup({ apiKey? })\`
|
|
1511
|
+
Authenticate. Two-phase device code flow by default; pass \`apiKey\` for
|
|
1512
|
+
headless. Only call when the user has never signed in or a previous tool
|
|
1513
|
+
returned \`auth_missing\` / \`auth_revoked\`. Do NOT call in response to 500s,
|
|
1514
|
+
404s, or network errors.
|
|
1515
|
+
|
|
1516
|
+
### \`mist_project({ action: "get" })\`
|
|
1517
|
+
Load plan progress, env vars, deploy info. Call before editing an existing
|
|
1518
|
+
Mistflow project so you understand its shape. Other actions: \`update\`,
|
|
1519
|
+
\`share\`, \`landing-designs\`, \`integrations\`, \`errors\`, \`logs\`,
|
|
1520
|
+
\`deployments\`, \`version\`.
|
|
1521
|
+
|
|
1522
|
+
### \`mist_plan({ description })\`
|
|
1523
|
+
Start a new plan. Pass the user's description EXACTLY as written \u2014 do NOT
|
|
1524
|
+
expand or add features. Returns \`status: "clarify"\` with \`questions[]\`
|
|
1525
|
+
(render via AskUserQuestion) OR \`status: "ready"\` if the description was
|
|
1526
|
+
specific enough.
|
|
1527
|
+
|
|
1528
|
+
Submit answers: \`mist_plan({ conversationId, answers: [{question, decisionKey, answer}, ...] })\`.
|
|
1529
|
+
Use the array form, not a \`{decisionKey: answer}\` map \u2014 multiple questions
|
|
1530
|
+
can share one decision key.
|
|
1531
|
+
|
|
1532
|
+
Modify existing plan: \`mist_plan({ description: "<change>", existingPlanId })\`.
|
|
1533
|
+
|
|
1534
|
+
Finalize after picking a design direction:
|
|
1535
|
+
\`mist_plan({ conversationId, designDirectionId })\`. When the tool returns
|
|
1536
|
+
\`status: "design_clarify_pending"\`, poll with the same conversationId until
|
|
1537
|
+
directions are ready, present them to the user, then submit the pick.
|
|
1538
|
+
|
|
1539
|
+
### \`mist_mockup({ planId, feedback?, approved?, projectPath? })\`
|
|
1540
|
+
Generate a grayscale HTML wireframe before scaffolding. Returns a
|
|
1541
|
+
\`wireframePrompt\` \u2014 you write the HTML to the returned \`mockupPath\`, open
|
|
1542
|
+
it for the user, wait for approval. Iterate with \`feedback\`, lock with
|
|
1543
|
+
\`approved: true\`. Do NOT proceed to mist_init until approved.
|
|
1544
|
+
|
|
1545
|
+
### \`mist_init({ planId, path })\`
|
|
1546
|
+
Scaffold a fresh Mistflow app from a plan. Transactional \u2014 registers cloud
|
|
1547
|
+
project first, scaffolds in temp, moves into place only after both succeed.
|
|
1548
|
+
Fast (~10s). Does NOT run npm install.
|
|
1549
|
+
|
|
1550
|
+
### \`mist_install({ projectPath })\`
|
|
1551
|
+
Fire-and-poll \`npm install\`. First call returns a \`jobId\`; poll with
|
|
1552
|
+
\`mist_install({ jobId })\`. Typical duration 30-90s.
|
|
1553
|
+
|
|
1554
|
+
### \`mist_implement({ projectPath })\`
|
|
1555
|
+
Execute the next plan step. Auto-marks the previous step complete on each
|
|
1556
|
+
call. Call repeatedly until all steps are done.
|
|
1557
|
+
|
|
1558
|
+
### \`mist_build({ projectPath, script? })\`
|
|
1559
|
+
Fire-and-poll production build. Script defaults to \`build\`. On failure,
|
|
1560
|
+
response has \`missingModules[]\` \u2014 chain mist_install with those packages
|
|
1561
|
+
then mist_build again, without asking the user.
|
|
1562
|
+
|
|
1563
|
+
### \`mist_debug({ projectPath?, buildOutput? })\`
|
|
1564
|
+
Parse a failed build into structured errors + suggestions. Call with
|
|
1565
|
+
\`projectPath\` to run \`npm run build\` and parse output; call with
|
|
1566
|
+
\`buildOutput\` to parse output captured elsewhere.
|
|
1567
|
+
|
|
1568
|
+
### \`mist_deploy({ action, projectPath?, deploymentId?, environment?, adminEmail? })\`
|
|
1569
|
+
Fire-and-poll deploy. \`action: "deploy"\` (default) tars + uploads + starts
|
|
1570
|
+
backend orchestration, returns a \`deploymentId\`. Poll with
|
|
1571
|
+
\`mist_deploy({ action: "status", deploymentId })\`.
|
|
1572
|
+
|
|
1573
|
+
When status flips to \`complete\`, response has \`qaRequired: true\` + a
|
|
1574
|
+
\`url\`. Do NOT surface the URL to the user until mist_qa returns
|
|
1575
|
+
\`status: "complete"\`.
|
|
1576
|
+
|
|
1577
|
+
Other actions: \`promote\` (staging \u2192 prod \u2014 re-uses the preview artifact,
|
|
1578
|
+
~10s), \`rollback\` (revert to a specific deploymentId).
|
|
1579
|
+
|
|
1580
|
+
### \`mist_qa({ projectPath, baseUrl?, grep? })\`
|
|
1581
|
+
Fire-and-poll Playwright runner against the deployed URL. Call AFTER
|
|
1582
|
+
mist_deploy's \`complete\`. Only surface the deploy URL once mist_qa exits 0.
|
|
1583
|
+
|
|
1584
|
+
### \`mist_config({ resource, action, ... })\`
|
|
1585
|
+
Manage env vars and custom domains. \`resource: "env"\` actions: \`set\`,
|
|
1586
|
+
\`list\`, \`delete\`. \`resource: "domain"\` actions: \`add\`, \`list\`,
|
|
1587
|
+
\`verify\`, \`remove\`. Env values are encrypted at rest and available on the
|
|
1588
|
+
next deployment.
|
|
1589
|
+
|
|
1590
|
+
### \`mist_browser({ action, url?, selector?, ... })\`
|
|
1591
|
+
Browser automation for testing the running app. Actions: \`navigate\`,
|
|
1592
|
+
\`click\`, \`type\`, \`screenshot\`, \`snapshot\`. Returns screenshots inline.
|
|
1593
|
+
Use after mist_deploy / mist_qa to verify flows.
|
|
1594
|
+
|
|
1595
|
+
### \`mist_help\`
|
|
1596
|
+
This reference. Static \u2014 safe to call frequently.
|
|
1597
|
+
|
|
1598
|
+
## End-to-end chain for a new app
|
|
1599
|
+
|
|
1600
|
+
mist_plan({ description: "habit tracker" })
|
|
1601
|
+
\u2192 { status: "clarify", conversationId: "...", questions: [...] }
|
|
1602
|
+
|
|
1603
|
+
# AI renders questions via AskUserQuestion, collects answers:
|
|
1604
|
+
mist_plan({ conversationId, answers: [...] })
|
|
1605
|
+
\u2192 { status: "design_clarify_pending", conversationId: "..." }
|
|
1606
|
+
|
|
1607
|
+
# Poll until directions are ready:
|
|
1608
|
+
mist_plan({ conversationId })
|
|
1609
|
+
\u2192 { status: "ready", directions: [...], previewPath: "..." }
|
|
1610
|
+
|
|
1611
|
+
# Open previewPath for the user, ask them to pick:
|
|
1612
|
+
mist_plan({ conversationId, designDirectionId: "modern-editorial" })
|
|
1613
|
+
\u2192 { status: "ready", plan: { ... }, planId: "..." }
|
|
1614
|
+
|
|
1615
|
+
# Optional but recommended: show wireframe before scaffolding:
|
|
1616
|
+
mist_mockup({ planId, projectPath })
|
|
1617
|
+
\u2192 { wireframePrompt: "...", mockupPath: "..." }
|
|
1618
|
+
# AI writes the HTML, opens it, waits for user approval:
|
|
1619
|
+
mist_mockup({ planId, approved: true })
|
|
1620
|
+
|
|
1621
|
+
mist_init({ planId, path: "/Users/you/projects/habit-tracker" })
|
|
1622
|
+
\u2192 { projectId, path, status: "initialized" }
|
|
1623
|
+
|
|
1624
|
+
mist_install({ projectPath })
|
|
1625
|
+
\u2192 { status: "running", jobId: "job_..." }
|
|
1626
|
+
# Poll:
|
|
1627
|
+
mist_install({ jobId })
|
|
1628
|
+
\u2192 { status: "complete", exitCode: 0 }
|
|
1629
|
+
|
|
1630
|
+
# Implement loop \u2014 call repeatedly until all steps done:
|
|
1631
|
+
mist_implement({ projectPath })
|
|
1632
|
+
\u2192 { status: "step_completed", nextStep: { ... } } | { status: "all_done" }
|
|
1633
|
+
|
|
1634
|
+
mist_build({ projectPath })
|
|
1635
|
+
\u2192 { status: "running", jobId: "..." }
|
|
1636
|
+
mist_build({ jobId })
|
|
1637
|
+
\u2192 { status: "complete" } | { status: "failed", missingModules: [...] }
|
|
1638
|
+
# On missingModules, chain mist_install with those packages, then
|
|
1639
|
+
# mist_build again. Do not ask the user.
|
|
1640
|
+
|
|
1641
|
+
mist_deploy({ action: "deploy", projectPath })
|
|
1642
|
+
\u2192 { status: "running", deploymentId: "dep_..." }
|
|
1643
|
+
mist_deploy({ action: "status", deploymentId })
|
|
1644
|
+
\u2192 { status: "complete", url: "...", qaRequired: true }
|
|
1645
|
+
# URL is NOT shown to the user yet.
|
|
1646
|
+
|
|
1647
|
+
mist_qa({ projectPath })
|
|
1648
|
+
\u2192 { status: "running", jobId: "..." }
|
|
1649
|
+
mist_qa({ jobId })
|
|
1650
|
+
\u2192 { status: "complete", exitCode: 0 }
|
|
1651
|
+
# Now safe to show the URL to the user.
|
|
1652
|
+
|
|
1653
|
+
## End-to-end chain for adding a feature (existing app)
|
|
1654
|
+
|
|
1655
|
+
**Decide the change shape first**, then pick the right chain. Ask product
|
|
1656
|
+
questions BEFORE any tool call \u2014 "what fields, what view, what workflow,
|
|
1657
|
+
what constraints" \u2014 unless the change is trivial. Getting the spec right
|
|
1658
|
+
is cheaper than building the wrong thing and iterating.
|
|
1659
|
+
|
|
1660
|
+
### Cosmetic / single-file edit (change a color, fix a typo, tweak copy)
|
|
1661
|
+
|
|
1662
|
+
# No planning, no mist_plan. Edit the file directly, then:
|
|
1663
|
+
mist_build({ projectPath }) # fire-and-poll
|
|
1664
|
+
mist_deploy({ action: "deploy", projectPath })
|
|
1665
|
+
mist_qa({ projectPath }) # only if user-facing behavior changed
|
|
1666
|
+
|
|
1667
|
+
### New page or feature with NO new data model (settings page, dark mode, search filter)
|
|
1668
|
+
|
|
1669
|
+
# 1. Load context first \u2014 read the current plan + schema so edits
|
|
1670
|
+
# respect existing conventions.
|
|
1671
|
+
mist_project({ action: "get", projectPath })
|
|
1672
|
+
\u2192 { plan, dataModel, features, envVars, ... }
|
|
1673
|
+
|
|
1674
|
+
# 2. Ask the user product questions if non-trivial.
|
|
1675
|
+
# 3. Edit the code directly (new routes, components, etc.). Reuse
|
|
1676
|
+
# existing schema \u2014 no mist_plan needed.
|
|
1677
|
+
# 4. Ship:
|
|
1678
|
+
mist_build({ projectPath })
|
|
1679
|
+
mist_deploy({ action: "deploy", projectPath })
|
|
1680
|
+
mist_qa({ projectPath })
|
|
1681
|
+
|
|
1682
|
+
### Feature needing a new data model (add comments to posts, add teams)
|
|
1683
|
+
|
|
1684
|
+
# 1. Context + spec questions.
|
|
1685
|
+
mist_project({ action: "get", projectPath })
|
|
1686
|
+
# Ask: what fields, relationships, constraints, who can read/write.
|
|
1687
|
+
|
|
1688
|
+
# 2. Modify the plan \u2014 existingPlanId points at the current plan; the
|
|
1689
|
+
# backend preserves completed steps and appends new ones.
|
|
1690
|
+
mist_plan({ description: "<change request>", existingPlanId: "..." })
|
|
1691
|
+
\u2192 { status: "clarify" | "ready", ... }
|
|
1692
|
+
|
|
1693
|
+
# 3. Implement the new steps one at a time:
|
|
1694
|
+
mist_implement({ projectPath })
|
|
1695
|
+
\u2192 { status: "step_completed", nextStep }
|
|
1696
|
+
# Repeat until all_done.
|
|
1697
|
+
|
|
1698
|
+
# 4. Build + ship:
|
|
1699
|
+
mist_build({ projectPath })
|
|
1700
|
+
mist_deploy({ action: "deploy", projectPath })
|
|
1701
|
+
mist_qa({ projectPath })
|
|
1702
|
+
|
|
1703
|
+
### Adding a third-party integration (Resend, ElevenLabs, OpenAI, Twilio)
|
|
1704
|
+
|
|
1705
|
+
# 1. Browse the catalog (or pass integrationId for full details):
|
|
1706
|
+
mist_project({ action: "integrations", projectPath })
|
|
1707
|
+
|
|
1708
|
+
# 2. Ask product questions \u2014 which flows use this, when triggered,
|
|
1709
|
+
# retry policy, etc.
|
|
1710
|
+
|
|
1711
|
+
# 3. Plan the change \u2014 the integration blueprint auto-injects when
|
|
1712
|
+
# the plan matches:
|
|
1713
|
+
mist_plan({ description: "<change request>", existingPlanId })
|
|
1714
|
+
|
|
1715
|
+
# 4. Implement:
|
|
1716
|
+
mist_implement({ projectPath }) # repeat until done
|
|
1717
|
+
|
|
1718
|
+
# 5. Set required secrets BEFORE deploy. mist_implement will surface
|
|
1719
|
+
# which keys the integration needs:
|
|
1720
|
+
mist_config({ resource: "env", action: "set", projectPath,
|
|
1721
|
+
key: "RESEND_API_KEY", value: "re_..." })
|
|
1722
|
+
|
|
1723
|
+
# 6. Ship:
|
|
1724
|
+
mist_build({ projectPath })
|
|
1725
|
+
mist_deploy({ action: "deploy", projectPath })
|
|
1726
|
+
mist_qa({ projectPath })
|
|
1727
|
+
|
|
1728
|
+
### Bug fix / something broke
|
|
1729
|
+
|
|
1730
|
+
# 1. Build failure \u2192 structured errors:
|
|
1731
|
+
mist_debug({ projectPath })
|
|
1732
|
+
\u2192 { errors: [{ file, line, humanMessage, suggestion }, ...] }
|
|
1733
|
+
|
|
1734
|
+
# 2. Runtime failure in prod \u2192 runtime errors:
|
|
1735
|
+
mist_project({ action: "errors", projectPath, period: "24h" })
|
|
1736
|
+
|
|
1737
|
+
# 3. Fix the code directly (no mist_plan for bugs).
|
|
1738
|
+
|
|
1739
|
+
# 4. Ship:
|
|
1740
|
+
mist_build({ projectPath })
|
|
1741
|
+
mist_deploy({ action: "deploy", projectPath })
|
|
1742
|
+
mist_qa({ projectPath })
|
|
1743
|
+
|
|
1744
|
+
### Promoting a staging preview to production
|
|
1745
|
+
|
|
1746
|
+
# Projects with deploy_strategy=staging auto-route to preview. After
|
|
1747
|
+
# mist_qa passes on the preview URL:
|
|
1748
|
+
mist_deploy({ action: "promote", projectPath })
|
|
1749
|
+
mist_deploy({ action: "status", deploymentId }) # poll
|
|
1750
|
+
# Promote re-runs the preview artifact on prod \u2014 ~10s.
|
|
1751
|
+
|
|
1752
|
+
### Rolling back a bad deploy
|
|
1753
|
+
|
|
1754
|
+
mist_project({ action: "deployments", projectPath })
|
|
1755
|
+
\u2192 { deployments: [{ id, status, created_at }, ...] }
|
|
1756
|
+
|
|
1757
|
+
mist_deploy({ action: "rollback", deploymentId: "<last known good>" })
|
|
1758
|
+
mist_deploy({ action: "status", deploymentId }) # poll
|
|
1759
|
+
`,Es={name:"mist_help",description:Oo,inputSchema:As.object({command:As.string().optional().describe("Optional: name of a specific tool (e.g. 'mist_plan') to get focused reference for. Omit to get the full catalog.")}),handler:async t=>{let{command:e}=t;if(!e)return c(Cs);let o=e.startsWith("mist_")?e:`mist_${e}`,n=Cs.split(`
|
|
1760
|
+
`),s=new RegExp(`^### \`${o}`),a=-1,r=n.length;for(let i=0;i<n.length;i++)if(s.test(n[i]))a=i;else if(a>=0&&n[i].startsWith("### ")){r=i;break}else if(a>=0&&n[i].startsWith("## ")&&i>a){r=i;break}return a<0?c(`No tool named '${o}' found. Call mist_help with no args to see the full catalog.`,!0):c(n.slice(a,r).join(`
|
|
1761
|
+
`).trim())}}});import{existsSync as Xt,mkdirSync as Os,readFileSync as Ms,readdirSync as Us,writeFileSync as Da}from"fs";import{join as Ne,resolve as Oa}from"path";import{homedir as so}from"os";import{z as It}from"zod";function nt(t){return t.entity??t.name??"Unknown"}function ot(t){return typeof t=="string"?t:t.name}function oo(t){return typeof t=="string"?"text":t.type}function js(t){let e=t.sampleRows;if(Array.isArray(e)&&e.length>0)return e.slice(0,3).map(s=>{let a={};for(let[r,i]of Object.entries(s))a[r]=i==null?"":String(i);return a});let o=t.fields||[],n=[];for(let s=0;s<3;s++){let a={};for(let r of o)a[ot(r)]=Ma(ot(r),oo(r),nt(t),s);n.push(a)}return n}function Ma(t,e,o,n){let s=t.toLowerCase(),a=(e||"text").toLowerCase();return s==="name"||s==="title"?[`${o} Alpha`,`${o} Beta`,`${o} Gamma`][n]:s==="email"?["alice@example.com","bob@example.com","carol@example.com"][n]:s==="status"?["Active","Pending","Completed"][n]:s==="priority"?["High","Medium","Low"][n]:s.includes("date")||a==="date"?["Jan 15, 2024","Feb 20, 2024","Mar 10, 2024"][n]:s.includes("price")||s.includes("amount")||s.includes("cost")?["$29","$49","$99"][n]:s.includes("count")||s.includes("quantity")||a==="number"||a==="integer"?["12","34","56"][n]:a==="boolean"||a==="bool"?["Yes","No","Yes"][n]:s.includes("description")||a==="textarea"?["Brief description here","Another example entry","Third sample item"][n]:`Sample ${n+1}`}function Ua(t){let e=t.dataModel??[],o=t.pages??[],n=t.design??{},s=o.map(u=>({label:u.name??u.path??"Page",route:u.path??u.route??"/"})),a=[],r=e.slice(0,3).map(u=>({name:nt(u),fields:(u.fields||[]).map(d=>({name:ot(d),type:oo(d)})),sampleData:js(u)})),i=[];t.primaryAction&&(i.push(`PRIMARY: ${t.primaryAction.action} \u2014 this is the first thing the user sees and does`),i.push(`SURFACE: ${t.primaryAction.dashboardSurface}`)),i.push(`METRICS: Key counts for ${e.map(u=>nt(u)).join(", ")}`),i.push("RECENT: Latest activity or items"),a.push({name:"Dashboard",type:"dashboard",route:"/dashboard",purpose:t.primaryAction?`Action surface \u2014 user comes here to ${t.primaryAction.action.toLowerCase()}. Not a stats display.`:`Overview of ${e.map(u=>nt(u)).join(", ")} with key metrics.`,informationHierarchy:i,interactionStates:["Empty state: new user, no data yet \u2014 show onboarding prompt","Loading state: skeleton placeholders for metrics and table","Populated state: real data with metrics, recent items, quick actions"],entities:r});let l=e[0];if(l){let u=nt(l),d=u.toLowerCase().endsWith("s")?u:`${u}s`;a.push({name:`${u} List`,type:"detail",route:`/${d.toLowerCase()}`,purpose:`Browse, search, and manage ${d.toLowerCase()}. Create new ${u.toLowerCase()}s.`,informationHierarchy:[`HEADER: "${d}" title + "Add ${u}" button`,"SEARCH: Filter/search bar \u2014 users will have many items",`TABLE: ${(l.fields||[]).slice(0,5).map(b=>ot(b)).join(", ")} columns`,"ROW ACTIONS: Edit, delete on each row"],interactionStates:[`Empty state: "No ${d.toLowerCase()} yet" with create CTA`,"Loading state: skeleton table rows",`Search with no results: "No ${d.toLowerCase()} matching..." with clear filter`],entities:[{name:u,fields:(l.fields||[]).map(b=>({name:ot(b),type:oo(b)})),sampleData:js(l)}]})}t.steps.some(u=>{let d=`${u.name??u.title??""} ${u.description??""}`.toLowerCase();return d.includes("landing")||d.includes("hero")||d.includes("marketing")||d.includes("homepage")})&&a.push({name:"Landing Page",type:"landing",route:"/",purpose:`Convince visitors to sign up for ${t.name}. Answer: what is this, who is it for, why should I care.`,informationHierarchy:[`HERO: One sentence about what ${t.name} does \u2014 not "Transform your X", be specific`,"CTA: Sign up / Get started \u2014 one clear action","PROOF: What makes this valuable (features, not buzzwords)","SECONDARY CTA: Repeat the sign up prompt"],interactionStates:["Mobile: hero stacks vertically, nav collapses to hamburger","Desktop: hero side-by-side or centered, full nav"],entities:[]});let m=[];for(let u of e.slice(0,3)){let d=nt(u);(u.fields||[]).find(R=>{let w=ot(R).toLowerCase();return w==="name"||w==="title"})&&m.push(`What if a ${d.toLowerCase()}'s name is 47 characters? Does the layout break?`),m.push(`What if there are 0 ${d.toLowerCase()}s? 1? 500?`)}return t.authModel&&t.authModel!=="none"&&m.push("What does a brand-new user see? (no data, no setup)"),m.push("What if the network is slow? What loads first?"),{appName:t.name,summary:t.summary??"",screens:a,navigation:{style:t.navStyle??"sidebar",items:s},primaryAction:t.primaryAction??null,designDirection:{tone:n.tone??"professional",accentColor:n.accentColor??"blue",navStyle:t.navStyle??"sidebar",fonts:n.fonts??{heading:"Inter",body:"Inter"}},edgeCases:m}}function $a(t,e,o){let n=[];n.push(`# Wireframe sketch for ${t.appName}`),n.push(""),n.push(`**${t.appName}** \u2014 ${t.summary}`),n.push(""),e&&(n.push("## Feedback to apply"),n.push(e),n.push("")),n.push("## Design principles"),n.push(""),n.push("Apply these when deciding layout and hierarchy:"),n.push("1. **Information hierarchy** \u2014 What does the user see first, second, third? The primary action is first. Metrics are second. Everything else is supporting."),n.push("2. **Interaction states** \u2014 Every screen has at least: empty, loading, populated. Show the populated state but add HTML comments noting the others."),n.push("3. **Edge case paranoia** \u2014 What if there are 0 items? 500 items? A 47-character name? Think about these and comment where they matter."),n.push(`4. **Subtraction** \u2014 "As little design as possible" (Dieter Rams). Every element earns its pixels. If removing something doesn't hurt, remove it.`),n.push("5. **Design for trust** \u2014 Clear labels, predictable layout, obvious actions. No mystery meat navigation."),n.push(""),n.push("## Wireframe rules (strict)"),n.push(""),n.push(`Write a **single self-contained HTML file** saved to \`${o}\`.`),n.push(""),n.push("The wireframe must:"),n.push("- Use **system fonts only** (`-apple-system, system-ui, sans-serif`) \u2014 no Google Fonts, no CDN"),n.push("- Use **inline CSS only** \u2014 no external stylesheets, no Tailwind CDN"),n.push("- Look **intentionally rough** \u2014 thin gray borders (#ddd), light backgrounds (#f8f8f8), no color, no shadows"),n.push("- Use **realistic placeholder content** that matches this specific app (sample data provided below) \u2014 NOT lorem ipsum"),n.push("- Include **HTML comments** explaining design decisions"),n.push("- Show **all screens in a single page** using tabs/sections that the user can click through"),n.push("- Be **responsive** \u2014 test that it looks reasonable at both 1200px and 375px widths"),n.push("- Include a small header bar showing: screen name tabs + the design direction summary"),n.push(""),n.push("The wireframe must NOT:"),n.push("- Use any color except grayscale (#333, #666, #999, #ddd, #f8f8f8, white)"),n.push("- Use any external dependencies \u2014 no CDN, no imports, no build step"),n.push("- Look polished \u2014 it should feel like a sketch on a whiteboard, not a finished product"),n.push("- Include decorative elements \u2014 no icons (use text labels), no illustrations, no gradients"),n.push(""),n.push("## Screens to wireframe"),n.push("");for(let s of t.screens){n.push(`### ${s.name} (\`${s.route}\`)`),n.push(`**Purpose**: ${s.purpose}`),n.push(""),n.push("**Information hierarchy** (render in this order, top to bottom):");for(let a of s.informationHierarchy)n.push(`- ${a}`);n.push(""),n.push("**Interaction states** (add HTML comments for non-visible states):");for(let a of s.interactionStates)n.push(`- ${a}`);if(n.push(""),s.entities.length>0){n.push("**Data model and sample content** (use this real data, not lorem ipsum):");for(let a of s.entities)n.push(`
|
|
1762
|
+
**${a.name}** \u2014 fields: ${a.fields.map(r=>`${r.name} (${r.type})`).join(", ")}`),n.push("```json"),n.push(JSON.stringify(a.sampleData,null,2)),n.push("```");n.push("")}}n.push("## Navigation"),n.push(`**Style**: ${t.navigation.style} (use this layout)`),n.push("**Items**:");for(let s of t.navigation.items)n.push(`- ${s.label} \u2192 \`${s.route}\``);if(n.push(""),t.primaryAction&&(n.push("## Primary action (this drives the layout)"),n.push(`- **Action**: ${t.primaryAction.action}`),n.push(`- **Flow**: ${t.primaryAction.flow}`),n.push(`- **Dashboard must show**: ${t.primaryAction.dashboardSurface}`),n.push(""),n.push("The dashboard is an ACTION surface. The primary action should be the most prominent thing on the page \u2014 above the metrics, above the recent items. Users came here to DO something, not to look at numbers."),n.push("")),t.edgeCases.length>0){n.push("## Edge cases to consider"),n.push("Add HTML comments in the wireframe where these matter:");for(let s of t.edgeCases)n.push(`- ${s}`);n.push("")}return n.push("## Design direction (DO NOT apply to wireframe \u2014 this is for reference only)"),n.push(`The final app will use: ${t.designDirection.tone} tone, ${t.designDirection.accentColor} accent, ${t.designDirection.navStyle} nav, ${t.designDirection.fonts.heading} / ${t.designDirection.fonts.body} fonts.`),n.push("The wireframe is grayscale and rough. These tokens will be applied during the actual build."),n.push(""),n.push("## After writing the wireframe"),n.push(`1. Write the file to \`${o}\``),n.push(`2. Open it for the user: \`open "${o}"\``),n.push(`3. Tell the user: "Here's a rough wireframe of your app. Does the layout feel right? Let me know what to change, or I can start building if it's close."`),n.push("4. WAIT for the user's response. Do NOT call mist_init until they approve the layout."),n.join(`
|
|
1763
|
+
`)}function $s(t){return Ne(so(),".mistflow","mockup-state",`${t}.json`)}function La(t){let e=$s(t);if(!Xt(e))return null;try{return JSON.parse(Ms(e,"utf-8"))}catch{return null}}function Ds(t,e){let o=Ne(so(),".mistflow","mockup-state");Os(o,{recursive:!0}),Da($s(t),JSON.stringify(e,null,2))}function Fs(t){let e=Ne(t,".mistflow","mockups");return Xt(e)?Us(e).filter(o=>o.endsWith(".html")).map(o=>Ne(e,o)):[]}var Fa,Ls,ro=x(()=>{"use strict";Te();W();Fa=It.object({planId:It.string().min(1).describe("Plan ID from mist_plan. Required."),projectPath:It.string().optional().describe("Project directory (default: cwd). The mockup is written to <projectPath>/.mistflow/mockups/."),feedback:It.string().optional().describe("User feedback to apply to the next iteration."),approved:It.boolean().optional().describe("Mark the wireframe as approved (terminal \u2014 unlocks scaffolding).")}).refine(t=>!(t.feedback&&t.approved),{message:"Pass either 'feedback' or 'approved' \u2014 not both. Feedback iterates the design; approved locks it in."}),Ls={name:"mist_mockup",description:Uo,inputSchema:Fa,handler:async t=>{let e=t,{planId:o,feedback:n,approved:s}=e,a=Oa(e.projectPath??process.cwd()),r=Ne(so(),".mistflow","plans",`${o}.json`);if(!Xt(r))return c(`Plan not found for planId '${o}'. Call mist_plan to generate a plan first.`,!0);let i;try{i=JSON.parse(Ms(r,"utf-8"))}catch{return c("Failed to read plan file. Call mist_plan again.",!0)}let l=i.plan;if(!l)return c("Plan data is empty. Call mist_plan again.",!0);let p=La(o);p||(p={planId:o,iterationCount:0,approved:!1,screens:[],feedback:[]});let m=Ne(a,".mistflow","mockups");Os(m,{recursive:!0});let u=`mockup-${o}.html`,d=Ne(m,u);if(s){p.approved=!0,Ds(o,p);let k=Xt(m)?Us(m).filter(U=>U.endsWith(".html")).map(U=>Ne(".mistflow","mockups",U)):[];return c(JSON.stringify({status:"approved",message:`Wireframe approved after ${p.iterationCount} iteration(s). Layout direction is locked in.`,mockupFiles:k,nextAction:`Call mist_init with planId='${o}' and path='<absolute project path>' to scaffold the project. Mockups in .mistflow/mockups/ will be used as layout reference during implementation.`}))}p.iterationCount++,n&&p.feedback.push(n);let b=Ua(l);p.screens=b.screens.map(k=>k.name),Ds(o,p);let R=$a(b,n??void 0,d),w=p.iterationCount>=3?"The wireframe is shaping up \u2014 want to keep refining the layout, or start building?":void 0,y=n?`Apply the user's feedback to ${d}. Rewrite the file, open it for review, then ask if they want more changes or are ready to build.`:`Generate the wireframe HTML following the wireframePrompt, write it to ${d}, then open it in the browser. Ask the user if the layout feels right.`;return c(JSON.stringify({status:"wireframe",iterationCount:p.iterationCount,screens:b.screens.map(k=>({name:k.name,type:k.type,route:k.route})),wireframePrompt:R,designDirection:b.designDirection,...w?{nudge:w}:{},mockupFile:u,mockupPath:d,nextAction:y}))}}});function Zt(t){let e=[],o=/([^\s(]+)\((\d+),(\d+)\):\s*error\s+(TS\d+):\s*(.+)/g;for(let i of t.matchAll(o)){let[,l,p,m,u,d]=i;e.push({file:l,line:parseInt(p,10),column:parseInt(m,10),message:`${u}: ${d}`,humanMessage:`There is a type error in ${l} on line ${p}: ${d}`,suggestion:`Check line ${p} in ${l}. ${u==="TS2345"?"The types of the arguments do not match.":`Fix the ${u} error.`}`})}let n=/(?:Error:\s*)?\.\/([^\s:]+):(\d+):(\d+)\s*\n\s*(.+)/g;for(let i of t.matchAll(n)){let[,l,p,m,u]=i;e.some(d=>d.file===l&&d.line===parseInt(p,10))||e.push({file:l,line:parseInt(p,10),column:parseInt(m,10),message:u,humanMessage:`There is an error in ${l} on line ${p}: ${u.trim()}`,suggestion:`Check line ${p} in ${l} and fix the issue.`})}let s=/Module not found:\s*(?:Error:\s*)?Can't resolve ['"]([^'"]+)['"]\s*(?:in\s*['"]?([^'"]+)['"]?)?/g;for(let i of t.matchAll(s)){let[,l,p]=i;e.push({file:p,message:`Module not found: ${l}`,humanMessage:`The file ${p??"your project"} is trying to import '${l}' which is not installed.`,suggestion:`Run npm install ${l}`})}let a=/Package subpath ['"]([^'"]+)['"] is not defined by "exports" in .*?node_modules\/([^/]+(?:\/[^/]+)?)\//g;for(let i of t.matchAll(a)){let[,l,p]=i;e.push({message:`ERR_PACKAGE_PATH_NOT_EXPORTED: ${p}${l}`,humanMessage:`The package '${p}' does not export the subpath '${l}'. This is usually caused by a version conflict between packages that depend on different major versions of '${p}'.`,suggestion:`Add '${p}' 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 r=/SyntaxError:\s*([^\s:]+):\s*(.+?)\s*\((\d+):(\d+)\)/g;for(let i of t.matchAll(r)){let[,l,p,m,u]=i;e.some(d=>d.file===l&&d.line===parseInt(m,10))||e.push({file:l,line:parseInt(m,10),column:parseInt(u,10),message:`SyntaxError: ${p}`,humanMessage:`There is a syntax error in ${l} on line ${m}.`,suggestion:`Check line ${m} in ${l} for a missing closing bracket or unexpected token.`})}return e}var io=x(()=>{"use strict"});import{z as ao}from"zod";import{resolve as qa}from"path";import{spawn as Ba}from"child_process";function Ha(t){return new Promise(e=>{let o=Ba("npm",["run","build"],{cwd:t,stdio:["ignore","pipe","pipe"]}),n="";o.stdout?.on("data",s=>{n+=s.toString()}),o.stderr?.on("data",s=>{n+=s.toString()}),o.on("error",s=>{e({exitCode:127,combined:`${n}
|
|
1764
|
+
${s.message}`})}),o.on("close",s=>{e({exitCode:s??1,combined:n})})})}var za,qs,Bs=x(()=>{"use strict";Te();W();io();za=ao.object({projectPath:ao.string().optional().describe("Absolute path to the project directory. Defaults to cwd."),buildOutput:ao.string().optional().describe("Build output to parse. If omitted, the tool runs `npm run build` in projectPath.")});qs={name:"mist_debug",description:Mo,inputSchema:za,handler:async t=>{let e=t,o=qa(e.projectPath??process.cwd()),n=e.buildOutput??"";if(!e.buildOutput){let r=await Ha(o);if(r.exitCode===0)return c(JSON.stringify({errors:[],rawOutput:"",message:"Build succeeded with no errors."}));n=r.combined}let s=Zt(n),a=n.slice(0,2e3);return s.length===0?c(JSON.stringify({errors:s,rawOutput:a,message:"Build output could not be parsed into structured errors. See rawOutput for the first 2KB."})):c(JSON.stringify({errors:s,rawOutput:a,message:`Found ${s.length} error${s.length===1?"":"s"} in the build output.`}))}}});function en(t,e,o,n=3e3){if(e===void 0)return{stop:()=>{}};let s=0,a=!1,i=setInterval(()=>{a||(s++,t.notification({method:"notifications/progress",params:{progressToken:e,progress:s,message:o()}}).catch(()=>{}))},n);return{stop:()=>{a||(a=!0,clearInterval(i))}}}var lo=x(()=>{"use strict"});function zs(t,e,o){let n=o?.suggestedName||Ga(t),s=e.primaryActor==="both"?"Staff + Customers":e.primaryActor==="staff"?"Staff / Admin":e.primaryActor==="customers"?"End Users":"Users",a=e.audienceType??(e.surfaceType==="internal-tool"?"internal":(e.primaryActor==="customers"||e.primaryActor==="both","b2c")),r=e.surfaceType==="internal-tool"?"Internal tool":e.surfaceType==="marketplace"?"Marketplace":e.surfaceType==="content-site"?"Content site":e.surfaceType==="game"?"Game":"App",i;if(o?.suggestedFeatures&&o.suggestedFeatures.length>0)i=o.suggestedFeatures.map(l=>({name:l.name,description:l.description,checked:l.recommended,source:l.recommended?"explicit":"suggested"}));else{let l=`${t} ${e.primaryAction||""}`;i=[];for(let p of Wa){let m=p.keywords.test(l),u=p.condition(e);(m||u)&&i.push({name:p.name,description:p.description,checked:m,source:m?"explicit":"suggested"})}}return{name:n,audience:s,audienceType:a,surfaceType:r,primaryAction:e.primaryAction||"manage items",features:i,publicLanding:e.publicLanding??!0,authModel:e.authModel??"email",dbProvider:e.dbProvider??"neon",integrations:e.integrations??[],language:o?.language||"English"}}function Hs(t){let e=t.features.filter(i=>i.checked),o=t.features.filter(i=>!i.checked),n={email:"Email sign-up",none:"No login (public)",social:"Social login","invite-only":"Invite-only"},s={neon:"Postgres",turso:"SQLite (legacy)"},a={b2c:"Your customers use this app (business-to-customer)",b2b:"Other businesses sign up for this (SaaS platform)",internal:"Internal team tool (staff only)"},r=[`**${t.name}** \u2014 ${t.surfaceType} for ${t.audience}`,`Audience: ${a[t.audienceType]??t.audienceType}`,`Primary action: ${t.primaryAction}`,`Access: ${n[t.authModel]??t.authModel} | Database: ${s[t.dbProvider]??t.dbProvider}${t.publicLanding?" | Landing page: Yes":""}${t.language&&t.language!=="English"?` | Language: ${t.language}`:""}`,""];if(e.length>0){r.push("**Included:**");for(let i of e)r.push(` \u2713 ${i.name} \u2014 ${i.description}`)}if(t.integrations.length>0&&(r.push(""),r.push(`**Integrations:** ${t.integrations.join(", ")}`)),o.length>0){r.push(""),r.push("**Available to add:**");for(let i of o)r.push(` \u25CB ${i.name} \u2014 ${i.description}`)}return r.join(`
|
|
1765
|
+
`)}function Ga(t){let e=t.match(/\b(?:called|named)\s+["']?([A-Za-z][A-Za-z0-9 ]{1,30})["']?/i);if(e)return co(e[1]);let o=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"]),s=t.toLowerCase().replace(/[^a-z0-9\s]/g,"").split(/\s+/).filter(a=>a.length>2&&!o.has(a)).slice(0,3);return s.length===0?"my-app":s.join("-")}function co(t){return t.toLowerCase().replace(/[^a-z0-9\s]/g,"").trim().replace(/\s+/g,"-")}var Wa,Ws=x(()=>{"use strict";Wa=[{name:"Dashboard",description:"Overview with key stats and today's activity",condition:t=>t.surfaceType==="internal-tool"||t.surfaceType==="customer-app",keywords:/\b(dashboard|overview|home.?page|stats)\b/i},{name:"Landing Page",description:"Public page explaining what this does",condition:t=>t.publicLanding===!0,keywords:/\b(landing|marketing|hero|homepage)\b/i},{name:"Scheduling / Booking",description:"Calendar, time slots, reservations",condition:t=>t.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:t=>t.multiRole===!0||t.primaryActor==="both",keywords:/\b(admin|panel|manage.?user|moderat)\b/i},{name:"User Profiles",description:"Account pages, settings, preferences",condition:t=>t.primaryActor==="customers"||t.primaryActor==="both",keywords:/\b(profile|account|settings|preferences)\b/i},{name:"Search / Browse",description:"Find and filter content or listings",condition:t=>t.surfaceType==="marketplace",keywords:/\b(search|browse|filter|discover|explore)\b/i},{name:"Email Notifications",description:"Welcome emails, alerts, reminders",condition:t=>t.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:t=>t.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:t=>t.integrations?.includes("ai")===!0,keywords:/\b(ai|chatbot|gpt|llm|generat|assistant)\b/i},{name:"Maps / Location",description:"Google Maps, location search, geolocation",condition:t=>t.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:t=>t.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:t=>t.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:t=>t.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:t=>t.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 po(t,e,o){return e.includes(t)?t:o}function ne(t){return String(t??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function st(t,e){return typeof t!="string"?e:/^#[0-9a-fA-F]{3}([0-9a-fA-F]{3})?$/.test(t.trim())?t.trim():e}function Ya(t){let e=new Set;for(let n of t)n.fonts?.display&&e.add(n.fonts.display),n.fonts?.body&&e.add(n.fonts.body);return e.size===0?"":`https://fonts.googleapis.com/css2?${[...e].map(n=>`family=${n.trim().replace(/\s+/g,"+").replace(/[^A-Za-z0-9+]/g,"")}:wght@400;700`).join("&")}&display=swap`}function Gs(t){let e=(t||"").trim(),o=e.toLowerCase(),n=/mono|courier|code/.test(o)?"ui-monospace, monospace":/serif|garamond|bodoni|fraunces|playfair|lora|sentient|migra|sectra|cormorant|abril|crimson/.test(o)?"Georgia, serif":"system-ui, sans-serif";return e?`"${e.replace(/"/g,"")}", ${n}`:n}function Qa(t){switch(t){case"sharp":return{card:"0px",button:"0px",chip:"0px"};case"pill":return{card:"20px",button:"999px",chip:"999px"};case"organic":return{card:"4px 24px 4px 24px",button:"24px 4px 24px 4px",chip:"12px 2px 12px 2px"};default:return{card:"10px",button:"8px",chip:"6px"}}}function Xa(){let t=`url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='180' height='180'><filter id='n'><feTurbulence type='fractalNoise' baseFrequency='0.85' numOctaves='2' stitchTiles='stitch'/><feColorMatrix values='0 0 0 0 0.3 0 0 0 0 0.3 0 0 0 0 0.3 0 0 0 0.55 0'/></filter><rect width='100%25' height='100%25' filter='url(%23n)'/></svg>")`;return`
|
|
1766
|
+
.card-hero { position: relative; overflow: hidden; isolation: isolate; }
|
|
1767
|
+
.card-hero::before {
|
|
1768
|
+
content: "";
|
|
1769
|
+
position: absolute;
|
|
1770
|
+
inset: 0;
|
|
1771
|
+
pointer-events: none;
|
|
1772
|
+
z-index: 0;
|
|
1773
|
+
opacity: 0;
|
|
1774
|
+
mix-blend-mode: overlay;
|
|
1775
|
+
}
|
|
1776
|
+
.card-hero > * { position: relative; z-index: 1; }
|
|
1777
|
+
|
|
1778
|
+
.card-hero.texture-flat::before { opacity: 0; }
|
|
1779
|
+
|
|
1780
|
+
.card-hero.texture-paper-grain::before {
|
|
1781
|
+
opacity: 0.35;
|
|
1782
|
+
background-image: ${t};
|
|
1783
|
+
mix-blend-mode: multiply;
|
|
1784
|
+
}
|
|
1785
|
+
.card-hero.texture-film-grain::before {
|
|
1786
|
+
opacity: 0.5;
|
|
1787
|
+
background-image: ${t};
|
|
1788
|
+
mix-blend-mode: overlay;
|
|
1789
|
+
}
|
|
1790
|
+
.card-hero.texture-noise::before {
|
|
1791
|
+
opacity: 0.25;
|
|
1792
|
+
background-image: ${t};
|
|
1793
|
+
mix-blend-mode: overlay;
|
|
1794
|
+
}
|
|
1795
|
+
.card-hero.texture-scanlines::before {
|
|
1796
|
+
opacity: 0.4;
|
|
1797
|
+
background: repeating-linear-gradient(
|
|
1798
|
+
to bottom,
|
|
1799
|
+
rgba(255,255,255,0.08) 0 1px,
|
|
1800
|
+
transparent 1px 3px
|
|
1801
|
+
);
|
|
1802
|
+
mix-blend-mode: screen;
|
|
1803
|
+
}
|
|
1804
|
+
.card-hero.texture-gradient-mesh::before {
|
|
1805
|
+
opacity: 1;
|
|
1806
|
+
background:
|
|
1807
|
+
radial-gradient(circle at 15% 20%, rgba(255,255,255,0.18), transparent 48%),
|
|
1808
|
+
radial-gradient(circle at 85% 80%, rgba(0,0,0,0.22), transparent 55%),
|
|
1809
|
+
radial-gradient(circle at 60% 10%, rgba(255,255,255,0.12), transparent 40%);
|
|
1810
|
+
mix-blend-mode: normal;
|
|
1811
|
+
}
|
|
1812
|
+
.card-hero.texture-glassmorphic {
|
|
1813
|
+
position: relative;
|
|
1814
|
+
}
|
|
1815
|
+
.card-hero.texture-glassmorphic::before {
|
|
1816
|
+
opacity: 1;
|
|
1817
|
+
background:
|
|
1818
|
+
radial-gradient(circle at 20% 30%, rgba(255,255,255,0.25), transparent 42%),
|
|
1819
|
+
radial-gradient(circle at 80% 70%, rgba(255,255,255,0.15), transparent 45%);
|
|
1820
|
+
backdrop-filter: blur(14px);
|
|
1821
|
+
mix-blend-mode: normal;
|
|
1822
|
+
}
|
|
1823
|
+
`}function Za(t,e,o,n){let s=st(t.colors?.bg??"","#0f0f0f"),a=st(t.colors?.fg??"","#f5f5f5"),r=st(t.colors?.accent??"","#7c9cff"),i=ne(t.name),l=ne(t.hero_headline||t.name),p=ne(t.body_sample||t.summary||""),m=ne(t.cta_text||"Continue"),u=`<div class="hero-eyebrow" style="font-family:${o}">${i.toUpperCase()}</div>`,d=`<h2 class="hero-headline" style="font-family:${e}">${l}</h2>`,b=`<p class="hero-body" style="font-family:${o}">${p}</p>`,R=`<button class="hero-cta" style="background:${r};color:${s};font-family:${o};border-radius:${n.button}">${m}</button>`,w=po(t.hero_treatment,Va,"typographic");if(w==="terminal"){let y=`"${(t.fonts?.display??"JetBrains Mono").replace(/"/g,"")}", ui-monospace, monospace`;return`
|
|
1824
|
+
${u}
|
|
1825
|
+
<div class="hero-terminal-lines" style="font-family:${y};color:${a}">
|
|
1826
|
+
<div>$ status --all</div>
|
|
1827
|
+
<div>api.service.......<span style="color:${r}">OK</span></div>
|
|
1828
|
+
<div>worker.queue......<span style="color:${r}">OK</span></div>
|
|
1829
|
+
<div>db.primary.......<span style="color:${r}">OK</span></div>
|
|
1830
|
+
</div>
|
|
1831
|
+
${d}
|
|
1832
|
+
${b}
|
|
1833
|
+
<div class="hero-cta-row">${R}</div>
|
|
1834
|
+
`}return w==="split-panel"?`
|
|
1835
|
+
<div class="hero-split">
|
|
1836
|
+
<div class="hero-split-left" style="background:${r};color:${s};font-family:${e}">
|
|
1837
|
+
<div class="hero-split-mark" style="font-family:${o};color:${s}">${i[0]??"\xB7"}</div>
|
|
1838
|
+
</div>
|
|
1839
|
+
<div class="hero-split-right">
|
|
1840
|
+
${u}
|
|
1841
|
+
${d}
|
|
1842
|
+
${b}
|
|
1843
|
+
<div class="hero-cta-row">${R}</div>
|
|
1844
|
+
</div>
|
|
1845
|
+
</div>
|
|
1846
|
+
`:w==="full-bleed-photo"?`
|
|
1847
|
+
<div class="hero-photo" style="background: linear-gradient(160deg, ${r}30 0%, ${a}08 35%, ${s} 100%), ${s}">
|
|
1848
|
+
<span class="hero-photo-label" style="font-family:${o};color:${a}">photo slot</span>
|
|
1849
|
+
</div>
|
|
1850
|
+
${u}
|
|
1851
|
+
${d}
|
|
1852
|
+
${b}
|
|
1853
|
+
<div class="hero-cta-row">${R}</div>
|
|
1854
|
+
`:w==="magazine-hero"?`
|
|
1855
|
+
${u}
|
|
1856
|
+
<h2 class="hero-headline hero-headline-mag" style="font-family:${e}">${l}</h2>
|
|
1857
|
+
<div class="hero-rule" style="background:${a}"></div>
|
|
1858
|
+
<p class="hero-body hero-body-mag" style="font-family:${o}">${p}</p>
|
|
1859
|
+
<div class="hero-byline" style="font-family:${o};color:${a}">\u2014 Volume 01 \xB7 Issue 01</div>
|
|
1860
|
+
<div class="hero-cta-row">${R}</div>
|
|
1861
|
+
`:`
|
|
1862
|
+
${u}
|
|
1863
|
+
${d}
|
|
1864
|
+
${b}
|
|
1865
|
+
<div class="hero-cta-row">${R}</div>
|
|
1866
|
+
`}function Vs(t,e){let o=Ya(e),n=e.map(s=>{let a=st(s.colors?.bg??"","#0f0f0f"),r=st(s.colors?.fg??"","#f5f5f5"),i=st(s.colors?.accent??"","#7c9cff"),l=Gs(s.fonts?.display??""),p=Gs(s.fonts?.body??""),m=po(s.shape_lang,Ja,"soft"),u=po(s.texture,Ka,"flat"),d=Qa(m),b=Za(s,l,p,d),R=ne(s.name),w=ne(s.id),y=ne(s.fonts?.display??""),k=ne(s.fonts?.body??""),U=ne(s.summary||""),Y=ne(s.decoration_hint||""),G=(ie,B)=>`<div class="card-meta-row"><span class="card-meta-label">${ie}</span><span class="card-meta-value">${B}</span></div>`;return` <article class="card" data-direction-id="${w}" style="border-radius:${d.card}">
|
|
1867
|
+
<div class="card-hero texture-${u}" style="background:${a};color:${r}">${b}
|
|
1868
|
+
</div>
|
|
1869
|
+
<div class="card-meta" style="border-top-color:${r}14">
|
|
1870
|
+
<div class="card-meta-title">${R}</div>
|
|
1871
|
+
<p class="card-meta-summary">${U}</p>
|
|
1872
|
+
${G("Fonts",`${y||"\u2014"} <span class="sep">\xB7</span> ${k||"\u2014"}`)}
|
|
1873
|
+
${G("Palette",`
|
|
1874
|
+
<span class="card-meta-swatches">
|
|
1875
|
+
<span class="card-meta-swatch" title="${a}" style="background:${a}"></span>
|
|
1876
|
+
<span class="card-meta-swatch" title="${r}" style="background:${r}"></span>
|
|
1877
|
+
<span class="card-meta-swatch" title="${i}" style="background:${i}"></span>
|
|
1878
|
+
</span>
|
|
1879
|
+
`)}
|
|
1880
|
+
${G("Shape",`<span class="chip" style="border-radius:${d.chip}">${m}</span>`)}
|
|
1881
|
+
${G("Texture",`<span class="chip" style="border-radius:${d.chip}">${ne(u)}</span>`)}
|
|
1882
|
+
${Y?G("Decoration",ne(Y)):""}
|
|
1883
|
+
${G("Pick with",`<code>${R}</code>`)}
|
|
1884
|
+
</div>
|
|
1885
|
+
</article>`}).join(`
|
|
1886
|
+
`);return`<!DOCTYPE html>
|
|
1887
|
+
<html lang="en">
|
|
1888
|
+
<head>
|
|
1889
|
+
<meta charset="UTF-8" />
|
|
1890
|
+
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
|
1891
|
+
<title>Design directions \u2014 ${ne(t)}</title>
|
|
1892
|
+
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
|
1893
|
+
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
|
1894
|
+
${o?`<link rel="stylesheet" href="${o}" />`:""}
|
|
1895
|
+
<style>
|
|
1896
|
+
:root {
|
|
1897
|
+
--chrome-bg: #f4f3ef;
|
|
1898
|
+
--chrome-ink: #1a1a1a;
|
|
1899
|
+
--chrome-muted: #6b6b6b;
|
|
1900
|
+
--chrome-rule: #e4e2dc;
|
|
1901
|
+
--card-shadow: 0 1px 2px rgba(0,0,0,0.04), 0 20px 40px -20px rgba(0,0,0,0.12);
|
|
1902
|
+
--chrome-font: "S\xF6hne", ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
|
|
1903
|
+
}
|
|
1904
|
+
* { box-sizing: border-box; }
|
|
1905
|
+
html, body { margin: 0; padding: 0; }
|
|
1906
|
+
body {
|
|
1907
|
+
background: var(--chrome-bg);
|
|
1908
|
+
color: var(--chrome-ink);
|
|
1909
|
+
font-family: var(--chrome-font);
|
|
1910
|
+
-webkit-font-smoothing: antialiased;
|
|
1911
|
+
line-height: 1.5;
|
|
1912
|
+
min-height: 100vh;
|
|
1913
|
+
}
|
|
1914
|
+
.page { max-width: 1280px; margin: 0 auto; padding: 56px 28px 96px; }
|
|
1915
|
+
header.page-header { margin-bottom: 48px; max-width: 820px; }
|
|
1916
|
+
.eyebrow {
|
|
1917
|
+
font-size: 12px; letter-spacing: 0.14em; text-transform: uppercase;
|
|
1918
|
+
color: var(--chrome-muted); font-weight: 500;
|
|
1919
|
+
display: inline-flex; align-items: center; gap: 10px;
|
|
1920
|
+
}
|
|
1921
|
+
.eyebrow-dot { width: 6px; height: 6px; border-radius: 999px; background: #111; display: inline-block; }
|
|
1922
|
+
h1.page-title {
|
|
1923
|
+
font-size: clamp(28px, 3.6vw, 42px); font-weight: 600; letter-spacing: -0.02em;
|
|
1924
|
+
line-height: 1.1; margin: 16px 0 14px;
|
|
1925
|
+
}
|
|
1926
|
+
p.page-sub { color: var(--chrome-muted); font-size: 16px; margin: 0; max-width: 680px; }
|
|
1927
|
+
p.page-sub strong { color: var(--chrome-ink); font-weight: 600; }
|
|
1928
|
+
.grid {
|
|
1929
|
+
display: grid;
|
|
1930
|
+
grid-template-columns: repeat(2, minmax(0, 1fr));
|
|
1931
|
+
gap: 28px;
|
|
1932
|
+
}
|
|
1933
|
+
@media (max-width: 920px) {
|
|
1934
|
+
.grid { grid-template-columns: 1fr; gap: 20px; }
|
|
1935
|
+
.page { padding: 36px 18px 72px; }
|
|
1936
|
+
}
|
|
1937
|
+
|
|
1938
|
+
/* \u2500\u2500 Card shell \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
|
|
1939
|
+
.card {
|
|
1940
|
+
background: #fff;
|
|
1941
|
+
box-shadow: var(--card-shadow);
|
|
1942
|
+
overflow: hidden;
|
|
1943
|
+
display: flex;
|
|
1944
|
+
flex-direction: column;
|
|
1945
|
+
transition: transform 180ms ease, box-shadow 180ms ease;
|
|
1946
|
+
}
|
|
1947
|
+
.card:hover {
|
|
1948
|
+
transform: translateY(-2px);
|
|
1949
|
+
box-shadow: 0 1px 2px rgba(0,0,0,0.05), 0 28px 56px -20px rgba(0,0,0,0.18);
|
|
1950
|
+
}
|
|
1951
|
+
|
|
1952
|
+
/* \u2500\u2500 Hero block \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
|
|
1953
|
+
.card-hero {
|
|
1954
|
+
padding: 40px 36px 32px;
|
|
1955
|
+
min-height: 380px;
|
|
1956
|
+
display: flex;
|
|
1957
|
+
flex-direction: column;
|
|
1958
|
+
gap: 12px;
|
|
1959
|
+
}
|
|
1960
|
+
.hero-eyebrow {
|
|
1961
|
+
font-size: 11px;
|
|
1962
|
+
letter-spacing: 0.18em;
|
|
1963
|
+
opacity: 0.7;
|
|
1964
|
+
font-weight: 500;
|
|
1965
|
+
}
|
|
1966
|
+
.hero-headline {
|
|
1967
|
+
font-size: clamp(30px, 2.8vw, 42px);
|
|
1968
|
+
line-height: 1.05;
|
|
1969
|
+
letter-spacing: -0.01em;
|
|
1970
|
+
margin: 0;
|
|
1971
|
+
font-weight: 700;
|
|
1972
|
+
}
|
|
1973
|
+
.hero-body {
|
|
1974
|
+
font-size: 15px;
|
|
1975
|
+
line-height: 1.55;
|
|
1976
|
+
opacity: 0.85;
|
|
1977
|
+
margin: 0;
|
|
1978
|
+
max-width: 44ch;
|
|
1979
|
+
}
|
|
1980
|
+
.hero-cta-row {
|
|
1981
|
+
margin-top: auto;
|
|
1982
|
+
padding-top: 20px;
|
|
1983
|
+
display: flex;
|
|
1984
|
+
align-items: center;
|
|
1985
|
+
gap: 12px;
|
|
1986
|
+
flex-wrap: wrap;
|
|
1987
|
+
}
|
|
1988
|
+
.hero-cta {
|
|
1989
|
+
border: 0;
|
|
1990
|
+
padding: 12px 22px;
|
|
1991
|
+
font-size: 14px;
|
|
1992
|
+
font-weight: 600;
|
|
1993
|
+
cursor: default;
|
|
1994
|
+
letter-spacing: 0.01em;
|
|
1995
|
+
}
|
|
1996
|
+
|
|
1997
|
+
/* \u2500\u2500 Hero treatment: terminal \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
|
|
1998
|
+
.hero-terminal-lines {
|
|
1999
|
+
font-size: 13px;
|
|
2000
|
+
line-height: 1.7;
|
|
2001
|
+
opacity: 0.85;
|
|
2002
|
+
padding: 12px 14px;
|
|
2003
|
+
border: 1px solid currentColor;
|
|
2004
|
+
border-opacity: 0.3;
|
|
2005
|
+
background: rgba(0,0,0,0.18);
|
|
2006
|
+
margin-bottom: 6px;
|
|
2007
|
+
}
|
|
2008
|
+
.hero-terminal-lines > div { white-space: pre; }
|
|
2009
|
+
|
|
2010
|
+
/* \u2500\u2500 Hero treatment: split-panel \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
|
|
2011
|
+
.hero-split {
|
|
2012
|
+
display: flex;
|
|
2013
|
+
flex: 1;
|
|
2014
|
+
margin: -40px -36px -32px;
|
|
2015
|
+
min-height: 380px;
|
|
2016
|
+
}
|
|
2017
|
+
.hero-split-left {
|
|
2018
|
+
width: 32%;
|
|
2019
|
+
display: flex;
|
|
2020
|
+
align-items: center;
|
|
2021
|
+
justify-content: center;
|
|
2022
|
+
padding: 24px;
|
|
2023
|
+
}
|
|
2024
|
+
.hero-split-mark {
|
|
2025
|
+
font-size: 96px;
|
|
2026
|
+
font-weight: 800;
|
|
2027
|
+
line-height: 1;
|
|
2028
|
+
}
|
|
2029
|
+
.hero-split-right {
|
|
2030
|
+
flex: 1;
|
|
2031
|
+
padding: 40px 36px 32px;
|
|
2032
|
+
display: flex;
|
|
2033
|
+
flex-direction: column;
|
|
2034
|
+
gap: 12px;
|
|
2035
|
+
}
|
|
2036
|
+
|
|
2037
|
+
/* \u2500\u2500 Hero treatment: full-bleed-photo \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
|
|
2038
|
+
.hero-photo {
|
|
2039
|
+
height: 160px;
|
|
2040
|
+
margin: -40px -36px 20px;
|
|
2041
|
+
position: relative;
|
|
2042
|
+
display: flex;
|
|
2043
|
+
align-items: flex-end;
|
|
2044
|
+
justify-content: flex-start;
|
|
2045
|
+
padding: 18px;
|
|
2046
|
+
}
|
|
2047
|
+
.hero-photo-label {
|
|
2048
|
+
font-size: 10px;
|
|
2049
|
+
letter-spacing: 0.2em;
|
|
2050
|
+
text-transform: uppercase;
|
|
2051
|
+
opacity: 0.4;
|
|
2052
|
+
}
|
|
2053
|
+
|
|
2054
|
+
/* \u2500\u2500 Hero treatment: magazine-hero \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
|
|
2055
|
+
.hero-headline-mag {
|
|
2056
|
+
font-size: clamp(34px, 3.2vw, 48px);
|
|
2057
|
+
font-weight: 700;
|
|
2058
|
+
letter-spacing: -0.02em;
|
|
2059
|
+
}
|
|
2060
|
+
.hero-rule {
|
|
2061
|
+
height: 2px;
|
|
2062
|
+
width: 48px;
|
|
2063
|
+
margin: 8px 0;
|
|
2064
|
+
opacity: 0.8;
|
|
2065
|
+
}
|
|
2066
|
+
.hero-body-mag {
|
|
2067
|
+
font-style: italic;
|
|
2068
|
+
max-width: 40ch;
|
|
2069
|
+
}
|
|
2070
|
+
.hero-byline {
|
|
2071
|
+
font-size: 11px;
|
|
2072
|
+
letter-spacing: 0.16em;
|
|
2073
|
+
text-transform: uppercase;
|
|
2074
|
+
opacity: 0.6;
|
|
2075
|
+
margin-top: 4px;
|
|
2076
|
+
}
|
|
2077
|
+
|
|
2078
|
+
${Xa()}
|
|
2079
|
+
|
|
2080
|
+
/* \u2500\u2500 Card meta footer \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
|
|
2081
|
+
.card-meta {
|
|
2082
|
+
padding: 22px 28px 26px;
|
|
2083
|
+
border-top: 1px solid var(--chrome-rule);
|
|
2084
|
+
display: flex;
|
|
2085
|
+
flex-direction: column;
|
|
2086
|
+
gap: 10px;
|
|
2087
|
+
background: #fff;
|
|
2088
|
+
font-family: var(--chrome-font);
|
|
2089
|
+
}
|
|
2090
|
+
.card-meta-title {
|
|
2091
|
+
font-size: 15px;
|
|
2092
|
+
font-weight: 600;
|
|
2093
|
+
color: var(--chrome-ink);
|
|
2094
|
+
letter-spacing: -0.01em;
|
|
2095
|
+
}
|
|
2096
|
+
.card-meta-summary {
|
|
2097
|
+
font-size: 13px;
|
|
2098
|
+
color: var(--chrome-muted);
|
|
2099
|
+
line-height: 1.5;
|
|
2100
|
+
margin: -2px 0 6px;
|
|
2101
|
+
}
|
|
2102
|
+
.card-meta-row {
|
|
2103
|
+
display: flex;
|
|
2104
|
+
align-items: center;
|
|
2105
|
+
gap: 14px;
|
|
2106
|
+
font-size: 13px;
|
|
2107
|
+
}
|
|
2108
|
+
.card-meta-label {
|
|
2109
|
+
flex-shrink: 0;
|
|
2110
|
+
width: 82px;
|
|
2111
|
+
color: var(--chrome-muted);
|
|
2112
|
+
font-size: 11px;
|
|
2113
|
+
letter-spacing: 0.1em;
|
|
2114
|
+
text-transform: uppercase;
|
|
2115
|
+
font-weight: 500;
|
|
2116
|
+
}
|
|
2117
|
+
.card-meta-value {
|
|
2118
|
+
color: var(--chrome-ink);
|
|
2119
|
+
font-size: 13px;
|
|
2120
|
+
display: inline-flex;
|
|
2121
|
+
align-items: center;
|
|
2122
|
+
gap: 8px;
|
|
2123
|
+
}
|
|
2124
|
+
.card-meta-value .sep { color: var(--chrome-muted); margin: 0 2px; }
|
|
2125
|
+
.card-meta-swatches {
|
|
2126
|
+
display: inline-flex;
|
|
2127
|
+
gap: 6px;
|
|
2128
|
+
}
|
|
2129
|
+
.card-meta-swatch {
|
|
2130
|
+
width: 20px;
|
|
2131
|
+
height: 20px;
|
|
2132
|
+
border-radius: 999px;
|
|
2133
|
+
display: inline-block;
|
|
2134
|
+
box-shadow: inset 0 0 0 1px rgba(0,0,0,0.08);
|
|
2135
|
+
}
|
|
2136
|
+
.chip {
|
|
2137
|
+
display: inline-block;
|
|
2138
|
+
background: #f0efe9;
|
|
2139
|
+
padding: 3px 10px;
|
|
2140
|
+
font-size: 11px;
|
|
2141
|
+
letter-spacing: 0.04em;
|
|
2142
|
+
font-weight: 500;
|
|
2143
|
+
color: var(--chrome-ink);
|
|
2144
|
+
}
|
|
2145
|
+
.card-meta code {
|
|
2146
|
+
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
|
|
2147
|
+
background: #f0efe9;
|
|
2148
|
+
padding: 2px 8px;
|
|
2149
|
+
border-radius: 6px;
|
|
2150
|
+
font-size: 12px;
|
|
2151
|
+
color: #222;
|
|
2152
|
+
}
|
|
2153
|
+
footer.page-footer {
|
|
2154
|
+
margin-top: 56px;
|
|
2155
|
+
padding-top: 28px;
|
|
2156
|
+
border-top: 1px solid var(--chrome-rule);
|
|
2157
|
+
color: var(--chrome-muted);
|
|
2158
|
+
font-size: 14px;
|
|
2159
|
+
line-height: 1.6;
|
|
2160
|
+
display: flex;
|
|
2161
|
+
gap: 28px;
|
|
2162
|
+
flex-wrap: wrap;
|
|
2163
|
+
align-items: flex-start;
|
|
2164
|
+
justify-content: space-between;
|
|
2165
|
+
}
|
|
2166
|
+
footer.page-footer .escape {
|
|
2167
|
+
padding: 10px 16px;
|
|
2168
|
+
border: 1px dashed var(--chrome-rule);
|
|
2169
|
+
border-radius: 10px;
|
|
2170
|
+
background: #fff;
|
|
2171
|
+
color: var(--chrome-ink);
|
|
2172
|
+
font-size: 13px;
|
|
2173
|
+
}
|
|
2174
|
+
footer .escape code {
|
|
2175
|
+
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
|
|
2176
|
+
font-size: 12px;
|
|
2177
|
+
background: #f0efe9;
|
|
2178
|
+
padding: 2px 6px;
|
|
2179
|
+
border-radius: 4px;
|
|
2180
|
+
}
|
|
2181
|
+
</style>
|
|
2182
|
+
</head>
|
|
2183
|
+
<body>
|
|
2184
|
+
<div class="page">
|
|
2185
|
+
<header class="page-header">
|
|
2186
|
+
<div class="eyebrow"><span class="eyebrow-dot"></span>Mistflow \xB7 design direction</div>
|
|
2187
|
+
<h1 class="page-title">How should <strong>${ne(t)}</strong> feel?</h1>
|
|
2188
|
+
<p class="page-sub">Each card commits to a different extreme \u2014 different fonts, colors, hero layout, corner radius, texture, and voice. Pick one by telling your coding assistant its name, or describe your own.</p>
|
|
2189
|
+
</header>
|
|
2190
|
+
|
|
2191
|
+
<div class="grid">
|
|
2192
|
+
${n}
|
|
2193
|
+
</div>
|
|
2194
|
+
|
|
2195
|
+
<footer class="page-footer">
|
|
2196
|
+
<div>
|
|
2197
|
+
<div><strong>How to pick</strong></div>
|
|
2198
|
+
<div>Reply to your assistant with the direction name \u2014 e.g. “pick <em>Morning Paper</em>.” The final DESIGN.md will honor the fonts, palette, layout, and voice you see here.</div>
|
|
2199
|
+
</div>
|
|
2200
|
+
<div class="escape">
|
|
2201
|
+
<strong>None fit?</strong> Tell your assistant <code>describe your own</code> and give a short description.
|
|
2202
|
+
</div>
|
|
2203
|
+
</footer>
|
|
2204
|
+
</div>
|
|
2205
|
+
</body>
|
|
2206
|
+
</html>
|
|
2207
|
+
`}var Va,Ja,Ka,Js=x(()=>{"use strict";Va=["typographic","split-panel","terminal","full-bleed-photo","magazine-hero"],Ja=["sharp","soft","pill","organic"],Ka=["flat","paper-grain","film-grain","scanlines","gradient-mesh","noise","glassmorphic"]});import{z as _}from"zod";import{existsSync as _t,mkdirSync as nn,readFileSync as Ys,readdirSync as el,statSync as tl,unlinkSync as nl,writeFileSync as on}from"fs";import{dirname as ol,isAbsolute as sl,join as oe}from"path";import{homedir as je}from"os";import{createHash as rl,createHmac as Qs,randomBytes as il,randomUUID as Ks,timingSafeEqual as al}from"crypto";function Xs(){let t=oe(je(),".mistflow","confirm-secret");if(_t(t))try{return Buffer.from(Ys(t,"utf-8").trim(),"hex")}catch{}let e=il(32);return nn(oe(je(),".mistflow"),{recursive:!0}),on(t,e.toString("hex"),{mode:384}),e}function Zs(t){return rl("sha256").update(t.trim().toLowerCase()).digest("hex").slice(0,16)}function cl(t,e){let o={cwd:t,d:Zs(e),exp:Date.now()+ll},n=Buffer.from(JSON.stringify(o)).toString("base64url"),s=Qs("sha256",Xs()).update(n).digest("base64url");return`${n}.${s}`}function pl(t,e,o){let n=t.split(".");if(n.length!==2)return!1;let[s,a]=n,r=Qs("sha256",Xs()).update(s).digest("base64url"),i=Buffer.from(a),l=Buffer.from(r);if(i.length!==l.length||!al(i,l))return!1;try{let p=JSON.parse(Buffer.from(s,"base64url").toString("utf-8"));return!(typeof p.exp!="number"||Date.now()>p.exp||p.cwd!==e||p.d!==Zs(o))}catch{return!1}}function dl(t){let e=t,o=je(),n=!1;for(let s=0;s<64;s++){if(_t(oe(e,"mistflow.json")))return"mistflow";if(!n&&_t(oe(e,"package.json"))&&(n=!0),e===o)break;let a=ol(e);if(a===e)break;e=a}return n?"foreign":"none"}function ul(t){let e=je(),o=t.replace(/\/+$/,"");if(o===e||o==="/"||o===""||o==="/tmp"||o==="/private/tmp")return!0;let n=["Desktop","Documents","Downloads"];for(let s of n)if(o===oe(e,s))return!0;return!1}function hl(t){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[n,s]of e)if(n.test(t))return s;return t.replace(/[?.,!]/g,"").split(/\s+/).filter(n=>!["what","how","do","does","is","are","the","a","an","would","should","you","your","for","this","that","to","of","or","and","want","like","prefer"].includes(n.toLowerCase())).slice(0,2).join(" ").slice(0,12)||"Option"}function gl(t){let e=oe(je(),".mistflow","plans",`${t}.json`);if(!_t(e))return null;try{return JSON.parse(Ys(e,"utf-8")).plan??null}catch{return null}}async function fl(t){for(let n=0;n<60;n++){try{let s=await En(t.design_conversation_id);if(s.status==="ready")return{status:"design_clarify",design_conversation_id:t.design_conversation_id,directions:s.directions,plan:s.plan,methodology:s.methodology};if(s.status==="failed")return{status:"ready",plan:s.plan,methodology:s.methodology}}catch(s){let a=s instanceof Error?s.message:String(s);if(a.toLowerCase().includes("not found"))return{status:"ready",plan:t.plan,methodology:t.methodology};console.error(`[plan] directions poll attempt ${n+1} failed: ${a}`)}await new Promise(s=>setTimeout(s,2e3))}return console.error("[plan] directions poll exhausted, falling back to ready"),{status:"ready",plan:t.plan,methodology:t.methodology}}async function yl(t,e){let{description:o,projectPath:n,conversationId:s,answers:a,existingPlan:r,existingPlanId:i,templateToken:l,remixDescription:p,autonomous:m,language:u,landingDesign:d,appStyle:b,brandMentioned:R,confirmToken:w,urlChoice:y,designConversationId:k,designDirection:U}=t;if(s&&!o&&!a&&!k&&!U&&!r&&!i&&!l)try{let h=await qt(s);return h.status==="clarify_pending"?c(JSON.stringify({status:"running",conversationId:s,phase:"generating_questions",nextAction:`Still generating. Call mist_plan with { projectPath, conversationId: "${s}" } again in ~10-15s.`})):c(JSON.stringify(h))}catch(h){let g=h instanceof Error?h.message:String(h);return c(`Could not poll plan conversation '${s}': ${g}`,!0)}let Y=o??"";if(!Y.trim()&&!s&&!r&&!i&&!l)return c("mist_plan requires a `description` for the first call (the user's app idea). Pass { conversationId } alone to poll an in-flight call, or along with { answers } to submit responses.",!0);let G=r;if(!G&&i&&(G=gl(i)??void 0,!G))return c("Your previous plan is no longer available. Please describe your app again to generate a new plan.",!0);let ie=s;if(!J())return c("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let B;if(!ie&&!G&&!l){if(!sl(n))return c(`projectPath must be an absolute path \u2014 received '${n}'. Pass the full absolute path to the user's project directory (e.g. /Users/alice/projects/my-app).`,!0);let h=dl(n);if(h!=="mistflow"&&ul(n))return c(JSON.stringify({status:"unsafe_cwd",projectPath:n,instruction:[`The projectPath you passed (${n}) 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 ${n}/<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(`
|
|
2208
|
+
`)}),!0);if(h==="foreign"&&!R){if(!(w?pl(w,n,Y):!1)){let P=cl(n,Y);return c(JSON.stringify({status:"confirm_new_project",projectPath:n,description:Y,confirmToken:P,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.",w?"The previous confirmToken was invalid, expired, or did not match the current directory/description. Use the fresh token above.":""].filter(Boolean).join(`
|
|
2209
|
+
`)}))}B="Note: You're inside an existing project. Mistflow will create the new app in a subdirectory. It won't modify this codebase."}else h==="foreign"&&R&&(B="Note: You're inside an existing project. Mistflow will create the new app in a subdirectory. It won't modify this codebase.")}if(l)try{if(!(await Wn(l)).plan)return c("This template has no plan to fork. Try a different template.",!0);let g=await Gn(l),P=g.plan,I="";if(p&&g.has_source)try{let ee=await Bt(g.plan,p),$=ee.plan??ee,Dt=ee.diff,q=$?.steps??[],yn=new Set([...(Dt?.added??[]).map(pe=>pe.number),...(Dt?.modified??[]).map(pe=>pe.number)]),_e=q.map(pe=>{let fi=pe.number;return yn.has(fi)?{...pe,status:"pending"}:{...pe,status:"completed",source:"forked"}});$.steps=_e,P=$;let Fe=_e.filter(pe=>pe.status==="pending").length;I=` Remixed: ${_e.filter(pe=>pe.status==="completed").length} steps unchanged, ${Fe} steps need re-implementation.`}catch(ee){console.error("[plan] Remix failed, using original plan:",ee),I=" (Remix failed \u2014 using original plan. You can modify it later.)"}let V=Ks(),F=oe(je(),".mistflow","plans");nn(F,{recursive:!0}),on(oe(F,`${V}.json`),JSON.stringify({plan:P,projectId:g.id,sourceDeploymentId:g.source_deployment_id,forkToken:g.fork_token,requiredEnvVars:g.required_env_vars,dbProvider:g.db_provider}));let X=P?.name??"forked-app",Z=g.has_source,ht=Z?"Source code will be restored during init. Run init promptly \u2014 the download token expires in 1 hour.":"",Le=g.deploy_url?` Instant deploy started \u2014 your app will be live at ${g.deploy_url} in under a minute.`:"";return c(JSON.stringify({planId:V,forkedFrom:g.forked_from,projectId:g.id,hasSource:Z,deployUrl:g.deploy_url,message:`Forked "${g.forked_from}" into your workspace.${I}${Le} ${ht} NEXT: Call mist_init, name='${X}', and planId='${V}' to create the project now.`}))}catch(h){let g=h instanceof Error?h.message:"Failed to fork template";return c(g,!0)}if(G){let h;try{h=await Bt(G,Y)}catch(F){let X=F instanceof Error?F.message:"Failed to modify plan";return c(X,!0)}let g=h.plan,P=h.diff,I=[];if(P?.added?.length){let F=P.added.map(X=>X.title);I.push(`Added ${F.length} step(s): ${F.join(", ")}`)}if(P?.removed?.length){let F=P.removed.map(X=>X.title);I.push(`Removed ${F.length} step(s): ${F.join(", ")}`)}if(P?.modified?.length){let F=P.modified.map(X=>X.title);I.push(`Modified ${F.length} step(s): ${F.join(", ")}`)}let V=I.length>0?I.join(". "):"No changes detected.";return c(JSON.stringify({plan:g,diff:P,message:`Plan modified. ${V}. Update mistflow.json with the new plan, then continue with mist_implement.`}))}let v=y?.trim()||void 0,L=a;if(!v&&a&&tn in a&&(v=a[tn]),a&&tn in a){let{[tn]:h,...g}=a;L=Object.keys(g).length>0?g:void 0}if(v&&(v=v.replace(/^Keep\s+/i,"").replace(/\s*\(Recommended\)\s*$/i,"").replace(/\.mistflow\.app.*$/i,"").trim()||void 0),v){let h=v.toLowerCase().replace(/\s+/g,"-");/^[a-z0-9][a-z0-9-]{1,30}[a-z0-9]$/.test(h)?v=h:(console.error(`[mist_plan] Discarding urlChoice '${v}' \u2014 does not look like a subdomain. Backend will auto-generate.`),v=void 0)}let Q;if(U){Q={...U};let h={fontsHint:"fonts_hint",colorMood:"color_mood",heroHeadline:"hero_headline",ctaText:"cta_text",bodySample:"body_sample",heroTreatment:"hero_treatment",shapeLang:"shape_lang",decorationHint:"decoration_hint"};for(let[g,P]of Object.entries(h))U[g]!==void 0&&Q[P]===void 0&&(Q[P]=U[g])}let se=a?"Generating plan with your answers (LLM call)":k?"Finalizing design direction":"Thinking through discovery questions",xe=e?en(e.server,e.progressToken,()=>se):{stop:()=>{}};e&&(e.cleanup=()=>xe.stop());let E;try{ie&&!L&&!k&&!G&&!i?E=await qt(ie):E=await Nn(Y,{conversationId:ie,answers:L,autonomous:m,language:u,designConversationId:k,designDirection:Q})}catch(h){xe.stop();let g=h instanceof Error?h.message:"Failed to generate plan";return c(g,!0)}if(E.status==="clarify_pending"){xe.stop();let h=E;return c(JSON.stringify({status:"running",conversationId:h.conversation_id,phase:"generating_questions",nextAction:`Discovery questions are generating (backend Sonnet call). Call mist_plan with { projectPath, description: "", conversationId: "${h.conversation_id}" } in ~10-15s to poll. Do NOT re-send description or answers \u2014 just the conversationId.`}))}if(E.status==="design_clarify_pending"&&(se="Generating creative design directions",E=await fl(E)),xe.stop(),E.status==="clarify"){let h=E.reflection||"",g=E.suggestedName||"",P=E.suggestedFeatures??[],I=E.questions??[],V=I.some(q=>Array.isArray(q.options)&&typeof q.options[0]=="object"&&q.options[0]?.label),F={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"},X=I.map(q=>{let yn=q.decisionKey&&F[q.decisionKey]||hl(q.question),_e;return V&&Array.isArray(q.options)?_e=q.options.map(Fe=>({label:Fe.label,description:Fe.description??""})):Array.isArray(q.options)?_e=q.options.map((Fe,Eo)=>({label:Eo===0?`${Fe} (Recommended)`:String(Fe),description:q.why??""})):_e=[{label:"Yes (Recommended)",description:q.why??""},{label:"No",description:""}],{question:q.question,header:yn,options:_e,multiSelect:!1}}),ht=E.decisions?.audienceType??null,Le=P.length>0?zs(Y,{primaryActor:null,primaryAction:null,surfaceType:null,audienceType:ht,multiRole:null,publicLanding:null,realMoney:null,scheduling:null,authModel:null,dbProvider:null,integrations:null},{suggestedName:g,suggestedFeatures:P,language:u}):null,ee=Le?Hs(Le):"",$=co(g||"my-app").slice(0,32);try{let q=await An($);!q.available&&q.suggestion&&($=q.suggestion)}catch{}ee&&(ee+=`
|
|
2210
|
+
|
|
2211
|
+
**Your app URL:** https://${$}.mistflow.app`);let Dt={question:`Your app will be at ${$}.mistflow.app \u2014 want to customize the URL?`,header:"URL",options:[{label:`Keep ${$}.mistflow.app (Recommended)`,description:"This URL is available"},{label:"Choose a different URL",description:"Type your preferred subdomain"}],multiSelect:!1};return X.push(Dt),c(JSON.stringify({status:"clarify",conversation_id:E.conversation_id,questions:I,questionCount:I.length,suggestedFeatures:P,suggestedName:g,suggestedSubdomain:$,reflection:h,briefText:ee,askUserQuestions:X,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:[...B?[B,""]:[],h?`${h}
|
|
2212
|
+
`:"",ee?`Here's what I'd build:
|
|
2213
|
+
|
|
2214
|
+
${ee}
|
|
2215
|
+
`:"",`I have ${I.length} quick question${I.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: "${E.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: "${$}".`,'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(`
|
|
2216
|
+
`)}))}if(E.status==="design_clarify"){let h=E.directions??[],g=E.plan.name??"your app",P;try{let Z=h.map($=>({id:$.id,name:$.name,summary:$.summary,hero_headline:$.hero_headline,cta_text:$.cta_text,body_sample:$.body_sample,fonts:$.fonts,colors:$.colors,hero_treatment:$.hero_treatment,shape_lang:$.shape_lang,texture:$.texture,decoration_hint:$.decoration_hint})),ht=Vs(g,Z),Le=oe(n,".mistflow");nn(Le,{recursive:!0});let ee=oe(Le,"design-directions.html");on(ee,ht,"utf-8"),P=ee}catch(Z){console.error(`[mist_plan] design-directions preview render failed: ${Z instanceof Error?Z.message:String(Z)}`)}let I=h.map(Z=>({label:Z.name,description:`${Z.summary} \u2014 ${Z.fonts?.display??""} + ${Z.fonts?.body??""}`}));I.push({label:"Describe your own direction",description:"Skip the proposed options and give me a short description of how the app should feel."});let V={question:`${g} is planned. Now pick the creative direction \u2014 this shapes fonts, colors, and overall feel.`,header:"Design",options:I,multiSelect:!1},F=P?`A visual preview of all ${h.length} directions has been written to ${P}. Open it in the browser \u2014 each card is rendered in its direction's own fonts + palette so the user can see what they're picking.`:"No visual preview rendered (see server logs). The AskUserQuestion options below carry fonts + mood so the user can still pick.",X=P?`open "${P}"`:"";return c(JSON.stringify({status:"design_clarify",designConversationId:E.design_conversation_id,directions:h,previewPath:P,askUserQuestion:V,instruction:[`The plan for "${g}" is ready. I've proposed ${h.length} creative directions \u2014 each commits to a specific aesthetic (fonts, colors, voice).`,"",F,X?`Run this command for the user: ${X}`:"","","MANDATORY: After opening the preview, use the AskUserQuestion tool to present the directionQuestion above. Do NOT present it as text.","","Once the user picks a direction, call mist_plan again with:"," description: (same description as before)",` designConversationId: "${E.design_conversation_id}"`," designDirection: <the full direction object from the 'directions' array that the user picked>","","IF the user picks 'Describe your own direction':"," Ask them a short open question ('How should the app feel? Any fonts or colors in mind?')."," Then call mist_plan with designDirection: { custom: '<their description>' } and the same designConversationId.","","The next mist_plan call takes ~10-20s \u2014 that's the LLM generating the final DESIGN.md with the picked direction. Tell the user 'Locking in the direction now \u2014 this takes about 15 seconds.' before calling."].filter(Boolean).join(`
|
|
2217
|
+
`)}))}let N=E.plan,fe=N.name??"Untitled App",Ie=E.methodology,D=N.steps;if(!Array.isArray(D)||D.length===0)return c("Plan generation incomplete \u2014 the plan is missing implementation steps. Please call mist_plan again with the same description to retry.",!0);let re=N.publicPages;if(!re||Array.isArray(re)&&re.length===0){let h=N.pages,g=D.some(I=>typeof I.name=="string"&&I.name.toLowerCase().includes("landing")||typeof I.title=="string"&&I.title.toLowerCase().includes("landing")),P=Array.isArray(h)&&h.some(I=>I.path==="/"||I.route==="/");g||P?re=["/","/pricing"]:re=["/"]}let dt=N.primaryAction;if(!dt){let h=N.features;if(Array.isArray(h)&&h.length>0){let P=h.find(V=>typeof V.priority=="string"&&V.priority.toLowerCase()==="must-have")??h[0];dt={entity:P.name??P.title??"item",action:"create",fromPage:"/dashboard"}}}let Me=N.nonNegotiables;(!Me||Array.isArray(Me)&&Me.length===0)&&(Me=["Landing page renders correctly at / with content (not a redirect)","Core user action works end-to-end (create entity, see it in list)"]);let z=Ks(),Ge=oe(je(),".mistflow","plans");nn(Ge,{recursive:!0});try{let g=Date.now();for(let P of[Ge,oe(je(),".mistflow","mockup-state")])if(_t(P))for(let I of el(P))try{let V=oe(P,I),F=tl(V).mtimeMs;g-F>6048e5&&nl(V)}catch{}}catch{}let ae;if(d){let h=Gt(d);h?ae=h.id:console.error(`Landing design '${d}' not found \u2014 ignoring. Use mist_project action='landing-designs' to browse available landing designs.`)}let Ue=b||void 0,ce=!!ae,ut=D.some(h=>{let g=`${h.name??h.title} ${h.description??""}`.toLowerCase();return g.includes("landing")||g.includes("hero")||g.includes("marketing")||g.includes("homepage")}),ye=!ce&&ut?ks(Y,{maxResults:2}):[];ye.length>0&&(ae=ye[0].id,console.error(`Auto-assigned landing layout preset (default): ${ye[0].title} (${ae})`));let gn={name:N.name,summary:N.summary,dataModel:N.dataModel,pages:N.pages,features:N.features,steps:D.map(h=>({...h,name:h.name??h.title})),design:N.design,landingDesign:ae,appStyle:Ue,dbProvider:N.dbProvider??"neon",authModel:N.authModel,audienceType:N.audienceType??"b2c",roles:N.roles,defaultRole:N.defaultRole,publicPages:re,navStyle:N.navStyle,multiTenant:N.multiTenant,primaryAction:dt,nonNegotiables:Me,requestedSubdomain:v,...u&&u.toLowerCase()!=="english"?{language:u}:{}};on(oe(Ge,`${z}.json`),JSON.stringify({plan:gn,methodology:Ie}));let fn=D.map(h=>`${h.number}. ${h.name??h.title}`),ke="",mt=[],$e;!ce&&ye.length>0&&(mt=ye.map(g=>({id:g.id,slug:g.slug,title:g.title,description:g.description,url:`${Ke()}/designs?tab=landing-designs`})),$e={question:"What landing page style fits this app?",header:"Landing Design",options:[...ye.map((g,P)=>({label:P===0?`${g.title} (Recommended)`:g.title,description:g.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 ${Ke()}/designs?tab=landing-designs and pass the ID back.`}],multiSelect:!1},ke=` REQUIRED: ask the user which landing design they want using the AskUserQuestion tool with the 'landingDesignQuestion' object before calling mist_init. Do NOT assume the recommended option \u2014 the user may want a different style than we inferred. Recommended: ${ye.map(g=>g.title).join(" or ")}. If they pick "Design from scratch", pass landingDesign='freeform' to mist_init. If they pick a specific preset title, look up its ID via mist_project action='landing-designs' and pass that. If they pick the recommended option, pass landingDesign='${ye[0].id}' explicitly.`);let jt="",f=[],S=void 0,H=(N.audienceType??"b2c")==="b2c",be={question:"Include a lifestyle photo in your landing page hero? Photos add warmth and human context; pure CSS stays cleaner.",header:"Hero",options:[{label:H?"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:H?"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_init call.",T="",M=[];for(let h of D){let g=h.name??h.title,P=h.integrationId;if(P){let I=et(P);if(I){let V=tt(I.id);M.push({step:g,presetId:I.id,presetName:I.name,envVars:V?.envVars??[]})}}}if(M.length>0){let h=M.flatMap(I=>I.envVars),g=[...new Set(h.map(I=>I.key))];T=` This plan uses integrations (${M.map(I=>I.presetName).join(", ")}). Detailed blueprints will be auto-injected during each integration step.${g.length>0?` The user will need these API keys: ${g.join(", ")}.`:""}`}return c(JSON.stringify({planId:z,name:N.name,summary:N.summary,stepCount:D.length,steps:fn,design:N.design,...ae?{landingDesign:ae}:{},...Ue?{appStyle:Ue}:{},...f.length>0?{recommendedAppStyles:f}:{},...S?{appStyleQuestion:S}:{},...mt.length>0?{recommendedLandingDesigns:mt}:{},...$e?{landingDesignQuestion:$e}:{},heroPhotoQuestion:be,...M.length>0?{integrations:M.map(h=>({step:h.step,preset:h.presetId,name:h.presetName,envVars:h.envVars}))}:{},message:`Plan generated for "${fe}" (${D.length} steps).${ae?` Landing layout "${ae}" set as default.`:""}${Ue?` App style "${Ue}" will be applied across all pages.`:""}${T}${jt}${ke}${we}`,timingContext:`Planning took ~90 seconds. Building will take roughly ${Math.max(15,D.length*3)}\u2013${D.length*5} minutes total across ${D.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_mockup({ planId: '${z}' }). If the user says skip or "just build it", call mist_init({ planId: '${z}', path: '<absolute path>' }) immediately.`,...B?{warning:B}:{}}))}var tn,ll,ml,er,tr=x(()=>{"use strict";W();le();lo();eo();Vt();Ws();Js();tn="__mistflow_url_choice__",ll=600*1e3;ml=_.object({description:_.string().optional().describe("App description or modification request. Required for the first call; omit on follow-up polls where only conversationId is passed. "),projectPath:_.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:_.string().optional().describe("Returned by a previous mist_plan call with status 'clarify' or 'running'. Pass it back alone (no description) to poll an in-flight discovery call; pass with answers to submit responses."),answers:_.record(_.string()).optional().describe("User's answers to the clarifying questions from the previous round. Keys are the questions, values are the answers."),existingPlan:_.record(_.unknown()).optional().describe("If provided, modifies this existing plan instead of creating a new one. Pass the current plan object from mistflow.json."),existingPlanId:_.string().optional().describe("Alternative to existingPlan \u2014 pass the planId from a previous mist_plan call to modify that plan."),templateToken:_.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:_.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:_.boolean().optional().describe("Skip clarifying questions and generate the plan immediately"),landingDesign:_.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:_.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:_.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:_.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:_.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:_.string().optional().describe("The user's answer to the 'Your app URL' question from a previous mist_plan response. Pass JUST the subdomain (e.g. 'nutrition-tracker'), not the full URL or the option label. If the user kept the default suggestion, pass the suggested subdomain verbatim. If they typed a custom URL like 'myapp.mistflow.app', pass just 'myapp'. Pass this as a top-level parameter \u2014 do NOT nest it inside answers. The answers-dict magic key is deprecated and unreliable."),designConversationId:_.string().optional().describe("Returned by a previous mist_plan call with status 'design_clarify'. Pass it back on the follow-up call together with designDirection to finalize the plan's DESIGN.md."),designDirection:_.object({id:_.string().optional(),name:_.string().optional(),summary:_.string().optional(),heroHeadline:_.string().optional(),ctaText:_.string().optional(),bodySample:_.string().optional(),fontsHint:_.string().optional(),fonts:_.object({display:_.string(),body:_.string()}).partial().optional(),colorMood:_.string().optional(),colors:_.object({bg:_.string(),fg:_.string(),accent:_.string()}).partial().optional(),heroTreatment:_.string().optional(),shapeLang:_.string().optional(),texture:_.string().optional(),decorationHint:_.string().optional(),custom:_.string().optional()}).passthrough().optional().describe("The creative direction the user picked from a previous 'design_clarify' response. Pass the FULL direction object the user chose (all fields from the 'directions' array). If the user wrote their own description instead of picking one, pass { custom: '<their description>' } and omit the other fields.")});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_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(`
|
|
2218
|
+
`),inputSchema:ml,handler:yl}});function nr(t){if(!t)return"Item";let e=t.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^A-Za-z0-9]+/).filter(Boolean);return e.length===0?"Item":e.map(o=>o.charAt(0).toUpperCase()+o.slice(1).toLowerCase()).join("")}function bl(t){return t&&t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^A-Za-z0-9]+/g,"-").toLowerCase().replace(/^-+|-+$/g,"")||"item"}function wl(t){let e=nr(t);return e.charAt(0).toLowerCase()+e.slice(1)}function mo(){return["# Integration contracts","","This directory holds the single source of truth for every API shape in","this app. Frontend code and backend routes both import from here, so","drift becomes a compile error instead of a silent runtime bug.","","## The convention","","Every entity defined in `db/schema.ts` MUST have a matching contract","file in this directory. Each contract file exports three things:","","- `<Entity>Schema` \u2014 the Zod schema for reading the entity (derived from"," the Drizzle table via `createSelectSchema`).","- `Create<Entity>Input` \u2014 the Zod schema for creating a new row"," (derived via `createInsertSchema`, typically with `id` and"," `createdAt` omitted).","- `<Entity>` \u2014 the inferred TypeScript type from `<Entity>Schema`.","","File name is the kebab-case singular of the entity, e.g. `habit.ts`,","`blog-post.ts`. One entity per file.","","## Example","","```ts","// contracts/habit.ts",'import { createSelectSchema, createInsertSchema } from "drizzle-zod";','import { z } from "zod";','import { habit } from "@/db/schema";',"","export const HabitSchema = createSelectSchema(habit);","export type Habit = z.infer<typeof HabitSchema>;","","export const CreateHabitInput = createInsertSchema(habit).omit({"," id: true,"," createdAt: true,","});","export type CreateHabitInput = z.infer<typeof CreateHabitInput>;","```","","## Usage","","Frontend fetch and backend route should BOTH import from `contracts/`:","","```ts","// app/api/habits/route.ts",'import { CreateHabitInput, HabitSchema } from "@/contracts/habit";',"","export async function POST(request: Request) {"," const body = CreateHabitInput.parse(await request.json());"," const row = await db.insert(habit).values(body).returning();"," return Response.json(HabitSchema.parse(row[0]));","}","```","","```ts","// app/habits/page.tsx",'import type { Habit } from "@/contracts/habit";',"",'const res = await fetch("/api/habits");',"const habits: Habit[] = await res.json();","```","","## Adding a new entity","","1. Add the Drizzle table to `db/schema.ts`.","2. Create the matching `contracts/<entity>.ts` file using the template above.","3. Import from `contracts/` in every route, server action, and client"," component that touches the entity. Never inline the type.","","Run `mist_doctor` to check for entities that are missing a contract.",""].join(`
|
|
2219
|
+
`)}function or(){return["<!-- mist:contracts:start -->","## Integration contracts","","Every API shape in this app lives in `contracts/`. The directory holds","Zod schemas derived from `db/schema.ts` via `drizzle-zod`. Frontend and","backend both import from `contracts/`, so type drift becomes a compile","error instead of a runtime bug.","","### Rules for AI agents","","1. Every API route (`app/api/**/route.ts`) and server action MUST"," import its request + response types from `contracts/<entity>.ts`."," Never inline a Zod schema or a TypeScript type for an entity that"," already has a contract. Never `z.object({ ... })` inside a route"," handler for a known entity.","2. When you add a new entity to `db/schema.ts`, you MUST create the"," matching contract file BEFORE writing any route that uses it. Order"," matters: schema -> contract -> route.","3. Validate every request body with the contract's `.parse()` method."," If validation fails, return a 400 with the Zod error message \u2014 the"," contract is the boundary, not a decoration.","4. Validate every response body before returning it. Use the select"," schema's `.parse()` on the row(s) you read from the DB. This catches"," the case where the DB shape has drifted from the contract.","5. Client components that fetch an entity MUST import the inferred",' TypeScript type (`import type { Habit } from "@/contracts/habit"`)'," \u2014 never hand-write a duplicate type.","","### Contract file shape","","```ts","// contracts/<entity>.ts",'import { createSelectSchema, createInsertSchema } from "drizzle-zod";','import { z } from "zod";','import { entityTable } from "@/db/schema";',"","export const EntitySchema = createSelectSchema(entityTable);","export type Entity = z.infer<typeof EntitySchema>;","","export const CreateEntityInput = createInsertSchema(entityTable).omit({"," id: true,"," createdAt: true,","});","export type CreateEntityInput = z.infer<typeof CreateEntityInput>;","```","","### Example route using a contract","","```ts","// app/api/entities/route.ts",'import { db } from "@/lib/db";','import { entityTable } from "@/db/schema";','import { CreateEntityInput, EntitySchema } from "@/contracts/entity";',"","export async function POST(request: Request) {"," const body = CreateEntityInput.parse(await request.json());"," const [row] = await db.insert(entityTable).values(body).returning();"," return Response.json(EntitySchema.parse(row));","}","```","","Run `mist_doctor` to check every entity in `db/schema.ts` has a","contract file. Missing contracts are reported as warnings.","<!-- mist:contracts:end -->",""].join(`
|
|
2220
|
+
`)}function ho(t){let e=or();if(t.includes(uo)){let n=t.indexOf(uo),s=sr,a=t.indexOf(s,n);if(a===-1)return t.slice(0,n)+e;let r=t.slice(a+s.length);return t.slice(0,n)+e+r.replace(/^\n+/,"")}return t.replace(/\s+$/,"")+`
|
|
2221
|
+
|
|
2222
|
+
`+e}function go(t,e){let o=nr(t),n=e??wl(t);return['import { createSelectSchema, createInsertSchema } from "drizzle-zod";','import { z } from "zod";',`import { ${n} } from "@/db/schema";`,"","// Select schema \u2014 shape of a row read from the DB. Use this on both","// sides of the wire: backend validates responses, frontend gets types.",`export const ${o}Schema = createSelectSchema(${n});`,`export type ${o} = z.infer<typeof ${o}Schema>;`,"","// Insert schema \u2014 shape accepted when creating a new row. id +","// createdAt are generated server-side, so we strip them from the","// input contract. Adjust if your schema uses different column names.",`export const Create${o}Input = createInsertSchema(${n}).omit({`," id: true,"," createdAt: true,","});",`export type Create${o}Input = z.infer<typeof Create${o}Input>;`,""].join(`
|
|
2223
|
+
`)}function fo(t){return`contracts/${bl(t)}.ts`}var uo,sr,yo=x(()=>{"use strict";uo="<!-- mist:contracts:start -->",sr="<!-- mist:contracts:end -->"});import{z as Tt}from"zod";import{existsSync as He,mkdirSync as bo,writeFileSync as wo,readFileSync as rn,readdirSync as ar,copyFileSync as vl}from"fs";import{join as he,resolve as lr,dirname as Rt,isAbsolute as xl}from"path";import{homedir as kl}from"os";import{spawn as gu}from"child_process";import{randomBytes as Sl}from"crypto";import{simpleGit as Il}from"simple-git";function Pl(t){let e=he(kl(),".mistflow","plans",`${t}.json`);if(!He(e))return null;try{let o=JSON.parse(rn(e,"utf-8"));return o.plan?{plan:o.plan}:null}catch{return null}}function _l(t){let e=Rt(lr(t)),o=10,n=0;for(;n<o&&e!==Rt(e);){if(He(he(e,"pnpm-workspace.yaml"))||He(he(e,"lerna.json")))return e;let s=he(e,"package.json");if(He(s))try{if(JSON.parse(rn(s,"utf-8")).workspaces)return e}catch{}e=Rt(e),n++}return null}function A(t,e,o){let n=he(t,e);bo(Rt(n),{recursive:!0}),wo(n,o)}function Rl(t){if(!He(t))return!0;let e;try{e=ar(t)}catch{return!1}return e.filter(n=>n!==".mistflow").length===0}function El(t){let e=t.match(/^---\n([\s\S]*?)\n---/);if(!e)return null;let o=e[1],n={theme:"light",colors:{},typography:{},rounded:{},spacing:{}},s=o.split(`
|
|
2224
|
+
`),a=null,r=null,i=l=>l.replace(/^["']|["']$/g,"").trim();for(let l of s){let p=l.replace(/\r$/,"");if(!p.trim()||p.trim().startsWith("#"))continue;if(p.startsWith("theme:")){let d=i(p.slice(6).trim());(d==="dark"||d==="light")&&(n.theme=d);continue}let m=p.match(/^(colors|typography|rounded|spacing):\s*$/);if(m){a=m[1],r=null;continue}if(a==="typography"){let d=p.match(/^ {2}([a-zA-Z0-9_-]+):\s*$/);if(d){r=d[1].replace(/-/g,"_"),n.typography[r]={};continue}let b=p.match(/^ {4}([a-zA-Z0-9_-]+):\s*(.+)$/);if(b&&r){n.typography[r][b[1]]=i(b[2]);continue}}let u=p.match(/^ {2}([a-zA-Z0-9_-]+):\s*(.+)$/);if(u&&a){let d=u[1].replace(/-/g,"_"),b=i(u[2]);a==="colors"?n.colors[d]=b:a==="rounded"?n.rounded[d]=b:a==="spacing"&&(n.spacing[d]=b)}}return n}function Nl(t,e){let o=t.colors,s=[["--color-background",o.background],["--color-foreground",o.on_background??o.on_surface],["--color-card",o.surface??o.background],["--color-card-foreground",o.on_surface??o.on_background],["--color-popover",o.surface??o.background],["--color-popover-foreground",o.on_surface??o.on_background],["--color-muted",o.surface_variant??o.outline_variant??o.outline],["--color-muted-foreground",o.on_surface_variant??o.outline],["--color-border",o.outline_variant??o.outline],["--color-input",o.outline_variant??o.outline],["--color-primary",o.primary],["--color-primary-foreground",o.on_primary],["--color-ring",o.primary],["--color-secondary",o.secondary],["--color-secondary-foreground",o.on_secondary],["--color-accent",o.secondary],["--color-accent-foreground",o.on_secondary],["--color-destructive",o.error],["--color-destructive-foreground",o.on_error],["--color-success",o.success],["--color-success-foreground",o.on_success],["--color-warning",o.warning],["--color-warning-foreground",o.on_warning],["--color-info",o.info??o.primary],["--color-info-foreground",o.on_info??o.on_primary]].filter(i=>typeof i[1]=="string").map(([i,l])=>` ${i}: ${l};`).join(`
|
|
2225
|
+
`),a=[` --radius-sm: ${t.rounded.sm??"0.25rem"};`,` --radius-md: ${t.rounded.md??e};`,` --radius-lg: ${t.rounded.lg??"0.5rem"};`,` --radius-xl: ${t.rounded.xl??"0.75rem"};`].join(`
|
|
2226
|
+
`);return`@import "tailwindcss";
|
|
2227
|
+
@import "tw-animate-css";
|
|
2228
|
+
|
|
2229
|
+
@theme {
|
|
2230
|
+
${s}
|
|
2231
|
+
${a}
|
|
2232
|
+
}
|
|
2233
|
+
|
|
2234
|
+
|
|
2235
|
+
@layer base {
|
|
2236
|
+
* { border-color: var(--color-border); }
|
|
2237
|
+
body { background-color: var(--color-background); color: var(--color-foreground); }
|
|
2238
|
+
}
|
|
2239
|
+
|
|
2240
|
+
:root {
|
|
2241
|
+
--ease-quart-out: cubic-bezier(0.25, 1, 0.5, 1);
|
|
2242
|
+
--ease-expo-out: cubic-bezier(0.16, 1, 0.3, 1);
|
|
2243
|
+
--ease-back-out: cubic-bezier(0.34, 1.56, 0.64, 1);
|
|
2244
|
+
--duration-micro: 80ms;
|
|
2245
|
+
--duration-short: 150ms;
|
|
2246
|
+
--duration-medium: 250ms;
|
|
2247
|
+
--duration-long: 400ms;
|
|
2248
|
+
--z-dropdown: 10;
|
|
2249
|
+
--z-sticky: 20;
|
|
2250
|
+
--z-modal-backdrop: 30;
|
|
2251
|
+
--z-modal: 40;
|
|
2252
|
+
--z-toast: 50;
|
|
2253
|
+
--z-tooltip: 60;
|
|
2254
|
+
}
|
|
2255
|
+
|
|
2256
|
+
@keyframes fade-up { from { opacity: 0; transform: translateY(12px); } to { opacity: 1; transform: translateY(0); } }
|
|
2257
|
+
@keyframes fade-in { from { opacity: 0; } to { opacity: 1; } }
|
|
2258
|
+
.animate-fade-up { animation: fade-up 0.5s var(--ease-expo-out) both; }
|
|
2259
|
+
.animate-fade-in { animation: fade-in 0.3s var(--ease-quart-out) both; }
|
|
2260
|
+
|
|
2261
|
+
.stagger > :nth-child(1) { animation-delay: 0ms; }
|
|
2262
|
+
.stagger > :nth-child(2) { animation-delay: 50ms; }
|
|
2263
|
+
.stagger > :nth-child(3) { animation-delay: 100ms; }
|
|
2264
|
+
.stagger > :nth-child(4) { animation-delay: 150ms; }
|
|
2265
|
+
.stagger > :nth-child(5) { animation-delay: 200ms; }
|
|
2266
|
+
.stagger > :nth-child(6) { animation-delay: 250ms; }
|
|
2267
|
+
|
|
2268
|
+
@media (prefers-reduced-motion: reduce) {
|
|
2269
|
+
*, *::before, *::after {
|
|
2270
|
+
animation-duration: 0.01ms !important;
|
|
2271
|
+
animation-iteration-count: 1 !important;
|
|
2272
|
+
transition-duration: 0.01ms !important;
|
|
2273
|
+
}
|
|
2274
|
+
}
|
|
2275
|
+
|
|
2276
|
+
:focus-visible { outline: 2px solid var(--color-primary); outline-offset: 2px; }
|
|
2277
|
+
:focus:not(:focus-visible) { outline: none; }
|
|
2278
|
+
|
|
2279
|
+
button, [role="button"] { transition: transform 100ms var(--ease-quart-out); }
|
|
2280
|
+
button:active:not(:disabled), [role="button"]:active:not(:disabled) { transform: scale(0.97); }
|
|
2281
|
+
`}function jl(t,e,o){let n=t?.borderRadius??"subtle",s=Al[n]??"0.375rem";if(o){let r=El(o);if(r)return Nl(r,s)}return`@import "tailwindcss";
|
|
2282
|
+
@import "tw-animate-css";
|
|
2283
|
+
|
|
2284
|
+
@theme {
|
|
2285
|
+
${[...Cl.map(([r,i])=>` ${r}: ${i};`)," --radius-sm: 0.25rem;",` --radius-md: ${s};`," --radius-lg: 0.5rem;"," --radius-xl: 0.75rem;"].join(`
|
|
2286
|
+
`)}
|
|
2287
|
+
}
|
|
2288
|
+
|
|
2289
|
+
@layer base {
|
|
2290
|
+
* { border-color: var(--color-border); }
|
|
2291
|
+
body { background-color: var(--color-background); color: var(--color-foreground); }
|
|
2292
|
+
}
|
|
2293
|
+
|
|
2294
|
+
:root {
|
|
2295
|
+
--ease-quart-out: cubic-bezier(0.25, 1, 0.5, 1);
|
|
2296
|
+
--ease-expo-out: cubic-bezier(0.16, 1, 0.3, 1);
|
|
2297
|
+
--ease-back-out: cubic-bezier(0.34, 1.56, 0.64, 1);
|
|
2298
|
+
--duration-micro: 80ms;
|
|
2299
|
+
--duration-short: 150ms;
|
|
2300
|
+
--duration-medium: 250ms;
|
|
2301
|
+
--duration-long: 400ms;
|
|
2302
|
+
--z-dropdown: 10;
|
|
2303
|
+
--z-sticky: 20;
|
|
2304
|
+
--z-modal-backdrop: 30;
|
|
2305
|
+
--z-modal: 40;
|
|
2306
|
+
--z-toast: 50;
|
|
2307
|
+
--z-tooltip: 60;
|
|
2308
|
+
}
|
|
2309
|
+
|
|
2310
|
+
@keyframes fade-up { from { opacity: 0; transform: translateY(12px); } to { opacity: 1; transform: translateY(0); } }
|
|
2311
|
+
@keyframes fade-in { from { opacity: 0; } to { opacity: 1; } }
|
|
2312
|
+
.animate-fade-up { animation: fade-up 0.5s var(--ease-expo-out) both; }
|
|
2313
|
+
.animate-fade-in { animation: fade-in 0.3s var(--ease-quart-out) both; }
|
|
2314
|
+
|
|
2315
|
+
.stagger > :nth-child(1) { animation-delay: 0ms; }
|
|
2316
|
+
.stagger > :nth-child(2) { animation-delay: 50ms; }
|
|
2317
|
+
.stagger > :nth-child(3) { animation-delay: 100ms; }
|
|
2318
|
+
.stagger > :nth-child(4) { animation-delay: 150ms; }
|
|
2319
|
+
.stagger > :nth-child(5) { animation-delay: 200ms; }
|
|
2320
|
+
.stagger > :nth-child(6) { animation-delay: 250ms; }
|
|
2321
|
+
|
|
2322
|
+
@media (prefers-reduced-motion: reduce) {
|
|
2323
|
+
*, *::before, *::after {
|
|
2324
|
+
animation-duration: 0.01ms !important;
|
|
2325
|
+
animation-iteration-count: 1 !important;
|
|
2326
|
+
transition-duration: 0.01ms !important;
|
|
2327
|
+
}
|
|
2328
|
+
}
|
|
2329
|
+
|
|
2330
|
+
:focus-visible { outline: 2px solid var(--color-primary); outline-offset: 2px; }
|
|
2331
|
+
:focus:not(:focus-visible) { outline: none; }
|
|
2332
|
+
|
|
2333
|
+
button, [role="button"] { transition: transform 100ms var(--ease-quart-out); }
|
|
2334
|
+
button:active:not(:disabled), [role="button"]:active:not(:disabled) { transform: scale(0.97); }
|
|
2335
|
+
`}function ir(t){let e=t.replace(/[^A-Za-z0-9_ -]/g,"");return rr[e]?rr[e]:e.replace(/\s+/g,"_")}function Dl(t){return t?{english:"en",spanish:"es",french:"fr",german:"de",italian:"it",portuguese:"pt",dutch:"nl",russian:"ru",japanese:"ja",chinese:"zh",korean:"ko",arabic:"ar",hebrew:"he",hindi:"hi",turkish:"tr",polish:"pl",swedish:"sv",norwegian:"no",danish:"da",finnish:"fi",thai:"th",vietnamese:"vi",indonesian:"id",malay:"ms",farsi:"fa",persian:"fa",czech:"cs",greek:"el",romanian:"ro",hungarian:"hu",ukrainian:"uk",bengali:"bn",tamil:"ta",telugu:"te",urdu:"ur"}[t.toLowerCase()]??"en":"en"}function Ml(t,e,o){let n=t.replace(/[\\"`$]/g,""),s=Dl(o),r=Ol.has(s)?`lang="${s}" dir="rtl"`:`lang="${s}"`,i=e?.fonts?.heading,l=e?.fonts?.body;if(!i&&!l)return`import type { Metadata } from "next";
|
|
2336
|
+
import { DM_Sans } from "next/font/google";
|
|
2337
|
+
import { Toaster } from "sonner";
|
|
2338
|
+
import "./globals.css";
|
|
2339
|
+
|
|
2340
|
+
const body = DM_Sans({ subsets: ["latin"], variable: "--font-body" });
|
|
2341
|
+
|
|
2342
|
+
export const metadata: Metadata = { title: "${n}", description: "Built with Mistflow" };
|
|
2343
|
+
|
|
2344
|
+
export default function RootLayout({ children }: { children: React.ReactNode }) {
|
|
2345
|
+
return (
|
|
2346
|
+
<html ${r}>
|
|
2347
|
+
<body className={body.variable}>{children}<Toaster richColors /></body>
|
|
2348
|
+
</html>
|
|
2349
|
+
);
|
|
2350
|
+
}
|
|
2351
|
+
`;let p=ir(i??l),m=ir(l??i);return p===m?`import type { Metadata } from "next";
|
|
2352
|
+
import { ${p} } from "next/font/google";
|
|
2353
|
+
import { Toaster } from "sonner";
|
|
2354
|
+
import "./globals.css";
|
|
2355
|
+
|
|
2356
|
+
const font = ${p}({ subsets: ["latin"], variable: "--font-body" });
|
|
2357
|
+
|
|
2358
|
+
export const metadata: Metadata = { title: "${n}", description: "Built with Mistflow" };
|
|
2359
|
+
|
|
2360
|
+
export default function RootLayout({ children }: { children: React.ReactNode }) {
|
|
2361
|
+
return (
|
|
2362
|
+
<html ${r}>
|
|
2363
|
+
<body className={font.variable}>{children}<Toaster richColors /></body>
|
|
2364
|
+
</html>
|
|
2365
|
+
);
|
|
2366
|
+
}
|
|
2367
|
+
`:`import type { Metadata } from "next";
|
|
2368
|
+
import { ${p}, ${m} } from "next/font/google";
|
|
2369
|
+
import { Toaster } from "sonner";
|
|
2370
|
+
import "./globals.css";
|
|
2371
|
+
|
|
2372
|
+
const heading = ${p}({ subsets: ["latin"], variable: "--font-heading" });
|
|
2373
|
+
const body = ${m}({ subsets: ["latin"], variable: "--font-body" });
|
|
2374
|
+
|
|
2375
|
+
export const metadata: Metadata = { title: "${n}", description: "Built with Mistflow" };
|
|
2376
|
+
|
|
2377
|
+
export default function RootLayout({ children }: { children: React.ReactNode }) {
|
|
2378
|
+
return (
|
|
2379
|
+
<html ${r}>
|
|
2380
|
+
<body className={\`\${heading.variable} \${body.variable}\`}>{children}<Toaster richColors /></body>
|
|
2381
|
+
</html>
|
|
2382
|
+
);
|
|
2383
|
+
}
|
|
2384
|
+
`}function sn(t,...e){let o=JSON.stringify(t).toLowerCase();return e.some(n=>o.includes(n.toLowerCase()))}function vo(t){let e=t.toLowerCase().replace(/[^a-z]/g,"");for(let[o,n]of Object.entries(Ul))if(e.includes(o))return n;return"Circle"}function At(t){return t.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function $l(t){if(t.authModel==="none")return null;let e=["/login","/register","/forgot-password","/reset-password","/api/auth","/api/health","/api/webhooks","/api/admin/seed"];if(t.publicPages&&Array.isArray(t.publicPages))for(let a of t.publicPages){if(typeof a!="string"||a.length<1)continue;let r=a.replace(/[\u201C\u201D\u201E\u201F\u2018\u2019\u2033\u2036]/g,"").trim();if(!r)continue;let i=r.startsWith("/")?r:"/"+r;e.includes(i)||e.push(i)}let o=e.filter(a=>a==="/"),n=e.filter(a=>a!=="/"),s=[];s.push('import { NextRequest, NextResponse } from "next/server";'),s.push(""),s.push("const PUBLIC_PREFIXES = [");for(let a of n)s.push(' "'+a+'",');return s.push("];"),s.push(""),o.length>0&&(s.push('const PUBLIC_EXACT = ["'+o.join('", "')+'"];'),s.push("")),s.push("export function middleware(req: NextRequest) {"),s.push(" const { pathname, search } = req.nextUrl;"),s.push(""),o.length>0&&s.push(" if (PUBLIC_EXACT.includes(pathname)) return NextResponse.next();"),s.push(" if (PUBLIC_PREFIXES.some((p) => pathname.startsWith(p))) return NextResponse.next();"),s.push(""),s.push(' const token = req.cookies.get("better-auth.session_token")?.value || req.cookies.get("__Secure-better-auth.session_token")?.value;'),s.push(" if (!token) {"),s.push(' const loginUrl = new URL("/login", req.url);'),s.push(" const params = new URLSearchParams(search);"),s.push(' for (const key of ["verified", "error"]) {'),s.push(" const v = params.get(key);"),s.push(" if (v) loginUrl.searchParams.set(key, v);"),s.push(" }"),s.push(" return NextResponse.redirect(loginUrl);"),s.push(" }"),s.push(""),s.push(" return NextResponse.next();"),s.push("}"),s.push(""),s.push("export const config = {"),s.push(' matcher: ["/((?!_next|static|favicon\\\\.ico).*)"],'),s.push("};"),s.push(""),s.join(`
|
|
2385
|
+
`)}function Ll(t){if(t.navStyle==="none")return null;let e=["/api","/login","/register","/sign-in","/sign-up","/admin","/pricing","/about","/contact","/terms","/privacy","/onboarding","/join","/forgot-password","/reset-password"],n=(t.pages??[]).filter(l=>{let p=l.path??l.route??"";return p==="/"||p===""||p.includes("[")||p.replace(/^\//,"").split("/").length>1?!1:!e.some(u=>p.startsWith(u))}).map(l=>{let p=l.path??l.route??"",m=p.startsWith("/")?p:"/"+p,u=l.name??At(p.replace(/^\//,"")),d=vo(u);return{label:u,href:m,icon:d}});n.some(l=>l.href==="/dashboard")||n.unshift({label:"Dashboard",href:"/dashboard",icon:"Home"});let s=t.authModel==="none",a=[...new Set(n.map(l=>l.icon))];s||a.push("LogOut");let r=At(t.name);if(t.navStyle==="topbar"){let l=[];l.push('"use client";'),l.push(""),l.push('import Link from "next/link";'),l.push('import { usePathname } from "next/navigation";'),s||l.push('import { authClient } from "@/lib/auth-client";'),l.push('import { Button } from "@/components/ui/button";'),l.push('import { cn } from "@/lib/utils";'),l.push("import { "+a.join(", ")+' } from "lucide-react";'),l.push(""),l.push("interface TopNavProps {"),l.push(" user: { name: string | null; email: string; role?: string | undefined };"),l.push("}"),l.push(""),l.push("const NAV_ITEMS = [");for(let p of n)l.push(' { label: "'+p.label+'", href: "'+p.href+'", icon: '+p.icon+" },");return l.push("];"),l.push(""),l.push("export default function TopNav({ user }: TopNavProps) {"),l.push(" const pathname = usePathname();"),l.push(""),l.push(" return ("),l.push(' <nav className="border-b bg-card">'),l.push(' <div className="mx-auto flex h-14 max-w-7xl items-center justify-between px-4">'),l.push(' <div className="flex items-center gap-6">'),l.push(' <span className="text-lg font-semibold">'+r+"</span>"),l.push(' <div className="flex items-center gap-1">'),l.push(" {NAV_ITEMS.map((item) => ("),l.push(" <Link"),l.push(" key={item.href}"),l.push(" href={item.href}"),l.push(' aria-current={pathname === item.href ? "page" : undefined}'),l.push(" className={cn("),l.push(' "flex items-center gap-1.5 rounded-md px-3 py-1.5 text-sm font-medium transition-colors",'),l.push(' pathname === item.href ? "bg-primary/10 text-primary" : "text-muted-foreground hover:text-foreground"'),l.push(" )}"),l.push(" >"),l.push(' <item.icon className="h-4 w-4" />'),l.push(" {item.label}"),l.push(" </Link>"),l.push(" ))}"),l.push(" </div>"),l.push(" </div>"),s?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(`
|
|
2386
|
+
`)}}let i=[];i.push('"use client";'),i.push(""),i.push('import { useState } from "react";'),i.push('import Link from "next/link";'),i.push('import { usePathname } from "next/navigation";'),s||i.push('import { authClient } from "@/lib/auth-client";'),i.push('import { Button } from "@/components/ui/button";'),i.push('import { Sheet, SheetContent, SheetTrigger, SheetTitle } from "@/components/ui/sheet";'),i.push('import { cn } from "@/lib/utils";'),i.push("import { Menu, "+a.join(", ")+' } from "lucide-react";'),i.push(""),i.push("interface SidebarProps {"),i.push(" user: { name: string | null; email: string; role?: string | undefined };"),i.push("}"),i.push(""),i.push("const NAV_ITEMS = [");for(let l of n)i.push(' { label: "'+l.label+'", href: "'+l.href+'", icon: '+l.icon+" },");return i.push("];"),i.push(""),i.push('function NavContent({ pathname, user, onNavigate }: { pathname: string; user: SidebarProps["user"]; onNavigate?: () => void }) {'),i.push(" return ("),i.push(" <>"),i.push(' <div className="flex h-14 items-center border-b px-4">'),i.push(' <span className="text-lg font-semibold">'+r+"</span>"),i.push(" </div>"),i.push(' <nav className="flex-1 space-y-1 p-2">'),i.push(" {NAV_ITEMS.map((item) => ("),i.push(" <Link"),i.push(" key={item.href}"),i.push(" href={item.href}"),i.push(" onClick={onNavigate}"),i.push(' aria-current={pathname === item.href ? "page" : undefined}'),i.push(" className={cn("),i.push(' "flex items-center gap-3 rounded-md px-3 py-2.5 text-sm font-medium transition-colors",'),i.push(' pathname === item.href ? "bg-primary/10 text-primary" : "text-muted-foreground hover:bg-muted hover:text-foreground"'),i.push(" )}"),i.push(" >"),i.push(' <item.icon className="h-4 w-4" />'),i.push(" {item.label}"),i.push(" </Link>"),i.push(" ))}"),i.push(" </nav>"),i.push(' <div className="border-t p-4">'),i.push(' <div className="flex items-center gap-3">'),i.push(' <div className="flex-1 truncate">'),i.push(' <p className="truncate text-sm font-medium">{user.name ?? "User"}</p>'),i.push(' <p className="truncate text-xs text-muted-foreground">{user.email}</p>'),i.push(" </div>"),s||(i.push(" <Button"),i.push(' variant="ghost"'),i.push(' size="icon"'),i.push(' onClick={() => authClient.signOut({ fetchOptions: { onSuccess: () => { window.location.href = "/login"; } } })}'),i.push(" >"),i.push(' <LogOut className="h-4 w-4" />'),i.push(" </Button>")),i.push(" </div>"),i.push(" </div>"),i.push(" </>"),i.push(" );"),i.push("}"),i.push(""),i.push("export default function Sidebar({ user }: SidebarProps) {"),i.push(" const pathname = usePathname();"),i.push(" const [open, setOpen] = useState(false);"),i.push(""),i.push(" return ("),i.push(" <>"),i.push(' <aside className="hidden md:flex h-screen w-64 flex-col border-r bg-card">'),i.push(" <NavContent pathname={pathname} user={user} />"),i.push(" </aside>"),i.push(' <div className="sticky top-0 z-[var(--z-sticky)] flex h-14 items-center gap-3 border-b bg-card px-4 md:hidden">'),i.push(" <Sheet open={open} onOpenChange={setOpen}>"),i.push(" <SheetTrigger asChild>"),i.push(' <Button variant="ghost" size="icon" className="-ml-2">'),i.push(' <Menu className="h-5 w-5" />'),i.push(" </Button>"),i.push(" </SheetTrigger>"),i.push(' <SheetContent side="left" className="w-64 p-0">'),i.push(' <SheetTitle className="sr-only">Navigation</SheetTitle>'),i.push(' <div className="flex h-full flex-col">'),i.push(" <NavContent pathname={pathname} user={user} onNavigate={() => setOpen(false)} />"),i.push(" </div>"),i.push(" </SheetContent>"),i.push(" </Sheet>"),i.push(' <span className="text-lg font-semibold">'+r+"</span>"),i.push(" </div>"),i.push(" </>"),i.push(" );"),i.push("}"),i.push(""),{path:"components/sidebar.tsx",content:i.join(`
|
|
2387
|
+
`)}}function Fl(t){if(!t.roles||t.roles.length===0)return null;let e=t.roles,o=t.defaultRole??e[0],n=[];n.push("export type Role = "+e.map(s=>'"'+s+'"').join(" | ")+";"),n.push(""),n.push("export const ROLES = ["+e.map(s=>'"'+s+'"').join(", ")+"] as const;"),n.push(""),n.push('export const DEFAULT_ROLE: Role = "'+o+'";'),n.push(""),n.push("export const ROLE_LABELS: Record<Role, string> = {");for(let s of e){let a=s.charAt(0).toUpperCase()+s.slice(1);n.push(' "'+s+'": "'+a+'",')}return n.push("};"),n.push(""),n.push("export function getUserRole(user: Record<string, unknown>): Role {"),n.push(" const role = (user.role as string) ?? DEFAULT_ROLE;"),n.push(" if (ROLES.includes(role as Role)) return role as Role;"),n.push(" return DEFAULT_ROLE;"),n.push("}"),n.push(""),n.push("export function hasRole(userRole: string | undefined, required: Role | Role[]): boolean {"),n.push(" if (!userRole) return false;"),n.push(" const allowed = Array.isArray(required) ? required : [required];"),n.push(" return allowed.includes(userRole as Role);"),n.push("}"),n.push(""),n.join(`
|
|
2388
|
+
`)}function ql(t){let e=At(t.name);if(t.authModel==="none"){let a=[];return a.push("export default function HomePage() {"),a.push(" return ("),a.push(' <main className="flex min-h-screen flex-col items-center justify-center p-8">'),a.push(' <h1 className="text-4xl font-bold">'+e+"</h1>"),t.summary&&a.push(' <p className="mt-4 text-lg text-muted-foreground">'+t.summary+"</p>"),a.push(" </main>"),a.push(" );"),a.push("}"),a.push(""),a.join(`
|
|
2389
|
+
`)}let o=t.publicPages?.includes("/"),n=t.design?.landingTone;if(o&&n){let a=[];return a.push('import Link from "next/link";'),a.push(""),a.push("export default function HomePage() {"),a.push(" return ("),a.push(' <main className="flex min-h-screen flex-col">'),a.push(' <section className="flex flex-1 flex-col items-center justify-center gap-6 px-4 py-24 text-center">'),a.push(' <h1 className="text-5xl font-bold tracking-tight">'+e+"</h1>"),t.summary&&a.push(' <p className="max-w-2xl text-xl text-muted-foreground">'+t.summary+"</p>"),a.push(' <div className="flex gap-4">'),a.push(' <Link href="/register" className="inline-flex h-11 items-center rounded-md bg-primary px-8 text-sm font-medium text-primary-foreground hover:bg-primary/90">'),a.push(" Get Started"),a.push(" </Link>"),a.push(' <Link href="/login" className="inline-flex h-11 items-center rounded-md border px-8 text-sm font-medium hover:bg-muted">'),a.push(" Sign In"),a.push(" </Link>"),a.push(" </div>"),a.push(" </section>"),a.push(" </main>"),a.push(" );"),a.push("}"),a.push(""),a.join(`
|
|
2390
|
+
`)}if(o){let a=[];return a.push('import Link from "next/link";'),a.push(""),a.push("export default function HomePage() {"),a.push(" return ("),a.push(' <main className="flex min-h-screen flex-col items-center justify-center gap-6 p-8 text-center">'),a.push(' <h1 className="text-4xl font-bold">'+e+"</h1>"),t.summary&&a.push(' <p className="text-lg text-muted-foreground">'+t.summary+"</p>"),a.push(' <Link href="/login" className="inline-flex h-10 items-center rounded-md bg-primary px-6 text-sm font-medium text-primary-foreground hover:bg-primary/90">'),a.push(" Sign In"),a.push(" </Link>"),a.push(" </main>"),a.push(" );"),a.push("}"),a.push(""),a.join(`
|
|
2391
|
+
`)}let s=[];return s.push('import { headers } from "next/headers";'),s.push('import { redirect } from "next/navigation";'),s.push('import { auth } from "@/lib/auth";'),s.push(""),s.push("export default async function HomePage() {"),s.push(" const session = await auth.api.getSession({ headers: await headers() });"),s.push(' if (session) redirect("/dashboard");'),s.push(' redirect("/login");'),s.push("}"),s.push(""),s.join(`
|
|
2392
|
+
`)}function Bl(t,e){let o=t.authModel==="none",n=[];o||(n.push('import { Suspense } from "react";'),n.push('import { headers } from "next/headers";'),n.push('import { redirect } from "next/navigation";'),n.push('import { auth } from "@/lib/auth";'),n.push('import { VerifiedBanner } from "@/components/auth/verified-banner";')),t.navStyle==="topbar"?n.push('import TopNav from "@/components/topnav";'):t.navStyle!=="none"&&n.push('import Sidebar from "@/components/sidebar";'),!o&&t.roles&&t.roles.length>0&&n.push('import { getUserRole } from "@/lib/roles";'),n.push(""),n.push("export default async function DashboardLayout({ children }: { children: React.ReactNode }) {"),o?n.push(' const user = { name: "Guest", email: "" };'):(n.push(" const session = await auth.api.getSession({ headers: await headers() });"),n.push(' if (!session) redirect("/login");'),n.push(""),t.roles&&t.roles.length>0?(n.push(" const role = getUserRole(session.user as Record<string, unknown>);"),n.push(" const user = { name: session.user.name, email: session.user.email, role };")):(n.push(" const user = {"),n.push(" name: session.user.name,"),n.push(" email: session.user.email,"),n.push(" role: (session.user as Record<string, unknown>).role as string | undefined,"),n.push(" };"))),n.push("");let s=o?"":"<Suspense fallback={null}><VerifiedBanner /></Suspense>";return t.navStyle==="topbar"?(n.push(" return ("),n.push(' <div className="min-h-screen">'),n.push(" <TopNav user={user} />"),n.push(' <main className="mx-auto max-w-7xl p-6">'+s+"{children}</main>"),n.push(" </div>"),n.push(" );")):t.navStyle==="none"?(n.push(" return ("),n.push(' <div className="min-h-screen">'),n.push(' <main className="mx-auto max-w-5xl p-6">'+s+"{children}</main>"),n.push(" </div>"),n.push(" );")):(n.push(" return ("),n.push(' <div className="flex flex-col md:flex-row min-h-screen">'),n.push(" <Sidebar user={user} />"),n.push(' <main className="flex-1 overflow-x-hidden p-4 md:p-6">'+s+"{children}</main>"),n.push(" </div>"),n.push(" );")),n.push("}"),n.push(""),n.join(`
|
|
2393
|
+
`)}function zl(t){let e=At(t.name),o=t.dataModel??[],n=[];if(o.length>0){let s=o.map(r=>vo(r.entity??r.name??"item")),a=[...new Set(s)];n.push('import { Card, CardContent } from "@/components/ui/card";'),n.push("import { "+a.join(", ")+' } from "lucide-react";'),n.push("")}if(n.push("export default function DashboardPage() {"),n.push(" return ("),n.push(' <div className="space-y-6">'),n.push(" <div>"),n.push(' <h1 className="text-3xl font-bold">'+e+"</h1>"),t.summary&&n.push(' <p className="mt-1 text-muted-foreground">'+t.summary+"</p>"),n.push(" </div>"),o.length>0){n.push(' <div className="rounded-lg border p-8 text-center">'),n.push(' <h2 className="text-lg font-semibold">Get started</h2>'),n.push(` <p className="mt-1 text-sm text-muted-foreground">Here's what you can do</p>`),n.push(' <div className="mt-6 grid gap-3 sm:grid-cols-2 text-left">');for(let s of o){let a=s.entity??s.name??"Item",r=vo(a),i=At(a.replace(/_/g,"-"));n.push(' <div className="flex items-center gap-3 rounded-md border p-3">'),n.push(" <"+r+' className="h-5 w-5 text-muted-foreground" />'),n.push(' <span className="text-sm font-medium">Add your first '+i+"</span>"),n.push(" </div>")}n.push(" </div>"),n.push(" </div>")}return n.push(" </div>"),n.push(" );"),n.push("}"),n.push(""),n.join(`
|
|
2394
|
+
`)}function Hl(t,e=!1){if(!t.multiTenant)return null;let o=[];return e?(o.push('import { pgTable, text, timestamp, index } from "drizzle-orm/pg-core";'),o.push('import { user } from "./auth";'),o.push(""),o.push('export const organization = pgTable("organization", {'),o.push(' id: text("id").primaryKey(),'),o.push(' name: text("name").notNull(),'),o.push(' slug: text("slug").unique().notNull(),'),o.push(' createdAt: timestamp("created_at").defaultNow().notNull(),'),o.push(' updatedAt: timestamp("updated_at").defaultNow().notNull(),'),o.push("});"),o.push(""),o.push("export const orgMember = pgTable(")):(o.push('import { sqliteTable, text, index } from "drizzle-orm/sqlite-core";'),o.push('import { sql } from "drizzle-orm";'),o.push('import { user } from "./auth";'),o.push(""),o.push('export const organization = sqliteTable("organization", {'),o.push(' id: text("id").primaryKey(),'),o.push(' name: text("name").notNull(),'),o.push(' slug: text("slug").unique().notNull(),'),o.push(' createdAt: text("created_at").default(sql`CURRENT_TIMESTAMP`).notNull(),'),o.push(' updatedAt: text("updated_at").default(sql`CURRENT_TIMESTAMP`).notNull(),'),o.push("});"),o.push(""),o.push("export const orgMember = sqliteTable(")),o.push(' "org_member",'),o.push(" {"),o.push(' id: text("id").primaryKey(),'),o.push(' orgId: text("org_id").notNull().references(() => organization.id),'),o.push(' userId: text("user_id").notNull().references(() => user.id),'),o.push(' role: text("role").notNull(),'),e?o.push(' joinedAt: timestamp("joined_at").defaultNow().notNull(),'):o.push(' joinedAt: text("joined_at").default(sql`CURRENT_TIMESTAMP`).notNull(),'),o.push(" },"),o.push(" (table) => ({"),o.push(' orgIdx: index("org_member_org_idx").on(table.orgId),'),o.push(' userIdx: index("org_member_user_idx").on(table.userId),'),o.push(" }),"),o.push(");"),o.push(""),o.join(`
|
|
2395
|
+
`)}function Wl(t){if(!t.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(`
|
|
2396
|
+
`)}function Gl(t){if(!t.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(`
|
|
2397
|
+
`)}function Vl(t,e,o){let n=[],s=t.split("-").map(l=>l.charAt(0).toUpperCase()+l.slice(1)).join(" ");n.push(`# ${s}`),n.push(""),e?.summary&&(n.push(e.summary),n.push(""));let a=e?.features??[];if(a.length>0){n.push("## Features"),n.push("");for(let l of a){let p=l.description?` \u2014 ${l.description}`:"";n.push(`- **${l.name}**${p}`)}n.push("")}n.push("## Tech Stack"),n.push(""),n.push("| Layer | Technology |"),n.push("|-------|------------|"),n.push("| Framework | Next.js 15 (App Router) |"),n.push("| Database | Mistflow Cloud (Postgres) + Drizzle ORM |"),n.push("| Auth | Better Auth (email/password, social login) |"),n.push("| Styling | Tailwind CSS + shadcn/ui |"),n.push("| Deployment | Mistflow Cloud |"),o.hasStripe&&n.push("| Payments | Stripe |"),o.hasResend&&n.push("| Email | Resend + React Email |"),o.hasStorage&&n.push("| File Storage | Mistflow Cloud (managed blob storage) |"),o.hasAdmin&&n.push("| Admin | Better Auth admin plugin |"),o.hasAI&&n.push("| AI | Vercel AI SDK + OpenAI |"),n.push("");let r=e?.pages??[];if(r.length>0){n.push("## Pages"),n.push(""),n.push("| Route | Description |"),n.push("|-------|-------------|");for(let l of r){let p=l.path??l.route??l.name??"",m=l.description??"";n.push(`| \`${p.startsWith("/")?p:"/"+p}\` | ${m} |`)}n.push("")}let i=e?.dataModel??[];if(i.length>0){n.push("## Data Model"),n.push("");for(let l of i){let p=l.entity??l.name??"Unknown";if(n.push(`### ${p}`),n.push(""),l.fields.length>0){if(typeof l.fields[0]=="string")n.push(`Fields: ${l.fields.join(", ")}`);else{n.push("| Field | Type |"),n.push("|-------|------|");for(let m of l.fields)n.push(`| ${m.name} | ${m.type} |`)}n.push("")}}}return n.push("## Getting Started"),n.push(""),n.push("### Prerequisites"),n.push(""),n.push("- Node.js 20+"),n.push("- npm"),n.push(""),n.push("### Install"),n.push(""),n.push("The host AI calls mist_install (fire-and-poll) which handles this for you. Run manually with plain npm if needed:"),n.push(""),n.push("```bash"),n.push("npm install"),n.push("```"),n.push(""),n.push("### Set up environment"),n.push(""),n.push("Copy `.env.example` to `.env.local` and fill in the values:"),n.push(""),n.push("```bash"),n.push("cp .env.example .env.local"),n.push("```"),n.push(""),n.push("| Variable | Description | Required |"),n.push("|----------|-------------|----------|"),o.isNeon?n.push("| `DATABASE_URL` | Postgres connection URL | Yes |"):(n.push("| `TURSO_URL` | Database connection URL | Yes |"),n.push("| `TURSO_AUTH_TOKEN` | Database auth token | Yes |")),n.push("| `AUTH_SECRET` | Auth encryption secret (auto-generated) | Yes |"),o.hasStripe&&(n.push("| `STRIPE_SECRET_KEY` | Stripe secret key | Yes |"),n.push("| `STRIPE_WEBHOOK_SECRET` | Stripe webhook signing secret | Yes |"),n.push("| `NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY` | Stripe publishable key | Yes |")),o.hasResend&&(n.push("| `RESEND_API_KEY` | Resend API key | Yes |"),n.push("| `EMAIL_FROM` | Sender email address | Yes (production) |")),o.hasStorage&&(n.push("| `MISTFLOW_API_KEY` | Mistflow API key for file storage | Yes |"),n.push("| `MISTFLOW_PROJECT_ID` | Mistflow project ID | Yes |")),o.hasAI&&n.push("| `OPENAI_API_KEY` | OpenAI API key | Yes |"),n.push(""),n.push("### Local database"),n.push(""),o.isNeon?(n.push("For local development, start a local Postgres server:"),n.push(""),n.push("```bash"),n.push("# Using Docker:"),n.push("docker run -d --name postgres -e POSTGRES_PASSWORD=postgres -p 5432:5432 postgres:17"),n.push("# Or install via Homebrew: brew install postgresql@17 && brew services start postgresql@17"),n.push("```")):(n.push("For local development, start a local Turso server:"),n.push(""),n.push("```bash"),n.push("npx turso dev"),n.push("```")),n.push(""),n.push("Then set up the database:"),n.push(""),n.push("```bash"),n.push("npm run db:push"),n.push("```"),n.push(""),n.push("### Run"),n.push(""),n.push("```bash"),n.push("npm run dev"),n.push("```"),n.push(""),n.push("Open [http://localhost:3000](http://localhost:3000)."),n.push(""),n.push("## Project Structure"),n.push(""),n.push("```"),n.push("app/"),n.push(" (auth)/ Login and registration pages"),n.push(" (dashboard)/ Authenticated app pages"),o.hasAdmin&&n.push(" (admin)/ Admin panel pages"),n.push(" api/ API routes (auth, health, webhooks)"),n.push(" layout.tsx Root layout with fonts and providers"),n.push(" globals.css Design tokens and Tailwind config"),n.push("components/ Reusable UI components"),n.push("db/"),n.push(" schema/ Database table definitions"),n.push(" index.ts Schema exports"),n.push("lib/"),n.push(" auth.ts Better Auth server config"),n.push(" auth-client.ts Better Auth client config"),n.push(` db.ts ${o.isNeon?"Postgres":"SQLite"} database connection`),o.hasStripe&&n.push(" stripe.ts Stripe client"),o.hasResend&&(n.push(" resend.ts Resend client"),n.push(" email.ts Email send helpers")),o.hasStorage&&n.push(" storage.ts File upload/download helpers"),o.hasAI&&n.push(" ai.ts AI client (Vercel AI SDK + OpenAI)"),o.hasResend&&n.push("emails/ React Email templates"),n.push("```"),n.push(""),n.push("## Deploy"),n.push(""),n.push("Deploy to production with Mistflow:"),n.push(""),n.push("```"),n.push("# In your AI editor (Claude Code, Cursor, etc.):"),n.push("mist_deploy action='deploy'"),n.push("```"),n.push(""),n.push("Your app will be live at `https://<app-name>.mistflow.app`."),n.push(""),e?.design&&(n.push("## Design"),n.push(""),e.design.tone&&n.push(`- **Tone**: ${e.design.tone}`),e.design.fonts&&(n.push(`- **Heading font**: ${e.design.fonts.heading}`),n.push(`- **Body font**: ${e.design.fonts.body}`)),e.design.accentColor&&n.push(`- **Accent color**: ${e.design.accentColor}`),e.design.borderRadius&&n.push(`- **Border radius**: ${e.design.borderRadius}`),n.push("")),n.push("---"),n.push(""),n.push("Built with [Mistflow](https://mistflow.ai)"),n.push(""),n.join(`
|
|
2398
|
+
`)}async function Jl(t,e){let{name:o,plan:n,path:s,planId:a}=t;if(!s)return c("mist_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(!xl(s))return c(`mist_init 'path' must be an absolute path \u2014 received '${s}'. Pass the full absolute path to the target directory.`,!0);let r=lr(s),i=n;if(!i&&a){let f=Pl(a);if(!f)return c(`No plan found for planId '${a}'. Call mist_plan first, or pass the plan object inline.`,!0);i=f.plan}let l=i?.design,p=i?.appStyle,m=i?sn(i,"stripe","payment","billing","subscription","checkout","pricing"):!1,u=!0,d=i?sn(i,"upload","file storage","image upload","profile picture","attachment","gallery","media","blob"):!1,b=i?sn(i,"admin panel","admin dashboard","admin management"):!1,R=i?sn(i,"ai integration","openai","llm","ai chat","chatbot","gpt"):!1,w=i,y=!0;if(!Rl(r))return c(`A project already exists at this location (${r}). Choose a different name, or delete the existing folder first. (A .mistflow/ folder left over from planning is fine \u2014 init will preserve it.)`,!0);bo(r,{recursive:!0});try{let f=he(Rt(r),".mistflow","mockups");if(He(f)){let S=ar(f).filter(O=>O.endsWith(".html"));if(S.length>0){let O=he(r,".mistflow","mockups");bo(O,{recursive:!0});for(let H of S)vl(he(f,H),he(O,H));console.error(`Copied ${S.length} mockup file(s) into project`)}}}catch(f){console.error("Could not copy mockup files:",f instanceof Error?f.message:f)}let k=null;try{k=await Bn("nextjs")}catch(f){console.error("Could not fetch scaffold from API, using minimal scaffold:",f instanceof Error?f.message:f)}if(k){let f=o.toLowerCase().replace(/[^a-z0-9-]/g,"-");for(let T of k.files){if(T.path==="package.json"||T.path==="middleware.ts"||T.path==="components/sidebar.tsx"||T.path==="components/topnav.tsx"||T.path==="app/(dashboard)/layout.tsx"||T.path==="app/(dashboard)/page.tsx"||T.path==="app/(dashboard)/dashboard/page.tsx"||!m&&(T.path.includes("stripe")||T.path.includes("webhook/stripe"))||!u&&(T.path.includes("resend")||T.path.includes("emails/"))||!b&&(T.path.includes("(admin)")||T.path.includes("admin-sidebar"))||y&&(T.path==="lib/db.ts"||T.path==="lib/auth.ts"||T.path==="drizzle.config.ts"||T.path==="db/schema/auth.ts"))continue;let M=T.content.replace(/\{\{APP_NAME\}\}/g,o).replace(/\{\{WORKER_NAME\}\}/g,f);if(y&&T.path==="next.config.ts"&&(M=M.replace(/serverExternalPackages:\s*\[[^\]]*\],?/g,'serverExternalPackages: ["@electric-sql/pglite"],')),T.path==="next.config.ts"){let h=_l(r);h&&(console.error(`[init] Project is inside monorepo at ${h} \u2014 adding outputFileTracingRoot`),M.includes("outputFileTracingRoot")||(M=M.replace('import type { NextConfig } from "next";',`import type { NextConfig } from "next";
|
|
2399
|
+
import { dirname } from "path";
|
|
2400
|
+
import { fileURLToPath } from "url";
|
|
2401
|
+
|
|
2402
|
+
const __dirname = dirname(fileURLToPath(import.meta.url));`),M=M.replace("images: {",`outputFileTracingRoot: __dirname,
|
|
2403
|
+
images: {`)))}!b&&T.path.includes("sidebar")&&(M=M.replace(/\{user\.role === "admin"[\s\S]*?<\/Link>\s*\)\}/m,""),M=M.replace(/, Shield/g,"")),A(r,T.path,M)}let S={...k.dependencies},O={...k.devDependencies};if(S["drizzle-zod"]||(S["drizzle-zod"]="^0.5.1"),y&&(delete S["@libsql/client"],S["@neondatabase/serverless"]="^0.10.0",O["@electric-sql/pglite"]="^0.2.0"),m&&(S.stripe="^17.0.0"),u&&(S.resend="^4.0.0",S["@react-email/components"]="^0.0.31"),R&&(S.ai="^4.0.0",S["@ai-sdk/openai"]="^1.0.0",S.openai="^4.0.0"),A(r,"package.json",JSON.stringify({name:o,version:"0.1.0",private:!0,scripts:{dev:"next dev",build:"next build","build:cf":"opennextjs-cloudflare build",start:"next start",lint:"next lint","db:push":"drizzle-kit push","db:studio":"drizzle-kit studio"},dependencies:S,devDependencies:O,optionalDependencies:{"@noble/ciphers":"^1.3.0"},overrides:{react:"19.1.0","react-dom":"19.1.0",punycode:"^2.3.1"}},null,2)),k.methodology){let T=k.methodology;y&&(T=T.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")),T=ho(T),A(r,"AGENTS.md",T),A(r,"CLAUDE.md",T)}let we=i?.designMd;we&&A(r,"DESIGN.md",we),y&&(A(r,"lib/db.ts",['import { neon } from "@neondatabase/serverless";','import { drizzle as drizzleNeon } from "drizzle-orm/neon-http";',"","// eslint-disable-next-line @typescript-eslint/no-explicit-any","let _db: any = null;","","function getDb() {"," if (!_db) {",' if (process.env.DATABASE_URL && process.env.DATABASE_URL !== "pglite") {'," // Production / remote Postgres"," const sql = neon(process.env.DATABASE_URL);"," _db = drizzleNeon(sql);"," } else {"," // Local dev \u2014 PGlite (zero-install embedded Postgres). Lives in"," // lib/db-local.ts and is loaded through a runtime-only require"," // whose path is built from a variable, so esbuild's static"," // analysis can't follow it. Keeps pglite + its 30MB WASM out of"," // the Worker bundle.",' const localPath: string = "./" + "db-local";'," // eslint-disable-next-line @typescript-eslint/no-require-imports"," const { createLocalDb } = require(localPath);"," _db = createLocalDb();"," }"," }"," return _db;","}","","// Lazy proxy \u2014 DB isn't initialized at import/build time","// eslint-disable-next-line @typescript-eslint/no-explicit-any","export const db: any = new Proxy({} as any, {"," get(_target, prop, receiver) {"," const realDb = getDb();"," const value = Reflect.get(realDb, prop, receiver);",' if (typeof value === "function") {'," return value.bind(realDb);"," }"," return value;"," },","});",""].join(`
|
|
2404
|
+
`)),A(r,"lib/db-local.ts",["// Local-dev-only DB factory. Isolated from lib/db.ts so the production","// Cloudflare Worker bundle never loads drizzle-orm/pglite or its","// transitive 30MB WASM binary. Loaded via runtime-only require() from","// db.ts, where the path is built from a variable to defeat static analysis.","",'const pglitePkg: string = ["@electric-sql", "pglite"].join("/");',"// eslint-disable-next-line @typescript-eslint/no-require-imports","const { PGlite } = require(pglitePkg);","",'const drizzlePath: string = "drizzle-orm/" + "pglite";',"// eslint-disable-next-line @typescript-eslint/no-require-imports","const { drizzle } = require(drizzlePath);","","// eslint-disable-next-line @typescript-eslint/no-explicit-any","export function createLocalDb(): any {",' const client = new PGlite("./local.pg");'," return drizzle(client);","}",""].join(`
|
|
2405
|
+
`)),A(r,"drizzle.config.ts",['import { defineConfig } from "drizzle-kit";',"","// PGlite for local dev (no Postgres install needed), Mistflow Cloud for production",'const isPglite = !process.env.DATABASE_URL || process.env.DATABASE_URL === "pglite";',"","export default defineConfig({",' schema: "./db/schema",',' out: "./db/migrations",',' dialect: "postgresql",',' ...(isPglite ? { driver: "pglite", dbCredentials: { url: "./local.pg" } } : { dbCredentials: { url: process.env.DATABASE_URL! } }),',"});",""].join(`
|
|
2406
|
+
`)),A(r,"db/schema/auth.ts",['import { pgTable, text, boolean, timestamp } from "drizzle-orm/pg-core";',"",'export const user = pgTable("user", {',' id: text("id").primaryKey(),',' name: text("name").notNull(),',' email: text("email").notNull().unique(),',' emailVerified: boolean("email_verified").notNull().default(false),',' image: text("image"),',' role: text("role").default("user"),',' banned: boolean("banned").default(false),',' banReason: text("ban_reason"),',' banExpires: timestamp("ban_expires"),',' createdAt: timestamp("created_at").notNull(),',' updatedAt: timestamp("updated_at").notNull(),',"});","",'export const session = pgTable("session", {',' id: text("id").primaryKey(),',' expiresAt: timestamp("expires_at").notNull(),',' token: text("token").notNull().unique(),',' createdAt: timestamp("created_at").notNull(),',' updatedAt: timestamp("updated_at").notNull(),',' ipAddress: text("ip_address"),',' userAgent: text("user_agent"),',' userId: text("user_id").notNull().references(() => user.id, { onDelete: "cascade" }),',' impersonatedBy: text("impersonated_by"),',"});","",'export const account = pgTable("account", {',' id: text("id").primaryKey(),',' accountId: text("account_id").notNull(),',' providerId: text("provider_id").notNull(),',' userId: text("user_id").notNull().references(() => user.id, { onDelete: "cascade" }),',' accessToken: text("access_token"),',' refreshToken: text("refresh_token"),',' idToken: text("id_token"),',' accessTokenExpiresAt: timestamp("access_token_expires_at"),',' refreshTokenExpiresAt: timestamp("refresh_token_expires_at"),',' scope: text("scope"),',' password: text("password"),',' createdAt: timestamp("created_at").notNull(),',' updatedAt: timestamp("updated_at").notNull(),',"});","",'export const verification = pgTable("verification", {',' id: text("id").primaryKey(),',' identifier: text("identifier").notNull(),',' value: text("value").notNull(),',' expiresAt: timestamp("expires_at").notNull(),',' createdAt: timestamp("created_at"),',' updatedAt: timestamp("updated_at"),',"});",""].join(`
|
|
2407
|
+
`)),A(r,"lib/auth.ts",['import { betterAuth } from "better-auth";','import { drizzleAdapter } from "better-auth/adapters/drizzle";','import { admin } from "better-auth/plugins/admin";','import { nextCookies } from "better-auth/next-js";','import { db } from "./db";','import * as schema from "@/db";',"","async function sendEmail({ to, subject, html, fallbackUrl }: { to: string; subject: string; html: string; fallbackUrl?: string }) {"," const apiKey = process.env.RESEND_API_KEY;"," if (!apiKey) {"," if (fallbackUrl) {"," console.error(`\\n[auth] No RESEND_API_KEY set. Email to ${to} was not sent.`);"," console.error(`[auth] Dev fallback \u2014 use this link directly:\\n ${fallbackUrl}\\n`);"," } else {"," console.error(`[auth] RESEND_API_KEY not set \u2014 skipping email send to ${to}`);"," }"," return;"," }",' const from = process.env.EMAIL_FROM || "noreply@mail.mistflow.app";',' const res = await fetch("https://api.resend.com/emails", {',' method: "POST",',' headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },'," body: JSON.stringify({ from, to, subject, html }),"," });"," if (!res.ok) {",' const body = await res.text().catch(() => "unknown");'," console.error(`[auth] Email send failed (${res.status}): ${body}`);"," throw new Error(`Email send failed: ${res.status}`);"," }","}","","function createAuth() {",' const baseURL = process.env.BETTER_AUTH_URL || process.env.NEXT_PUBLIC_APP_URL || "http://localhost:3000";',' const isLocal = baseURL.includes("localhost") || baseURL.includes("127.0.0.1");'," const canSendEmail = Boolean(process.env.RESEND_API_KEY);"," // Refuse to boot a production app with email auth but no mail sender. Mistflow's"," // deploy pipeline injects a managed Resend key automatically; if it's missing,"," // that's a real misconfig and silent fallbacks let unverified users sign up."," if (!isLocal && !canSendEmail) {",` throw new Error("[auth] RESEND_API_KEY is required in production. The Mistflow deploy pipeline injects one automatically \u2014 if you're seeing this, check the project's env vars in the dashboard, or set your own RESEND_API_KEY.");`," }"," return betterAuth({"," baseURL,"," trustedOrigins: [baseURL],",' database: drizzleAdapter(db, { provider: "pg", schema }),'," emailAndPassword: {"," enabled: true,"," requireEmailVerification: !isLocal && canSendEmail,"," sendResetPassword: async ({ user, token }: { user: { email: string; name: string }; url: string; token: string }) => {"," // Better Auth's default reset URL points at /reset-password/:token (path),"," // which our frontend doesn't route. We build our own pointing at our"," // /reset-password?token=xxx page which reads the token from the query."," const resetUrl = `${baseURL}/reset-password?token=${token}`;"," await sendEmail({"," to: user.email,",' subject: "Reset your password",',' html: `<p>Hi ${user.name},</p><p>Click the link below to reset your password:</p><p><a href="${resetUrl}">${resetUrl}</a></p>`,'," fallbackUrl: isLocal ? resetUrl : undefined,"," });"," },"," },"," emailVerification: {"," sendOnSignUp: canSendEmail,"," autoSignInAfterVerification: true,"," sendVerificationEmail: async ({ user, url }: { user: { email: string; name: string }; url: string }) => {"," await sendEmail({"," to: user.email,",' subject: "Verify your email address",',' html: `<p>Hi ${user.name},</p><p>Click the link below to verify your email:</p><p><a href="${url}">${url}</a></p>`,'," fallbackUrl: isLocal ? url : undefined,"," });"," },"," },"," secret: process.env.AUTH_SECRET,",' plugins: [admin({ defaultRole: "user" }), nextCookies()],'," databaseHooks: {"," user: {"," create: {"," // Auto-promote the app owner to admin on first signup. ADMIN_EMAIL"," // is injected by the Mistflow deploy pipeline (the email of the"," // account that ran mist_deploy). Email verification still gates"," // login when Resend is configured, so a collision attempt can't"," // actually sign in without clicking a link delivered to the"," // owner's inbox."," before: async (user: { email?: string; [k: string]: unknown }) => {"," const adminEmail = process.env.ADMIN_EMAIL;"," if (adminEmail && user.email?.toLowerCase() === adminEmail.toLowerCase()) {",' return { data: { ...user, role: "admin" } };'," }"," return { data: user };"," },"," },"," },"," },"," socialProviders: {"," ...(process.env.GOOGLE_CLIENT_ID ? {"," google: {"," clientId: process.env.GOOGLE_CLIENT_ID,"," clientSecret: process.env.GOOGLE_CLIENT_SECRET!,"," },"," } : {}),"," ...(process.env.GITHUB_CLIENT_ID ? {"," github: {"," clientId: process.env.GITHUB_CLIENT_ID,"," clientSecret: process.env.GITHUB_CLIENT_SECRET!,"," },"," } : {}),"," },"," });","}","","// Lazy init \u2014 process.env isn't populated at module scope on Cloudflare Workers.","// The `has` trap is required: better-auth's toNextJsHandler does",'// `"handler" in auth ? auth.handler(request) : auth(request)` \u2014 without a `has`',"// trap the default forwards to the empty target object, returns false, and the","// handler tries to call the Proxy as a function, which throws TypeError and","// returns 500 on every /api/auth/* request.","let _auth: ReturnType<typeof createAuth> | null = null;","export const auth = new Proxy({} as ReturnType<typeof createAuth>, {"," get(_target, prop, receiver) {"," if (!_auth) _auth = createAuth();"," const value = Reflect.get(_auth, prop, receiver);",' if (typeof value === "function") return value.bind(_auth);'," return value;"," },"," has(_target, prop) {"," if (!_auth) _auth = createAuth();"," return prop in _auth;"," },","});",""].join(`
|
|
2408
|
+
`)))}else A(r,"package.json",JSON.stringify({name:o,version:"0.1.0",private:!0},null,2));let U=i?.designMd;A(r,"app/globals.css",jl(l,p,U)),A(r,"app/layout.tsx",Ml(o,l,w?.language)),A(r,"README.md",Vl(o,i,{hasStripe:m,hasResend:u,hasStorage:d,hasAdmin:b,hasAI:R,isNeon:y})),A(r,"contracts/README.md",mo());let Y=i?.dataModel??[],G=new Set,ie=0;for(let f of Y){let S=f.entity??f.name;if(!S||typeof S!="string")continue;let O=fo(S);G.has(O)||(G.add(O),A(r,O,go(S)),ie++)}ie===0&&A(r,"contracts/.gitkeep","");let B=[],v=i?.publicPages;if(Array.isArray(v))B=v;else if(typeof v=="string"){try{B=JSON.parse(v)}catch{B=[]}Array.isArray(B)||(B=[])}if(!B.includes("/")){let f=i?.steps?.some(O=>{let H=((O.name??"")+" "+(O.description??"")).toLowerCase();return H.includes("landing")||H.includes("marketing")||H.includes("homepage")}),S=i?.pages?.some(O=>O.path==="/");(f||S)&&(B=["/",...B])}let L={name:o,summary:i?.summary,authModel:i?.authModel,roles:i?.roles,defaultRole:i?.defaultRole,publicPages:B,navStyle:i?.navStyle,multiTenant:i?.multiTenant,pages:i?.pages,dataModel:i?.dataModel,design:i?.design},Q=$l(L);Q&&A(r,"middleware.ts",Q);let se=Ll(L);se&&A(r,se.path,se.content);let xe=Fl(L);if(xe&&A(r,"lib/roles.ts",xe),A(r,"app/page.tsx",ql(L)),A(r,"app/(dashboard)/layout.tsx",Bl(L,b)),A(r,"app/(dashboard)/dashboard/page.tsx",zl(L)),L.multiTenant){let f=Hl(L,y);f&&A(r,"db/schema/organization.ts",f);let S=Wl(L);S&&A(r,"lib/org.ts",S);let O=Gl(L);O&&A(r,"components/org-switcher.tsx",O)}A(r,"tsconfig.json",JSON.stringify({compilerOptions:{target:"ES2017",lib:["dom","dom.iterable","esnext"],allowJs:!0,skipLibCheck:!0,strict:!1,noEmit:!0,esModuleInterop:!0,module:"esnext",moduleResolution:"bundler",resolveJsonModule:!0,isolatedModules:!0,jsx:"preserve",incremental:!0,plugins:[{name:"next"}],paths:{"@/*":["./*"]}},include:["next-env.d.ts","**/*.ts","**/*.tsx",".next/types/**/*.ts"],exclude:["node_modules"]},null,2)),m&&A(r,"lib/stripe.ts",['import Stripe from "stripe";',"","let _stripe: Stripe | null = null;","","function getStripe(): Stripe {"," if (!_stripe) {"," if (!process.env.STRIPE_SECRET_KEY) {",' throw new Error("STRIPE_SECRET_KEY is not set");'," }"," _stripe = new Stripe(process.env.STRIPE_SECRET_KEY, {"," typescript: true,"," });"," }"," return _stripe;","}","","// Lazy proxy \u2014 Stripe isn't initialized at import/build time","export const stripe = new Proxy({} as Stripe, {"," get(_target, prop) {"," return (getStripe() as unknown as Record<string | symbol, unknown>)[prop];"," },","});",""].join(`
|
|
2409
|
+
`)),u&&(A(r,"lib/resend.ts",['import { Resend } from "resend";',"","let _resend: Resend | null = null;","","function getResend(): Resend {"," if (!_resend) {"," if (!process.env.RESEND_API_KEY) {",' throw new Error("RESEND_API_KEY is not set");'," }"," _resend = new Resend(process.env.RESEND_API_KEY);"," }"," return _resend;","}","","// Lazy proxy \u2014 Resend isn't initialized at import/build time","export const resend = new Proxy({} as Resend, {"," get(_target, prop) {"," return (getResend() as unknown as Record<string | symbol, unknown>)[prop];"," },","});",""].join(`
|
|
2410
|
+
`)),A(r,"lib/email.ts",['import { resend } from "./resend";',"",'const FROM = process.env.EMAIL_FROM ?? "onboarding@resend.dev";',"","export async function sendEmail({"," to,"," subject,"," react,","}: {"," to: string;"," subject: string;"," react: React.ReactElement;","}) {"," return resend.emails.send({ from: FROM, to, subject, react });","}",""].join(`
|
|
2411
|
+
`))),d&&(A(r,"lib/storage.ts",['const MISTFLOW_API = process.env.MISTFLOW_API_URL ?? "https://api.mistflow.ai";',"const MISTFLOW_API_KEY = process.env.MISTFLOW_API_KEY;","const PROJECT_ID = process.env.MISTFLOW_PROJECT_ID;","","interface UploadResult {"," upload_url: string;"," download_url: string;"," key: string;","}","","function authHeaders(): Record<string, string> {"," return {",' "Content-Type": "application/json",',' "Authorization": `ApiKey ${MISTFLOW_API_KEY}`,'," };","}","",'export async function getUploadUrl(filename: string, contentType: string = "application/octet-stream"): Promise<UploadResult> {'," const res = await fetch(`${MISTFLOW_API}/api/storage/upload-url`, {",' method: "POST",'," headers: authHeaders(),"," body: JSON.stringify({ project_id: PROJECT_ID, filename, content_type: contentType }),"," });"," if (!res.ok) throw new Error(`Storage error: ${res.status}`);"," return res.json();","}","","export async function getDownloadUrl(filename: string): Promise<string> {"," const res = await fetch(`${MISTFLOW_API}/api/storage/download-url`, {",' method: "POST",'," headers: authHeaders(),"," body: JSON.stringify({ project_id: PROJECT_ID, filename }),"," });"," if (!res.ok) throw new Error(`Storage error: ${res.status}`);"," const data = await res.json();"," return data.download_url;","}","","export async function deleteFile(filename: string): Promise<void> {"," await fetch(`${MISTFLOW_API}/api/storage/delete`, {",' method: "POST",'," headers: authHeaders(),"," body: JSON.stringify({ project_id: PROJECT_ID, filename }),"," });","}","","export async function uploadFile(file: File): Promise<string> {"," const { upload_url, download_url } = await getUploadUrl(file.name, file.type);",' await fetch(upload_url, { method: "PUT", body: file, headers: { "Content-Type": file.type } });'," return download_url;","}",""].join(`
|
|
2412
|
+
`)),A(r,"app/api/upload/route.ts",['import { NextRequest, NextResponse } from "next/server";','import { getUploadUrl } from "@/lib/storage";',"","export async function POST(req: NextRequest) {"," const { filename, contentType } = await req.json();"," if (!filename) {",' return NextResponse.json({ error: "filename is required" }, { status: 400 });'," }"," try {",' const result = await getUploadUrl(filename, contentType ?? "application/octet-stream");'," return NextResponse.json(result);"," } catch {",' return NextResponse.json({ error: "Failed to get upload URL" }, { status: 500 });'," }","}",""].join(`
|
|
2413
|
+
`))),R&&(A(r,"lib/ai.ts",['import { createOpenAI } from "@ai-sdk/openai";',"","export const openai = createOpenAI({"," apiKey: process.env.OPENAI_API_KEY,","});",""].join(`
|
|
2414
|
+
`)),A(r,"app/api/chat/route.ts",['import { openai } from "@/lib/ai";','import { streamText } from "ai";',"","export async function POST(req: Request) {"," const { messages } = await req.json();",""," const result = streamText({",' model: openai("gpt-4o"),'," messages,"," });",""," return result.toDataStreamResponse();","}",""].join(`
|
|
2415
|
+
`)));let E={name:o,methodologyVersion:k?.version??"1.0",createdAt:new Date().toISOString(),...a?{planId:a}:{},plan:Array.isArray(i?.steps)?{...i,steps:i.steps.map(f=>({number:f.number,name:f.name??f.title,description:f.description,entities:f.entities,pages:f.pages,features:f.features,status:"pending"}))}:i,dbProvider:"neon",env:{managed:{DATABASE_URL:{description:"Postgres connection URL",scope:"production"},AUTH_SECRET:{description:"Auth encryption secret",scope:"production"},...m?{STRIPE_SECRET_KEY:{description:"Stripe secret key",scope:"production"},STRIPE_WEBHOOK_SECRET:{description:"Stripe webhook signing secret",scope:"production"},NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY:{description:"Stripe publishable key",scope:"production"}}:{},...u?{RESEND_API_KEY:{description:"Resend API key \u2014 managed by Mistflow by default, override with your own key from resend.com",scope:"production"},EMAIL_FROM:{description:"Sender email address \u2014 managed by Mistflow by default",scope:"production"}}:{},...d?{MISTFLOW_API_KEY:{description:"Mistflow API key for file storage",scope:"production"},MISTFLOW_PROJECT_ID:{description:"Mistflow project ID",scope:"production"}}:{}},...R?{required:{OPENAI_API_KEY:{description:"OpenAI API key",setupUrl:"https://platform.openai.com/api-keys"}}}:{}},authModel:i?.authModel??"email",roles:i?.roles??null,navStyle:i?.navStyle??"sidebar",multiTenant:i?.multiTenant??!1,hasAdmin:b,hasResend:u,hasStorage:d,hasAI:R,deploy:null};A(r,"mistflow.json",JSON.stringify(E,null,2));let N=Sl(32).toString("hex"),fe=m?`
|
|
2416
|
+
# Stripe
|
|
2417
|
+
STRIPE_SECRET_KEY=
|
|
2418
|
+
STRIPE_WEBHOOK_SECRET=
|
|
2419
|
+
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=
|
|
2420
|
+
`:"",Ie=u?`
|
|
2421
|
+
# Email (Resend)
|
|
2422
|
+
RESEND_API_KEY=
|
|
2423
|
+
EMAIL_FROM=onboarding@resend.dev
|
|
2424
|
+
`:"",D=d?`
|
|
2425
|
+
# File Storage (Mistflow managed)
|
|
2426
|
+
MISTFLOW_API_KEY=
|
|
2427
|
+
MISTFLOW_PROJECT_ID=
|
|
2428
|
+
`:"",re=R?`
|
|
2429
|
+
# AI (get your key at https://platform.openai.com/api-keys)
|
|
2430
|
+
OPENAI_API_KEY=
|
|
2431
|
+
`:"",dt=`# Local dev: PGlite is used automatically (zero-install embedded Postgres)
|
|
2432
|
+
# Set DATABASE_URL only for production or to use a remote Postgres
|
|
2433
|
+
# DATABASE_URL=postgresql://postgres:postgres@localhost:5432/devdb`,Me=`# Local dev: PGlite is used automatically (zero-install embedded Postgres)
|
|
2434
|
+
# Set DATABASE_URL only for production or to use a remote Postgres
|
|
2435
|
+
# DATABASE_URL=postgresql://postgres:postgres@localhost:5432/devdb`;A(r,".env.local",`${dt}
|
|
2436
|
+
AUTH_SECRET=${N}
|
|
2437
|
+
${fe}${Ie}${D}${re}`),A(r,".env.example",`${Me}
|
|
2438
|
+
AUTH_SECRET=your-secret-here
|
|
2439
|
+
${fe}${Ie}${D}${re}`);let z=[],Ge=(f,S)=>{z.push({phase:f,message:S})},ae=(f,S)=>{let O=z.find(H=>H.phase===f&&!H.durationMs);O&&(O.durationMs=S)};if(e){let f=en(e.server,e.progressToken,()=>z[z.length-1]?.message??"Setting up project...");e.cleanup=()=>f.stop()}let Ue=w?.requestedSubdomain||void 0,ce,ut;Ge("register","Registering project on Mistflow...");let ye=Date.now();try{let f=await vt(o,void 0,"neon",Ue);ce=f.id;let S=he(r,"mistflow.json"),O=JSON.parse(rn(S,"utf-8"));if(O.projectId=ce,wo(S,JSON.stringify(O,null,2)),kt(r,St(ce,o)),f.managed_env&&Object.keys(f.managed_env).length>0){let H=he(r,".env.local"),be=He(H)?rn(H,"utf-8"):"";for(let[we,T]of Object.entries(f.managed_env)){let M=new RegExp(`^${we}=.*$`,"m");M.test(be)?be=be.replace(M,`${we}=${T}`):be+=`
|
|
2440
|
+
${we}=${T}`}wo(H,be)}try{let{getBaseUrl:H,getAuthHeaders:be}=await Promise.resolve().then(()=>(le(),os)),we=be(),T=i?.features,M=i?.steps,h={};Array.isArray(T)&&T.length>0&&(h.features=T.map(g=>g.name)),i&&(h.plan=i),Array.isArray(M)&&M.length>0&&(h.provenance=M.map(g=>({feature:g.name??g.title??`Step ${g.number??"?"}`,user_intent:(g.description??"").slice(0,500),decisions:"Seeded from plan at init",tradeoffs:"",files_affected:[]}))),Object.keys(h).length>0&&await fetch(`${H()}/api/projects/${encodeURIComponent(ce)}/state`,{method:"PUT",headers:{...we,"Content-Type":"application/json"},body:JSON.stringify(h)})}catch{}z[z.length-1].message=`Registered as ${ce.slice(0,8)}`}catch(f){let S=f instanceof Error?f.message:String(f);console.error("Could not register project on backend:",S),ut=`Project created locally but NOT registered on Mistflow servers (${S}). Deploy will auto-register it.`,z[z.length-1].message="Registration skipped (offline \u2014 deploy will retry)"}ae("register",Date.now()-ye),Ge("git","Initializing git repository...");let gn=Date.now();try{let f=Il(r);await f.init(),await f.add("."),await f.commit("Initial Mistflow project setup"),z[z.length-1].message="Git repository initialized"}catch{console.error("Git initialization failed, continuing without git."),z[z.length-1].message="Git init skipped"}ae("git",Date.now()-gn);let fn=z.reduce((f,S)=>f+(S.durationMs??0),0),ke={projectPath:r,projectId:ce,status:"awaiting_install"},mt=z.map(f=>{let S=f.durationMs?` (${(f.durationMs/1e3).toFixed(1)}s)`:"";return`${f.message}${S}`});ke.progress=mt,ke.totalSetupTime=`${(fn/1e3).toFixed(1)}s`;let $e=[];ce||$e.push("Project was not registered with Mistflow (not signed in). Run mist_setup to sign in BEFORE deploying \u2014 deploy will fail without it."),ut&&(ke.registrationWarning=ut),$e.length>0&&(ke.warnings=$e);let jt=`NEXT: Call mist_install({ projectPath: "${r}" }). This is fire-and-poll \u2014 the first call returns a jobId and status: "running"; re-call with the same jobId every ~15-30s until status is "complete". Typical duration 30-90s. Do NOT ask the user for permission \u2014 install is a required follow-up to init, not a decision point. After install completes, call mist_implement({ projectPath: "${r}" }) to build the first plan step.`;return ke.nextAction=ce?jt:`${jt} IMPORTANT: You MUST also run mist_setup to sign in before deploying \u2014 the project could not be registered because auth is missing.`,c(JSON.stringify(ke))}var Tl,Al,Cl,rr,Ol,Ul,cr,pr=x(()=>{"use strict";W();lo();le();Be();yo();yo();Tl=Tt.object({name:Tt.string().min(1).describe("Human-readable app name (e.g. 'Task Flow')."),plan:Tt.any().optional().describe("Full plan object. Optional when planId is provided \u2014 the tool loads the cached plan from ~/.mistflow/plans/<planId>.json."),path:Tt.string().optional().describe("Absolute path where the project should be scaffolded."),planId:Tt.string().optional().describe("Plan ID from a prior mist_plan call. When present, the full plan is loaded from disk if 'plan' is omitted.")});Al={sharp:"0.125rem",subtle:"0.375rem",rounded:"0.75rem",pill:"9999px"},Cl=[["--color-background","#ffffff"],["--color-foreground","#0a0a0a"],["--color-card","#ffffff"],["--color-card-foreground","#0a0a0a"],["--color-popover","#ffffff"],["--color-popover-foreground","#0a0a0a"],["--color-muted","#f5f5f5"],["--color-muted-foreground","#525252"],["--color-border","#e5e5e5"],["--color-input","#e5e5e5"],["--color-primary","#0a0a0a"],["--color-primary-foreground","#ffffff"],["--color-ring","#0a0a0a"],["--color-secondary","#f5f5f5"],["--color-secondary-foreground","#0a0a0a"],["--color-accent","#f5f5f5"],["--color-accent-foreground","#0a0a0a"],["--color-destructive","#b91c1c"],["--color-destructive-foreground","#ffffff"],["--color-success","#15803d"],["--color-success-foreground","#ffffff"],["--color-warning","#a16207"],["--color-warning-foreground","#ffffff"],["--color-info","#0369a1"],["--color-info-foreground","#ffffff"]];rr={"Fredoka One":"Fredoka","Source Sans Pro":"Source_Sans_3","Source Serif Pro":"Source_Serif_4","Open Sans Condensed":"Open_Sans","Baloo 2":"Baloo_2","DM Serif Display":"DM_Serif_Display","DM Serif Text":"DM_Serif_Text","IBM Plex Mono":"IBM_Plex_Mono","IBM Plex Sans":"IBM_Plex_Sans","IBM Plex Serif":"IBM_Plex_Serif","Fira Code":"Fira_Code","Fira Sans":"Fira_Sans","Noto Sans JP":"Noto_Sans_JP","PT Sans":"PT_Sans","PT Serif":"PT_Serif","Work Sans":"Work_Sans","Space Mono":"Space_Mono","Space Grotesk":"Space_Grotesk","Plus Jakarta Sans":"Plus_Jakarta_Sans"};Ol=new Set(["ar","he","fa","ur"]);Ul={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"};cr={name:"mist_init",description:"Initialize a new Next.js project using the Mistflow stack. Downloads templates from the Mistflow registry, installs dependencies, sets up auth, and initializes git. Use this after mist_plan to create the project.",inputSchema:Tl,handler:Jl}});var ur,dr=x(()=>{ur="\nApply these choices to every file you create. Customize the shadcn CSS variables in globals.css to match. Do NOT use default shadcn blue/zinc theme.\n\n**CRITICAL: shadcn/ui components are already installed. NEVER write components/ui/*.tsx files from scratch.** If you need a shadcn component, run `npx shadcn@latest add <component>` to pull it. The project already includes: button, card, input, label, form, dialog, table, dropdown-menu, badge, separator, skeleton, sheet, tabs, avatar, select, textarea, checkbox, switch, tooltip, popover, sonner.\n\n**shadcn MCP server is available.** You have the `shadcn` MCP server installed \u2014 use it to browse and search for components, blocks, and landing page sections from the shadcn registry. Before building a landing page section from scratch, check the registry for existing blocks (hero sections, feature grids, pricing tables, testimonials, footers) and customize them instead of reinventing.\n\n**Project routes (use these exact paths):** Login is at `/login` (NOT /sign-in). Register is at `/register` (NOT /sign-up). All landing page and nav links MUST use `/login` and `/register`.\n\n### Design quality rules (non-negotiable):\n\n**Typography**: Use the plan fonts everywhere. font-heading for headings, font-body for body text.\n- **Modular scale**: Use a 1.25-1.5 ratio between sizes. A 5-level system covers most needs: xs (0.75rem captions), sm (0.875rem metadata), base (1rem body), lg (1.25-1.5rem subheadings), xl+ (2-4rem headlines). Sizes too close together (14/15/16px) create muddy hierarchy.\n- **Vertical rhythm**: Your line-height IS your spacing unit. If body is 16px with line-height 1.5 (= 24px), vertical spacing should be multiples of 24px.\n- **Weight contrast**: Use font-medium/font-semibold contrast, not just size. Bold headings + regular body creates natural hierarchy without extra sizes.\n- **Measure**: Set `max-width: 65ch` on text containers. Long lines kill readability.\n- **OpenType polish**: Use `font-variant-numeric: tabular-nums` on data tables for aligned columns.\n- Never use more than 2 font families. One well-chosen family in multiple weights is cleaner than two competing typefaces.\n- Never fall back to system fonts. Never use decorative fonts for body text. Minimum 16px (1rem) for body.\n\n**Color**: Build a functional palette, not a rainbow.\n- **Tinted neutrals**: Pure gray is dead. Add a tiny tint toward the accent color to all your grays (borders, backgrounds, muted text). The tint should be subtle enough not to read as 'colored' but creates subconscious cohesion.\n- **60/30/10 rule**: 60% neutral backgrounds/whitespace, 30% secondary colors (text, borders, inactive states), 10% accent (CTAs, highlights, focus). Accent colors work BECAUSE they're rare. Overuse kills their power.\n- **Dangerous combos to avoid**: Light gray text on white (#1 accessibility fail). Gray text on any colored background (looks washed out and dead, use a darker shade of the background color instead). Yellow text on white. Thin light text on images.\n- **Dark mode is not inverted light mode**: Use lighter surfaces for depth (no shadows). Desaturate accents slightly. Never pure black backgrounds, use dark gray (12-18% lightness). Reduce body text weight slightly (350 vs 400) because light-on-dark reads heavier.\n- Never use pure #000 or #fff. Customize the shadcn CSS variables in globals.css to match the plan palette.\n\n**Layout & space**: Space is a design material, not leftover.\n- **4px base unit**: All spacing should be multiples of 4: 4, 8, 12, 16, 24, 32, 48, 64, 96px. No arbitrary values. Name tokens semantically (`space-sm`, `space-lg`), not by value.\n- **Use `gap` not margins**: Use `gap` for sibling spacing. It eliminates margin collapse hacks and is more predictable. Reserve margin for positioning, not spacing between siblings.\n- **Rhythm through contrast**: Tight groupings within related items (8-12px), generous separation between sections (48-96px). Vary spacing WITHIN sections too. Not every row needs the same gap. The ratio between inner and outer spacing creates hierarchy.\n- **Density matches content**: Data-dense UIs (dashboards, tables, admin panels) need tighter spacing with more information visible. Marketing pages need generous whitespace and breathing room. Match density to what the user is doing.\n- **The squint test**: Blur your eyes. Can you still identify primary, secondary, and clear groupings? If everything looks the same weight, hierarchy is broken. The most important content should be obvious within 2 seconds.\n- **Asymmetry > centering**: Left-aligned with asymmetric layouts feels more designed. Center-alignment is fine for hero sections and CTAs, not for body content.\n- **Flex vs Grid**: Use Flexbox for 1D layouts (rows of items, navbars, button groups, card contents, most component internals). Use Grid for 2D layouts (page-level structure, dashboards, data-dense interfaces where rows AND columns need coordinated control). Don't default to Grid when Flexbox with `flex-wrap` would be simpler. Use `repeat(auto-fit, minmax(280px, 1fr))` for responsive grids without breakpoints. Use named `grid-template-areas` for complex page layouts and redefine at breakpoints.\n- **Cards earn their existence**: Only use cards when content needs clear separation, grid comparison, or interaction boundaries. Not everything needs a container. Never nest cards inside cards. Vary card sizes or mix cards with non-card content to break repetition.\n- **Section variety**: Don't make every section the same structure. Alternate layouts (text-left/image-right, then image-left/text-right), vary section heights, mix full-width with contained content. Monotonous section rhythm signals no designer touched this.\n- **Z-index scale**: Use a semantic scale, not arbitrary numbers. dropdown(10) -> sticky(20) -> modal-backdrop(30) -> modal(40) -> toast(50) -> tooltip(60). Never use 999 or 9999.\n- **Touch targets**: Minimum 44x44px for all interactive elements, even if the visual element is smaller (use padding).\n\n**Cards & surfaces**: Match the plan's cardStyle. Stat cards need background fills with the accent color as a subtle icon background or tinted left border. Use bg-muted/30 for section differentiation between page areas. Build a consistent shadow scale (sm -> md -> lg) and use elevation to reinforce hierarchy, not as decoration.\n\n**Sidebar**: App name + icon at top. Nav items with hover:bg-muted rounded-md transition. Active item: bg-primary/10 text-primary font-medium. User email + sign out at bottom. The sidebar should feel like a distinct surface (bg-card or bg-muted/50).\n**Mobile navigation**: The desktop sidebar must collapse to a hamburger menu on mobile. Use the shadcn `Sheet` component: a hamburger icon button (visible at `md:hidden`) opens a Sheet from the left containing the same nav items. The desktop sidebar is `hidden md:flex`. For simple apps with 3-5 nav items, a bottom tab bar (`fixed bottom-0`) is an alternative. Always respect `env(safe-area-inset-bottom)` for notched phones.\n\n**Interaction design**: Every interactive element needs 8 states, not just default and hover.\n- **Required states**: default, hover, focus, active/pressed, disabled, loading, error, success. Design all of them intentionally.\n- **Focus rings**: Use `:focus-visible` (not `:focus`) so rings show for keyboard users but not mouse clicks. Never remove focus indicators without replacement.\n- **Button hierarchy**: Don't make every button primary. Use ghost, outline, secondary, and text-link variants. One primary CTA per view.\n- **Progressive disclosure**: Simple first, advanced behind expandable sections. Don't overwhelm with options.\n- **Undo over confirmation**: For destructive actions, remove immediately + show an undo toast, then permanently delete after timeout. Better than confirmation dialogs that users click through blindly.\n- **Form patterns**: Visible `<label>` elements always (placeholders aren't labels, they disappear). Validate on blur, not on keystroke. Show format expectations with examples.\n\n**Empty states**: Every empty list/table needs a rich empty state. Not just 'Nothing here'. Include: a simple inline SVG illustration (48x48, relevant to the feature), a specific message that teaches ('Create your first habit to start tracking your daily routine'), and a primary action button. Empty states are the first thing new users see. Make them inviting.\n\n**Loading states**: Use the shadcn `Skeleton` component. Show skeleton versions of cards, lists, and stats during data fetches. Example: `<Skeleton className=\"h-8 w-32\" />` for a stat number, `<Skeleton className=\"h-20 w-full\" />` for a card. Add a `loading.tsx` file in dashboard route groups. Never show a blank page or a lone spinner.\n\n**Images**: For Unsplash images on landing pages, use `next/image` with `placeholder=\"blur\"` and a blurDataURL (a tiny 10x6 base64 image \u2014 generate a solid color blur like `data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAGCAYAAAD68A/GAAAAP0lEQVQYV2N89+7dfwYGBgZGRkYGBgYmBjIBE7kaPHv27D8DA8N/BgYGRkZGRgYGJgYyARO5GkjWQHEoxRoAAPyTGAGBMpEAAAAASUVORK5CYII=`). This creates a smooth shimmer-in effect instead of images popping in.\n\n**Motion** (`motion` package is installed):\n\n**Hero moment strategy**: Pick ONE signature animation per page. Not scattered animations on everything. On a landing page, the hero entrance is your hero moment. On a dashboard, a satisfying success animation after the primary action. One great animation > ten mediocre ones. Everything else gets subtle transitions.\n\n**Animation opportunity audit** -- check these 5 categories:\n1. **Missing feedback**: Button has no press response? Add `active:scale-[0.97]` (CSS) or `whileTap={{ scale: 0.97 }}` (motion). Toggle has no slide? Animate it.\n2. **Jarring transitions**: Menu appears instantly? Add 200ms fade + slide. Content swaps without transition? Crossfade between states.\n3. **Unclear relationships**: Parent-child not visually connected? Stagger children 50ms after parent. Deleted item just disappears? Animate it out (opacity + height collapse).\n4. **Lack of delight**: Success state is flat? Draw a checkmark SVG with stroke-dashoffset animation. Empty state is static? Add a gentle float on the illustration.\n5. **Missed guidance**: First-time user gets no hint? Pulse the primary CTA once on page load. New feature unnoticed? Brief highlight animation.\n\n**Timing hierarchy**: 100-150ms for instant feedback (buttons, toggles). 200-300ms for state changes (menus, tooltips). 300-500ms for layout shifts (accordions, modals). 500-800ms for entrances (page loads). Exit animations run at 75% of entrance duration.\n\n**Easing**: Use exponential curves (Quart out, Expo out) for sophisticated physics. Never `ease` (generic), never bounce/elastic (dated). Real objects decelerate smoothly. CSS: `cubic-bezier(0.25, 1, 0.5, 1)` (Quart out) or `cubic-bezier(0.16, 1, 0.3, 1)` (Expo out).\n\n**Micro-interaction recipes**:\n- **Button press**: `active:scale-[0.97] transition-transform duration-100` (CSS only, no motion needed)\n- **Success checkmark**: SVG `<path>` with `stroke-dasharray` + `stroke-dashoffset` animation from full to 0. 400ms Expo out.\n- **Height expand/collapse**: `grid-template-rows: 0fr -> 1fr` with `transition: grid-template-rows 300ms`. No JS layout measurement needed.\n- **Skeleton to content**: Skeleton pulses (CSS `animate-pulse`), then crossfades to real content with `opacity` transition. Use the pre-scaffolded `<ContentLoader>` component.\n- **Staggered list entrance**: CSS `animation-delay` on children: `.animate-fade-up:nth-child(1) { animation-delay: 0ms } :nth-child(2) { animation-delay: 50ms }` etc. Or use `<StaggerList>` component.\n- **Number count-up**: Use `@number-flow/react` for smooth digit morphing on stats/metrics.\n\n**Performance**: Only animate `transform` and `opacity` (GPU-accelerated). Never animate width, height, top, left, margin, or padding. For scroll-tied effects on landing pages, use CSS `animation-timeline: scroll()` where supported (progressive enhancement).\n\n**Accessibility**: Always respect `prefers-reduced-motion`. Wrap animations in `@media (prefers-reduced-motion: no-preference) { ... }`. Provide static alternatives that convey the same information.\n\n**SSR-safe (CRITICAL)**: This app deploys to Mistflow Cloud's edge runtime where IntersectionObserver may not fire. NEVER use `initial={{ opacity: 0 }}` (content stays invisible forever). Use CSS @keyframes for entrance effects:\n```tsx\n// SAFE: CSS @keyframes in globals.css:\n// @keyframes fade-up { from { opacity: 0; transform: translateY(16px); } to { opacity: 1; transform: translateY(0); } }\n// .animate-fade-up { animation: fade-up 0.5s ease-out both; }\n// Use motion ONLY for hover/tap/gesture interactions:\nimport { motion } from 'motion/react';\n<motion.div whileHover={{ scale: 1.02 }} whileTap={{ scale: 0.97 }} transition={{ duration: 0.15 }}>\n// NEVER: <motion.div initial={{ opacity: 0 }} whileInView={{ opacity: 1 }}>\n```\nFor dashboard pages, keep animations minimal. Button press feedback + skeleton loading + success states. No entrance animations on dashboard pages.\n\n**UX writing**: Every word earns its place.\n- **Buttons**: Use outcome-focused verb + object ('Save changes', 'Create account'), never generic ('Submit', 'OK', 'Click here').\n- **Destructive actions**: State exact consequences ('Delete 5 items permanently', not 'Delete selected'). Distinguish 'Delete' (permanent) from 'Remove' (recoverable).\n- **Error messages**: Answer three questions: what happened, why, and how to fix it. 'Email address is not valid. Include an @ symbol.' not 'Invalid input'. Never blame the user.\n- **Empty states**: Explain what will appear here, why it matters, and give a clear next action.\n- **Loading/progress**: Set time expectations. 'Deploying your app (usually takes 30 seconds)' not just a spinner.\n- **Consistency**: Pick one term and stick with it. 'Delete' everywhere, not Delete/Remove/Trash interchangeably.\n- **Link text**: Make it standalone for accessibility. 'View pricing plans' not 'Click here'.\n\n**Responsive design**: Mobile-first, then enhance.\n- **Mobile-first CSS**: Write base styles for mobile, then use `min-width` media queries to enhance for larger screens. Never start with desktop and try to cram it into mobile.\n- **Input method matters more than screen size**: Use `@media (pointer: fine)` for mouse/trackpad (smaller targets OK, hover effects work), `@media (pointer: coarse)` for touch (44px targets required, no hover-dependent UI). Use `@media (hover: none)` to detect devices that can't hover. Never require hover to reveal functionality.\n- **Safe areas**: Add `<meta name='viewport' content='width=device-width, initial-scale=1, viewport-fit=cover'>` and use `env(safe-area-inset-bottom)` for bottom navigation on notched phones. Fixed bottom bars must respect safe areas.\n- **Self-adjusting grids**: Use `grid-template-columns: repeat(auto-fit, minmax(280px, 1fr))` for card grids. Columns reflow naturally without breakpoint management.\n- **Container queries over media queries**: For reusable components, use `container-type: inline-size` on the parent and `@container (min-width: 400px)` on children. Components adapt to their container, not the viewport.\n- **No horizontal scroll**: Nothing should overflow the viewport width. Test at 320px width (smallest common phone). Use `overflow-x: hidden` on the body as a safety net but fix the root cause.\n- **Touch-friendly spacing**: On mobile, increase padding on list items and nav links. Thumb zone for primary actions is bottom-center of the screen.\n- **Responsive images**: Use `next/image` with `sizes` prop for responsive sizing. For art direction changes, use `<picture>` with `<source media='...'>`. Always set `width` and `height` to prevent layout shift.\n\n**Cognitive load**: Simpler apps feel better, even with the same features.\n- **Max 4 items per group**: Humans hold 4 items in working memory. Navigation menus: max 5 top-level items. Forms: max 4 fields per section. Dashboards: max 4 metrics visible without scrolling. Pricing: max 3 tiers.\n- **Single focus per view**: Every page has ONE primary task. If there are two equal CTAs, neither is primary. One primary action, everything else is secondary or tertiary.\n- **Sequential decisions**: Don't present all options at once. Multi-step forms beat one long form. Each step should have one decision.\n- **Progressive disclosure**: Show the essential first, reveal complexity on demand. Use expandable sections, tabs, or drill-down navigation. The default view should cover 80% of use cases.\n- **Visual grouping**: Related items must be visually grouped (proximity + shared background or border). Unrelated items must have clear separation. The Gestalt principle of proximity is the easiest way to reduce cognitive load.\n- **Reduce choice anxiety**: For important decisions, provide a recommended/default option. Highlight it visually. 'Most popular' badges on pricing plans reduce decision time.\n- **Keep context visible**: In multi-step flows, show a progress indicator and allow going back. Never make users remember what they entered on a previous screen.\n\n**Production hardening**: Designs that only work with perfect data aren't production-ready.\n- **Text overflow**: Use `text-overflow: ellipsis` + `overflow: hidden` for single-line text in constrained spaces. Use `-webkit-line-clamp` for multi-line. Add `min-width: 0` on flex items to prevent overflow.\n- **Extreme inputs**: Test with 100+ character names, emoji in text fields, and empty strings. The layout should not break.\n- **Error resilience**: Every API call needs error UI. Network failures, 404s, 500s all need clear messages with recovery options. Never show raw stack traces.\n\n**Landing page component patterns** (use these for professional, non-generic landing pages):\nBuild these components inline (shadcn + motion + Tailwind is enough):\n- **Animated number counters**: Use `@number-flow/react` (installed) for stat sections. `<NumberFlow value={count} />` with smooth digit transitions.\n- **Marquee / logo ticker**: CSS-only infinite scroll (`@keyframes marquee { from { transform: translateX(0) } to { transform: translateX(-50%) } }`) with duplicated content. Pause on hover.\n- **Bento grid**: CSS grid with varied `col-span` and `row-span`. Each cell gets a unique visual. Never make all cells the same size.\n- **Animated beam / connection lines**: SVG paths with `motion` stroke-dashoffset animation for 'how it works' sections.\n- **Shimmer borders**: `background: conic-gradient(...)` wrapper with animation for hero CTAs.\n- **Comparison tables**: Sticky-header table with check/x icons and row highlighting on the recommended plan.\n- **Testimonial carousel**: CSS scroll-snap for horizontal cards with avatar, quote, name, role. Auto-scroll paused on hover.\n- **Gradient mesh backgrounds**: Multiple layered `radial-gradient` backgrounds for hero sections.\nPick 3-5 per landing page based on the app's content. The goal: every landing page should look like it was designed by a human, not generated by AI.\n\n**Landing page navbar (non-negotiable):** Fully transparent (no background, no border, no backdrop-blur) and NOT sticky/fixed. It sits inside the hero section and scrolls naturally. White text on dark hero backgrounds. Primary CTA button in the nav uses the accent color (solid fill, rounded-md). Do NOT use `sticky`, `fixed`, `top-0`, or `backdrop-blur` on landing page navbars. Dashboard sidebar/nav IS fixed (different pattern).\n\n**Design for THIS app, not any app** (the #1 way to avoid generic AI output):\n- Every layout decision should be informed by what THIS app does. A gym check-in app needs a prominent search bar. A habit tracker needs a daily view. A CRM needs a pipeline. Don't default to the same dashboard-with-stats layout for everything.\n- Write copy that is SPECIFIC to the app's domain. Not 'Manage your data efficiently' but 'Check in members in under 3 seconds'. Every headline, empty state, and CTA should reference what the user actually does in this app.\n- Choose visual emphasis based on the primary action. If the user comes to log a workout, the workout form should be the biggest thing on the dashboard.\n- Use domain-appropriate metaphors. A fitness app uses progress rings. A project tracker uses kanban columns. A recipe app uses cards with photos. Don't use the same card grid for everything.\n\n**NEVER do these (AI slop anti-patterns)**:\nThe following are telltale signs of AI-generated design. Avoid all of them.\n*Visual patterns*:\n- Cyan-on-dark, purple-to-blue gradients, neon accents on dark backgrounds (the AI color palette)\n- Gradient text on headings or metrics (decorative noise, not meaningful)\n- Glassmorphism / blur effects used decoratively (only use blur for overlays/modals that need it)\n- Rounded rectangles with thick colored border on one side (lazy accent, never looks intentional)\n- Dark mode with glowing colored box-shadows on accent elements\n- Small rounded-square icon tiles stacked above headings (the icon-tile pattern)\n- Pure black (#000) backgrounds in dark mode (use tinted dark gray instead)\n- 3-column icon + title + paragraph feature grid (use asymmetric layouts, bento grids, or varied card sizes)\n- Nested cards inside cards (visual noise, flatten the hierarchy)\n- Everything center-aligned (use left-alignment for body content, reserve center for heroes/CTAs)\n- Monotonous spacing (same gap everywhere signals no designer touched this)\n*Copy patterns*:\n- Hero text like 'Transform your X' / 'One Day at a Time' / 'Join thousands' / 'Unlock the power of' (write SPECIFIC copy)\n- Generic feature descriptions ('Powerful analytics', 'Seamless integration', 'Lightning fast')\n- The hero metric template (big number, small label, supporting stats, gradient accent)\n- Repeating information users can already see. Every word must earn its place.\n*Functional patterns*:\n- Bounce/elastic easing on animations (feels dated, real objects decelerate smoothly, use Quart/Expo out)\n- Modals for things that could be inline (modals are a last resort, not a default)\n- Nav links to pages that don't exist. EVERY link in the sidebar/topnav MUST have a corresponding page.\n- FAKE FORMS. NEVER use `setTimeout` or `await new Promise` to simulate API calls. Every form MUST have a real server action (actions.ts with 'use server') that writes to the database. If a form doesn't persist data, the feature is BROKEN.\n\n**Favicon**: A default SVG favicon exists at app/icon.svg. On the landing page step, update it to match the app. Keep it simple (a single icon/letter on a rounded square, using the accent color).\n"});var hr,mr=x(()=>{hr=`# Landing Page Rules
|
|
2441
|
+
|
|
2442
|
+
These rules apply to every landing page. They are non-negotiable.
|
|
2443
|
+
|
|
2444
|
+
---
|
|
2445
|
+
|
|
2446
|
+
## 1. Copy Rules
|
|
2447
|
+
|
|
2448
|
+
### Banned Phrases (Tier 1 -- instant delete)
|
|
2449
|
+
|
|
2450
|
+
Never use these words in any landing page copy. They are the fingerprint of AI-generated text. Replace them with specifics or delete the sentence.
|
|
2451
|
+
|
|
2452
|
+
revolutionize, cutting-edge, seamless, leverage, unlock, empower, game-changing, disruptive, unprecedented, holistic approach, scalable solutions, supercharge, next-generation, state-of-the-art, harness the power, at the forefront, elevate your
|
|
2453
|
+
|
|
2454
|
+
### Red Flag Phrases (Tier 2 -- replace with specifics)
|
|
2455
|
+
|
|
2456
|
+
These are not banned outright, but they signal lazy copy. Every time you write one, replace it with a number, a concrete outcome, or a timeframe.
|
|
2457
|
+
|
|
2458
|
+
| Red flag | Replace with |
|
|
2459
|
+
|----------|-------------|
|
|
2460
|
+
| "Innovative solutions" | What specifically does it do? "Finds duplicate invoices in 3 seconds" |
|
|
2461
|
+
| "Tailored to your needs" | Whose needs? "Built for 2-person startups, not enterprises" |
|
|
2462
|
+
| "Drive growth" | How much? "Teams using [product] close 40% more deals" |
|
|
2463
|
+
| "Robust platform" | What makes it robust? "99.97% uptime since launch" |
|
|
2464
|
+
| "Streamline your workflow" | Which workflow? "Cuts weekly reporting from 2 hours to 10 minutes" |
|
|
2465
|
+
| "All-in-one platform" | All of what? List the 3 things it replaces |
|
|
2466
|
+
| "In today's fast-paced world" | Delete the sentence. Start with what you actually offer. |
|
|
2467
|
+
|
|
2468
|
+
### Structural AI Tells (Tier 3 -- rewrite)
|
|
2469
|
+
|
|
2470
|
+
These patterns reveal AI-generated structure even if individual words are fine:
|
|
2471
|
+
|
|
2472
|
+
- Opening with "In today's [adjective] world/landscape, businesses must..."
|
|
2473
|
+
- Three consecutive paragraphs of identical length
|
|
2474
|
+
- Transition words every 2-3 sentences ("Moreover," "Furthermore," "Additionally")
|
|
2475
|
+
- Vague claims without numbers or specifics
|
|
2476
|
+
- Headlines that work for ANY product (the logo-swap test)
|
|
2477
|
+
|
|
2478
|
+
### The Logo-Swap Test
|
|
2479
|
+
|
|
2480
|
+
After writing every headline and subheadline, ask: "Could I swap in any competitor's logo and this copy still makes sense?"
|
|
2481
|
+
|
|
2482
|
+
- YES = rewrite. Add the product name, a specific number, or a concrete outcome.
|
|
2483
|
+
- NO = ship it. The copy is specific to THIS product.
|
|
2484
|
+
|
|
2485
|
+
**Examples:**
|
|
2486
|
+
- FAILS: "Build the future of work" (any SaaS company could say this)
|
|
2487
|
+
- PASSES: "Close deals 40% faster" (specific claim, specific metric)
|
|
2488
|
+
- FAILS: "The platform teams love" (generic)
|
|
2489
|
+
- PASSES: "Notion + Slack + Docs in one tab" (specific, concrete)
|
|
2490
|
+
|
|
2491
|
+
### The Specificity Formula
|
|
2492
|
+
|
|
2493
|
+
Every claim on the landing page should follow this pattern:
|
|
2494
|
+
|
|
2495
|
+
\`\`\`
|
|
2496
|
+
SLOP = abstract verb + buzzword noun
|
|
2497
|
+
CLEAN = specific number + concrete outcome + timeframe/context
|
|
2498
|
+
\`\`\`
|
|
2499
|
+
|
|
2500
|
+
Examples:
|
|
2501
|
+
- SLOP: "Supercharge your productivity" -> CLEAN: "Ship 3x faster this quarter"
|
|
2502
|
+
- SLOP: "Unlock actionable insights" -> CLEAN: "See which deals will close this month"
|
|
2503
|
+
- SLOP: "Seamless integration" -> CLEAN: "Connects to Slack in 2 clicks. No code."
|
|
2504
|
+
- SLOP: "Scalable solution" -> CLEAN: "Handles 10 users or 10,000. Same price."
|
|
2505
|
+
|
|
2506
|
+
If you don't have a real number, use a plausible one based on the app's domain. A habit tracker: "Join 2,000+ people building better habits." A booking app: "Book in under 30 seconds." The number grounds the claim.
|
|
2507
|
+
|
|
2508
|
+
---
|
|
2509
|
+
|
|
2510
|
+
## 2. Conversion Structure
|
|
2511
|
+
|
|
2512
|
+
Every landing page follows the AIDA framework mapped to sections:
|
|
2513
|
+
|
|
2514
|
+
| Section | AIDA phase | Goal | Time budget |
|
|
2515
|
+
|---------|-----------|------|-------------|
|
|
2516
|
+
| Hero | Attention | Hook in 5 seconds. Value prop + primary CTA. | Above the fold |
|
|
2517
|
+
| Problem / Pain | Interest | Make visitors feel understood. State THEIR pain. | First scroll |
|
|
2518
|
+
| Benefits / Features | Desire | Show the outcome, not the feature | Mid-page |
|
|
2519
|
+
| Social Proof | Trust | Specific testimonials with numbers | Near CTA |
|
|
2520
|
+
| CTA | Action | One clear next step | Bottom |
|
|
2521
|
+
|
|
2522
|
+
### Section Order by App Type
|
|
2523
|
+
|
|
2524
|
+
**SaaS / Dashboard tool:**
|
|
2525
|
+
Hero -> Logo bar -> Problem -> Benefits (alternating rows) -> Testimonials -> Pricing -> FAQ -> CTA -> Footer
|
|
2526
|
+
|
|
2527
|
+
**Consumer / Lifestyle app (gym, habits, recipes):**
|
|
2528
|
+
Hero (with photo) -> Social proof badge -> Features (bento grid) -> How it works (3 steps) -> Testimonials -> CTA -> Footer
|
|
2529
|
+
|
|
2530
|
+
**Marketplace / Platform:**
|
|
2531
|
+
Hero -> Logo bar -> For buyers section -> For sellers section -> Stats/numbers -> Testimonials -> CTA -> Footer
|
|
2532
|
+
|
|
2533
|
+
**Dev tool / API:**
|
|
2534
|
+
Hero (dark, code snippets) -> Code example -> Features (icon grid) -> Docs link -> Pricing -> Footer
|
|
2535
|
+
|
|
2536
|
+
**Game / Creative:**
|
|
2537
|
+
Hero (full visual, minimal text) -> Gameplay/preview -> Features -> CTA -> Footer
|
|
2538
|
+
|
|
2539
|
+
### One Page, One Goal
|
|
2540
|
+
|
|
2541
|
+
Every element on the page drives toward the primary CTA. If a section doesn't move the visitor closer to clicking that button, cut it. Common violations:
|
|
2542
|
+
- Blog links in the nav (sends people away)
|
|
2543
|
+
- Multiple competing CTAs ("Sign up" AND "Book a demo" AND "Watch video")
|
|
2544
|
+
- Feature sections that read like documentation instead of benefits
|
|
2545
|
+
|
|
2546
|
+
---
|
|
2547
|
+
|
|
2548
|
+
## 3. Section Catalog
|
|
2549
|
+
|
|
2550
|
+
### Hero (required)
|
|
2551
|
+
|
|
2552
|
+
The most important section. Must have:
|
|
2553
|
+
- A headline that's large and bold (min \`text-4xl md:text-6xl lg:text-7xl\`)
|
|
2554
|
+
- A subheadline (1-2 sentences, \`text-lg\` to \`text-xl\`, muted color)
|
|
2555
|
+
- One or two CTAs (primary filled button + optional secondary ghost/outline)
|
|
2556
|
+
- A visual element: product screenshot, photo, abstract shape, or animated element
|
|
2557
|
+
|
|
2558
|
+
**Hero anti-patterns (instant slop signals):**
|
|
2559
|
+
- Centered text + centered image below = the most overused AI layout
|
|
2560
|
+
- "Welcome to [Product]" headline
|
|
2561
|
+
- Purple-to-blue gradient background
|
|
2562
|
+
- Generic stock illustration of people high-fiving
|
|
2563
|
+
- Three identical feature cards below the hero
|
|
2564
|
+
- Floating dashboard mockup in empty space
|
|
2565
|
+
|
|
2566
|
+
**Good hero patterns:**
|
|
2567
|
+
- Split layout (text left ~55%, visual right ~45%) with slight vertical offset
|
|
2568
|
+
- Full-bleed background (photo or gradient mesh) with overlaid text
|
|
2569
|
+
- Oversized headline that breaks the grid
|
|
2570
|
+
- Product UI in a browser frame or glass card
|
|
2571
|
+
|
|
2572
|
+
### Social Proof / Logo Bar
|
|
2573
|
+
|
|
2574
|
+
- Row of grayscale logos, \`opacity-50 hover:opacity-100\` transition
|
|
2575
|
+
- Specific metric: "Trusted by 2,847 companies" (not just "Trusted by")
|
|
2576
|
+
- Logos should be SVGs, same height (\`h-6\` to \`h-8\`)
|
|
2577
|
+
- If no real logos: use a social proof badge instead ("Rated 4.9/5 by 2,700+ users")
|
|
2578
|
+
|
|
2579
|
+
### Problem Section
|
|
2580
|
+
|
|
2581
|
+
Make visitors feel understood. Be specific about THEIR pain.
|
|
2582
|
+
|
|
2583
|
+
- SLOP: "In today's fast-paced business environment, teams struggle with inefficiencies"
|
|
2584
|
+
- CLEAN: "Your team wastes 6 hours/week switching between 12 different tools"
|
|
2585
|
+
|
|
2586
|
+
Use numbers and real time measurements. State the consequence of not solving.
|
|
2587
|
+
|
|
2588
|
+
### Benefits / Features
|
|
2589
|
+
|
|
2590
|
+
Choose ONE layout per feature section (do not use the same layout twice on one page):
|
|
2591
|
+
- **Bento grid**: Asymmetric grid with cards of varying sizes
|
|
2592
|
+
- **Alternating rows**: Feature image + text, flipping sides each row
|
|
2593
|
+
- **Icon grid**: 3-4 column grid with icon + title + description per card
|
|
2594
|
+
- **Large spotlight**: One feature takes full width with a large visual
|
|
2595
|
+
|
|
2596
|
+
Each feature:
|
|
2597
|
+
- Lead with the BENEFIT, not the feature name
|
|
2598
|
+
- SLOP: "Real-time collaboration" -> CLEAN: "See your teammate's cursor. Ship together."
|
|
2599
|
+
- Include a visual: real screenshot, not a generic icon
|
|
2600
|
+
|
|
2601
|
+
### Testimonials
|
|
2602
|
+
|
|
2603
|
+
- Quote includes outcome with numbers: "We closed $847K in Q3 directly from leads [product] surfaced."
|
|
2604
|
+
- Real name, role, company
|
|
2605
|
+
- Photo if available (not stock)
|
|
2606
|
+
- SLOP: "Great product! Really helped our team." (delete this, it says nothing)
|
|
2607
|
+
|
|
2608
|
+
### Pricing
|
|
2609
|
+
|
|
2610
|
+
- Use shadcn Card for each tier
|
|
2611
|
+
- Highlight recommended plan with \`ring-2 ring-primary\` and a badge
|
|
2612
|
+
- Clear feature list with checkmarks
|
|
2613
|
+
- CTA button per tier
|
|
2614
|
+
- Description says WHO this is for, not just the price
|
|
2615
|
+
|
|
2616
|
+
### CTA Section
|
|
2617
|
+
|
|
2618
|
+
- Full-width section with contrasting background (if page is light, this section is dark, or vice versa)
|
|
2619
|
+
- Restate core promise in headline
|
|
2620
|
+
- One button. Same CTA as the hero.
|
|
2621
|
+
- No more than 3 elements total.
|
|
2622
|
+
|
|
2623
|
+
### Footer
|
|
2624
|
+
|
|
2625
|
+
- Multi-column layout with link groups
|
|
2626
|
+
- Logo + tagline on the left
|
|
2627
|
+
- Link columns: Product, Company, Resources, Legal
|
|
2628
|
+
- Copyright at bottom
|
|
2629
|
+
- Keep it simple. The footer is not a second homepage.
|
|
2630
|
+
|
|
2631
|
+
---
|
|
2632
|
+
|
|
2633
|
+
## 4. Visual Strategy
|
|
2634
|
+
|
|
2635
|
+
The visual approach depends on the app's domain. Pick ONE strategy:
|
|
2636
|
+
|
|
2637
|
+
| App type | Visual strategy | Hero visual |
|
|
2638
|
+
|----------|----------------|-------------|
|
|
2639
|
+
| Consumer/lifestyle (gym, restaurant, travel) | **photo-hero** | Full-bleed photo with dark overlay + text on top |
|
|
2640
|
+
| Content/community (blog, social, marketplace) | **photo-accent** | Photos in feature sections, not hero |
|
|
2641
|
+
| SaaS/dashboard/dev tool | **product-ui** | Glass card or browser frame showing the app's dashboard |
|
|
2642
|
+
| Game/creative | **generated** | CSS art, canvas, shaders, particles |
|
|
2643
|
+
| Portfolio/agency | **abstract** | Geometric visuals, gradient meshes, typography-only |
|
|
2644
|
+
|
|
2645
|
+
**Photo-hero rules:**
|
|
2646
|
+
- Photo must be domain-specific (a gym app shows someone training, not a generic "modern workspace")
|
|
2647
|
+
- Dark overlay (bg-black/40 to bg-black/60) for text contrast
|
|
2648
|
+
- Text is white/light on the overlay
|
|
2649
|
+
- Photo loaded via Unsplash using the plan's \`imageSearchQueries\`
|
|
2650
|
+
|
|
2651
|
+
**Product-ui rules:**
|
|
2652
|
+
- Show a REAL-looking preview of what the app's dashboard will look like
|
|
2653
|
+
- Use a glass card (\`bg-white/10 backdrop-blur-lg border border-white/20 rounded-2xl\`) or browser chrome frame
|
|
2654
|
+
- Fill with domain-specific fake data (a gym app shows member stats, not lorem ipsum)
|
|
2655
|
+
- Never show a generic "analytics dashboard" -- it must match THIS app's data model
|
|
2656
|
+
|
|
2657
|
+
**Generated/abstract rules:**
|
|
2658
|
+
- CSS gradients, canvas, or WebGL only -- no assets you can't generate from code
|
|
2659
|
+
- Respect \`prefers-reduced-motion\` with a static fallback
|
|
2660
|
+
- Lazy-load heavy 3D via \`next/dynamic\` with \`{ ssr: false }\`
|
|
2661
|
+
- Target 60fps
|
|
2662
|
+
|
|
2663
|
+
---
|
|
2664
|
+
|
|
2665
|
+
## 5. Motion Menu
|
|
2666
|
+
|
|
2667
|
+
Use the \`motion\` package (Framer Motion, pre-installed) as the default. Reach for gsap only when motion cannot do the job (scroll-pinned timelines, SplitText). Never import Magic UI or Aceternity UI unless the tone file specifically says to.
|
|
2668
|
+
|
|
2669
|
+
### Scroll Reveals (pick ONE style, apply consistently across all sections)
|
|
2670
|
+
|
|
2671
|
+
- **Fade-up**: \`initial={{ opacity: 0, y: 24 }}\` (works for all tones)
|
|
2672
|
+
- **Fade-scale**: \`initial={{ opacity: 0, scale: 0.96 }}\` (luxury, editorial)
|
|
2673
|
+
- **Clip reveal**: \`initial={{ clipPath: "inset(100% 0 0 0)" }}\` (brutalist, bold)
|
|
2674
|
+
- **Blur-in**: \`initial={{ opacity: 0, filter: "blur(8px)" }}\` (soft SaaS, dreamy)
|
|
2675
|
+
|
|
2676
|
+
### Staggered Children (for card grids, feature lists)
|
|
2677
|
+
|
|
2678
|
+
\`\`\`tsx
|
|
2679
|
+
const container = { hidden: {}, show: { transition: { staggerChildren: 0.08 } } };
|
|
2680
|
+
const item = { hidden: { opacity: 0, y: 16 }, show: { opacity: 1, y: 0 } };
|
|
2681
|
+
|
|
2682
|
+
<motion.div variants={container} initial="hidden" whileInView="show" viewport={{ once: true }}>
|
|
2683
|
+
{features.map(f => <motion.div key={f.id} variants={item}>{/* card */}</motion.div>)}
|
|
2684
|
+
</motion.div>
|
|
2685
|
+
\`\`\`
|
|
2686
|
+
|
|
2687
|
+
### Hero Headline Animation (pick ONE)
|
|
2688
|
+
|
|
2689
|
+
- **Per-word stagger**: words fade in individually (soft-saas, editorial)
|
|
2690
|
+
- **Line-by-line**: each line slides up as a block (luxury, clean)
|
|
2691
|
+
- **Typewriter**: characters appear one at a time (dark-terminal, dev tools)
|
|
2692
|
+
- **Scale entrance**: headline scales from 0.9 to 1 with opacity (bold, playful)
|
|
2693
|
+
|
|
2694
|
+
### Card Interactions (pick ONE per app)
|
|
2695
|
+
|
|
2696
|
+
- **Hover lift**: \`hover:-translate-y-1 hover:shadow-lg\` (universal)
|
|
2697
|
+
- **Tilt on mouse**: perspective + rotateX/Y tracking cursor (premium)
|
|
2698
|
+
- **Border glow**: \`hover:border-primary/20 hover:shadow-primary/5\` (dark themes)
|
|
2699
|
+
- **Scale**: \`hover:scale-[1.02]\` (playful, minimal)
|
|
2700
|
+
|
|
2701
|
+
### Background Depth (pick ONE per section, vary across the page)
|
|
2702
|
+
|
|
2703
|
+
- **Floating shapes**: \`bg-primary/5 rounded-full blur-3xl\` with CSS float animation
|
|
2704
|
+
- **Dot grid**: \`radial-gradient(circle, rgba(0,0,0,.06) 1px, transparent 1px)\`
|
|
2705
|
+
- **Grain texture**: SVG noise filter overlay at 5-8% opacity
|
|
2706
|
+
- **Gradient mesh**: 2-3 radial gradients at low opacity, positioned asymmetrically
|
|
2707
|
+
|
|
2708
|
+
### Number Counter (for stats sections)
|
|
2709
|
+
|
|
2710
|
+
\`\`\`tsx
|
|
2711
|
+
import NumberFlow from "@number-flow/react";
|
|
2712
|
+
<NumberFlow value={1234} format={{ notation: "compact" }} className="text-4xl font-bold tabular-nums" />
|
|
2713
|
+
\`\`\`
|
|
2714
|
+
|
|
2715
|
+
### Rules
|
|
2716
|
+
|
|
2717
|
+
- Do NOT add motion to every element. Use it for: hero entrance, section reveals, card grids, stats counters.
|
|
2718
|
+
- Keep all durations under 400ms for UI motion. Scroll reveals can be up to 700ms for luxury/editorial tones.
|
|
2719
|
+
- Always set \`viewport={{ once: true }}\` on scroll-triggered animations. Elements should not re-animate when scrolling back up.
|
|
2720
|
+
- Respect \`prefers-reduced-motion\`: wrap animations in a check, provide static fallback.
|
|
2721
|
+
- No two apps should use the same combination of motion techniques. The tone file specifies which techniques fit.
|
|
2722
|
+
|
|
2723
|
+
---
|
|
2724
|
+
|
|
2725
|
+
## 6. Anti-Slop Audit Checklist
|
|
2726
|
+
|
|
2727
|
+
Run this checklist before finishing the landing page. Every item must pass.
|
|
2728
|
+
|
|
2729
|
+
### Copy Audit
|
|
2730
|
+
|
|
2731
|
+
- [ ] Zero Tier 1 banned phrases anywhere on the page
|
|
2732
|
+
- [ ] All Tier 2 phrases replaced with specific numbers or outcomes
|
|
2733
|
+
- [ ] No structural AI tells (cookie-cutter intros, uniform paragraphs, transition-word chains)
|
|
2734
|
+
- [ ] Every claim has a number, example, or proof point
|
|
2735
|
+
- [ ] Headlines pass the logo-swap test (specific to THIS product)
|
|
2736
|
+
- [ ] Copy sounds like a human excited about THIS product, not a press release
|
|
2737
|
+
- [ ] Testimonials include specific outcomes with numbers (not "Great product!")
|
|
2738
|
+
|
|
2739
|
+
### Design Audit
|
|
2740
|
+
|
|
2741
|
+
- [ ] NOT using Inter as the only font (use the project's configured fonts from layout.tsx)
|
|
2742
|
+
- [ ] NOT using a purple-to-blue gradient as the primary visual
|
|
2743
|
+
- [ ] NOT centering everything on every section (vary alignment)
|
|
2744
|
+
- [ ] Hero has a real visual element (product UI, photo, or generated art -- not just text)
|
|
2745
|
+
- [ ] At least one section has an asymmetric or unexpected layout
|
|
2746
|
+
- [ ] Colors are the project's design tokens (CSS custom properties), not Tailwind defaults
|
|
2747
|
+
- [ ] No identical feature cards (vary card sizes, layouts, or content structure)
|
|
2748
|
+
- [ ] Section spacing is generous (\`py-20 md:py-32\`), not cramped
|
|
2749
|
+
- [ ] Typography has clear hierarchy (hero headline is dramatically larger than body)
|
|
2750
|
+
- [ ] Headlines use \`tracking-tight\`, body uses \`leading-relaxed\`
|
|
2751
|
+
- [ ] At least one dark-background section for contrast rhythm
|
|
2752
|
+
|
|
2753
|
+
### Motion Audit
|
|
2754
|
+
|
|
2755
|
+
- [ ] At least 2-3 motion techniques used, matching the tone
|
|
2756
|
+
- [ ] Motion style is consistent with tone (slow for luxury, snappy for brutalist, bouncy for playful)
|
|
2757
|
+
- [ ] Hero headline has an entrance animation
|
|
2758
|
+
- [ ] Card grids use staggered entrance
|
|
2759
|
+
- [ ] Scroll reveals use \`viewport={{ once: true }}\`
|
|
2760
|
+
- [ ] No competing animations (max one animated element visible at a time)
|
|
2761
|
+
|
|
2762
|
+
### The Ultimate Test
|
|
2763
|
+
|
|
2764
|
+
Read the page aloud. Then ask:
|
|
2765
|
+
- "Does this look and sound like it was made for THIS specific product?"
|
|
2766
|
+
- "Would someone remember this page tomorrow?"
|
|
2767
|
+
- "Could I swap in a competitor's logo and nothing feels wrong?"
|
|
2768
|
+
|
|
2769
|
+
If the answer to the last question is yes, the page is not done.
|
|
2770
|
+
|
|
2771
|
+
---
|
|
2772
|
+
|
|
2773
|
+
## 7. Color and Typography Rules
|
|
2774
|
+
|
|
2775
|
+
**This is a hard rule, not a guideline.** Every color on the page MUST come from the app's CSS custom properties. Never use Tailwind palette utilities like \`bg-emerald-500\`, \`text-blue-600\`, \`border-slate-200\`, \`from-purple-500\`, \`via-pink-300\`, \`to-amber-400\`, etc. These bypass the design system, break when the user swaps styles, and produce the "landing is emerald but the app is blue" bug.
|
|
2776
|
+
|
|
2777
|
+
**Allowed color utilities (and only these):**
|
|
2778
|
+
|
|
2779
|
+
| Role | Tailwind class |
|
|
2780
|
+
|-------------------|-----------------------------------------------------------|
|
|
2781
|
+
| Page background | \`bg-background\` |
|
|
2782
|
+
| Body text | \`text-foreground\` |
|
|
2783
|
+
| Primary accent | \`bg-primary\`, \`text-primary\`, \`text-primary-foreground\` |
|
|
2784
|
+
| Muted surface | \`bg-muted\`, \`text-muted-foreground\` |
|
|
2785
|
+
| Cards | \`bg-card\`, \`text-card-foreground\` |
|
|
2786
|
+
| Borders | \`border-border\`, \`ring-ring\` |
|
|
2787
|
+
| Destructive | \`bg-destructive\`, \`text-destructive-foreground\` |
|
|
2788
|
+
| Opacity variants | \`bg-primary/10\`, \`text-foreground/60\`, etc. |
|
|
2789
|
+
|
|
2790
|
+
**Forbidden patterns** \u2014 scan your output before submitting:
|
|
2791
|
+
- \`bg-[anything]-[number]\` (e.g. \`bg-emerald-500\`, \`bg-stone-100\`, \`bg-yellow-400\`) \u2014 banned
|
|
2792
|
+
- \`text-[anything]-[number]\` \u2014 banned
|
|
2793
|
+
- \`border-[anything]-[number]\`, \`from-*\`, \`via-*\`, \`to-*\` with numbered palettes \u2014 banned
|
|
2794
|
+
- Hex literals (\`#3b82f6\`), rgb/rgba/hsl literals in className or inline style \u2014 banned
|
|
2795
|
+
|
|
2796
|
+
**Gradients** use the app's primary token, not a named palette:
|
|
2797
|
+
\`\`\`tsx
|
|
2798
|
+
<span className="bg-gradient-to-r from-primary to-primary/60 bg-clip-text text-transparent">keyword</span>
|
|
2799
|
+
\`\`\`
|
|
2800
|
+
|
|
2801
|
+
Typography: use the fonts configured in \`layout.tsx\` (from \`plan.design.fonts\`). The heading font for headlines, the body font for everything else. Never import a different font than what the project uses.
|
|
2802
|
+
|
|
2803
|
+
---
|
|
2804
|
+
|
|
2805
|
+
## 8. Responsive Rules
|
|
2806
|
+
|
|
2807
|
+
- Always test at: 375px (mobile), 768px (tablet), 1280px (desktop)
|
|
2808
|
+
- Hero layout: stack vertically on mobile (\`flex-col lg:flex-row\`)
|
|
2809
|
+
- Feature grids: \`grid-cols-1 md:grid-cols-2 lg:grid-cols-3\`
|
|
2810
|
+
- Reduce headline sizes on mobile: \`text-3xl md:text-5xl lg:text-7xl\`
|
|
2811
|
+
- Touch targets: all buttons min \`h-12 px-6\` on mobile
|
|
2812
|
+
- Section padding: \`py-16 md:py-24 lg:py-32\` (scale up with screen size)
|
|
2813
|
+
- Max content width: \`max-w-6xl mx-auto\` or \`max-w-7xl mx-auto\`
|
|
2814
|
+
- Inner padding: \`px-6 md:px-8\`
|
|
2815
|
+
|
|
2816
|
+
---
|
|
2817
|
+
|
|
2818
|
+
## 9. File Structure
|
|
2819
|
+
|
|
2820
|
+
\`\`\`
|
|
2821
|
+
components/
|
|
2822
|
+
landing/
|
|
2823
|
+
hero.tsx
|
|
2824
|
+
logo-bar.tsx
|
|
2825
|
+
features.tsx
|
|
2826
|
+
testimonials.tsx
|
|
2827
|
+
pricing.tsx
|
|
2828
|
+
cta-section.tsx
|
|
2829
|
+
footer.tsx
|
|
2830
|
+
app/
|
|
2831
|
+
page.tsx -- composes sections, imports from components/landing/
|
|
2832
|
+
globals.css -- design tokens (already generated by init)
|
|
2833
|
+
layout.tsx -- fonts (already generated by init)
|
|
2834
|
+
\`\`\`
|
|
2835
|
+
|
|
2836
|
+
Each section is a separate component file. The page.tsx simply imports and stacks them. Do NOT build one monolithic page component.
|
|
2837
|
+
`});var fr,gr=x(()=>{fr=`# Design Doctrine
|
|
2838
|
+
|
|
2839
|
+
This is the standard for every UI you generate. It is not aspirational. It is the floor.
|
|
2840
|
+
|
|
2841
|
+
## The Standard
|
|
2842
|
+
|
|
2843
|
+
Every interface you produce \u2014 landing, dashboard, auth page, CRUD screen, email \u2014 is a chance to be remarkable. Remarkable is not "less generic." Remarkable means someone opening your page would describe it with a specific word: clinical, brutalist, warm, industrial, editorial, playful. They would remember it.
|
|
2844
|
+
|
|
2845
|
+
If the result could be the landing page for a hundred other SaaS products, it's a failure \u2014 no matter how cleanly the code is written.
|
|
2846
|
+
|
|
2847
|
+
## Commit to an Extreme
|
|
2848
|
+
|
|
2849
|
+
Before writing any component:
|
|
2850
|
+
|
|
2851
|
+
1. **Read DESIGN.md.** Note the Aesthetic Direction. It names one extreme \u2014 execute it, don't hedge toward the middle.
|
|
2852
|
+
2. **Pick the memorable moment.** One signature element per page: a typographic hero, a staggered load animation, a product-specific illustration, an unexpected layout. Every page gets exactly one. Zero is generic. Three is noise.
|
|
2853
|
+
3. **Decide the motion vocabulary.** Minimal-functional (only transitions that aid comprehension) or orchestrated (one designed page-load sequence). Not both, not neither.
|
|
2854
|
+
|
|
2855
|
+
Then implement code that is:
|
|
2856
|
+
- Production-grade and functional
|
|
2857
|
+
- Visually striking and memorable
|
|
2858
|
+
- Cohesive with the DESIGN.md direction
|
|
2859
|
+
- Meticulously refined in every detail
|
|
2860
|
+
|
|
2861
|
+
## What Makes a Page Remarkable (and what doesn't)
|
|
2862
|
+
|
|
2863
|
+
| Remarkable | Generic |
|
|
2864
|
+
|---|---|
|
|
2865
|
+
| Asymmetric hero with content bleeding off-grid | Centered pill \u2192 headline \u2192 CTA \u2192 3 bullets |
|
|
2866
|
+
| Bold display font with character (Satoshi, Fraunces, Instrument Serif) | Inter / Geist / Roboto / system-ui |
|
|
2867
|
+
| One dominant color, used confidently on CTAs and accents | Evenly-distributed palette with multiple accents |
|
|
2868
|
+
| Product-specific copy: real feature names, real numbers, real user language | "The platform teams love" / "Boost your productivity" |
|
|
2869
|
+
| Real product preview (actual screens, not fake browser chrome) | A rounded box with red/yellow/green dots and "app.example.com" |
|
|
2870
|
+
| Typography that stops a scroll (massive hero, tight tracking, asymmetric break) | Text-xl h1 centered in a max-w-3xl container |
|
|
2871
|
+
| Motion that is specifically about this product | Generic fade-in everywhere |
|
|
2872
|
+
| Texture: grain, gradient mesh, layered transparencies, decorative borders | Solid white with emerald-500 accents |
|
|
2873
|
+
|
|
2874
|
+
## The "Never" List
|
|
2875
|
+
|
|
2876
|
+
Never do any of these. They are instant generic-AI tells:
|
|
2877
|
+
|
|
2878
|
+
- Purple gradient on a white background. Any gradient that reads "generic AI-generated" is off-limits.
|
|
2879
|
+
- A badge pill that says "New:" or "Built for X" or "Made for Y" at the top of the hero.
|
|
2880
|
+
- A fake browser chrome mockup with three colored dots.
|
|
2881
|
+
- A "Trusted by these logos" row without real logos.
|
|
2882
|
+
- Three checkmark bullets in a row below the CTAs.
|
|
2883
|
+
- Tailwind palette utilities (\`bg-emerald-500\`, \`text-blue-600\`, \`border-slate-200\`). Every color goes through CSS variables \u2014 see the Color reference.
|
|
2884
|
+
- Inter, Roboto, Arial, system-ui as the primary font.
|
|
2885
|
+
- Center-stacked single-column hero. Asymmetric layouts only.
|
|
2886
|
+
- "Features, Pricing, Teams, About" navbar with "Sign in / Start Free" on the right. This exact navbar is on 10,000 SaaS landings.
|
|
2887
|
+
- Stock Unsplash photos of "diverse teams in modern offices" as hero images. If you must use a photo, it must be domain-specific (a habit-tracker hero shows actual tracked habits, not an office scene).
|
|
2888
|
+
|
|
2889
|
+
## The Self-Audit
|
|
2890
|
+
|
|
2891
|
+
Before submitting any UI file, read it with this checklist and regenerate if any answer is wrong:
|
|
2892
|
+
|
|
2893
|
+
1. Does the hero have a \`<Badge>\` / pill that says "Built for" or "New:" or similar? **Regenerate without it.**
|
|
2894
|
+
2. Is the hero centered in a single column with headline over subheadline over two buttons? **Regenerate with an asymmetric layout.**
|
|
2895
|
+
3. Are there three \`<CheckCircle2>\` / checkmark bullets in a row? **Remove or redesign.**
|
|
2896
|
+
4. Does the file contain \`bg-emerald-*\`, \`bg-red-*\`, \`bg-amber-*\`, \`text-violet-*\`, or similar palette classes? **Replace with \`bg-primary\`, \`bg-success\`, \`bg-destructive\`, \`bg-warning\`, or variable-based classes.**
|
|
2897
|
+
5. Is the font \`Inter\`, \`Geist\`, \`Roboto\`, \`Arial\`, or \`system-ui\`? **Pick a distinctive font from Fontshare or Google Fonts that matches DESIGN.md.**
|
|
2898
|
+
6. Is there a fake browser chrome with dots and a fake URL? **Delete it. If you need a product preview, render the actual component.**
|
|
2899
|
+
7. Can you describe this page in one characterful word (clinical / brutalist / warm / editorial / playful / industrial)? **If not, the aesthetic direction is too safe \u2014 pick an extreme.**
|
|
2900
|
+
8. Is there ONE memorable moment on the page (signature typography / orchestrated motion / unexpected layout)? **If zero, add one. If three, keep the strongest one.**
|
|
2901
|
+
|
|
2902
|
+
If any answer fails, the UI is not ready. Redesign \u2014 not tweak \u2014 the failing piece.
|
|
2903
|
+
`});var br,yr=x(()=>{br=`# Typography
|
|
2904
|
+
|
|
2905
|
+
Typography is the cheapest way to escape AI slop and the most visible place it shows up. Every generic landing uses Inter. Every remarkable landing picks something you'd notice.
|
|
2906
|
+
|
|
2907
|
+
## Font Selection
|
|
2908
|
+
|
|
2909
|
+
Pick a distinctive display font. Default to the fonts declared in DESIGN.md; if DESIGN.md doesn't specify, choose from this catalog:
|
|
2910
|
+
|
|
2911
|
+
**Display / Hero (pick one):**
|
|
2912
|
+
- **Satoshi** \u2014 geometric with warmth, distinctive lowercase \`a\` and \`g\`. Works for dev tools and productivity. Load from Fontshare.
|
|
2913
|
+
- **Instrument Serif** \u2014 editorial, elegant, italic-capable. Works for luxury, editorial, content apps. Load from Google Fonts.
|
|
2914
|
+
- **Fraunces** \u2014 variable axis (soft\u2192wonky), magazine feel with personality. Load from Google Fonts.
|
|
2915
|
+
- **DM Serif Display** \u2014 high-contrast, confident, editorial. Load from Google Fonts.
|
|
2916
|
+
- **Space Grotesk** \u2014 geometric, technical, suits analytical dashboards. Load from Google Fonts. *(Note: has become common; use only if it genuinely fits.)*
|
|
2917
|
+
- **Manrope** \u2014 modern humanist, flexible, works as display OR body. Load from Google Fonts.
|
|
2918
|
+
|
|
2919
|
+
**Body / UI (pick one):**
|
|
2920
|
+
- **DM Sans** \u2014 clean, humanist, pairs well with almost any display. Load from Google Fonts.
|
|
2921
|
+
- **Manrope** \u2014 same family as above, use if also using Manrope display for harmony.
|
|
2922
|
+
- **Geist** \u2014 Vercel's font, works but common. Avoid if display is also Geist.
|
|
2923
|
+
- **Inter Tight** \u2014 denser Inter; still Inter-family so only use if you really need the readability.
|
|
2924
|
+
|
|
2925
|
+
**Code / Data (pick one):**
|
|
2926
|
+
- **JetBrains Mono** \u2014 distinctive lowercase \`r\`, \`g\`, \`@\`. Default for data-dense UI.
|
|
2927
|
+
- **IBM Plex Mono** \u2014 variable weight, more characterful than most monos.
|
|
2928
|
+
- **Berkeley Mono** \u2014 premium mono with character. Requires license; use only if the user has it.
|
|
2929
|
+
|
|
2930
|
+
**Banned as primary font** (use them as fallbacks only, never as the leading choice):
|
|
2931
|
+
- Inter, Roboto, Arial, Helvetica, system-ui, ui-sans-serif, SF Pro
|
|
2932
|
+
|
|
2933
|
+
## Loading
|
|
2934
|
+
|
|
2935
|
+
All fonts must be loaded in \`app/layout.tsx\` via \`next/font\`. Do NOT use external \`<link>\` tags (loses preload + causes layout shift).
|
|
2936
|
+
|
|
2937
|
+
\`\`\`tsx
|
|
2938
|
+
// For Google Fonts
|
|
2939
|
+
import { Manrope, DM_Sans, JetBrains_Mono } from "next/font/google";
|
|
2940
|
+
|
|
2941
|
+
const displayFont = Manrope({ subsets: ["latin"], weight: ["700", "800"], variable: "--font-display" });
|
|
2942
|
+
const bodyFont = DM_Sans({ subsets: ["latin"], weight: ["400", "500", "600"], variable: "--font-body" });
|
|
2943
|
+
const monoFont = JetBrains_Mono({ subsets: ["latin"], variable: "--font-mono" });
|
|
2944
|
+
\`\`\`
|
|
2945
|
+
|
|
2946
|
+
\`\`\`tsx
|
|
2947
|
+
// For Fontshare fonts, use next/font/local with the TTF files
|
|
2948
|
+
import localFont from "next/font/local";
|
|
2949
|
+
const satoshi = localFont({
|
|
2950
|
+
src: [
|
|
2951
|
+
{ path: "./fonts/Satoshi-Bold.woff2", weight: "700" },
|
|
2952
|
+
{ path: "./fonts/Satoshi-Black.woff2", weight: "900" },
|
|
2953
|
+
],
|
|
2954
|
+
variable: "--font-display",
|
|
2955
|
+
});
|
|
2956
|
+
\`\`\`
|
|
2957
|
+
|
|
2958
|
+
## Scale
|
|
2959
|
+
|
|
2960
|
+
Use the scale declared in DESIGN.md. If not declared, default to:
|
|
2961
|
+
|
|
2962
|
+
| Role | Size | Weight | Line-height | Tracking |
|
|
2963
|
+
|---|---|---|---|---|
|
|
2964
|
+
| Hero | \`clamp(40px, 6vw, 72px)\` | 800-900 | 1.0 | -0.03em |
|
|
2965
|
+
| H1 | 48px | 700 | 1.1 | -0.02em |
|
|
2966
|
+
| H2 | 32px | 700 | 1.15 | -0.01em |
|
|
2967
|
+
| H3 | 24px | 600 | 1.2 | 0 |
|
|
2968
|
+
| H4 | 18px | 600 | 1.3 | 0 |
|
|
2969
|
+
| Body | 16px | 400 | 1.55 | 0 |
|
|
2970
|
+
| Small | 14px | 400 | 1.5 | 0 |
|
|
2971
|
+
| Micro | 12px | 500 | 1.4 | 0 |
|
|
2972
|
+
| Nano | 11px | 600 | 1.4 | 0.05em (tracking-wide, uppercase for eyebrows) |
|
|
2973
|
+
|
|
2974
|
+
## Hierarchy Rules
|
|
2975
|
+
|
|
2976
|
+
- Hero typography carries the page. \`text-6xl md:text-7xl\` is a floor, not a ceiling. If the hero is \`text-4xl\`, it's too timid.
|
|
2977
|
+
- Use weight contrast aggressively. 900 display against 400 body reads as "designed". 700 against 500 reads as "default".
|
|
2978
|
+
- Tight tracking (\`tracking-tight\` / \`-0.02em\`) on large display. Normal tracking on body. Wide tracking (\`tracking-wider\` / 0.08em) on eyebrow labels, uppercase.
|
|
2979
|
+
- One typeface does most of the work. Two is a deliberate pairing. Three is a mistake.
|
|
2980
|
+
|
|
2981
|
+
## Memorable Moment Options
|
|
2982
|
+
|
|
2983
|
+
Pick exactly one:
|
|
2984
|
+
- **Asymmetric headline break** \u2014 the headline splits mid-sentence to an offset second line, with an italic or color-shifted word at the break.
|
|
2985
|
+
- **Giant eyebrow label** \u2014 nano-sized tracked-wide uppercase label above the hero, specific to the product ("ASYNC FOR TEAMS OF 3-30").
|
|
2986
|
+
- **Italic pull-quote** \u2014 a sentence in the display font, italic, at the hero's bottom edge.
|
|
2987
|
+
- **Variable-weight transition** \u2014 a single word animates its variable-font weight on page load (for Fraunces, Satoshi Variable).
|
|
2988
|
+
- **Mixed case display** \u2014 Title Case for proper nouns, SmallCaps for the verb. Editorial feel.
|
|
2989
|
+
|
|
2990
|
+
Do NOT use: gradient text (\`bg-clip-text\`) on one word of the headline. That effect is the most overused generic-AI marker.
|
|
2991
|
+
`});var vr,wr=x(()=>{vr="# Color\n\nColor is a commitment, not a palette swatch. The #1 failure mode in AI-generated landings is an evenly-distributed palette: a little emerald here, a little amber there, a gradient, a badge. That's visual hedging \u2014 it signals \"I couldn't pick a point of view.\"\n\nPick one color. Use it with intent.\n\n## The Token System\n\nEvery color on every screen goes through a CSS variable defined in `globals.css`. You do not hand-pick hex values in JSX. You do not use Tailwind palette utilities (`bg-emerald-500`, `text-blue-600`, `border-slate-200`). If a color isn't in the token scheme, it doesn't exist for this app.\n\n### Core tokens\n\n- `--color-background` \u2014 page background\n- `--color-foreground` \u2014 default body text\n- `--color-card` \u2014 elevated surface (cards, panels)\n- `--color-card-foreground` \u2014 text on cards\n- `--color-muted` \u2014 low-emphasis surface fill\n- `--color-muted-foreground` \u2014 secondary text (\u2265 WCAG AA contrast vs background)\n- `--color-border` \u2014 subtle dividers\n- `--color-input` \u2014 form input borders\n- `--color-popover` / `--color-popover-foreground` \u2014 dropdowns, tooltips, menus\n\n### Interactive tokens\n\n- `--color-primary` \u2014 primary CTAs, links, active tab, focus ring\n- `--color-primary-foreground` \u2014 text on primary (derived for WCAG AA contrast)\n- `--color-ring` \u2014 focus outline (same hue as primary)\n- `--color-secondary` / `--color-secondary-foreground` \u2014 quieter than primary, more than muted\n- `--color-accent` / `--color-accent-foreground` \u2014 hover states on neutrals\n\n### Semantic tokens\n\n- `--color-success` \u2014 confirmation, \"verified\" banners, positive states\n- `--color-warning` \u2014 pending states, attention, non-destructive caution\n- `--color-destructive` / `--color-destructive-foreground` \u2014 errors, irreversible actions\n- `--color-info` \u2014 neutral system messages, tips\n\n**You use these semantic tokens for all status UI.** When you need a \"green checkmark\" you reach for `text-success`, not `text-emerald-500`. When you need an amber alert you reach for `bg-warning/10 text-warning`, not `bg-amber-50 text-amber-700`.\n\n## Usage Rules\n\n**Primary color:**\n- Primary CTAs, links, the active navigation tab, focus rings.\n- NOT for headings. Black or foreground-colored headings are stronger.\n- NOT for large surface fills (it's a splash of color, not a wash).\n- NOT for borders except focus rings.\n- One bold use of primary beats twenty sprinkled uses.\n\n**Neutrals do the structural work:**\n- Background, cards, borders \u2014 all come from the neutral scale.\n- Text hierarchy via opacity on foreground (`text-foreground`, `text-foreground/80`, `text-muted-foreground`) \u2014 not different colors.\n\n**Semantic colors:**\n- Use `bg-success/10 text-success border border-success/30` for success banners (reproducibility: a light-tinted version of the success color for surface, the solid version for text and border).\n- Same shape for warning, info, destructive.\n\n## Dark Mode\n\nCommit to one theme. If DESIGN.md says the app is dark-themed, make it unambiguously dark \u2014 `#0c0c0c` / near-black base, not neutral-900. If light-themed, commit to light.\n\nDo NOT auto-swap based on `prefers-color-scheme` when the design system declared a theme direction. The appStyle chose a theme for a reason; respect it.\n\n## Forbidden\n\n- Palette utilities: `bg-emerald-500`, `text-blue-600`, `border-slate-200`, `from-purple-500`, `via-pink-300`, `to-amber-400`. Every one of these in your output is a slop indicator.\n- Hex literals inside `className` or inline `style` props.\n- Named colors from CSS (`red`, `lightgrey`, `rebeccapurple`) \u2014 never used in production UI; always a sign of rushed work.\n- Purple gradients on white. The single most overused AI-design pattern.\n- Three-color gradient pills. Rainbow badges. \"Vibrant\" anything.\n\n## Contrast\n\nEvery text/surface pair in DESIGN.md is already WCAG AA-verified by Mistflow's contrast test. You do not need to re-check \u2014 the tokens are safe by construction. You DO need to:\n\n- Not override token combinations with hardcoded classes that might fail contrast.\n- Maintain contrast for overlays (text on images, modals on scrims). When stacking text over a gradient or image, include a scrim (`bg-background/80 backdrop-blur-sm`) so body text stays \u2265 4.5:1.\n\n## Getting Color Wrong\n\nThe specific failure mode to avoid: a page where primary is used in five places, all small and incidental \u2014 a checkmark, a hover state, a tiny badge. That's AI hedging. Either use primary confidently on a hero CTA and mean it, OR don't use primary on the page at all and let neutrals carry the identity.\n"});var kr,xr=x(()=>{kr=`# Motion
|
|
2992
|
+
|
|
2993
|
+
Motion is the most-ignored dimension of AI-generated UI. Generic landings either have no motion or sprinkle tiny fades on everything. Remarkable landings pick ONE orchestrated moment and execute it precisely.
|
|
2994
|
+
|
|
2995
|
+
## The Principle
|
|
2996
|
+
|
|
2997
|
+
One designed motion moment per page beats twenty scattered micro-interactions.
|
|
2998
|
+
|
|
2999
|
+
A user describing your page afterward should be able to name the motion: "the headline loaded line-by-line," "the product preview drifted in from below," "the nav underline sweeps across on hover." If they can't name it, there wasn't one.
|
|
3000
|
+
|
|
3001
|
+
## Tokens
|
|
3002
|
+
|
|
3003
|
+
Use these tokens (already in \`globals.css\`), not arbitrary cubic-bezier curves:
|
|
3004
|
+
|
|
3005
|
+
**Easing:**
|
|
3006
|
+
- \`--ease-quart-out\` : \`cubic-bezier(0.25, 1, 0.5, 1)\` \u2014 standard enter / settle. Default.
|
|
3007
|
+
- \`--ease-expo-out\` : \`cubic-bezier(0.16, 1, 0.3, 1)\` \u2014 confident enter for hero elements.
|
|
3008
|
+
- \`--ease-back-out\` : \`cubic-bezier(0.34, 1.56, 0.64, 1)\` \u2014 overshoot for playful accents only.
|
|
3009
|
+
|
|
3010
|
+
**Duration scale:**
|
|
3011
|
+
- \`micro\` \u2014 80ms (button press, toggle flip)
|
|
3012
|
+
- \`short\` \u2014 150ms (hover, focus ring)
|
|
3013
|
+
- \`medium\` \u2014 250ms (modal reveal, card hover-lift, dropdown)
|
|
3014
|
+
- \`long\` \u2014 400ms (page section reveal, hero load)
|
|
3015
|
+
|
|
3016
|
+
## Signature Moment Patterns
|
|
3017
|
+
|
|
3018
|
+
Pick ONE. Execute it well.
|
|
3019
|
+
|
|
3020
|
+
### 1. Staggered hero reveal (most versatile)
|
|
3021
|
+
On page load, the hero's children animate in with a 50ms stagger.
|
|
3022
|
+
|
|
3023
|
+
\`\`\`tsx
|
|
3024
|
+
// app/page.tsx hero section
|
|
3025
|
+
<section className="stagger animate-fade-up">
|
|
3026
|
+
<p className="text-xs uppercase tracking-wider">Eyebrow label</p>
|
|
3027
|
+
<h1 className="text-6xl">Main headline</h1>
|
|
3028
|
+
<p className="text-lg">Subhead</p>
|
|
3029
|
+
<div className="flex gap-3"><button>Primary</button><button>Secondary</button></div>
|
|
3030
|
+
</section>
|
|
3031
|
+
\`\`\`
|
|
3032
|
+
|
|
3033
|
+
With this CSS (already in \`globals.css\`):
|
|
3034
|
+
|
|
3035
|
+
\`\`\`css
|
|
3036
|
+
.stagger > :nth-child(1) { animation-delay: 0ms; }
|
|
3037
|
+
.stagger > :nth-child(2) { animation-delay: 50ms; }
|
|
3038
|
+
.stagger > :nth-child(3) { animation-delay: 100ms; }
|
|
3039
|
+
.stagger > :nth-child(4) { animation-delay: 150ms; }
|
|
3040
|
+
\`\`\`
|
|
3041
|
+
|
|
3042
|
+
### 2. Typographic reveal (for editorial / luxury)
|
|
3043
|
+
The headline scrubs its variable-font weight from 100 \u2192 800 over 600ms on load. Requires a variable font (Fraunces, Recursive, Satoshi Variable).
|
|
3044
|
+
|
|
3045
|
+
### 3. Scroll-triggered product preview
|
|
3046
|
+
The hero's product preview slides up and into focus as the user scrolls past 20vh. Use CSS \`@supports (animation-timeline: scroll())\` with a \`view-timeline\`, or Intersection Observer for broader support.
|
|
3047
|
+
|
|
3048
|
+
### 4. Nav underline sweep
|
|
3049
|
+
On hover, a 2px underline animates from 0% to 100% of the link's width with \`--ease-expo-out\` over 200ms. Subtle but deliberate.
|
|
3050
|
+
|
|
3051
|
+
### 5. Button press depth
|
|
3052
|
+
Primary CTA has a 2px vertical translate on \`:active\` with 80ms \`--ease-quart-out\`. Feels physical. Already in \`globals.css\` as default button behavior.
|
|
3053
|
+
|
|
3054
|
+
## Patterns to Avoid
|
|
3055
|
+
|
|
3056
|
+
- **Fade-in on everything.** If every section fades in on scroll, nothing is memorable.
|
|
3057
|
+
- **Random bounce on icons.** Decorative-only motion is noise.
|
|
3058
|
+
- **Autoplaying video loops as the hero background.** They look flashy for 3 seconds and become distracting on page 2.
|
|
3059
|
+
- **Parallax scrolling on every section.** Overused; feels dated.
|
|
3060
|
+
- **Spring physics on nav links.** Too much motion in a commonly-hit target is annoying.
|
|
3061
|
+
|
|
3062
|
+
## Reduced Motion
|
|
3063
|
+
|
|
3064
|
+
\`globals.css\` already respects \`prefers-reduced-motion: reduce\` and disables animations for users who opt out. Do not override this. Do not condition content on motion playing. If the hero reveal is the memorable moment, the static state must also look intentional.
|
|
3065
|
+
|
|
3066
|
+
## One-Line Motion Rule
|
|
3067
|
+
|
|
3068
|
+
If the motion you're about to add could be described as "subtle animation on scroll", delete it. Design motion is specific, named, and described in one sentence: "the headline lines drop in from above with a 50ms stagger at page load." If you can't describe it that specifically, you don't have a motion design \u2014 you have motion noise.
|
|
3069
|
+
`});var Pr,Sr=x(()=>{Pr=`# Spatial Composition
|
|
3070
|
+
|
|
3071
|
+
Layout is where AI-slop is most visible. A centered single-column hero with a pill, headline, subhead, and two CTAs is the most-recognizable generic-SaaS pattern on the internet. It is the layout you must not use.
|
|
3072
|
+
|
|
3073
|
+
## The Principle
|
|
3074
|
+
|
|
3075
|
+
Commit to one layout posture per page. Asymmetry and restraint both work. The safe middle \u2014 centered, evenly-padded, predictable grid \u2014 does not.
|
|
3076
|
+
|
|
3077
|
+
## Base Grid
|
|
3078
|
+
|
|
3079
|
+
- **Base unit:** 4px. Every spacing value is a multiple: \`2px, 4px, 8px, 12px, 16px, 20px, 24px, 32px, 48px, 64px, 96px\`.
|
|
3080
|
+
- **Columns:** 12 at \`lg+\` (1024px+), 6 at \`md\` (768-1023px), 1 at \`sm\` (<768px).
|
|
3081
|
+
- **Max content widths:**
|
|
3082
|
+
- Hero text block: \`max-w-2xl\` (640px) \u2014 long lines are unreadable
|
|
3083
|
+
- Long-form content: \`max-w-5xl\` (1080px)
|
|
3084
|
+
- Dashboards / data: \`max-w-6xl\` (1200px)
|
|
3085
|
+
- Full-bleed hero: no max width, margin by percent (\`px-[8vw]\`)
|
|
3086
|
+
|
|
3087
|
+
## Layout Posture \u2014 Pick One
|
|
3088
|
+
|
|
3089
|
+
### A. Asymmetric editorial
|
|
3090
|
+
Hero content is offset from center. Visual element (illustration, product preview, typography as image) anchors the other side. Neither side fills evenly. Example: Linear.app hero \u2014 text at left 55%, product preview at right 45% with a deliberate vertical offset.
|
|
3091
|
+
|
|
3092
|
+
### B. Full-bleed typographic
|
|
3093
|
+
A giant headline fills the viewport. No sidebar visual, no product preview. The typography IS the hero. Example: Vercel.com hero, Framer's landing.
|
|
3094
|
+
|
|
3095
|
+
### C. Split-canvas
|
|
3096
|
+
Two contrasting halves \u2014 one dark, one light, or one content-heavy and one illustrative. Diagonal break line often. Example: Apple product pages.
|
|
3097
|
+
|
|
3098
|
+
### D. Spatially-dense dashboard-first
|
|
3099
|
+
For internal tools and admin apps \u2014 the landing SHOWS the product running with real-looking data. No marketing framing; the interface sells itself. Example: Linear when logged-out still shows a stylized issue tracker.
|
|
3100
|
+
|
|
3101
|
+
### E. Narrative-scrolling long-form
|
|
3102
|
+
A landing that scrolls through a story. Each section has a distinct layout (not a repeating card grid). Requires real narrative thinking \u2014 don't attempt if the product is "a dashboard for X."
|
|
3103
|
+
|
|
3104
|
+
**Prohibited posture: centered single-column.** A pill above a headline above a subhead above two buttons in a \`max-w-3xl\` container is the default AI landing. Regenerate if you produced this.
|
|
3105
|
+
|
|
3106
|
+
## Density
|
|
3107
|
+
|
|
3108
|
+
- **Dashboards, data tables, settings:** Comfortable-dense. \`gap-3\` between table rows, \`gap-4\` between sections. Users look at many things quickly; too-airy density reads as "underdesigned."
|
|
3109
|
+
- **Marketing hero:** Generous. \`py-24\` or \`py-32\` on the hero section. Oversized typography needs oversized spacing to breathe.
|
|
3110
|
+
- **Forms:** Structured. \`gap-4\` between fields, \`gap-2\` between label and input. No surprises.
|
|
3111
|
+
- **Cards in a feature grid:** Equal vertical rhythm across rows. \`gap-6\` between cards, \`p-6\` inside.
|
|
3112
|
+
|
|
3113
|
+
## Radius Conventions
|
|
3114
|
+
|
|
3115
|
+
Use these by role, not by taste:
|
|
3116
|
+
|
|
3117
|
+
- **Buttons, inputs, badges:** \`rounded-md\` (8px). Click-target elements.
|
|
3118
|
+
- **Cards, panels:** \`rounded-lg\` (12px). Content containers.
|
|
3119
|
+
- **Modals, hero cards:** \`rounded-xl\` (16px). Elevated or focal.
|
|
3120
|
+
- **Pills, avatars:** \`rounded-full\`.
|
|
3121
|
+
- **Pricing-card "recommended" highlight:** ring-2, not a different radius.
|
|
3122
|
+
|
|
3123
|
+
If DESIGN.md says the app is brutalist, override to \`rounded-none\` everywhere. If luxury / editorial, \`rounded-sm\` (4px) \u2014 less rounded is more refined.
|
|
3124
|
+
|
|
3125
|
+
## Breaking the Grid
|
|
3126
|
+
|
|
3127
|
+
To signal "designed, not templated":
|
|
3128
|
+
|
|
3129
|
+
- **Content bleed:** one element extends past the standard \`max-w-6xl\` container. An image bleeds to the viewport edge. A quote spans wider than surrounding text.
|
|
3130
|
+
- **Diagonal elements:** a rotated text block (2-4\xB0), a skewed background accent, an off-axis arrow. Use sparingly \u2014 one per page.
|
|
3131
|
+
- **Overlap:** a card overlaps two sections, half in one and half in another. Requires careful z-index management but reads as intentional.
|
|
3132
|
+
- **Asymmetric columns:** a feature grid with deliberately uneven column widths (e.g., \`grid-cols-[2fr_1fr_1fr]\`) rather than equal thirds.
|
|
3133
|
+
|
|
3134
|
+
## The Empty-Space Rule
|
|
3135
|
+
|
|
3136
|
+
Negative space is a design element. A hero with \`py-32\` and a tight \`max-w-2xl\` text block in a wide viewport reads as confident. A hero that fills every pixel with checkmarks, logos, and counters reads as scared.
|
|
3137
|
+
|
|
3138
|
+
Pick: generous breathing (luxury / refined / editorial) OR controlled density (dashboards / industrial / brutalist). Never a mushy middle.
|
|
3139
|
+
`});var _r,Ir=x(()=>{_r=`# Interaction
|
|
3140
|
+
|
|
3141
|
+
Every interactive element has a designed state for every phase: rest, hover, focus, active, disabled. The difference between remarkable and adequate lives in these states.
|
|
3142
|
+
|
|
3143
|
+
## States
|
|
3144
|
+
|
|
3145
|
+
For every button, link, input, and card:
|
|
3146
|
+
|
|
3147
|
+
- **Rest:** the default, designed state.
|
|
3148
|
+
- **Hover:** a specific visual change (background shift, border darken, small translate, not just \`opacity-80\`). \`transition-colors duration-150\` minimum.
|
|
3149
|
+
- **Focus (keyboard):** \`focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2\` \u2014 always. Keyboard users must see the target.
|
|
3150
|
+
- **Active (pressed):** physical feedback. Buttons: \`active:translate-y-[1px]\` or \`active:scale-[0.97]\`. Already in globals.css as default.
|
|
3151
|
+
- **Disabled:** \`disabled:opacity-50 disabled:cursor-not-allowed\`. Explicit, not left to default browser styling.
|
|
3152
|
+
|
|
3153
|
+
## Forms
|
|
3154
|
+
|
|
3155
|
+
- **Label above input**, not placeholder-as-label. Placeholders disappear on focus and hide context.
|
|
3156
|
+
- **Inline validation** on blur, not just on submit. Red border + specific error message below ("Email must include @").
|
|
3157
|
+
- **Password fields** show/hide toggle, not a plain masked field.
|
|
3158
|
+
- **Submit buttons** have a loading state (\`disabled\` + spinner or \`"Saving\u2026"\`). Never a dead-click submit.
|
|
3159
|
+
- **Form field \`autocomplete\` attributes** must be correct: \`autocomplete="email"\`, \`autocomplete="current-password"\`, \`autocomplete="new-password"\`. Browsers fill forms faster when you do this.
|
|
3160
|
+
|
|
3161
|
+
## Feedback
|
|
3162
|
+
|
|
3163
|
+
- **Success actions** show a toast or inline green banner with the specific outcome ("Invite sent to maya@team.com").
|
|
3164
|
+
- **Error states** show the error inline where the user can fix it, not in a dismissable toast they'll miss.
|
|
3165
|
+
- **Optimistic updates** for actions that usually succeed (liking, checking off a task). Rollback on failure with a visible indicator.
|
|
3166
|
+
- **Loading** \u2014 never a blank white screen. Skeleton loaders for content, spinners for actions under 2s, progress bars for actions over 2s.
|
|
3167
|
+
|
|
3168
|
+
## Nav
|
|
3169
|
+
|
|
3170
|
+
- **Current page indication** via a specific marker (underline, side indicator, tinted background). Not just \`font-semibold\` \u2014 users don't read weight changes as "current".
|
|
3171
|
+
- **Hover on nav links** animates a signature element (underline sweep, side dot grow, color shift). See motion.md patterns.
|
|
3172
|
+
- **Mobile nav** has a specific close affordance \u2014 a clear \`X\` in the top-right, not just "tap outside". Users don't know outside-tap works.
|
|
3173
|
+
|
|
3174
|
+
## Links
|
|
3175
|
+
|
|
3176
|
+
- **Primary links** are the accent color (\`text-primary\`) or underlined. Not just "blue underline" default.
|
|
3177
|
+
- **Hover** changes something: color shift, underline fade-in, arrow appear (\`\u2192\`), slight translate.
|
|
3178
|
+
- **External links** are marked (icon, new-tab indicator, or explicit \`target="_blank"\` with \`aria-label\` noting the new window).
|
|
3179
|
+
|
|
3180
|
+
## Buttons
|
|
3181
|
+
|
|
3182
|
+
Three variants, no more:
|
|
3183
|
+
|
|
3184
|
+
- **Primary** \u2014 solid background, high-emphasis CTA. One per section max. Use the product's voice ("Start Free", "Book a Demo", "Get Started") not generic ("Submit", "Click here").
|
|
3185
|
+
- **Secondary / outline** \u2014 bordered or ghost, lower emphasis.
|
|
3186
|
+
- **Tertiary / link-like** \u2014 text-only, smallest emphasis. For "Cancel", "Skip", "Learn more".
|
|
3187
|
+
|
|
3188
|
+
Button text is specific and active-voice. "Start Free" > "Start". "Reset password" > "Submit". "Cancel" is fine when the action is ambiguous; "Keep editing" is better when it isn't.
|
|
3189
|
+
|
|
3190
|
+
## Inputs
|
|
3191
|
+
|
|
3192
|
+
- **Base radius matches buttons** \u2014 if buttons are \`rounded-md\`, inputs are \`rounded-md\`.
|
|
3193
|
+
- **Focus ring** same color as primary, via \`focus-visible:ring-ring\`.
|
|
3194
|
+
- **Error state** is a red border (\`border-destructive\`) + error message below, not a red background fill.
|
|
3195
|
+
- **Required fields** marked with a subtle indicator (asterisk in muted color, or "required" label), not just browser default.
|
|
3196
|
+
|
|
3197
|
+
## Modals
|
|
3198
|
+
|
|
3199
|
+
- **Scrim** is \`bg-background/80 backdrop-blur-sm\` \u2014 not pure black, not pure transparent.
|
|
3200
|
+
- **Escape key closes** the modal. Clicking outside closes unless there's unsaved input.
|
|
3201
|
+
- **Focus trap** \u2014 keyboard focus stays inside the modal while open, restores to the trigger on close.
|
|
3202
|
+
- **Animation** \u2014 fade + slight translate-up on enter (200ms medium), same in reverse on exit.
|
|
3203
|
+
- **Modal size** matches content \u2014 tall forms get more height, short confirmations stay compact. Never a giant modal for a "Are you sure?" confirm.
|
|
3204
|
+
|
|
3205
|
+
## Accessibility
|
|
3206
|
+
|
|
3207
|
+
- **All interactive elements** respond to keyboard \u2014 Tab to focus, Enter/Space to activate.
|
|
3208
|
+
- **Alt text** on meaningful images; \`alt=""\` on decorative ones.
|
|
3209
|
+
- **Heading hierarchy** is correct \u2014 one \`<h1>\` per page, \`<h2>\` for main sections, \`<h3>\` for subsections. Don't skip levels.
|
|
3210
|
+
- **ARIA labels** on icon-only buttons (\`aria-label="Close"\`, \`aria-label="Sort"\`).
|
|
3211
|
+
- **Color alone is not information** \u2014 a red "error" badge needs text, not just \`bg-destructive\`.
|
|
3212
|
+
|
|
3213
|
+
## Micro-Interactions Catalog
|
|
3214
|
+
|
|
3215
|
+
Small moments that add up to "designed":
|
|
3216
|
+
|
|
3217
|
+
- **Copy-to-clipboard** button flashes a checkmark for 1.2s, then reverts.
|
|
3218
|
+
- **Saving state** changes the button label: "Save" \u2192 "Saving\u2026" \u2192 "Saved" (600ms) \u2192 "Save".
|
|
3219
|
+
- **Delete confirm** \u2014 two-step: first click arms ("Click again to delete"), second click fires. Prevents accidental destruction.
|
|
3220
|
+
- **Skeleton loaders** match the shape of the loaded content, not generic gray boxes.
|
|
3221
|
+
- **Empty states** offer a specific next action, not "No data yet".
|
|
3222
|
+
|
|
3223
|
+
These micro-interactions are the texture of a designed product. Ship them.
|
|
3224
|
+
`});var Rr,Tr=x(()=>{Rr=`# UX Writing
|
|
3225
|
+
|
|
3226
|
+
Copy is design. A remarkable page has copy that could only be about this specific product. A generic page has copy that could describe a hundred.
|
|
3227
|
+
|
|
3228
|
+
## The Principle
|
|
3229
|
+
|
|
3230
|
+
Specificity beats cleverness. "Cut standup meetings from 30 minutes to 3" beats "Boost team productivity". "Free for teams up to 10" beats "Free for small teams".
|
|
3231
|
+
|
|
3232
|
+
## Voice
|
|
3233
|
+
|
|
3234
|
+
Pick a voice. Possibilities:
|
|
3235
|
+
- **Confident-founder** \u2014 "We replaced the 9am Zoom." Direct, declarative, uses "we" sparingly but with intent.
|
|
3236
|
+
- **Specific-expert** \u2014 "Engineers ship 3-4 standups per week. We made each one take 90 seconds." Numbers-forward.
|
|
3237
|
+
- **Plainspoken-friend** \u2014 "Post it when you post it. We'll digest." Short, rhythmic, casual.
|
|
3238
|
+
- **Editorial-precise** \u2014 "Async, by design. Read in two minutes." Period-heavy, pause-laden.
|
|
3239
|
+
- **Playful-with-teeth** \u2014 "Standups, but they don't make you want to quit." Uses humor; never saccharine.
|
|
3240
|
+
|
|
3241
|
+
Pick one. Commit. Don't mix.
|
|
3242
|
+
|
|
3243
|
+
## Anti-Patterns
|
|
3244
|
+
|
|
3245
|
+
Every one of these is immediate-generic:
|
|
3246
|
+
|
|
3247
|
+
- **"The platform teams love"** / "The tool X companies use" / "Loved by [big logos]" without proof.
|
|
3248
|
+
- **"Boost your productivity"** / "Unlock insights" / "Streamline your workflow" \u2014 all empty verbs.
|
|
3249
|
+
- **"Designed with you in mind"** / "Built for modern teams" / "Tailored to your needs" \u2014 who isn't?
|
|
3250
|
+
- **"Say goodbye to X"** / "No more Y" \u2014 overused opening pattern.
|
|
3251
|
+
- **"Everything you need to Z"** \u2014 a filler phrase with no information.
|
|
3252
|
+
- **"Powered by AI"** as a hero line \u2014 unless the product IS the AI, this is filler.
|
|
3253
|
+
- **Exclamation points.** More than zero per page, ideally.
|
|
3254
|
+
- **Three-item lists with vague words** \u2014 "Fast. Simple. Reliable." \u2014 every product says this.
|
|
3255
|
+
|
|
3256
|
+
## Rules
|
|
3257
|
+
|
|
3258
|
+
**Headlines** name a specific tension or outcome, not a category:
|
|
3259
|
+
- \u274C "Async team collaboration"
|
|
3260
|
+
- \u2705 "No more 9am standups. Your team still knows what's up."
|
|
3261
|
+
|
|
3262
|
+
**Subheads** give one concrete number, workflow, or mechanism:
|
|
3263
|
+
- \u274C "Streamline your team's workflow with powerful async tools."
|
|
3264
|
+
- \u2705 "Post in two minutes. Scan the team in thirty seconds. Spot blockers before they eat a day."
|
|
3265
|
+
|
|
3266
|
+
**Feature descriptions** use the product's actual noun:
|
|
3267
|
+
- \u274C "Track your progress."
|
|
3268
|
+
- \u2705 "See who shipped, who's blocked, and who's out this week \u2014 in one scannable feed."
|
|
3269
|
+
|
|
3270
|
+
**Button text** is the action + its result, not generic:
|
|
3271
|
+
- \u274C "Submit" / "Click here" / "Learn more"
|
|
3272
|
+
- \u2705 "Start Free" / "Book 15 minutes" / "See the pricing math"
|
|
3273
|
+
|
|
3274
|
+
**Microcopy** (error messages, empty states, tooltips) adds character, not just information:
|
|
3275
|
+
- \u274C "No data"
|
|
3276
|
+
- \u2705 "Nothing here yet. Post your first standup to get started."
|
|
3277
|
+
- \u274C "Error: invalid input"
|
|
3278
|
+
- \u2705 "That email's already on your team. Try a different one."
|
|
3279
|
+
|
|
3280
|
+
## Numbers and Proof
|
|
3281
|
+
|
|
3282
|
+
If you have real numbers, use them. If you don't, say so or omit. Fake proof reads as fake:
|
|
3283
|
+
|
|
3284
|
+
- \u274C "Trusted by 10,000+ teams" (fabricated)
|
|
3285
|
+
- \u274C "Used by engineers at Google, Meta, Stripe" (unless you actually know this)
|
|
3286
|
+
- \u2705 "Free for teams up to 10" (concrete tier limit)
|
|
3287
|
+
- \u2705 "Three-step setup, under a minute" (measurable claim you can defend)
|
|
3288
|
+
|
|
3289
|
+
## The Pricing Story
|
|
3290
|
+
|
|
3291
|
+
If there's a pricing page:
|
|
3292
|
+
- State the price clearly at the top of each tier, large.
|
|
3293
|
+
- Describe each tier in one sentence ("For teams of 1-10 who want the async feed, nothing else").
|
|
3294
|
+
- Free tiers don't hide: show them prominently. Hiding free tiers is the #1 complaint on pricing pages.
|
|
3295
|
+
- Differences between tiers are specific, not vague: "25 seats" > "small teams", "Priority support" > "Better support".
|
|
3296
|
+
|
|
3297
|
+
## The Footer
|
|
3298
|
+
|
|
3299
|
+
A footer with the same five links ("Product / Pricing / Docs / Blog / Terms") is fine, but the company name / tagline should be specific. "StandupSync \u2014 async updates, human-sized" is better than "\xA9 2026 StandupSync Inc."
|
|
3300
|
+
`});import{z as xo}from"zod";import{existsSync as Ct,readFileSync as So,writeFileSync as ko,mkdirSync as sc}from"fs";import{join as rt,resolve as rc,dirname as ic}from"path";import{createConnection as ac}from"net";function lc(t){return new Promise(e=>{let o=ac({port:t,host:"127.0.0.1"});o.on("connect",()=>{o.destroy(),e(!0)}),o.on("error",()=>{e(!1)})})}function pc(t){let e=rt(t,"mistflow.json");if(!Ct(e))return null;try{return JSON.parse(So(e,"utf-8"))}catch{return null}}function Ar(t,e){let o=rt(t,"mistflow.json");ko(o,JSON.stringify(e,null,2)+`
|
|
3301
|
+
`)}function an(t){return t.entity??t.name??"Unknown"}function dc(t){return t.length===0?"":typeof t[0]=="string"?t.join(", "):t.map(e=>`${e.name} (${e.type})`).join(", ")}function Cr(t){return t.path??t.route??t.name??""}function uc(t){let e=(t||"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 Er(t,e){if(!t.entities||t.entities.length===0)return e;let o=t.entities.map(n=>n.toLowerCase());return e.filter(n=>{let s=an(n).toLowerCase();return o.some(a=>s.includes(a)||a.includes(s))})}function mc(t,e){if(!t.pages||t.pages.length===0)return[];let o=t.pages.map(n=>n.toLowerCase());return e.filter(n=>{let s=(n.name??"").toLowerCase(),a=Cr(n).toLowerCase();return o.some(r=>s.includes(r)||r.includes(s)||a.includes(r))})}function gc(t){let e=t.stepType;if(e&&hc.has(e))return e;if(t.integrationId)return"integration";let o=`${t.name} ${t.description}`.toLowerCase();return o.includes("crud")||o.includes("list")&&o.includes("create")?"crud":o.includes("auth")||o.includes("login")||o.includes("register")?"auth":o.includes("admin")&&(o.includes("panel")||o.includes("dashboard")||o.includes("manage")||o.includes("users"))?"admin":o.includes("dashboard")||o.includes("overview")||o.includes("analytics")?"dashboard":o.includes("schema")||o.includes("database")||o.includes("model")?"schema":o.includes("layout")||o.includes("sidebar")||o.includes("navigation")?"layout":o.includes("deploy")||o.includes("cloudflare")?"deploy":o.includes("organization")||o.includes("team")||o.includes("workspace")||o.includes("multi-tenant")||o.includes("invite member")?"multi-tenant":o.includes("landing")||o.includes("hero")||o.includes("marketing")||o.includes("homepage")?"landing":o.includes("design")||o.includes("theme")||o.includes("styling")||o.includes("ui polish")||o.includes("visual")?"design":"general"}function fc(t){switch(t){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 yc(t,e){let o=[];if(o.push("### Design choices (decided at plan time \u2014 follow these exactly):"),t.tone&&o.push(`- **App tone**: ${t.tone}`),t.fonts&&(o.push(`- **Heading font**: ${t.fonts.heading} (load from Google Fonts)`),o.push(`- **Body font**: ${t.fonts.body} (load from Google Fonts)`)),o.push("- **All color comes from CSS variables** \u2014 never use Tailwind palette utilities like `bg-emerald-500`, `text-blue-600`, `border-slate-200`. Use `bg-primary`, `text-primary-foreground`, `bg-muted`, `text-muted-foreground`, `border-border`, `bg-card`, `text-foreground`, `bg-destructive`, etc. The primary/accent is already wired in globals.css from the chosen design system."),o.push("- **Outbound URLs (invite links, email CTAs, absolute hrefs in server code):** use `process.env.BETTER_AUTH_URL` as the base. Do NOT use `process.env.NEXT_PUBLIC_APP_URL` \u2014 Next.js bakes every `NEXT_PUBLIC_*` literal into the production bundle at build time, so the scaffolded localhost default ships to prod and invite emails land on `http://localhost:3000`. Client components should use relative URLs (they resolve to the current origin automatically)."),t.borderRadius){let n={sharp:"2px",subtle:"6px",rounded:"12px",pill:"9999px"};o.push(`- **Border radius**: ${t.borderRadius} (${n[t.borderRadius]??t.borderRadius}) \u2014 set as --radius in globals.css`)}if(t.shadowStyle){let n={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"};o.push(`- **Shadow style**: ${t.shadowStyle} \u2014 ${n[t.shadowStyle]??t.shadowStyle}`)}if(t.cardStyle){let n={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"};o.push(`- **Card style**: ${t.cardStyle} \u2014 ${n[t.cardStyle]??t.cardStyle}`)}if(t.landingTone&&o.push(`- **Landing page tone**: ${t.landingTone}`),t.visualStrategy){let n=t.visualStrategy,s=t.heroPhoto!==!1,a=s&&!!n.heroImages?.length;if(o.push(""),o.push("### Visual strategy:"),a&&n.heroImages&&n.heroImages.length>0){o.push("**Hero image** \u2014 use this Unsplash photo as the landing page hero BACKGROUND:");let r=n.heroImages[0];o.push(`- URL: ${r.url}`),o.push(`- Alt text for img tag: "${r.alt||"Hero image"} \u2014 Photo by ${r.photographer} on Unsplash"`),o.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 s&&!n.heroImages?.length?o.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.'"):s||o.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(n.sectionImages?.length){o.push("**Section images available** \u2014 use these for feature sections, about sections, or testimonial backgrounds (NOT the hero):");for(let r of n.sectionImages)o.push(`- ${r.url} \u2014 alt: "${r.alt||"section image"} \u2014 Photo by ${r.photographer} on Unsplash"`)}(a||n.sectionImages?.length)&&o.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."),o.push(""),o.push("**Hero layout \u2014 split hero with product UI mockup (follow this exactly):**"),o.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."),o.push(""),o.push("```"),o.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"),o.push("\u2502 [Logo] [Sign In] [CTA \u2192] \u2502 \u2190 transparent nav, NOT sticky"),o.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"),o.push("\u2502 \u2502"),o.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"),o.push("\u2502 \u2502 Glassmorphic \u2502 \u2502"),o.push("\u2502 Big bold headline, \u2502 product mockup \u2502 \u2502"),o.push("\u2502 accent color on key word \u2502 card showing \u2502 \u2502"),o.push("\u2502 \u2502 real app data \u2502 \u2502"),o.push("\u2502 Description paragraph \u2502 (stats, table, \u2502 \u2502"),o.push("\u2502 \u2502 chart, etc.) \u2502 \u2502"),o.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"),o.push("\u2502 \u2502"),o.push("\u2502 500+ 25K+ 99% \u2502"),o.push("\u2502 Label Label Label \u2502"),o.push("\u2502 \u2502"),a?o.push("\u2502 \u2190 full-bleed photo bg + dark overlay behind all \u2192 \u2502"):o.push("\u2502 \u2190 preset gradient / glass background behind all \u2192 \u2502"),o.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"),o.push("```"),o.push(""),o.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"),o.push("**Right side (~45%)**: A glassmorphic floating card that previews what the app looks like inside:"),o.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)"),o.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"),o.push("- Must be DOMAIN-SPECIFIC: a library app shows book catalog rows, a gym app shows check-in stats, a CRM shows pipeline cards"),o.push("- Add subtle inner elements with `bg-white/5` or `bg-white/10` for depth"),o.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 o.push(""),o.push(ur),o.join(`
|
|
3302
|
+
`)}async function bc(t){try{let e=await zn("nextjs",t);return{reminders:e.reminders,skill:e.skill}}catch{return{reminders:`### ${t} step
|
|
3303
|
+
- Follow existing patterns in the codebase
|
|
3304
|
+
- Server Components by default, "use client" only when interactivity is needed`,skill:""}}}async function wc(t,e,o,n,s,a){let r=[];r.push(`## Step ${t.number}: ${t.name}`),r.push(""),r.push("### What to build:"),r.push(t.description),r.push(""),e.primaryAction&&(r.push("### Primary user action (non-negotiable):"),r.push(`- **Core action**: ${e.primaryAction.action}`),r.push(`- **User flow**: ${e.primaryAction.flow}`),r.push(`- **Dashboard must show**: ${e.primaryAction.dashboardSurface}`),r.push(""),r.push("The dashboard is an ACTION surface, not a stats display. Users must be able to complete the core action directly from the dashboard without navigating to a separate page. If this step builds the dashboard, make sure the primary action is front and center with inline forms/buttons \u2014 not behind a link to another page."),r.push(""));let l=["landing","design","dashboard","crud","layout","admin","general","auth"].includes(s);if(e.design&&l?(r.push(yc(e.design,{hasDesignPreset:!!e.landingDesign&&(s==="landing"||s==="design")})),r.push("")):e.design&&!l&&(r.push("### Design tokens (for reference only \u2014 this step is not UI-focused):"),e.design.fonts&&r.push(`- Fonts: ${e.design.fonts.heading} / ${e.design.fonts.body}`),r.push("- Colors come from CSS variables (`--color-primary`, `--color-background`, etc.) \u2014 not Tailwind palette names."),r.push("")),a){let w=Fs(a);if(w.length>0){r.push("### Approved wireframe (MUST READ before writing any files):"),r.push("The user approved a wireframe sketch before building. **Read these files NOW before writing any code for this step:**");for(let y of w){let k=y.replace(a,"").replace(/^\//,"");r.push(`- \`${k}\``)}r.push(""),r.push("The wireframe defines the LAYOUT and INFORMATION HIERARCHY \u2014 what goes where, what's prominent, what's secondary. It includes HTML comments explaining WHY things are placed where they are."),r.push(""),r.push("The wireframe is intentionally rough (grayscale, system fonts). Your job is to:"),r.push("1. **Keep the same layout structure** \u2014 same information hierarchy, same element placement, same sections in the same order"),r.push("2. **Apply the design tokens** \u2014 colors, fonts, shadows, radius from the plan design choices above"),r.push("3. **Elevate the visual quality** \u2014 make it feel designed for THIS specific app, not generic"),r.push("4. **Respect the HTML comments** \u2014 they explain WHY things are placed where they are"),r.push("5. **If the wireframe shows a search bar at the top of the dashboard, your dashboard MUST have a search bar at the top** \u2014 do not rearrange the layout"),r.push("")}}e.roles&&Array.isArray(e.roles)&&e.roles.length>0&&(r.push("### Role system (from plan):"),r.push(`- Roles: ${e.roles.join(", ")}`),r.push(`- Default role for new signups: ${e.defaultRole??e.roles[0]}`),r.push("- Role helpers are in `lib/roles.ts` \u2014 use `getUserRole()` and `hasRole()` for access checks"),r.push("")),e.multiTenant&&(r.push("### Multi-tenant (from plan):"),r.push("- Organization tables are in `db/schema/organization.ts`"),r.push("- Org helpers are in `lib/org.ts` \u2014 use `getCurrentOrg()` to scope queries"),r.push("- All data queries MUST be scoped to the current org (filter by orgId)"),r.push("- Org switcher component is at `components/org-switcher.tsx`"),r.push("- CRITICAL: `getCurrentOrg()` returns null for new users who haven't created an org yet. The dashboard MUST handle this \u2014 if currentOrg is null, redirect to an onboarding page or show an inline 'Create your first team/workspace' form. NEVER call .id on a null org."),r.push("- WARNING: cookies().set() in server actions does NOT work on Mistflow Cloud's edge runtime. Do NOT use setCurrentOrgId() or any cookies().set() call inside server actions. Instead, pass the orgId as a form field or query param, or store the active org in the user's database record."),r.push("")),e.language&&(r.push(`### Language: ${e.language}`),r.push(`ALL user-facing text must be written in ${e.language}:`),r.push("- Page titles, headings, labels, button text, placeholder text"),r.push("- Navigation items, menu labels, footer text"),r.push("- Error messages, success messages, empty states"),r.push("- Landing page copy, marketing text, CTAs"),r.push("- Form labels and validation messages"),r.push("Code (variable names, comments, file names) stays in English."),r.push(`Set the HTML lang attribute to the appropriate locale code for ${e.language}.`),r.push(""));let p=["landing","design","auth","general","crud","dashboard"];e.audienceType&&p.includes(s)&&(e.audienceType==="b2c"?(r.push("### Audience: this app belongs to ONE business. The landing page talks TO their customers."),r.push("- Hero: what the customer gets ('Exceptional catering for your next event'), NOT what the tool does"),r.push("- CTAs: customer action ('Order Catering', 'Book Now'), NOT business action ('Get Started Free')"),r.push("- Testimonials: from customers ('They catered our wedding'), NOT from business owners"),r.push("- Features: customer benefits ('Specify your dietary needs'), NOT business benefits ('Track preferences')"),r.push("- Stats: social proof for customers ('2,400+ events served'), NOT internal metrics ('$48k revenue')"),r.push("- The business name IS the brand. Say it like a business homepage, not a SaaS onboarding."),r.push("")):e.audienceType==="b2b"?(r.push("### Audience: this is a SaaS platform. The landing page pitches TO business owners."),r.push("- Hero: the business pain + solution ('Catering orders managed in one place')"),r.push("- CTAs: business owner action ('Start Free Trial', 'Get Started')"),r.push("- Testimonials: from business owners who use the platform"),r.push("- Features: business benefits ('Track dietary preferences across all orders')"),r.push("- Stats: platform metrics ('500+ businesses', '50K+ orders processed')"),r.push("")):e.audienceType==="internal"&&(r.push("### Audience: internal staff tool. No marketing copy needed."),r.push("- No landing page. Auth page copy is functional: 'Sign in to continue'."),r.push("- Dashboard focuses on operational efficiency, not onboarding or sales."),r.push(""))),o.length>0&&(r.push("### Already completed:"),o.forEach(w=>r.push(`- ${w}`)),r.push(""));let m=e.dataModel?Er(t,e.dataModel):[];m.length>0&&(r.push("### Data model (from plan):"),m.forEach(w=>{let y=an(w),k=dc(w.fields);r.push(`- **${y}**: ${k}`),r.push(` Schema file: \`db/schema/${y.toLowerCase().replace(/\s+/g,"-")}.ts\``)}),r.push(""));let u=e.pages?mc(t,e.pages):[];if(u.length>0&&(r.push("### Pages to create/update:"),u.forEach(w=>{let y=w.description?` \u2014 ${w.description}`:"";r.push(`- \`${Cr(w)}\`${y}`)}),r.push("")),s==="crud"&&m.length>0&&m.forEach(w=>{let y=an(w),k=y.toLowerCase().replace(/\s+/g,"-"),U=k.endsWith("s")?k:`${k}s`;r.push(`### Files for ${y} CRUD:`),r.push(`- List page: \`app/(dashboard)/${U}/page.tsx\` (Server Component)`),r.push(`- Detail page: \`app/(dashboard)/${U}/[id]/page.tsx\``),r.push(`- Create page: \`app/(dashboard)/${U}/new/page.tsx\``),r.push(`- Server Actions: \`app/(dashboard)/${U}/actions.ts\``),r.push(`- DataTable columns: \`components/${k}-table-columns.tsx\``),r.push(`- Form: \`components/${k}-form.tsx\``),r.push("")}),l){r.push("## Design Doctrine (the standard for every UI step)"),r.push(""),r.push(fr),r.push(""),r.push("## Design Reference Library"),r.push(""),r.push("### Typography"),r.push(br),r.push(""),r.push("### Color"),r.push(vr),r.push(""),r.push("### Motion"),r.push(kr),r.push(""),r.push("### Spatial Composition"),r.push(Pr),r.push(""),r.push("### Interaction"),r.push(_r),r.push(""),r.push("### UX Writing"),r.push(Rr),r.push("");let w=a?rt(a,"DESIGN.md"):void 0,y=w&&Ct(w)?(()=>{try{return So(w,"utf-8")}catch{return null}})():null;y&&(r.push("### Design system (source of truth: DESIGN.md):"),r.push(""),r.push("The project's DESIGN.md defines the visual identity. Follow it exactly. It's emitted in google-labs-code/design.md format (YAML front matter with colors/typography/rounded/spacing tokens, plus markdown rationale). All UI elements must use the project's CSS custom properties (--color-primary, --color-background, etc. \u2014 these are generated from the YAML tokens) and the fonts configured in layout.tsx. If DESIGN.md and this plan disagree, DESIGN.md wins. The user may have edited it."),r.push(""),r.push(y),r.push(""))}(s==="landing"||s==="design")&&(r.push(hr),r.push(""));let d=t.integrationId?et(t.integrationId):void 0;if(d){let w=tt(d.id);if(r.push("### Integration blueprint (follow this closely):"),r.push(""),r.push(`Using integration: **${d.name}** (${d.category})`),w?.docsUrl&&r.push(`Official docs: ${w.docsUrl}`),w?.envVars?.length){r.push(""),r.push("**Required environment variables:**");for(let y of w.envVars)r.push(`- \`${y.key}\`: ${y.description} \u2014 Get it at ${y.setupUrl}`);r.push(""),r.push("**IMPORTANT: Never ask the user to paste API keys in chat.** Direct them to set keys in the Mistflow dashboard (Project Settings > Environment Variables) or at app.mistflow.ai. Use mist_config resource='env' action='list' to check if keys are set (has_value: true/false). Only proceed with deploy once all required keys are set.")}w?.packages?.length&&(r.push(""),r.push(`**Packages to install:** \`npm install ${w.packages.join(" ")}\``)),r.push(""),r.push("---"),r.push(d.prompt),r.push("---"),r.push(""),r.push("**Adaptation rules**: Follow the file structure and code patterns above. Replace placeholder values (app names, URLs, copy) with this app's specific content. Use the app's existing data models and route structure. Never ask the user to paste API keys or secrets in the chat. Direct them to set keys in the Mistflow dashboard."),r.push("")}let{reminders:b,skill:R}=await bc(s);return r.push(b),r.push(""),R&&!(s==="landing"&&e.landingDesign==="freeform")&&(r.push(`### ${s} reference:`),r.push(R),r.push("")),l&&(r.push("## Self-Audit \u2014 run before submitting this file"),r.push(""),r.push(`Read the file you just wrote and answer each of these. If any answer is "yes", REDESIGN the failing piece \u2014 don't tweak classes on the same template. A different composition is required.`),r.push(""),r.push('1. **Pill badge at the top?** A small rounded label saying "Built for" / "New:" / "Made for" with a colored dot? \u2192 redesign the hero without it.'),r.push("2. **Fake browser chrome?** A rounded box with red/yellow/green dots and a fake URL bar? \u2192 delete it. Show real components instead, or no preview."),r.push("3. **Centered single-column hero?** Pill \u2192 headline \u2192 subhead \u2192 two CTAs stacked vertically? \u2192 redesign asymmetrically (see spatial.md)."),r.push("4. **Three checkmark benefit bullets** below the hero CTAs? \u2192 remove the triplet pattern."),r.push("5. **Tailwind palette utilities?** Any `bg-emerald-*`, `bg-amber-*`, `text-violet-*`, `border-slate-*`, `from-purple-*`, etc.? \u2192 replace with token classes (`bg-primary`, `bg-success`, `bg-muted`, `border-border`). No exceptions."),r.push("6. **Inter, Geist, Roboto, Arial, or system-ui** as the primary font? \u2192 pick something distinctive (see typography.md)."),r.push("7. **Purple gradient on white background** anywhere? \u2192 that's the single most overused AI-design pattern. Replace."),r.push('8. **Hardcoded hex values** (e.g. `style={{ color: "#10b981" }}`) or named CSS colors (`red`, `lightgrey`) in className or inline styles? \u2192 replace with CSS variables.'),r.push('9. **Generic copy** ("Boost your productivity", "The platform teams love", "Everything you need to")? \u2192 rewrite with specific nouns, numbers, or mechanisms from this product (see writing.md).'),r.push("10. **Zero memorable moments?** Is there ONE signature element \u2014 typographic hero, orchestrated reveal, asymmetric break, product-specific illustration? If zero, the page is generic. Add one (see motion.md, typography.md)."),r.push(""),r.push(`If every answer is "no, I'm good" \u2014 then submit.`),r.push("")),r.join(`
|
|
3305
|
+
`)}async function vc(t){let{projectPath:e,step:o}=t,n=rc(e??process.cwd()),s=pc(n);if(!s)return Pe(n);if(!Ct(rt(n,"node_modules")))return c(`Dependencies are not installed at ${n}. Call mist_install and projectPath='${n}' before running implement. This is a one-time setup step after init.`,!0);try{let{ensureBackendRegistered:v,ensureShadcnComponents:L}=await Promise.resolve().then(()=>(Qn(),Yn));await v(n);let Q=await L(n);Q.failed?console.error(`[implement] ${Q.failed}`):Q.installed.length>0&&console.error(`[implement] installed ${Q.installed.length} shadcn components`)}catch(v){console.error("[implement] self-heal skipped:",v instanceof Error?v.message:String(v))}let a=s.plan;if(!a||!a.steps||a.steps.length===0)return c("No project plan found. Start by describing your app idea first \u2014 the AI will create a plan for you.",!0);let r,i=a.steps.find(v=>v.status==="in_progress");if(i){let v=a.steps.findIndex(L=>L.number===i.number);v!==-1&&(a.steps[v].status="completed",r=`Auto-completed step ${i.number} (${i.name})`,Ar(n,s))}let l;if(o!==void 0){if(l=a.steps.find(v=>v.number===o),!l)return c(`Step ${o} not found. The plan has ${a.steps.length} steps (numbered ${a.steps[0].number} to ${a.steps[a.steps.length-1].number}).`,!0)}else if(l=a.steps.find(v=>v.status!=="completed"),!l)return c(JSON.stringify({message:"All plan steps are completed!",completedSteps:a.steps.map(v=>v.name),nextAction:"NEXT: Deploy the app now. Call mist_deploy action='deploy'. Do NOT suggest localhost or ask the user \u2014 just deploy."}));let p=a.steps.filter(v=>v.status==="completed").map(v=>`Step ${v.number}: ${v.name}`),{readLocalState:m}=await Promise.resolve().then(()=>(Be(),Pt)),u=m(n),d=gc(l),b=[];if((d==="crud"||d==="schema")&&a.dataModel&&l.entities&&l.entities.length>0){let v=Er(l,a.dataModel);for(let L of v){let Q=an(L);try{let se=(L.fields||[]).map(D=>typeof D=="string"?{name:D,type:"text"}:{name:D.name,type:uc(D.type),required:D.required!==!1});if(se.length===0)continue;let xe=s.dbProvider==="neon"?"nextjs-neon":"nextjs",E=await Hn(xe,Q,se),N=0,fe=0;for(let D of E.files){let re=rt(n,D.path);if(Ct(re)){fe++;continue}sc(ic(re),{recursive:!0}),ko(re,D.content),N++}let Ie=rt(n,"db","index.ts");if(Ct(Ie)){let D=So(Ie,"utf-8");D.includes(E.dbExport)||ko(Ie,D.trimEnd()+`
|
|
3306
|
+
`+E.dbExport+`
|
|
3307
|
+
`)}N>0?b.push(`${E.entityPascal} CRUD (${N} new files${fe>0?`, ${fe} existing skipped`:""})`):fe>0&&b.push(`${E.entityPascal} CRUD (all ${fe} files already exist \u2014 skipped)`)}catch(se){console.error(`Module generation failed for ${Q} (non-fatal):`,se instanceof Error?se.message:se)}}}let R=await wc(l,a,p,null,d,n),w=a.steps.findIndex(v=>v.number===l.number);if(w!==-1&&(s.plan.steps[w].status="in_progress",Ar(n,s)),u&&s.projectId){let{syncRemoteState:v}=await Promise.resolve().then(()=>(Be(),Pt));v(s.projectId,u).catch(()=>{})}let y=a.steps.every(v=>v.status==="completed"||v.number===l.number),k;y?k=`THIS IS THE LAST STEP. Rules for speed:
|
|
3308
|
+
|
|
3309
|
+
1. Write ALL files using PARALLEL tool calls \u2014 batch multiple Write/Edit calls in a single message.
|
|
3310
|
+
2. Do NOT read files you already know (AGENTS.md, CLAUDE.md, mistflow.json, middleware.ts, lib/auth.ts, lib/db.ts).
|
|
3311
|
+
3. After writing, run 'npm run build' and fix any errors.
|
|
3312
|
+
4. Quick file checks (read only these):
|
|
3313
|
+
- app/page.tsx must be a real landing page, NOT a redirect to /login
|
|
3314
|
+
- middleware.ts must have "/" in PUBLIC_EXACT or PUBLIC_PREFIXES
|
|
3315
|
+
- Forms must use server actions (actions.ts with 'use server'), NOT setTimeout/simulate
|
|
3316
|
+
5. Call mist_build({ projectPath }) (fire-and-poll \u2014 re-call with the returned jobId until status 'complete'), then mist_deploy({ action: 'deploy', projectPath }). Do NOT pause between these two calls to ask the user \u2014 the build is expected, the deploy is expected, just chain them.`:k=`IMPLEMENT THIS STEP NOW. Rules for speed:
|
|
3317
|
+
|
|
3318
|
+
1. BEFORE writing any files, tell the user: "[stepTiming.announcement]" \u2014 use the exact announcement string from the stepTiming field so they know what's happening and how long it'll take. This is a one-line status update, NOT a request for permission.
|
|
3319
|
+
2. Write ALL files for this step using PARALLEL tool calls \u2014 batch multiple Write/Edit calls in a single message. Do NOT write one file at a time.
|
|
3320
|
+
3. Do NOT read files you already know: AGENTS.md, CLAUDE.md, mistflow.json, middleware.ts, lib/auth.ts, lib/db.ts, drizzle.config.ts \u2014 these haven't changed.
|
|
3321
|
+
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).
|
|
3322
|
+
5. After writing ALL files, call mist_implement to move to the next step. Do NOT pause to ask the user for permission between steps \u2014 proceed immediately. Do NOT offer options like "continue or stop" \u2014 the user already approved the build when they approved the plan. The previous step is auto-marked complete \u2014 do NOT call implement twice.`;let U=fc(d),Y={stepNumber:l.number,totalSteps:a.steps.length,estimatedMinutes:U,announcement:`Starting step ${l.number} of ${a.steps.length}: ${l.name}. This step usually takes ${U.min}\u2013${U.max} minutes.`},ie=JSON.stringify({instruction:R,step:{number:l.number,name:l.name,description:l.description,status:"in_progress"},stepTiming:Y,compactionGuidance:"If your context gets compacted mid-step (common on long builds), call mist_implement again immediately after the compaction finishes. The tool finds the in-progress step and returns fresh context \u2014 you don't need to re-read files or re-derive state.",...r?{autoCompleted:r}:{},...b.length>0?{generatedModules:b,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:`${p.length}/${a.steps.length} steps done`,nextAction:k});return await lc(3e3)?Jo("http://localhost:3000",ie):c(ie)}var cc,hc,Nr,jr=x(()=>{"use strict";W();le();Vt();ro();dr();mr();gr();yr();wr();xr();Sr();Ir();Tr();cc=xo.object({projectPath:xo.string().optional().describe("Path to the project directory (default: cwd)"),step:xo.number().optional().describe("Specific step number to implement (default: next incomplete step)")});hc=new Set(["landing","design","dashboard","crud","layout","admin","auth","schema","integration","multi-tenant","deploy","general"]);Nr={name:"mist_implement",description:"Execute the next step (or a specific step) from the app plan. Reads mistflow.json, finds the target step, and returns rich context and detailed implementation instructions for the host AI. Auto-commits a checkpoint before changes for safe undo. Use when the user says 'mist implement' or 'mist next step'.",inputSchema:cc,handler:vc}});import{z as De}from"zod";import{resolve as xc}from"path";async function Dr(t){let{projectPath:e,action:o,key:n,value:s,category:a,description:r,setupUrl:i}=t,l=xc(e??process.cwd());if(!J())return c("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let m=Ae(l)?.projectId;if(!m)return c("No project ID found. Deploy your project first with mist_deploy, or initialize with mist_plan + mist_init + mist_install.",!0);try{switch(o){case"set":return n?s?(await Mn(m,n,s,{category:a,description:r,setupUrl:i}),c(JSON.stringify({set:!0,key:n,message:`Environment variable '${n}' has been set. It will be available on your next deployment.`}))):c("Value is required. Provide the env var value.",!0):c("Key is required. Provide the env var name like 'STRIPE_SECRET_KEY'.",!0);case"list":{let u=await On(m);return u.length===0?c(JSON.stringify({envVars:[],message:"No environment variables configured. Use action 'set' to add one."})):c(JSON.stringify({envVars:u.map(d=>({key:d.key,category:d.category,description:d.description,hasValue:d.has_value})),message:`${u.length} environment variable(s) configured.`}))}case"delete":return n?(await Un(m,n),c(JSON.stringify({deleted:!0,key:n,message:`Environment variable '${n}' has been removed.`}))):c("Key is required. Provide the env var name to delete.",!0);default:return c(`Unknown action: ${o}. Use set, list, or delete.`,!0)}}catch(u){if(u instanceof C)return c(u.message,!0);let d=u instanceof Error?u.message:"An unexpected error occurred";return c(d,!0)}}var om,Or=x(()=>{"use strict";W();le();Je();om=De.object({projectPath:De.string().optional().describe("Path to the project directory (default: cwd)"),action:De.enum(["set","list","delete"]).describe("Action to perform"),key:De.string().optional().describe("Environment variable name (required for 'set' and 'delete')"),value:De.string().optional().describe("Environment variable value (required for 'set')"),category:De.string().optional().describe("Category for the env var (default: 'custom')"),description:De.string().optional().describe("Description of what this env var is for"),setupUrl:De.string().optional().describe("URL where the user can obtain this value (e.g. Stripe dashboard)")})});import{z as Et}from"zod";import{resolve as kc,join as Sc}from"path";import{existsSync as Pc,readFileSync as Ic,writeFileSync as _c}from"fs";function Po(t,e){let o=Sc(t,"mistflow.json");if(!Pc(o))return;let n;try{n=JSON.parse(Ic(o,"utf-8"))}catch{return}n.domains=e,_c(o,JSON.stringify(n,null,2)+`
|
|
3323
|
+
`)}async function Mr(t){let{projectPath:e,action:o,domain:n,domainId:s}=t,a=kc(e??process.cwd());if(!J())return c("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let i=Ae(a)?.projectId;if(!i)return c("No project ID found. Deploy your project first with mist_deploy, or initialize with mist_plan + mist_init + mist_install.",!0);try{switch(o){case"add":{if(!n)return c("Domain name is required. Provide the domain like 'myapp.com' or 'app.mycompany.com'.",!0);let l=await jn(i,n),p=await Ce(i);return Po(a,p.map(m=>({domain:m.domain,status:m.status}))),c(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 Ce(i);return l.length===0?c(JSON.stringify({domains:[],message:"No custom domains configured. Use action 'add' to add one."})):c(JSON.stringify({domains:l.map(p=>({id:p.id,domain:p.domain,status:p.status,ssl:p.ssl_status,error:p.error_message}))}))}case"verify":{if(!s){if(n){let u=(await Ce(i)).find(d=>d.domain===n);if(u){let d=await zt(i,u.id);return c(JSON.stringify({domain:d.domain,status:d.status,ssl:d.ssl_status,error:d.error_message,message:d.status==="active"?`Domain '${d.domain}' is active and serving traffic.`:`Domain '${d.domain}' is ${d.status}. Make sure DNS records are configured correctly.`}))}return c(`Domain '${n}' not found. Use action 'list' to see configured domains.`,!0)}return c("Provide either domainId or domain name to verify.",!0)}let l=await zt(i,s),p=await Ce(i);return Po(a,p.map(m=>({domain:m.domain,status:m.status}))),c(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(!s&&!n)return c("Provide either domainId or domain name to remove.",!0);let l=s;if(!l&&n){let u=(await Ce(i)).find(d=>d.domain===n);if(!u)return c(`Domain '${n}' not found.`,!0);l=u.id}await Dn(i,l);let p=await Ce(i);return Po(a,p.map(m=>({domain:m.domain,status:m.status}))),c(JSON.stringify({removed:!0,message:"Domain removed. It may take a few minutes for DNS changes to propagate."}))}default:return c(`Unknown action: ${o}. Use add, list, verify, or remove.`,!0)}}catch(l){if(l instanceof C)return c(l.message,!0);let p=l instanceof Error?l.message:"An unexpected error occurred";return c(p,!0)}}var dm,Ur=x(()=>{"use strict";W();le();Je();dm=Et.object({projectPath:Et.string().optional().describe("Path to the project directory (default: cwd)"),action:Et.enum(["add","list","verify","remove"]).describe("Action to perform"),domain:Et.string().optional().describe("Domain name (required for 'add' and 'remove')"),domainId:Et.string().optional().describe("Domain ID (required for 'verify' and 'remove')")})});import{z as ge}from"zod";var Tc,$r,Lr=x(()=>{"use strict";W();Or();Ur();Tc=ge.object({resource:ge.enum(["env","domain"]).describe("'env' manages app secrets and configuration values. 'domain' manages custom domains."),action:ge.string().describe("Action to perform. env: 'set', 'list', 'delete'. domain: 'add', 'list', 'verify', 'remove'."),projectPath:ge.string().optional().describe("Path to the project directory (default: cwd)"),key:ge.string().optional().describe("(env) Variable name"),value:ge.string().optional().describe("(env set) Variable value"),category:ge.string().optional().describe("(env set) Category"),description:ge.string().optional().describe("(env set) Description"),setupUrl:ge.string().optional().describe("(env set) URL to obtain the value"),domain:ge.string().optional().describe("(domain) Domain name"),domainId:ge.string().optional().describe("(domain) Domain ID")}),$r={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:Tc,handler:async t=>{let e=t;switch(e.resource){case"env":return Dr({projectPath:e.projectPath,action:e.action,key:e.key,value:e.value,category:e.category,description:e.description,setupUrl:e.setupUrl});case"domain":return Mr({projectPath:e.projectPath,action:e.action,domain:e.domain,domainId:e.domainId});default:return c(`Unknown resource: ${e.resource}. Use env or domain.`,!0)}}}});import{spawn as Rc,execFileSync as Ac}from"child_process";import{existsSync as ln,mkdirSync as Br,openSync as Io,closeSync as _o,readSync as Cc,readFileSync as zr,writeFileSync as Hr,renameSync as Wr,unlinkSync as Ec,readdirSync as vm,statSync as Nc}from"fs";import{homedir as Gr}from"os";import{join as ve,dirname as Vr}from"path";import{randomBytes as Jr,randomUUID as jc}from"crypto";function pn(){return ve(Gr(),".mistflow","jobs")}function Oc(){return ve(Gr(),".mistflow","job-wrapper.cjs")}function Mc(){let t=Oc(),e=Vr(t);ln(e)||Br(e,{recursive:!0});let o=`v${Kr}`;if(ln(t))try{if(zr(t,"utf-8").includes(o))return t}catch{}let n=ve(e,`.job-wrapper.tmp.${Jr(6).toString("hex")}`);return Hr(n,Dc),Wr(n,t),t}function cn(t){return ve(pn(),t)}function Yr(t){return ve(cn(t),"status.json")}function Fr(t,e){let o=Yr(t),n=ve(Vr(o),`.status.tmp.${Jr(6).toString("hex")}`);try{Hr(n,JSON.stringify(e,null,2)+`
|
|
3324
|
+
`),Wr(n,o)}catch(s){try{Ec(n)}catch{}throw s}}function Uc(t){let e=Yr(t);if(!ln(e))return null;try{return JSON.parse(zr(e,"utf-8"))}catch{return null}}async function it(t){let e=`job_${jc().replace(/-/g,"").slice(0,12)}`,o=cn(e);Br(o,{recursive:!0}),_o(Io(ve(o,"stdout.log"),"a")),_o(Io(ve(o,"stderr.log"),"a"));let n=new Date().toISOString(),s={id:e,type:t.type,status:"starting",pid:0,wrapperPid:0,startedAt:n,cmd:t.cmd,args:t.args,cwd:t.cwd};Fr(e,s);let a=Mc(),r={...process.env,...t.env??{}},i=Rc("node",[a,o,t.cwd,t.cmd,...t.args],{detached:!0,stdio:"ignore",env:r});i.unref();let l={...s,wrapperPid:i.pid??0};return Fr(e,l),l}function $c(t){let e=t.trim();if(!e)return NaN;let o=Date.parse(e);return Number.isFinite(o)?o:NaN}function Lc(t){let e=t.pid||t.wrapperPid;if(!e)return!1;try{process.kill(e,0)}catch{return!1}try{let o=Ac("ps",["-o","lstart=","-p",String(e)],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}),n=$c(o),s=Date.parse(t.startedAt);if(Number.isFinite(n)&&Number.isFinite(s)&&Math.abs(n-s)>2e3)return!1}catch{}return!0}function Fc(t,e){let o=Date.parse(t),n=e?Date.parse(e):Date.now();if(!Number.isFinite(o)||!Number.isFinite(n))return"0s";let s=Math.max(0,n-o),a=Math.floor(s/1e3);if(a<60)return`${a}s`;let r=Math.floor(a/60),i=a%60;return r<60?`${r}m ${i}s`:`${Math.floor(r/60)}h ${r%60}m`}function qr(t,e){if(!ln(t))return"";let o=Nc(t);if(o.size===0)return"";let n=o.size>e?o.size-e:0,s=o.size-n,a=Io(t,"r");try{let r=Buffer.alloc(s);return Cc(a,r,0,s,n),r.toString("utf-8")}finally{_o(a)}}function qc(t,e=20){let o=qr(ve(cn(t),"stdout.log"),16384),n=qr(ve(cn(t),"stderr.log"),16*1024),s=[];return o.trim()&&s.push(...o.split(`
|
|
3325
|
+
`).slice(-e).map(a=>`[out] ${a}`)),n.trim()&&s.push(...n.split(`
|
|
3326
|
+
`).slice(-e).map(a=>`[err] ${a}`)),s.filter(a=>a.trim().length>0).join(`
|
|
3327
|
+
`)}async function at(t){let e=Uc(t);if(!e)return null;let o=e;return(e.status==="running"||e.status==="starting")&&!Lc(e)&&(o={...e,status:"unknown_exit",endedAt:e.endedAt??new Date().toISOString()}),{...o,elapsed:Fc(o.startedAt,o.endedAt),logTail:qc(t)}}var Kr,Dc,dn=x(()=>{"use strict";Kr=1,Dc=`// Generated by @mistflow-ai/mcp local-jobs (v${Kr}). Do not edit.
|
|
3328
|
+
const { spawn } = require('node:child_process');
|
|
3329
|
+
const { readFileSync, writeFileSync, openSync, renameSync } = require('node:fs');
|
|
3330
|
+
const { join, dirname } = require('node:path');
|
|
3331
|
+
const { randomBytes } = require('node:crypto');
|
|
3332
|
+
|
|
3333
|
+
// argv: [node, wrapper, jobDir, cwd, cmd, ...args]
|
|
3334
|
+
const [, , jobDir, cwd, cmd, ...args] = process.argv;
|
|
3335
|
+
const statusPath = join(jobDir, 'status.json');
|
|
3336
|
+
const stdoutPath = join(jobDir, 'stdout.log');
|
|
3337
|
+
const stderrPath = join(jobDir, 'stderr.log');
|
|
3338
|
+
|
|
3339
|
+
function atomicWrite(path, content) {
|
|
3340
|
+
const tmp = join(dirname(path), '.status.tmp.' + randomBytes(6).toString('hex'));
|
|
3341
|
+
writeFileSync(tmp, content);
|
|
3342
|
+
renameSync(tmp, path);
|
|
3343
|
+
}
|
|
3344
|
+
|
|
3345
|
+
function updateStatus(patch) {
|
|
3346
|
+
let data;
|
|
3347
|
+
try { data = JSON.parse(readFileSync(statusPath, 'utf-8')); } catch { data = {}; }
|
|
3348
|
+
Object.assign(data, patch);
|
|
3349
|
+
atomicWrite(statusPath, JSON.stringify(data, null, 2) + '\\n');
|
|
3350
|
+
}
|
|
3351
|
+
|
|
3352
|
+
const stdoutFd = openSync(stdoutPath, 'a');
|
|
3353
|
+
const stderrFd = openSync(stderrPath, 'a');
|
|
3354
|
+
|
|
3355
|
+
let child;
|
|
3356
|
+
try {
|
|
3357
|
+
child = spawn(cmd, args, {
|
|
3358
|
+
cwd: cwd || process.cwd(),
|
|
3359
|
+
env: process.env,
|
|
3360
|
+
stdio: ['ignore', stdoutFd, stderrFd],
|
|
3361
|
+
});
|
|
3362
|
+
} catch (err) {
|
|
3363
|
+
updateStatus({
|
|
3364
|
+
status: 'failed',
|
|
3365
|
+
error: 'spawn failed: ' + (err && err.message ? err.message : String(err)),
|
|
3366
|
+
endedAt: new Date().toISOString(),
|
|
3367
|
+
});
|
|
3368
|
+
process.exit(1);
|
|
3369
|
+
}
|
|
3370
|
+
|
|
3371
|
+
updateStatus({ pid: child.pid, status: 'running' });
|
|
3372
|
+
|
|
3373
|
+
child.on('close', (code, signal) => {
|
|
3374
|
+
updateStatus({
|
|
3375
|
+
status: code === 0 ? 'complete' : 'failed',
|
|
3376
|
+
exitCode: code,
|
|
3377
|
+
signal: signal || null,
|
|
3378
|
+
endedAt: new Date().toISOString(),
|
|
3379
|
+
});
|
|
3380
|
+
process.exit(code == null ? 1 : code);
|
|
3381
|
+
});
|
|
3382
|
+
|
|
3383
|
+
child.on('error', (err) => {
|
|
3384
|
+
updateStatus({
|
|
3385
|
+
status: 'failed',
|
|
3386
|
+
error: err && err.message ? err.message : String(err),
|
|
3387
|
+
endedAt: new Date().toISOString(),
|
|
3388
|
+
});
|
|
3389
|
+
process.exit(1);
|
|
3390
|
+
});
|
|
3391
|
+
`});import{z as To}from"zod";import{resolve as Bc}from"path";import{existsSync as zc}from"fs";import{join as Hc}from"path";var Wc,Qr,Xr=x(()=>{"use strict";W();dn();Wc=To.object({projectPath:To.string().optional().describe("Absolute path to the project. Required for the first call (to start the install)."),jobId:To.string().optional().describe("Job ID returned from a previous call. Present means poll; absent means start.")}).refine(t=>!!t.projectPath||!!t.jobId,{message:"Pass projectPath to start an install, or jobId to poll an existing one."}),Qr={name:"mist_install",description:"Install a Mistflow project's npm dependencies with the fire-and-poll pattern. First call with { projectPath } starts the install and returns a jobId. Subsequent calls with { jobId } poll for progress (status: 'running' | 'complete' | 'failed'). Re-call while status is 'running' \u2014 each response is <1s so there is no 60s timeout risk.",inputSchema:Wc,handler:async t=>{let e=t;if(e.jobId){let i=await at(e.jobId);return i?i.status==="running"||i.status==="starting"?c(JSON.stringify({status:"running",jobId:i.id,elapsed:i.elapsed,logTail:i.logTail,nextAction:"Still running. Call mist_install with the same jobId in ~15-30s to check progress."})):i.status==="complete"?c(JSON.stringify({status:"complete",jobId:i.id,elapsed:i.elapsed,exitCode:i.exitCode,nextAction:"Dependencies installed. Run mist_implement next to start executing plan steps."})):c(JSON.stringify({status:i.status,jobId:i.id,elapsed:i.elapsed,exitCode:i.exitCode,logTail:i.logTail,nextAction:"npm install failed. Read the logTail for the error and fix it \u2014 usually a missing native dep or a version conflict. After fixing, start a new install with { projectPath }."}),!0):c(JSON.stringify({status:"not_found",jobId:e.jobId,message:`No install job found for jobId '${e.jobId}'. Start a new one with { projectPath }.`}),!0)}let o=Bc(e.projectPath);if(!zc(Hc(o,"package.json")))return c(`No package.json at ${o}. Confirm the path and that mist_init has scaffolded the project.`,!0);let a=`npm install && (${`npx --yes shadcn@latest add -y -o ${["button","card","input","label","form","dialog","table","dropdown-menu","badge","separator","skeleton","sheet","tabs","avatar","select","textarea","checkbox","switch","tooltip","popover","sonner"].join(" ")}`} || echo 'shadcn add failed \u2014 implement will retry lazily')`,r=await it({type:"install",cmd:"sh",args:["-c",a],cwd:o,env:{NPM_CONFIG_LEGACY_PEER_DEPS:"true"}});return c(JSON.stringify({status:"running",jobId:r.id,startedAt:r.startedAt,cwd:o,nextAction:"Install started in the background (npm install + shadcn components). Call mist_install again with { jobId: '"+r.id+"' } in ~15-30s to check progress. Typical duration: 30-90s."}))}}});import{z as un}from"zod";import{resolve as Gc,join as lt}from"path";import{existsSync as ct,readFileSync as Zr}from"fs";function Jc(t){let e=lt(pn(),t,"stdout.log"),o=lt(pn(),t,"stderr.log"),n="";try{ct(e)&&(n+=Zr(e,"utf-8"))}catch{}try{ct(o)&&(n+=`
|
|
3392
|
+
`+Zr(o,"utf-8"))}catch{}return n}function Kc(t){let e=/Module not found:\s*(?:Error:\s*)?Can't resolve ['"]([^'"]+)['"]/g,o=new Set;for(let n of t.matchAll(e)){let s=n[1];if(s.startsWith(".")||s.startsWith("@/")||s.startsWith("~/"))continue;let a=s.startsWith("@")?s.split("/").slice(0,2).join("/"):s.split("/")[0];a&&o.add(a)}return[...o]}var Vc,ei,ti=x(()=>{"use strict";W();dn();io();Vc=un.object({projectPath:un.string().optional().describe("Absolute path to the project. Required for the first call."),jobId:un.string().optional().describe("Job ID from a previous call. Present means poll; absent means start."),script:un.string().optional().describe("Optional override: run `npm run <script>` instead of the Cloudflare adapter. Default behavior is `npx @opennextjs/cloudflare build` when open-next.config.ts exists, else `npm run build`. Ignored on poll calls.")}).refine(t=>!!t.projectPath||!!t.jobId,{message:"Pass projectPath to start a build, or jobId to poll an existing one."});ei={name:"mist_build",description:"Run a Mistflow project's production build with the fire-and-poll pattern. First call with { projectPath } starts `npm run build` and returns a jobId. Subsequent calls with { jobId } poll status. On failure, the response surfaces structured errors (from parseBuildErrors) and any missingModules[] \u2014 chain into mist_install with those modules, then mist_build again, without asking the user.",inputSchema:Vc,handler:async t=>{let e=t;if(e.jobId){let l=await at(e.jobId);if(!l)return c(JSON.stringify({status:"not_found",jobId:e.jobId,message:`No build job found for jobId '${e.jobId}'. Start a new one with { projectPath }.`}),!0);if(l.status==="running"||l.status==="starting")return c(JSON.stringify({status:"running",jobId:l.id,elapsed:l.elapsed,logTail:l.logTail,nextAction:"Build still running. Call mist_build again with the same jobId in ~20-40s."}));if(l.status==="complete")return c(JSON.stringify({status:"complete",jobId:l.id,elapsed:l.elapsed,exitCode:l.exitCode,nextAction:"Build passed. Run mist_deploy next to ship \u2014 do NOT ask the user to confirm, the build is the approval gate."}));let p=Jc(l.id),m=Zt(p),u=Kc(p),d=u.length>0?`Build failed with missing modules: ${u.join(", ")}. Call mist_install with these packages (or chain mist_install { projectPath } to reinstall all), then call mist_build again. Do NOT ask the user.`:m.length>0?"Build failed with structured errors (see errors[]). Fix the code, then call mist_build again.":"Build failed. Read the logTail for the error, or call mist_debug with the failed jobId to extract structured errors.";return c(JSON.stringify({status:l.status,jobId:l.id,elapsed:l.elapsed,exitCode:l.exitCode,errors:m,missingModules:u,logTail:l.logTail,nextAction:d}),!0)}let o=Gc(e.projectPath);if(!ct(lt(o,"package.json")))return c(`No package.json at ${o}. Run mist_init first.`,!0);if(!ct(lt(o,"node_modules")))return c(`node_modules not installed. Run mist_install { projectPath: '${o}' } first.`,!0);let n,s,a,r=ct(lt(o,"open-next.config.ts"))||ct(lt(o,"open-next.config.js"));e.script?(n="npm",s=["run",e.script],a=e.script):r?(n="npx",s=["-y","@opennextjs/cloudflare","build"],a="@opennextjs/cloudflare build"):(n="npm",s=["run","build"],a="build");let i=await it({type:"build",cmd:n,args:s,cwd:o});return c(JSON.stringify({status:"running",jobId:i.id,startedAt:i.startedAt,cwd:o,script:a,nextAction:`Build started. Call mist_build again with { jobId: '${i.id}' } in ~30s to check progress. Typical duration: 30-90s on a fresh scaffold (Cloudflare adapter), 10-30s on subsequent builds.`}))}}});import{z as Nt}from"zod";import{resolve as Yc,join as Ro}from"path";import{existsSync as Ao}from"fs";var Qc,ni,oi=x(()=>{"use strict";W();dn();Qc=Nt.object({projectPath:Nt.string().optional().describe("Absolute path to the project. Required for the first call."),jobId:Nt.string().optional().describe("Job ID from a previous call. Present means poll; absent means start."),baseUrl:Nt.string().optional().describe("Override the URL Playwright tests hit \u2014 defaults to the project's configured base URL."),grep:Nt.string().optional().describe("Pass-through to `playwright test -g`. Useful for running a single scenario.")}).refine(t=>!!t.projectPath||!!t.jobId,{message:"Pass projectPath to start a QA run, or jobId to poll an existing one."}),ni={name:"mist_qa",description:"Run a Mistflow project's Playwright QA suite with the fire-and-poll pattern. First call with { projectPath, baseUrl? } starts the run and returns a jobId. Subsequent calls with { jobId } poll status. Call AFTER mist_deploy \u2014 the QA suite targets the deployed URL. Do NOT show the deploy URL to the user until mist_qa reports status: 'complete' with exitCode 0.",inputSchema:Qc,handler:async t=>{let e=t;if(e.jobId){let i=await at(e.jobId);return i?i.status==="running"||i.status==="starting"?c(JSON.stringify({status:"running",jobId:i.id,elapsed:i.elapsed,logTail:i.logTail,nextAction:"QA still running. Call mist_qa again with the same jobId in ~15-30s."})):i.status==="complete"?c(JSON.stringify({status:"complete",jobId:i.id,elapsed:i.elapsed,exitCode:i.exitCode,nextAction:"QA passed. Surface the deploy URL to the user now \u2014 the app is verified."})):c(JSON.stringify({status:i.status,jobId:i.id,elapsed:i.elapsed,exitCode:i.exitCode,logTail:i.logTail,nextAction:"QA failed. Read the logTail for which scenarios broke. Do NOT show the deploy URL to the user. Fix the code, redeploy (mist_deploy), then re-run mist_qa."}),!0):c(JSON.stringify({status:"not_found",jobId:e.jobId,message:`No QA job found for jobId '${e.jobId}'. Start a new one with { projectPath }.`}),!0)}let o=Yc(e.projectPath);if(!Ao(Ro(o,"package.json")))return c(`No package.json at ${o}. Run mist_init first.`,!0);if(!(Ao(Ro(o,"playwright.config.ts"))||Ao(Ro(o,"playwright.config.js"))))return c(`No playwright.config.ts at ${o}. Mistflow projects scaffold with Playwright; if missing, run mist_implement to regenerate or add one manually.`,!0);let s=["playwright","test"];e.grep&&s.push("-g",e.grep);let a={};e.baseUrl&&(a.BASE_URL=e.baseUrl);let r=await it({type:"qa",cmd:"npx",args:s,cwd:o,env:a});return c(JSON.stringify({status:"running",jobId:r.id,startedAt:r.startedAt,cwd:o,baseUrl:e.baseUrl??"(from project config)",nextAction:`QA started. Call mist_qa again with { jobId: '${r.id}' } in ~20s. Typical duration: 30-120s depending on scenario count.`}))}}});import{existsSync as mn,readdirSync as Xc,statSync as si,unlinkSync as ri}from"fs";import{join as We}from"path";import{execFile as Zc}from"child_process";function ep(t,e){let o=0;for(let n of e){let s=We(t,n);if(mn(s))try{let a=si(s);if(a.isFile())o++;else if(a.isDirectory()){let r=[s];for(;r.length;){let i=r.pop(),l=Xc(i,{withFileTypes:!0});for(let p of l){let m=We(i,p.name);p.isDirectory()?r.push(m):o++}}}}catch{}}return o}function ii(t,e,o){return new Promise(n=>{Zc("tar",t,{cwd:e,timeout:o,maxBuffer:10*1024*1024},(s,a,r)=>{n({success:!s,stderr:r?.toString()??""})})})}async function ai(t){let e=We(t,".open-next-build.tar.gz"),o=[".open-next"];mn(We(t,"db"))&&o.push("db"),mn(We(t,"drizzle.config.ts"))&&o.push("drizzle.config.ts"),mn(We(t,"package.json"))&&o.push("package.json");let n=ep(t,o),s=await ii(["-czf",e,"-C",t,...o],t,12e4);if(!s.success){try{ri(e)}catch{}throw new Error("Failed to create build archive. Check disk space and permissions."+(s.stderr?`
|
|
3393
|
+
${s.stderr.slice(-500)}`:""))}let a=0;try{a=si(e).size}catch{}return{path:e,sizeBytes:a,fileCount:n}}async function li(t){let e=We(t,".mistflow-source.tar.gz");return(await ii(["-czf",e,"-C",t,"--exclude",".open-next","--exclude","node_modules","--exclude",".git","--exclude",".next","--exclude",".open-next-build.tar.gz","--exclude",".mistflow-source.tar.gz","."],t,12e4)).success?e:null}function Co(t){if(t)try{ri(t)}catch{}}function ci(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/(1024*1024)).toFixed(1)}MB`}function pi(t){switch(t){case"pending":return"Provisioning...";case"building":return"Building your app...";case"deploying":return"Deploying to Mistflow Cloud...";case"verifying":return"Verifying deployment...";case"live":return"Live!";case"failed":return"Failed";default:return`Status: ${t}`}}var di=x(()=>{"use strict"});import{z as pt}from"zod";import{resolve as tp,join as np}from"path";import{existsSync as op}from"fs";function rp(t){return op(np(t,".open-next"))}function ip(t){return Ae(t)?.deploy?.strategy==="staging"?"preview":null}async function ap(t){let e=tp(t.projectPath);if(!J())return c("Not signed in. Call mist_setup first.",!0);let n=Ae(e)?.projectId;if(!n)return c(`No projectId in mistflow.json at ${e}. Run mist_init first.`,!0);if(!rp(e))return c(`No .open-next build output at ${e}. Run mist_build first \u2014 the deploy tool ships the build artifact, not the raw source.`,!0);let s=t.environment??ip(e)??"production",a=null,r=null;try{a=await ai(e),r=await li(e);let i=await Cn(n,a.path,s,t.adminEmail,void 0,r??void 0,void 0);return c(JSON.stringify({status:"running",jobId:i.deployment_id,deploymentId:i.deployment_id,environment:i.environment??s,buildSize:ci(a.sizeBytes),buildFileCount:a.fileCount,nextAction:`Upload complete. Call mist_deploy { action: 'status', deploymentId: '${i.deployment_id}' } in ~5-10s to poll deployment progress. Do NOT surface the URL to the user until mist_qa passes.`}))}catch(i){let l=i instanceof C||i instanceof Error?i.message:String(i);return c(`Deploy upload failed: ${l}`,!0)}finally{Co(a?.path),Co(r)}}async function lp(t){try{let e=await xt(t),o=pi(e.status);return e.status==="live"?c(JSON.stringify({status:"complete",jobId:e.id,deploymentId:e.id,url:e.url,completedAt:e.completedAt,qaRequired:!0,nextAction:`Deployment is live. Call mist_qa { projectPath, baseUrl: '${e.url??""}' } next. Do NOT show the URL to the user until mist_qa returns status: 'complete'.`})):e.status==="failed"?c(JSON.stringify({status:"failed",jobId:e.id,deploymentId:e.id,error:e.error,phase:o,nextAction:"Deployment failed. Read the error message, fix the code, then call mist_deploy { action: 'deploy', projectPath } again."}),!0):c(JSON.stringify({status:"running",jobId:e.id,deploymentId:e.id,phase:o,phaseCode:e.status,nextAction:`Still ${e.status}. Call mist_deploy { action: 'status', deploymentId: '${e.id}' } again in ~5-10s.`}))}catch(e){let o=e instanceof C||e instanceof Error?e.message:String(e);return c(`Could not fetch deploy status: ${o}`,!0)}}async function cp(t,e){if(!J())return c("Not signed in. Call mist_setup first.",!0);let n=Ae(t)?.projectId;if(!n)return c(`No projectId in mistflow.json at ${t}. Run mist_init first.`,!0);let s=e;if(!s)try{let r=(await Qe(n)).find(i=>i.environment==="preview"&&i.status==="live");if(!r)return c("No live preview deployment to promote. Deploy to preview first with { action: 'deploy', environment: 'preview' }.",!0);s=r.id}catch(a){let r=a instanceof C?a.message:String(a);return c(`Could not list deployments: ${r}`,!0)}try{let a=await Fn(n,s);return c(JSON.stringify({status:"running",jobId:a.deployment_id,deploymentId:a.deployment_id,promotedFrom:s,nextAction:`Promote started. Call mist_deploy { action: 'status', deploymentId: '${a.deployment_id}' } to poll. Promotion re-uses the preview artifact so it typically completes in ~10s.`}))}catch(a){let r=a instanceof C||a instanceof Error?a.message:String(a);return c(`Promote failed: ${r}`,!0)}}async function pp(t){if(!J())return c("Not signed in. Call mist_setup first.",!0);try{let e=await qn(t);return c(JSON.stringify({status:"running",jobId:e.deployment_id,deploymentId:e.deployment_id,rollbackFrom:e.rollback_from,nextAction:`Rollback started. Call mist_deploy { action: 'status', deploymentId: '${e.deployment_id}' } to poll.`}))}catch(e){let o=e instanceof C||e instanceof Error?e.message:String(e);return c(`Rollback failed: ${o}`,!0)}}var sp,ui,mi=x(()=>{"use strict";W();le();Je();di();sp=pt.object({action:pt.enum(["deploy","promote","rollback","status"]).default("deploy").describe("'deploy' (default) tars + uploads + starts a deployment. 'promote' promotes a staging preview to production. 'rollback' rolls back to a specific deployment. 'status' polls an in-flight deployment by id."),projectPath:pt.string().optional().describe("Absolute path to the project. Required for 'deploy' and 'promote'."),deploymentId:pt.string().optional().describe("Deployment id \u2014 required for 'rollback' and 'status'; the preview id for 'promote'."),environment:pt.enum(["production","preview"]).optional().describe("Deploy target. Defaults to 'production'; auto-redirects to 'preview' when the project uses staging mode."),adminEmail:pt.string().optional().describe("Admin email injected as BETTER_AUTH_ADMIN_EMAIL on first deploy of an auth-enabled project.")});ui={name:"mist_deploy",description:"Deploy a Mistflow project. action='deploy' (default) tars + uploads + starts backend orchestration; action='status' polls an in-flight deployment; action='promote' ships a staging preview to prod; action='rollback' reverts to a previous deployment. Fire-and-poll: deploy/promote/rollback return a jobId immediately; poll with { action: 'status', deploymentId }. Do NOT show the deploy URL to the user until mist_qa passes \u2014 qaRequired=true is returned on completion.",inputSchema:sp,handler:async t=>{let e=t;switch(e.action??"deploy"){case"deploy":return e.projectPath?ap({projectPath:e.projectPath,environment:e.environment,adminEmail:e.adminEmail}):c("projectPath is required for action='deploy'.",!0);case"status":return e.deploymentId?lp(e.deploymentId):c("deploymentId is required for action='status'.",!0);case"promote":return e.projectPath?cp(e.projectPath,e.deploymentId):c("projectPath is required for action='promote'.",!0);case"rollback":return e.deploymentId?pp(e.deploymentId):c("deploymentId is required for action='rollback'.",!0)}}}});var yp={};import{Server as dp}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as up}from"@modelcontextprotocol/sdk/server/stdio.js";import{CallToolRequestSchema as mp,ListToolsRequestSchema as hp}from"@modelcontextprotocol/sdk/types.js";import{zodToJsonSchema as gp}from"zod-to-json-schema";async function fp(){let t=process.argv.indexOf("--api-url");t!==-1&&process.argv[t+1]&&(process.env.MISTFLOW_API_URL=process.argv[t+1]),process.argv.includes("--local")&&!process.env.MISTFLOW_API_URL&&(process.env.MISTFLOW_API_URL="http://localhost:9100");let e=new up;await hn.connect(e),console.error(`Mistflow MCP server running on stdio (API: ${process.env.MISTFLOW_API_URL||"https://api.mistflow.ai"})`)}var hn,hi,gi=x(()=>{"use strict";Te();W();ls();_s();Rs();Ns();ro();Bs();tr();pr();jr();Lr();Xr();ti();oi();mi();hn=new dp({name:"mistflow",version:"1.0.0"},{capabilities:{tools:{}},instructions:$o()}),hi=[as,Is,Ts,Es,er,cr,Ls,Nr,qs,$r,Qr,ei,ni,ui];hn.setRequestHandler(hp,async()=>({tools:hi.map(t=>({name:t.name,description:t.description,inputSchema:gp(t.inputSchema)}))}));hn.setRequestHandler(mp,async t=>{let e=hi.find(o=>o.name===t.params.name);if(!e)return c(`Unknown tool: ${t.params.name}`,!0);try{let o=e.inputSchema.safeParse(t.params.arguments);if(!o.success){let a=o.error.issues.map(r=>`${r.path.join(".")}: ${r.message}`).join(", ");return c(`Invalid input: ${a}`,!0)}let n=t.params._meta?.progressToken,s={server:hn,progressToken:n};try{return await e.handler(o.data,s)}finally{s.cleanup?.()}}catch(o){let n=o instanceof Error?o.message:"An unexpected error occurred";return console.error("Tool error:",o),c(n,!0)}});fp().catch(t=>{console.error("Fatal error:",t),process.exit(1)})});import{readFileSync as bp}from"fs";import{dirname as wp,join as vp}from"path";import{fileURLToPath as xp}from"url";var Oe=process.argv[2];if(Oe==="--version"||Oe==="-v"){try{let t=wp(xp(import.meta.url)),e=vp(t,"..","package.json"),o=JSON.parse(bp(e,"utf-8"));console.log(o.version)}catch{console.log("unknown")}process.exit(0)}(Oe==="--help"||Oe==="-h")&&(console.log(`@mistflow-ai/mcp \u2014 Mistflow MCP server
|
|
214
3394
|
|
|
215
3395
|
Usage:
|
|
216
3396
|
npx @mistflow-ai/mcp Start the MCP server on stdio (default; invoked by editors)
|
|
@@ -218,8 +3398,8 @@ Usage:
|
|
|
218
3398
|
|
|
219
3399
|
To install the server into your editor config, use the installer:
|
|
220
3400
|
npx -y mistflow-ai install
|
|
221
|
-
`),process.exit(0));(
|
|
3401
|
+
`),process.exit(0));(Oe==="install"||Oe==="uninstall")&&(console.error(`'npx @mistflow-ai/mcp ${Oe}' is no longer supported.
|
|
222
3402
|
Use the installer package instead:
|
|
223
3403
|
|
|
224
|
-
npx -y mistflow-ai ${
|
|
225
|
-
`),process.exit(1));await Promise.resolve().then(()=>(
|
|
3404
|
+
npx -y mistflow-ai ${Oe}
|
|
3405
|
+
`),process.exit(1));await Promise.resolve().then(()=>(gi(),yp));
|