generatesaas 3.41.0 → 3.42.0

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.
Files changed (2) hide show
  1. package/dist/index.js +7 -6
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,11 +1,11 @@
1
1
  #!/usr/bin/env node
2
- import{Command as id}from"commander";import*as Cs from"@clack/prompts";import{existsSync as yp,readdirSync as bp,rmSync as wp}from"fs";import{join as vp,resolve as kp}from"path";import{Option as ee}from"commander";import*as E from"@clack/prompts";import*as Rt from"@clack/prompts";import cr from"picocolors";function Zr(e){let t=e?` GenerateSaaS v${e} `:" GenerateSaaS ";Rt.intro(cr.bgYellow(cr.black(t)))}function Qr(){Rt.outro(cr.yellow("Happy building!"))}import*as f from"@clack/prompts";import y from"picocolors";var gt={fullstack:{label:"Fullstack",hint:"Frontend hosts the API - works on serverless or long-running"},separate:{label:"Separate",hint:"Standalone Hono backend - long-running runtimes only (Docker, Render, Fly.io, Railway, Coolify, Dokploy)"}},_t={stripe:{label:"Stripe"},polar:{label:"Polar"},none:{label:"None",hint:"disable payments"}},Ot={smtp:{label:"SMTP",hint:"Mailpit for local dev"},ses:{label:"Amazon SES"},resend:{label:"Resend"}},xt={sentry:{label:"Sentry",hint:"web, server and desktop - release health, tracing, alerting"},posthog:{label:"PostHog",hint:"web and server, plus LLM analytics - no Electron SDK, so a desktop build reports nothing"}},en={postgres:{label:"PostgreSQL",hint:"port 5432",port:5432},redis:{label:"Redis",hint:"port 6379",port:6379},inngest:{label:"Inngest",hint:"port 8288",port:8288},mailpit:{label:"Mailpit",hint:"port 1025",port:1025}};var Ne={USD:{symbol:"$",name:"US Dollar",place:"left",space:!1},EUR:{symbol:"\u20AC",name:"Euro",place:"right",space:!1},GBP:{symbol:"\xA3",name:"British Pound",place:"left",space:!1},CAD:{symbol:"CA$",name:"Canadian Dollar",place:"left",space:!1},AUD:{symbol:"A$",name:"Australian Dollar",place:"left",space:!1},BRL:{symbol:"R$",name:"Brazilian Real",place:"left",space:!1},JPY:{symbol:"\xA5",name:"Japanese Yen",place:"left",space:!1}};var re={node:{label:"Node.js / Docker",hint:"long-running runtime - Render, Fly.io, Railway, Coolify, Dokploy, VPS",edgeRuntime:!1},vercel:{label:"Vercel",hint:"serverless functions",edgeRuntime:!0}},Ce={postgres:{label:"PostgreSQL (self-hosted)",hint:"local Docker, drizzle-orm/node-postgres",managed:!1,envVars:[{key:"DATABASE_URL",defaultValue:"postgres://postgres:postgres@localhost:5432/saas"}]},neon:{label:"Neon",hint:"serverless Postgres",managed:!0,envVars:[{key:"DATABASE_URL",comment:"# TODO: Add your Neon connection string"}]},supabase:{label:"Supabase",hint:"managed Postgres",managed:!0,envVars:[{key:"DATABASE_URL",comment:"# TODO: Add your Supabase connection string"}]}},Le={redis:{label:"Redis (self-hosted)",hint:"local Docker, ioredis",managed:!1,envVars:[{key:"REDIS_URL",defaultValue:"redis://localhost:6379"}]},upstash:{label:"Upstash",hint:"serverless Redis",managed:!0,envVars:[{key:"UPSTASH_REDIS_REST_URL",comment:"# TODO: Add your Upstash REST URL"},{key:"UPSTASH_REDIS_REST_TOKEN",comment:"# TODO: Add your Upstash REST token"}]}},et=[{target:"vercel",provider:"redis",reason:"Vercel serverless cannot maintain persistent Redis connections. Consider Upstash."},{target:"vercel",provider:"postgres",reason:"Vercel serverless cannot pool connections to a self-hosted Postgres. Use Neon or Supabase - both are managed, connection-pooled Postgres."}],tt=[{architecture:"separate",target:"vercel",reason:"Standalone backends need a long-running runtime. Vercel's per-function TypeScript check conflicts with pnpm's isolated install. Use --architecture fullstack for serverless, or deploy the standalone backend to a long-running runtime (Render, Fly.io, Railway, Coolify, Dokploy, or your own VPS via Docker)."}],ae={serverless:{label:"Serverless",hint:"Vercel + Neon + Upstash",values:{deploymentTarget:"vercel",databaseProvider:"neon",cacheProvider:"upstash"}},selfhost:{label:"Self-host",hint:"Docker or Node + Postgres + Redis",values:{deploymentTarget:"node",databaseProvider:"postgres",cacheProvider:"redis"}}},$e=Object.keys(ae);function lr(e){let t=[];for(let r of et)if(e.deploymentTarget===r.target&&(e.databaseProvider===r.provider||e.cacheProvider===r.provider)){let n=e.databaseProvider===r.provider?"databaseProvider":"cacheProvider";t.push(`\`${n}: "${r.provider}"\` with \`deploymentTarget: "${r.target}"\` - ${r.reason}`)}for(let r of tt)e.deploymentTarget===r.target&&e.architecture===r.architecture&&t.push(`\`architecture: "${r.architecture}"\` with \`deploymentTarget: "${r.target}"\` - ${r.reason}`);return t}var tn=["Local file storage (sharp, geoip-lite)","SMTP email (use Resend or SES instead)","Content API git integration"];function rt(e){let t=[];return e.databaseProvider==="postgres"&&t.push("postgres"),e.cacheProvider==="redis"&&t.push("redis"),e.emailProvider==="smtp"&&t.push("mailpit"),t.push("inngest"),t}var nt=["fullstack","separate"],it=["stripe","polar","none"],st=["smtp","ses","resend"],rn=["claude-code","cursor","codex","gemini-cli","windsurf"],ce=["USD","EUR","GBP","CAD","AUD","BRL","JPY"],le=["node","vercel"],pe=["postgres","neon","supabase"],de=["redis","upstash"],G=["sentry","posthog"],je=["revenuecat","none"];function ne(e){return e.paymentProvider!==void 0&&e.paymentProvider!=="none"}var pr=[{key:"architecture",label:"Architecture",hint:"Fullstack (frontend hosts the API) or a standalone Hono backend.",category:"Infrastructure",kind:"enum",default:"fullstack",choices:nt,adoptable:!1,impact:"structural",shapesTree:!0},{key:"deploymentTarget",label:"Deployment target",hint:"Node.js / Docker or Vercel serverless.",category:"Infrastructure",kind:"enum",default:"node",choices:le,adoptable:!1,impact:"config",shapesTree:!0},{key:"databaseProvider",label:"Database provider",hint:"Self-hosted PostgreSQL, Neon, or Supabase.",category:"Infrastructure",kind:"enum",default:"postgres",choices:pe,adoptable:!1,impact:"config",shapesTree:!0},{key:"cacheProvider",label:"Cache provider",hint:"Self-hosted Redis or Upstash.",category:"Infrastructure",kind:"enum",default:"redis",choices:de,adoptable:!1,impact:"config",shapesTree:!0},{key:"paymentProvider",label:"Payment provider",hint:"Stripe, Polar, or none.",category:"Features",kind:"enum",default:"none",choices:it,adoptable:!1,impact:"structural",shapesTree:!0},{key:"defaultCurrency",label:"Default currency",hint:"Billing and pricing currency.",category:"Features",kind:"enum",default:"USD",choices:ce,adoptable:!1,impact:"config",shapesTree:!1},{key:"emailProvider",label:"Email provider",hint:"SMTP, Amazon SES, or Resend.",category:"Features",kind:"enum",default:"smtp",choices:st,adoptable:!1,impact:"config",shapesTree:!1},{key:"observability",label:"Observability",hint:"Which services receive your app's errors, and on PostHog its LLM analytics. Pick any combination - anything you do not pick costs nothing, since its SDK and its adapter are never generated.",category:"Features",kind:"multiselect",default:[],choices:G,adoptable:!0,impact:"config",shapesTree:!0},{key:"multiTenancy",label:"Multi-tenancy (organizations)",hint:"Adds organizations - teams, members, and shared resources.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!1},{key:"projects",label:"Projects",hint:"Adds projects - a switcher that scopes a user's work inside their account or organization.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"config",shapesTree:!1},{key:"docs",label:"Docs app",hint:"Adds the self-hosted Fumadocs documentation site (apps/docs).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0},{key:"desktop",label:"Desktop app",hint:"Adds the cross-platform desktop app (apps/desktop, built with Electron).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0},{key:"mobile",label:"Mobile app",hint:"Adds the cross-platform mobile app (apps/mobile, built with Expo).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0},{key:"mobilePurchases",label:"Mobile store purchases",hint:"In-app purchases in the mobile app, through RevenueCat. Store purchases sit ON TOP of your web payment provider - a subscriber who buys in the app is the same account, billed by Apple or Google instead of by you. Off keeps the app on web billing, where the plan card says the subscription is managed on your website.",category:"Features",kind:"enum",default:()=>"none",choices:je,adoptable:!0,impact:"structural",shapesTree:!0,requires:e=>e.mobile===!0&&ne(e),requiresLabel:"requires the mobile app and a web payment provider - store purchases are additive to the web lane, never a replacement"},{key:"ai",label:"AI features",hint:"Adds the AI surface (chat, models, automations, integrations) and generates the outward MCP server on (config.mcpServer.enabled) so people can connect Claude or ChatGPT. A desktop project ALWAYS ships the app's local AI stack: this option sets config.desktop.agents.enabled (the runtime gate on those screens). Off keeps config.ai.enabled false so the AI nav stays hidden - the AI packages still ship, because packages/translate depends on @repo/ai for the i18n pipeline every project uses; off drops only the MCP widgets (packages/mcp-widgets).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0},{key:"webAi",label:"AI in the web app",hint:"Whether the WEB app shows the AI surfaces - chat, automations, model and integration settings, and their nav entries. Off is the app-first shape: your desktop or mobile app is where your AI product lives and the website keeps account, billing and licensing only. The AI SERVICE is untouched either way (config.ai.enabled, the /api/ai routes and the desktop agents all stay exactly as your AI option set them), so both apps keep talking to the same backend. Only meaningful with AI features and at least one app - the desktop app or the mobile app.",category:"Features",kind:"boolean",default:!0,adoptable:!0,impact:"config",shapesTree:!1,requires:e=>e.ai===!0&&(e.desktop===!0||e.mobile===!0),requiresLabel:"requires AI features and an app to host them (the desktop app or the mobile app)"},{key:"credits",label:"Metered credits",hint:"Adds metered usage credits on top of subscription plans.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"config",shapesTree:!1,requires:e=>ne(e),requiresLabel:"requires a payment provider"},{key:"revenueSharing",label:"Revenue sharing",hint:"Opt-in MRR leaderboard with dofollow backlinks.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"config",shapesTree:!1}];function $s(e,t){return e[t]!==void 0}function nn(e){return pr.filter(t=>t.adoptable&&!$s(e,t.key)&&(t.requires?t.requires(e):!0)).map(t=>({key:t.key,label:t.label,hint:t.hint,kind:t.kind,default:typeof t.default=="function"?t.default(e):t.default,...t.choices?{choices:t.choices}:{},impact:t.impact,...t.requiresLabel?{requiresLabel:t.requiresLabel}:{}}))}function js(e,t){switch(e.kind){case"boolean":return typeof t=="boolean";case"enum":return typeof t=="string"&&(e.choices??[]).includes(t);case"multiselect":return Array.isArray(t)&&t.every(r=>typeof r=="string"&&(e.choices??[]).includes(r))}}function Ms(e){let t=(e.choices??[]).map(r=>JSON.stringify(r)).join(", ");switch(e.kind){case"boolean":return"true or false";case"enum":return`one of ${t}`;case"multiselect":return`an array of ${t}`}}function sn(e){let t=[];for(let r of pr){let n=e[r.key];n!==void 0&&(js(r,n)||t.push(`\`${r.key}\` is ${JSON.stringify(n)}, but it must be ${Ms(r)}.`))}return t}function on(e){let t={};for(let r of pr)if(typeof r.default=="function"){if(r.requires&&!r.requires(e))continue;t[r.key]=r.default(e)}else t[r.key]=Array.isArray(r.default)?[...r.default]:r.default;return{...t,...e}}function dr(e,t){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||t}function Dt(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Nt(e){return/^[a-z][a-z0-9-]*$/.test(e)}function N(e){return e instanceof Error?e.message:String(e)}function yt(e){if(e.mobilePurchases!=="revenuecat")return e;if(e.mobile===!1)throw new Error("--mobile-purchases revenuecat requires the mobile app; remove --no-mobile.");if(e.paymentProvider==="none")throw new Error("--mobile-purchases revenuecat requires a payment provider (got --payment none): store purchases are additive to your web billing, never a replacement.");return e.mobile===void 0&&(e.mobile=!0),e}function bt(e){if(e.webAi!==!1)return e;if(e.ai===!1)throw new Error("--no-web-ai requires --ai (the desktop and mobile apps are where AI lives when the web surface is off).");if(e.desktop===!1&&e.mobile===!1)throw new Error("--no-web-ai requires --desktop or --mobile - with the web AI surface off, the desktop and mobile apps are the only places your AI features exist.");return e}function an(e){if(e.webAi!==!1)return[];let t=[];return e.desktop!==!0&&e.mobile!==!0&&t.push("neither `desktop` nor `mobile` is true, so this project has no desktop or mobile app - and with the web AI surface off, those apps are the only places its AI features would exist."),t}function cn(e){if(e.mobilePurchases!=="revenuecat")return[];let t=[];return e.mobile!==!0&&t.push("`mobile` is not true, so this project has no app to sell in - the store lane's paywall, purchase and restore surfaces all live in `apps/mobile`."),ne(e)||t.push('`paymentProvider` is absent or `"none"`, and store purchases are additive to your web billing - there is nothing here for them to sit on top of.'),t}function ln(e){let t=Us(e,e.desktopAi);return delete e.desktopAi,t}function Us(e,t){return e.desktop!==!0?{kind:"none"}:t===!0&&e.ai!==!0?{kind:"legacy-desktop-ai"}:t===!1&&e.ai===!0?{kind:"desktop-gains-ai"}:{kind:"none"}}function pn(e){let t={};if(e.name!==void 0){if(!Nt(e.name))throw new Error(`Invalid project name "${e.name}". Use lowercase letters, numbers, and hyphens only. Must start with a letter.`);t.projectName=e.name}if(e.appName!==void 0){if(!e.appName.trim())throw new Error("App name cannot be empty.");t.appName=e.appName}if(e.location!==void 0?t.projectDir=e.location==="."?process.cwd():e.location:t.projectName!==void 0&&(t.projectDir=`./${t.projectName}`),e.architecture!==void 0&&(t.architecture=e.architecture),e.payment!==void 0&&(t.paymentProvider=e.payment),e.email!==void 0&&(t.emailProvider=e.email),e.org!==void 0&&(t.multiTenancy=e.org),e.projects!==void 0&&(t.projects=e.projects),e.docs!==void 0&&(t.docs=e.docs),e.desktop!==void 0&&(t.desktop=e.desktop),e.mobile!==void 0&&(t.mobile=e.mobile),e.mobilePurchases!==void 0){if(!je.includes(e.mobilePurchases))throw new Error(`Invalid mobile purchases "${e.mobilePurchases}". Valid values: ${je.join(", ")}`);t.mobilePurchases=e.mobilePurchases}if(e.ai!==void 0&&(t.ai=e.ai),e.webAi!==void 0&&(t.webAi=e.webAi),yt(t),bt(t),e.revenueSharing!==void 0&&(t.revenueSharing=e.revenueSharing),e.credits!==void 0){if(e.credits===!0&&e.payment==="none")throw new Error("--credits requires a payment provider (got --payment none).");t.credits=e.credits}if(e.currency!==void 0){if(!ce.includes(e.currency))throw new Error(`Invalid currency "${e.currency}". Valid values: ${ce.join(", ")}`);t.defaultCurrency=e.currency}if(e.deploy!==void 0){if(!le.includes(e.deploy))throw new Error(`Invalid deployment target "${e.deploy}". Valid values: ${le.join(", ")}`);t.deploymentTarget=e.deploy}if(e.database!==void 0){if(!pe.includes(e.database))throw new Error(`Invalid database provider "${e.database}". Valid values: ${pe.join(", ")}`);t.databaseProvider=e.database}if(e.cache!==void 0){if(!de.includes(e.cache))throw new Error(`Invalid cache provider "${e.cache}". Valid values: ${de.join(", ")}`);t.cacheProvider=e.cache}if(e.observability!==void 0){let r=e.observability.split(",").map(i=>i.trim()).filter(Boolean),n=r.filter(i=>!G.includes(i));if(n.length>0)throw new Error(`Invalid observability provider ${JSON.stringify(n.join(", "))}. Valid values: ${G.join(", ")}`);t.observability=r}if(e.preset!==void 0){if(!$e.includes(e.preset))throw new Error(`Invalid preset "${e.preset}". Valid values: ${$e.join(", ")}`);let r=ae[e.preset].values;t.deploymentTarget??=r.deploymentTarget,t.databaseProvider??=r.databaseProvider,t.cacheProvider??=r.cacheProvider}if(e.demo===!0&&(t.demo=!0),e.baseUrl!==void 0){let r=e.baseUrl.trim();if(r==="")throw new Error("--base-url cannot be empty. Provide an absolute URL like https://example.com.");let n;try{n=new URL(r)}catch{throw new Error(`Invalid --base-url "${e.baseUrl}". Must be an absolute URL like https://example.com.`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw new Error(`Invalid --base-url "${e.baseUrl}". Must use http or https.`);t.baseUrl=`${n.protocol}//${n.host}`}return t}var ot={projectName:"my-saas",architecture:"fullstack",paymentProvider:"stripe",emailProvider:"smtp",multiTenancy:!1,projects:!1,docs:!1,desktop:!1,mobile:!1,mobilePurchases:"none",ai:!1,webAi:!0,revenueSharing:!1,credits:!0,defaultCurrency:"USD",deploymentTarget:"node",databaseProvider:"postgres",cacheProvider:"redis",observability:[]};function dn(e){let t=e.projectName??ot.projectName,r=e.projectDir??`./${t}`,n=e.appName??Dt(t),i=e.deploymentTarget??ot.deploymentTarget,s=re[i]?.edgeRuntime??!1,o=e.databaseProvider??(s?"neon":ot.databaseProvider),a=e.cacheProvider??(s?"upstash":ot.cacheProvider),p=e.emailProvider??(s?"resend":ot.emailProvider),h={...ot,...e,projectName:t,appName:n,projectDir:r,deploymentTarget:i,databaseProvider:o,cacheProvider:a,emailProvider:p};h.paymentProvider==="none"&&(h.credits=!1),(!h.mobile||h.paymentProvider==="none")&&(h.mobilePurchases="none"),yt(h);for(let g of et){if(h.deploymentTarget!==g.target)continue;let k=h.databaseProvider===g.provider?"database":"cache";if(h.databaseProvider===g.provider||h.cacheProvider===g.provider)throw new Error(`Incompatible: --deploy ${g.target} + --${k} ${g.provider}. ${g.reason}`)}for(let g of tt)if(h.architecture===g.architecture&&h.deploymentTarget===g.target)throw new Error(`Incompatible: --architecture ${g.architecture} + --deploy ${g.target}. ${g.reason}`);return bt(h),h}function I(e){f.isCancel(e)&&(f.cancel("Setup cancelled."),process.exit(0))}function ur(e){let t=[];return e.databaseProvider==="neon"&&t.push({key:"DATABASE_URL",message:"Neon connection string (optional):",placeholder:"postgres://...",secret:!0}),e.databaseProvider==="supabase"&&t.push({key:"DATABASE_URL",message:"Supabase connection string (optional):",placeholder:"postgres://...",secret:!0}),e.cacheProvider==="upstash"&&(t.push({key:"UPSTASH_REDIS_REST_URL",message:"Upstash REST URL (optional):",placeholder:"https://...",secret:!1}),t.push({key:"UPSTASH_REDIS_REST_TOKEN",message:"Upstash REST token (optional):",secret:!0})),e.paymentProvider==="stripe"&&(t.push({key:"STRIPE_SECRET_KEY",message:"Stripe secret key (optional):",placeholder:"sk_test_...",secret:!0}),t.push({key:"STRIPE_WEBHOOK_SECRET",message:"Stripe webhook secret (optional):",placeholder:"whsec_...",secret:!0})),e.paymentProvider==="polar"&&(t.push({key:"POLAR_ACCESS_TOKEN",message:"Polar access token (optional):",secret:!0}),t.push({key:"POLAR_WEBHOOK_SECRET",message:"Polar webhook secret (optional):",secret:!0})),e.emailProvider==="resend"&&t.push({key:"RESEND_API_KEY",message:"Resend API key (optional):",placeholder:"re_...",secret:!0}),e.emailProvider==="ses"&&(t.push({key:"AMAZON_SES_REGION",message:"Amazon SES region (optional):",placeholder:"us-east-1",secret:!1}),t.push({key:"AMAZON_SES_KEY",message:"Amazon SES access key (optional):",secret:!0}),t.push({key:"AMAZON_SES_SECRET",message:"Amazon SES secret (optional):",secret:!0})),e.demo&&t.push({key:"TURNSTILE_SECRET_KEY",message:"Cloudflare Turnstile secret key (optional):",secret:!0}),t}async function un(e,t){let r=!1;e&&yt(e),e&&bt(e),f.log.info(y.bold("Project"));let n=e?.projectName??await(async()=>{r=!0;let c=await f.text({message:"Project name:",placeholder:"my-saas",validate:d=>{if(!d?.trim())return"Project name is required.";if(!Nt(d))return"Use lowercase letters, numbers, and hyphens only. Must start with a letter."}});return I(c),c})(),i=e?.appName??await(async()=>{r=!0;let c=await f.text({message:"App name:",initialValue:Dt(n),validate:d=>{if(!d?.trim())return"App name is required."}});return I(c),c})(),s=e?.projectDir??await(async()=>{r=!0;let c=await f.text({message:"Project location:",initialValue:`./${n}`});return I(c),c==="."?process.cwd():c})();f.log.info(y.bold("Infrastructure"));let o={};if(e?.deploymentTarget===void 0&&e?.databaseProvider===void 0&&e?.cacheProvider===void 0){r=!0;let c=await f.select({message:"Infrastructure:",options:[...$e.map(d=>({value:d,label:ae[d].label,hint:ae[d].hint})),{value:"custom",label:"Customize",hint:"choose each piece yourself"}]});if(I(c),c!=="custom"){let d=ae[c].values;o.deploymentTarget=d.deploymentTarget,o.databaseProvider=d.databaseProvider,o.cacheProvider=d.cacheProvider,f.log.info(`${ae[c].label}: ${ae[c].hint}.`)}}let a=e?.deploymentTarget??o.deploymentTarget??"node";if(e?.deploymentTarget===void 0&&o.deploymentTarget===void 0){r=!0;let c=await f.select({message:"Deployment target:",options:le.map(d=>({value:d,label:re[d].label,hint:re[d].hint}))});I(c),a=c}let p=e?.architecture?tt.find(c=>c.architecture===e.architecture&&c.target===a):void 0;if(p)throw new Error(`Incompatible: --architecture ${p.architecture} + --deploy ${p.target}. ${p.reason}`);let h=new Set(tt.filter(c=>c.target===a).map(c=>c.architecture)),g=nt.filter(c=>!h.has(c)),k=e?.architecture??await(async()=>{if(g.length===1){let d=g[0];return f.log.info(`Auto-selected ${gt[d].label} architecture (only compatible option for ${re[a].label}).`),d}r=!0;let c=await f.select({message:"Architecture:",options:g.map(d=>({value:d,label:gt[d].label,hint:gt[d].hint}))});return I(c),c})(),w=e?.databaseProvider??o.databaseProvider??await(async()=>{r=!0;let c=pe.filter(R=>!et.some(Ee=>Ee.target===a&&Ee.provider===R));if(c.length===1){let R=c[0];return f.log.info(`Auto-selected ${Ce[R].label} (only compatible option for ${re[a].label}).`),R}let d=await f.select({message:"Database provider:",options:c.map(R=>({value:R,label:Ce[R].label,hint:Ce[R].hint}))});return I(d),d})(),P=e?.cacheProvider??o.cacheProvider??await(async()=>{r=!0;let c=de.filter(R=>!et.some(Ee=>Ee.target===a&&Ee.provider===R));if(c.length===1){let R=c[0];return f.log.info(`Auto-selected ${Le[R].label} (only compatible option for ${re[a].label}).`),R}let d=await f.select({message:"Cache provider:",options:c.map(R=>({value:R,label:Le[R].label,hint:Le[R].hint}))});return I(d),d})();if(re[a]?.edgeRuntime){let c=tn.map(d=>` - ${d}`).join(`
2
+ import{Command as id}from"commander";import*as Cs from"@clack/prompts";import{existsSync as yp,readdirSync as bp,rmSync as wp}from"fs";import{join as vp,resolve as kp}from"path";import{Option as ee}from"commander";import*as E from"@clack/prompts";import*as Rt from"@clack/prompts";import cr from"picocolors";function Zr(e){let t=e?` GenerateSaaS v${e} `:" GenerateSaaS ";Rt.intro(cr.bgYellow(cr.black(t)))}function Qr(){Rt.outro(cr.yellow("Happy building!"))}import*as f from"@clack/prompts";import y from"picocolors";var gt={fullstack:{label:"Fullstack",hint:"Frontend hosts the API - works on serverless or long-running"},separate:{label:"Separate",hint:"Standalone Hono backend - long-running runtimes only (Docker, Render, Fly.io, Railway, Coolify, Dokploy)"}},_t={stripe:{label:"Stripe"},polar:{label:"Polar"},none:{label:"None",hint:"disable payments"}},Ot={smtp:{label:"SMTP",hint:"Mailpit for local dev"},ses:{label:"Amazon SES"},resend:{label:"Resend"}},xt={sentry:{label:"Sentry",hint:"web, server and desktop - release health, tracing, alerting"},posthog:{label:"PostHog",hint:"web and server errors, LLM analytics and product analytics - no Electron SDK, so desktop errors go unreported"}},en={postgres:{label:"PostgreSQL",hint:"port 5432",port:5432},redis:{label:"Redis",hint:"port 6379",port:6379},inngest:{label:"Inngest",hint:"port 8288",port:8288},mailpit:{label:"Mailpit",hint:"port 1025",port:1025}};var Ne={USD:{symbol:"$",name:"US Dollar",place:"left",space:!1},EUR:{symbol:"\u20AC",name:"Euro",place:"right",space:!1},GBP:{symbol:"\xA3",name:"British Pound",place:"left",space:!1},CAD:{symbol:"CA$",name:"Canadian Dollar",place:"left",space:!1},AUD:{symbol:"A$",name:"Australian Dollar",place:"left",space:!1},BRL:{symbol:"R$",name:"Brazilian Real",place:"left",space:!1},JPY:{symbol:"\xA5",name:"Japanese Yen",place:"left",space:!1}};var re={node:{label:"Node.js / Docker",hint:"long-running runtime - Render, Fly.io, Railway, Coolify, Dokploy, VPS",edgeRuntime:!1},vercel:{label:"Vercel",hint:"serverless functions",edgeRuntime:!0}},Ce={postgres:{label:"PostgreSQL (self-hosted)",hint:"local Docker, drizzle-orm/node-postgres",managed:!1,envVars:[{key:"DATABASE_URL",defaultValue:"postgres://postgres:postgres@localhost:5432/saas"}]},neon:{label:"Neon",hint:"serverless Postgres",managed:!0,envVars:[{key:"DATABASE_URL",comment:"# TODO: Add your Neon connection string"}]},supabase:{label:"Supabase",hint:"managed Postgres",managed:!0,envVars:[{key:"DATABASE_URL",comment:"# TODO: Add your Supabase connection string"}]}},Le={redis:{label:"Redis (self-hosted)",hint:"local Docker, ioredis",managed:!1,envVars:[{key:"REDIS_URL",defaultValue:"redis://localhost:6379"}]},upstash:{label:"Upstash",hint:"serverless Redis",managed:!0,envVars:[{key:"UPSTASH_REDIS_REST_URL",comment:"# TODO: Add your Upstash REST URL"},{key:"UPSTASH_REDIS_REST_TOKEN",comment:"# TODO: Add your Upstash REST token"}]}},et=[{target:"vercel",provider:"redis",reason:"Vercel serverless cannot maintain persistent Redis connections. Consider Upstash."},{target:"vercel",provider:"postgres",reason:"Vercel serverless cannot pool connections to a self-hosted Postgres. Use Neon or Supabase - both are managed, connection-pooled Postgres."}],tt=[{architecture:"separate",target:"vercel",reason:"Standalone backends need a long-running runtime. Vercel's per-function TypeScript check conflicts with pnpm's isolated install. Use --architecture fullstack for serverless, or deploy the standalone backend to a long-running runtime (Render, Fly.io, Railway, Coolify, Dokploy, or your own VPS via Docker)."}],ae={serverless:{label:"Serverless",hint:"Vercel + Neon + Upstash",values:{deploymentTarget:"vercel",databaseProvider:"neon",cacheProvider:"upstash"}},selfhost:{label:"Self-host",hint:"Docker or Node + Postgres + Redis",values:{deploymentTarget:"node",databaseProvider:"postgres",cacheProvider:"redis"}}},$e=Object.keys(ae);function lr(e){let t=[];for(let r of et)if(e.deploymentTarget===r.target&&(e.databaseProvider===r.provider||e.cacheProvider===r.provider)){let n=e.databaseProvider===r.provider?"databaseProvider":"cacheProvider";t.push(`\`${n}: "${r.provider}"\` with \`deploymentTarget: "${r.target}"\` - ${r.reason}`)}for(let r of tt)e.deploymentTarget===r.target&&e.architecture===r.architecture&&t.push(`\`architecture: "${r.architecture}"\` with \`deploymentTarget: "${r.target}"\` - ${r.reason}`);return t}var tn=["Local file storage (sharp, geoip-lite)","SMTP email (use Resend or SES instead)","Content API git integration"];function rt(e){let t=[];return e.databaseProvider==="postgres"&&t.push("postgres"),e.cacheProvider==="redis"&&t.push("redis"),e.emailProvider==="smtp"&&t.push("mailpit"),t.push("inngest"),t}var nt=["fullstack","separate"],it=["stripe","polar","none"],st=["smtp","ses","resend"],rn=["claude-code","cursor","codex","gemini-cli","windsurf"],ce=["USD","EUR","GBP","CAD","AUD","BRL","JPY"],le=["node","vercel"],pe=["postgres","neon","supabase"],de=["redis","upstash"],G=["sentry","posthog"],je=["revenuecat","none"];function ne(e){return e.paymentProvider!==void 0&&e.paymentProvider!=="none"}var pr=[{key:"architecture",label:"Architecture",hint:"Fullstack (frontend hosts the API) or a standalone Hono backend.",category:"Infrastructure",kind:"enum",default:"fullstack",choices:nt,adoptable:!1,impact:"structural",shapesTree:!0},{key:"deploymentTarget",label:"Deployment target",hint:"Node.js / Docker or Vercel serverless.",category:"Infrastructure",kind:"enum",default:"node",choices:le,adoptable:!1,impact:"config",shapesTree:!0},{key:"databaseProvider",label:"Database provider",hint:"Self-hosted PostgreSQL, Neon, or Supabase.",category:"Infrastructure",kind:"enum",default:"postgres",choices:pe,adoptable:!1,impact:"config",shapesTree:!0},{key:"cacheProvider",label:"Cache provider",hint:"Self-hosted Redis or Upstash.",category:"Infrastructure",kind:"enum",default:"redis",choices:de,adoptable:!1,impact:"config",shapesTree:!0},{key:"paymentProvider",label:"Payment provider",hint:"Stripe, Polar, or none.",category:"Features",kind:"enum",default:"none",choices:it,adoptable:!1,impact:"structural",shapesTree:!0},{key:"defaultCurrency",label:"Default currency",hint:"Billing and pricing currency.",category:"Features",kind:"enum",default:"USD",choices:ce,adoptable:!1,impact:"config",shapesTree:!1},{key:"emailProvider",label:"Email provider",hint:"SMTP, Amazon SES, or Resend.",category:"Features",kind:"enum",default:"smtp",choices:st,adoptable:!1,impact:"config",shapesTree:!1},{key:"observability",label:"Observability",hint:"Which services receive your app's errors, and on PostHog its LLM analytics and product analytics. Pick any combination - anything you do not pick costs nothing, since its SDK and its adapter are never generated.",category:"Features",kind:"multiselect",default:[],choices:G,adoptable:!0,impact:"config",shapesTree:!0},{key:"multiTenancy",label:"Multi-tenancy (organizations)",hint:"Adds organizations - teams, members, and shared resources.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!1},{key:"projects",label:"Projects",hint:"Adds projects - a switcher that scopes a user's work inside their account or organization.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"config",shapesTree:!1},{key:"docs",label:"Docs app",hint:"Adds the self-hosted Fumadocs documentation site (apps/docs).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0},{key:"desktop",label:"Desktop app",hint:"Adds the cross-platform desktop app (apps/desktop, built with Electron).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0},{key:"mobile",label:"Mobile app",hint:"Adds the cross-platform mobile app (apps/mobile, built with Expo).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0},{key:"mobilePurchases",label:"Mobile store purchases",hint:"In-app purchases in the mobile app, through RevenueCat. Store purchases sit ON TOP of your web payment provider - a subscriber who buys in the app is the same account, billed by Apple or Google instead of by you. Off keeps the app on web billing, where the plan card says the subscription is managed on your website.",category:"Features",kind:"enum",default:()=>"none",choices:je,adoptable:!0,impact:"structural",shapesTree:!0,requires:e=>e.mobile===!0&&ne(e),requiresLabel:"requires the mobile app and a web payment provider - store purchases are additive to the web lane, never a replacement"},{key:"ai",label:"AI features",hint:"Adds the AI surface (chat, models, automations, integrations) and generates the outward MCP server on (config.mcpServer.enabled) so people can connect Claude or ChatGPT. A desktop project ALWAYS ships the app's local AI stack: this option sets config.desktop.agents.enabled (the runtime gate on those screens). Off keeps config.ai.enabled false so the AI nav stays hidden - the AI packages still ship, because packages/translate depends on @repo/ai for the i18n pipeline every project uses; off drops only the MCP widgets (packages/mcp-widgets).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0},{key:"webAi",label:"AI in the web app",hint:"Whether the WEB app shows the AI surfaces - chat, automations, model and integration settings, and their nav entries. Off is the app-first shape: your desktop or mobile app is where your AI product lives and the website keeps account, billing and licensing only. The AI SERVICE is untouched either way (config.ai.enabled, the /api/ai routes and the desktop agents all stay exactly as your AI option set them), so both apps keep talking to the same backend. Only meaningful with AI features and at least one app - the desktop app or the mobile app.",category:"Features",kind:"boolean",default:!0,adoptable:!0,impact:"config",shapesTree:!1,requires:e=>e.ai===!0&&(e.desktop===!0||e.mobile===!0),requiresLabel:"requires AI features and an app to host them (the desktop app or the mobile app)"},{key:"credits",label:"Metered credits",hint:"Adds metered usage credits on top of subscription plans.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"config",shapesTree:!1,requires:e=>ne(e),requiresLabel:"requires a payment provider"},{key:"revenueSharing",label:"Revenue sharing",hint:"Opt-in MRR leaderboard with dofollow backlinks.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"config",shapesTree:!1}];function $s(e,t){return e[t]!==void 0}function nn(e){return pr.filter(t=>t.adoptable&&!$s(e,t.key)&&(t.requires?t.requires(e):!0)).map(t=>({key:t.key,label:t.label,hint:t.hint,kind:t.kind,default:typeof t.default=="function"?t.default(e):t.default,...t.choices?{choices:t.choices}:{},impact:t.impact,...t.requiresLabel?{requiresLabel:t.requiresLabel}:{}}))}function js(e,t){switch(e.kind){case"boolean":return typeof t=="boolean";case"enum":return typeof t=="string"&&(e.choices??[]).includes(t);case"multiselect":return Array.isArray(t)&&t.every(r=>typeof r=="string"&&(e.choices??[]).includes(r))}}function Ms(e){let t=(e.choices??[]).map(r=>JSON.stringify(r)).join(", ");switch(e.kind){case"boolean":return"true or false";case"enum":return`one of ${t}`;case"multiselect":return`an array of ${t}`}}function sn(e){let t=[];for(let r of pr){let n=e[r.key];n!==void 0&&(js(r,n)||t.push(`\`${r.key}\` is ${JSON.stringify(n)}, but it must be ${Ms(r)}.`))}return t}function on(e){let t={};for(let r of pr)if(typeof r.default=="function"){if(r.requires&&!r.requires(e))continue;t[r.key]=r.default(e)}else t[r.key]=Array.isArray(r.default)?[...r.default]:r.default;return{...t,...e}}function dr(e,t){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||t}function Dt(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Nt(e){return/^[a-z][a-z0-9-]*$/.test(e)}function N(e){return e instanceof Error?e.message:String(e)}function yt(e){if(e.mobilePurchases!=="revenuecat")return e;if(e.mobile===!1)throw new Error("--mobile-purchases revenuecat requires the mobile app; remove --no-mobile.");if(e.paymentProvider==="none")throw new Error("--mobile-purchases revenuecat requires a payment provider (got --payment none): store purchases are additive to your web billing, never a replacement.");return e.mobile===void 0&&(e.mobile=!0),e}function bt(e){if(e.webAi!==!1)return e;if(e.ai===!1)throw new Error("--no-web-ai requires --ai (the desktop and mobile apps are where AI lives when the web surface is off).");if(e.desktop===!1&&e.mobile===!1)throw new Error("--no-web-ai requires --desktop or --mobile - with the web AI surface off, the desktop and mobile apps are the only places your AI features exist.");return e}function an(e){if(e.webAi!==!1)return[];let t=[];return e.desktop!==!0&&e.mobile!==!0&&t.push("neither `desktop` nor `mobile` is true, so this project has no desktop or mobile app - and with the web AI surface off, those apps are the only places its AI features would exist."),t}function cn(e){if(e.mobilePurchases!=="revenuecat")return[];let t=[];return e.mobile!==!0&&t.push("`mobile` is not true, so this project has no app to sell in - the store lane's paywall, purchase and restore surfaces all live in `apps/mobile`."),ne(e)||t.push('`paymentProvider` is absent or `"none"`, and store purchases are additive to your web billing - there is nothing here for them to sit on top of.'),t}function ln(e){let t=Us(e,e.desktopAi);return delete e.desktopAi,t}function Us(e,t){return e.desktop!==!0?{kind:"none"}:t===!0&&e.ai!==!0?{kind:"legacy-desktop-ai"}:t===!1&&e.ai===!0?{kind:"desktop-gains-ai"}:{kind:"none"}}function pn(e){let t={};if(e.name!==void 0){if(!Nt(e.name))throw new Error(`Invalid project name "${e.name}". Use lowercase letters, numbers, and hyphens only. Must start with a letter.`);t.projectName=e.name}if(e.appName!==void 0){if(!e.appName.trim())throw new Error("App name cannot be empty.");t.appName=e.appName}if(e.location!==void 0?t.projectDir=e.location==="."?process.cwd():e.location:t.projectName!==void 0&&(t.projectDir=`./${t.projectName}`),e.architecture!==void 0&&(t.architecture=e.architecture),e.payment!==void 0&&(t.paymentProvider=e.payment),e.email!==void 0&&(t.emailProvider=e.email),e.org!==void 0&&(t.multiTenancy=e.org),e.projects!==void 0&&(t.projects=e.projects),e.docs!==void 0&&(t.docs=e.docs),e.desktop!==void 0&&(t.desktop=e.desktop),e.mobile!==void 0&&(t.mobile=e.mobile),e.mobilePurchases!==void 0){if(!je.includes(e.mobilePurchases))throw new Error(`Invalid mobile purchases "${e.mobilePurchases}". Valid values: ${je.join(", ")}`);t.mobilePurchases=e.mobilePurchases}if(e.ai!==void 0&&(t.ai=e.ai),e.webAi!==void 0&&(t.webAi=e.webAi),yt(t),bt(t),e.revenueSharing!==void 0&&(t.revenueSharing=e.revenueSharing),e.credits!==void 0){if(e.credits===!0&&e.payment==="none")throw new Error("--credits requires a payment provider (got --payment none).");t.credits=e.credits}if(e.currency!==void 0){if(!ce.includes(e.currency))throw new Error(`Invalid currency "${e.currency}". Valid values: ${ce.join(", ")}`);t.defaultCurrency=e.currency}if(e.deploy!==void 0){if(!le.includes(e.deploy))throw new Error(`Invalid deployment target "${e.deploy}". Valid values: ${le.join(", ")}`);t.deploymentTarget=e.deploy}if(e.database!==void 0){if(!pe.includes(e.database))throw new Error(`Invalid database provider "${e.database}". Valid values: ${pe.join(", ")}`);t.databaseProvider=e.database}if(e.cache!==void 0){if(!de.includes(e.cache))throw new Error(`Invalid cache provider "${e.cache}". Valid values: ${de.join(", ")}`);t.cacheProvider=e.cache}if(e.observability!==void 0){let r=e.observability.split(",").map(i=>i.trim()).filter(Boolean),n=r.filter(i=>!G.includes(i));if(n.length>0)throw new Error(`Invalid observability provider ${JSON.stringify(n.join(", "))}. Valid values: ${G.join(", ")}`);t.observability=r}if(e.preset!==void 0){if(!$e.includes(e.preset))throw new Error(`Invalid preset "${e.preset}". Valid values: ${$e.join(", ")}`);let r=ae[e.preset].values;t.deploymentTarget??=r.deploymentTarget,t.databaseProvider??=r.databaseProvider,t.cacheProvider??=r.cacheProvider}if(e.demo===!0&&(t.demo=!0),e.baseUrl!==void 0){let r=e.baseUrl.trim();if(r==="")throw new Error("--base-url cannot be empty. Provide an absolute URL like https://example.com.");let n;try{n=new URL(r)}catch{throw new Error(`Invalid --base-url "${e.baseUrl}". Must be an absolute URL like https://example.com.`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw new Error(`Invalid --base-url "${e.baseUrl}". Must use http or https.`);t.baseUrl=`${n.protocol}//${n.host}`}return t}var ot={projectName:"my-saas",architecture:"fullstack",paymentProvider:"stripe",emailProvider:"smtp",multiTenancy:!1,projects:!1,docs:!1,desktop:!1,mobile:!1,mobilePurchases:"none",ai:!1,webAi:!0,revenueSharing:!1,credits:!0,defaultCurrency:"USD",deploymentTarget:"node",databaseProvider:"postgres",cacheProvider:"redis",observability:[]};function dn(e){let t=e.projectName??ot.projectName,r=e.projectDir??`./${t}`,n=e.appName??Dt(t),i=e.deploymentTarget??ot.deploymentTarget,s=re[i]?.edgeRuntime??!1,o=e.databaseProvider??(s?"neon":ot.databaseProvider),a=e.cacheProvider??(s?"upstash":ot.cacheProvider),p=e.emailProvider??(s?"resend":ot.emailProvider),h={...ot,...e,projectName:t,appName:n,projectDir:r,deploymentTarget:i,databaseProvider:o,cacheProvider:a,emailProvider:p};h.paymentProvider==="none"&&(h.credits=!1),(!h.mobile||h.paymentProvider==="none")&&(h.mobilePurchases="none"),yt(h);for(let g of et){if(h.deploymentTarget!==g.target)continue;let k=h.databaseProvider===g.provider?"database":"cache";if(h.databaseProvider===g.provider||h.cacheProvider===g.provider)throw new Error(`Incompatible: --deploy ${g.target} + --${k} ${g.provider}. ${g.reason}`)}for(let g of tt)if(h.architecture===g.architecture&&h.deploymentTarget===g.target)throw new Error(`Incompatible: --architecture ${g.architecture} + --deploy ${g.target}. ${g.reason}`);return bt(h),h}function I(e){f.isCancel(e)&&(f.cancel("Setup cancelled."),process.exit(0))}function ur(e){let t=[];return e.databaseProvider==="neon"&&t.push({key:"DATABASE_URL",message:"Neon connection string (optional):",placeholder:"postgres://...",secret:!0}),e.databaseProvider==="supabase"&&t.push({key:"DATABASE_URL",message:"Supabase connection string (optional):",placeholder:"postgres://...",secret:!0}),e.cacheProvider==="upstash"&&(t.push({key:"UPSTASH_REDIS_REST_URL",message:"Upstash REST URL (optional):",placeholder:"https://...",secret:!1}),t.push({key:"UPSTASH_REDIS_REST_TOKEN",message:"Upstash REST token (optional):",secret:!0})),e.paymentProvider==="stripe"&&(t.push({key:"STRIPE_SECRET_KEY",message:"Stripe secret key (optional):",placeholder:"sk_test_...",secret:!0}),t.push({key:"STRIPE_WEBHOOK_SECRET",message:"Stripe webhook secret (optional):",placeholder:"whsec_...",secret:!0})),e.paymentProvider==="polar"&&(t.push({key:"POLAR_ACCESS_TOKEN",message:"Polar access token (optional):",secret:!0}),t.push({key:"POLAR_WEBHOOK_SECRET",message:"Polar webhook secret (optional):",secret:!0})),e.emailProvider==="resend"&&t.push({key:"RESEND_API_KEY",message:"Resend API key (optional):",placeholder:"re_...",secret:!0}),e.emailProvider==="ses"&&(t.push({key:"AMAZON_SES_REGION",message:"Amazon SES region (optional):",placeholder:"us-east-1",secret:!1}),t.push({key:"AMAZON_SES_KEY",message:"Amazon SES access key (optional):",secret:!0}),t.push({key:"AMAZON_SES_SECRET",message:"Amazon SES secret (optional):",secret:!0})),e.demo&&t.push({key:"TURNSTILE_SECRET_KEY",message:"Cloudflare Turnstile secret key (optional):",secret:!0}),t}async function un(e,t){let r=!1;e&&yt(e),e&&bt(e),f.log.info(y.bold("Project"));let n=e?.projectName??await(async()=>{r=!0;let c=await f.text({message:"Project name:",placeholder:"my-saas",validate:d=>{if(!d?.trim())return"Project name is required.";if(!Nt(d))return"Use lowercase letters, numbers, and hyphens only. Must start with a letter."}});return I(c),c})(),i=e?.appName??await(async()=>{r=!0;let c=await f.text({message:"App name:",initialValue:Dt(n),validate:d=>{if(!d?.trim())return"App name is required."}});return I(c),c})(),s=e?.projectDir??await(async()=>{r=!0;let c=await f.text({message:"Project location:",initialValue:`./${n}`});return I(c),c==="."?process.cwd():c})();f.log.info(y.bold("Infrastructure"));let o={};if(e?.deploymentTarget===void 0&&e?.databaseProvider===void 0&&e?.cacheProvider===void 0){r=!0;let c=await f.select({message:"Infrastructure:",options:[...$e.map(d=>({value:d,label:ae[d].label,hint:ae[d].hint})),{value:"custom",label:"Customize",hint:"choose each piece yourself"}]});if(I(c),c!=="custom"){let d=ae[c].values;o.deploymentTarget=d.deploymentTarget,o.databaseProvider=d.databaseProvider,o.cacheProvider=d.cacheProvider,f.log.info(`${ae[c].label}: ${ae[c].hint}.`)}}let a=e?.deploymentTarget??o.deploymentTarget??"node";if(e?.deploymentTarget===void 0&&o.deploymentTarget===void 0){r=!0;let c=await f.select({message:"Deployment target:",options:le.map(d=>({value:d,label:re[d].label,hint:re[d].hint}))});I(c),a=c}let p=e?.architecture?tt.find(c=>c.architecture===e.architecture&&c.target===a):void 0;if(p)throw new Error(`Incompatible: --architecture ${p.architecture} + --deploy ${p.target}. ${p.reason}`);let h=new Set(tt.filter(c=>c.target===a).map(c=>c.architecture)),g=nt.filter(c=>!h.has(c)),k=e?.architecture??await(async()=>{if(g.length===1){let d=g[0];return f.log.info(`Auto-selected ${gt[d].label} architecture (only compatible option for ${re[a].label}).`),d}r=!0;let c=await f.select({message:"Architecture:",options:g.map(d=>({value:d,label:gt[d].label,hint:gt[d].hint}))});return I(c),c})(),w=e?.databaseProvider??o.databaseProvider??await(async()=>{r=!0;let c=pe.filter(R=>!et.some(Ee=>Ee.target===a&&Ee.provider===R));if(c.length===1){let R=c[0];return f.log.info(`Auto-selected ${Ce[R].label} (only compatible option for ${re[a].label}).`),R}let d=await f.select({message:"Database provider:",options:c.map(R=>({value:R,label:Ce[R].label,hint:Ce[R].hint}))});return I(d),d})(),P=e?.cacheProvider??o.cacheProvider??await(async()=>{r=!0;let c=de.filter(R=>!et.some(Ee=>Ee.target===a&&Ee.provider===R));if(c.length===1){let R=c[0];return f.log.info(`Auto-selected ${Le[R].label} (only compatible option for ${re[a].label}).`),R}let d=await f.select({message:"Cache provider:",options:c.map(R=>({value:R,label:Le[R].label,hint:Le[R].hint}))});return I(d),d})();if(re[a]?.edgeRuntime){let c=tn.map(d=>` - ${d}`).join(`
3
3
  `);f.note(c,"Unavailable on edge runtime")}f.log.info(y.bold("Features"));let u=e?.paymentProvider??await(async()=>{r=!0;let c=await f.select({message:"Payment provider:",options:it.map(d=>({value:d,label:_t[d].label,hint:_t[d].hint}))});return I(c),c})(),O=e?.defaultCurrency??await(async()=>{if(u==="none")return"USD";r=!0;let c=await f.select({message:"Default currency:",options:ce.map(d=>({value:d,label:d,hint:Ne[d].name}))});return I(c),c})(),be=e?.emailProvider??await(async()=>{r=!0;let c=await f.select({message:"Email provider:",options:st.map(d=>({value:d,label:Ot[d].label,hint:Ot[d].hint}))});return I(c),c})(),B=e?.observability??await(async()=>{r=!0;let c=await f.multiselect({message:"Observability (space to select, enter to confirm):",required:!1,initialValues:[],options:G.map(d=>({value:d,label:xt[d].label,hint:xt[d].hint}))});return I(c),c})(),oe=e?.multiTenancy??await(async()=>{r=!0;let c=await f.confirm({message:"Enable multi-tenancy (organizations)?",initialValue:!1});return I(c),c})(),Oe=e?.projects??await(async()=>{r=!0;let c=await f.confirm({message:"Enable projects (a switcher that scopes a user's work)?",initialValue:!1});return I(c),c})(),xe=e?.docs??await(async()=>{r=!0;let c=await f.confirm({message:"Include docs app? (self-hosted Fumadocs documentation site)",initialValue:!1});return I(c),c})(),De=t?.desktopAllowed!==!1,we=e?.desktop??(De?await(async()=>{r=!0;let c=await f.confirm({message:"Include the desktop app? (apps/desktop - cross-platform, built with Electron, device-auth). With AI on, it also runs a local AI stack.",initialValue:!1});return I(c),c})():(f.log.info(y.dim("Desktop app: available on the Pro plan and up - skipped.")),!1)),Qe=t?.mobileAllowed!==!1,v=e?.mobile??(Qe?await(async()=>{r=!0;let c=await f.confirm({message:"Include the mobile app? (apps/mobile - iOS and Android, built with Expo, with push notifications and universal links)",initialValue:!1});return I(c),c})():(f.log.info(y.dim("Mobile app: available on the Pro plan and up - skipped.")),!1)),L=!v||u==="none"?"none":e?.mobilePurchases??await(async()=>{r=!0;let R=await f.select({message:"Mobile in-app purchases?",options:[{value:"revenuecat",label:"RevenueCat",hint:"store billing on top of your web provider - Apple and Google charge, your app grants"},{value:"none",label:"None",hint:"web billing only; the app shows the plan, never a paywall"}],initialValue:"none"});return I(R),R})();yt({mobile:v,mobilePurchases:L,paymentProvider:u});let F=e?.ai??await(async()=>{r=!0;let c=await f.confirm({message:"Add AI features? (chat, models, automations, integrations)",initialValue:!1});return I(c),c})(),ve=e?.webAi??((we||v)&&F?await(async()=>{r=!0;let c=await f.confirm({message:"Show the AI surfaces in the web app? (No: app-first - your desktop or mobile app is where your AI product lives, and the web keeps account, billing, and licensing only)",initialValue:!0});return I(c),c})():!0);bt({webAi:ve,ai:F,desktop:we,mobile:v});let $=e?.revenueSharing??await(async()=>{r=!0;let c=await f.confirm({message:"Enable revenue sharing? (opt-in MRR leaderboard with dofollow backlinks)",initialValue:!1});return I(c),c})(),W=u==="none"?!1:e?.credits??await(async()=>{r=!0;let c=await f.confirm({message:"Enable credits? (metered usage on top of subscription plans)",initialValue:!0});return I(c),c})(),ke=e?.demo,z=ur({databaseProvider:w,cacheProvider:P,paymentProvider:u,emailProvider:be,demo:ke}),T={};if(z.length>0&&r){f.log.info(y.bold("Credentials")+y.dim(" all optional - press Enter to skip, fill in .env later"));for(let c of z)if(r=!0,c.secret){let d=await f.password({message:c.message,mask:"*"});I(d),typeof d=="string"&&d.trim()&&(T[c.key]=d.trim())}else{let d=await f.text({message:c.message,placeholder:c.placeholder});I(d),typeof d=="string"&&d.trim()&&(T[c.key]=d.trim())}}if(r){let c=[` Name: ${y.cyan(n)}`,` App name: ${y.cyan(i)}`,` Location: ${y.cyan(s)}`,` Architecture: ${y.cyan(gt[k].label)}`].join(`
4
4
  `),d=[` Deploy target: ${y.cyan(re[a]?.label??"Node.js / Docker")}`,` Database: ${y.cyan(Ce[w].label)}`,` Cache: ${y.cyan(Le[P].label)}`].filter(Boolean).join(`
5
5
  `),R=[u!=="none"?` Payment: ${y.cyan(_t[u].label)} (${O})`:` Payment: ${y.dim("none")}`,` Credits: ${W?y.cyan("Yes"):y.dim("No")}`,` AI features: ${F?y.cyan("Yes"):y.dim("No")}`,...ve?[]:[` Web AI: ${y.dim("No")} (app-first)`],` Email: ${y.cyan(Ot[be].label)}`,` Observability: ${B.length===0?y.dim("none"):y.cyan(B.map(ar=>xt[ar].label).join(", "))}`,` Multi-tenancy: ${oe?y.cyan("Yes"):y.dim("No")}`,` Projects: ${Oe?y.cyan("Yes"):y.dim("No")}`,` Docs app: ${xe?y.cyan("Yes"):y.dim("No")}`,` Desktop app: ${we?y.cyan("Yes"):y.dim("No")}`,` Mobile app: ${v?y.cyan("Yes"):y.dim("No")}`,...L==="none"?[]:[` In-app purch.: ${y.cyan("RevenueCat")}`],` Rev. sharing: ${$?y.cyan("Yes"):y.dim("No")}`].join(`
6
6
  `),Ee=[y.bold("Project"),c,"",y.bold("Infrastructure"),d,"",y.bold("Features"),R];if(z.length>0){let ar=z.map(Xr=>{let Ls=T[Xr.key]?y.green("provided"):y.dim("skipped");return` ${Xr.key}: ${Ls}`}).join(`
7
7
  `);Ee.push("",y.bold("Credentials"),ar)}f.note(Ee.join(`
8
- `),"Summary");let qr=await f.confirm({message:"Proceed with these settings?"});(f.isCancel(qr)||!qr)&&(f.cancel("Setup cancelled."),process.exit(0))}return{projectName:n,appName:i,projectDir:s,architecture:k,deploymentTarget:a,databaseProvider:w,cacheProvider:P,paymentProvider:u,emailProvider:be,observability:B,multiTenancy:oe,projects:Oe,docs:xe,desktop:we,mobile:v,mobilePurchases:L,ai:F,webAi:ve,revenueSharing:$,credits:W,defaultCurrency:O,...Object.keys(T).length>0?{credentials:T}:{},...e?.baseUrl!==void 0?{baseUrl:e.baseUrl}:{},...ke!==void 0?{demo:ke}:{}}}import{createReadStream as Sn,existsSync as Js}from"fs";import{mkdir as qs}from"fs/promises";import{join as Xs}from"path";import{Readable as Zs}from"stream";import{pipeline as Er}from"stream/promises";import{extract as Qs}from"tar";import{join as Me}from"path";import{homedir as Fs}from"os";var mr="https://cli.generatesaas.com",wt=process.env.GENERATESAAS_API_URL??mr,J=".generatesaas",ue=Me(J,"manifest.json"),mn="nextjs",hr="nuxt",fr="2.4.1",hn=Me(J,"hashes.json"),Ct=Me(J,"template-hashes.json"),Lt=Me(J,"template"),fn=Me(J,"staging"),gn=Me(J,"staging.json"),me=Me(Fs(),".generatesaas");var M=class extends Error{constructor(r,n,i){super(n);this.status=r;this.body=i}status;body;name="ApiError"};function he(e){return{apiKey:e,baseUrl:wt}}async function Se(e,t,r){let n=`${e.baseUrl}${t}`,i=await fetch(n,{...r,headers:{...r?.headers,Authorization:`Bearer ${e.apiKey}`,"User-Agent":"generatesaas-cli/3.41.0"}});if(!i.ok){let s,o;try{o=await i.json(),s=o.error??`API ${i.status}: ${t}`}catch{s=`API ${i.status}: ${t}`}throw new M(i.status,s,o)}return i}import{existsSync as Vs,mkdirSync as Bs,readFileSync as Gs,writeFileSync as Ks}from"fs";import{dirname as Hs}from"path";import*as Pe from"@clack/prompts";function vt(){if(!Vs(me))return null;try{let e=JSON.parse(Gs(me,"utf-8"));return e.apiKey?e.apiKey:(e.token&&!e.apiKey&&Pe.log.warning(`Found old GitHub token in ${me}. Run 'generatesaas init' to set up your API key.`),null)}catch{return null}}function Ue(e){let t=process.env.GENERATESAAS_API_URL;t&&t.replace(/\/+$/,"")!==mr||(Bs(Hs(me),{recursive:!0}),Ks(me,`${JSON.stringify({apiKey:e},null," ")}
8
+ `),"Summary");let qr=await f.confirm({message:"Proceed with these settings?"});(f.isCancel(qr)||!qr)&&(f.cancel("Setup cancelled."),process.exit(0))}return{projectName:n,appName:i,projectDir:s,architecture:k,deploymentTarget:a,databaseProvider:w,cacheProvider:P,paymentProvider:u,emailProvider:be,observability:B,multiTenancy:oe,projects:Oe,docs:xe,desktop:we,mobile:v,mobilePurchases:L,ai:F,webAi:ve,revenueSharing:$,credits:W,defaultCurrency:O,...Object.keys(T).length>0?{credentials:T}:{},...e?.baseUrl!==void 0?{baseUrl:e.baseUrl}:{},...ke!==void 0?{demo:ke}:{}}}import{createReadStream as Sn,existsSync as Js}from"fs";import{mkdir as qs}from"fs/promises";import{join as Xs}from"path";import{Readable as Zs}from"stream";import{pipeline as Er}from"stream/promises";import{extract as Qs}from"tar";import{join as Me}from"path";import{homedir as Fs}from"os";var mr="https://cli.generatesaas.com",wt=process.env.GENERATESAAS_API_URL??mr,J=".generatesaas",ue=Me(J,"manifest.json"),mn="nextjs",hr="nuxt",fr="2.4.1",hn=Me(J,"hashes.json"),Ct=Me(J,"template-hashes.json"),Lt=Me(J,"template"),fn=Me(J,"staging"),gn=Me(J,"staging.json"),me=Me(Fs(),".generatesaas");var M=class extends Error{constructor(r,n,i){super(n);this.status=r;this.body=i}status;body;name="ApiError"};function he(e){return{apiKey:e,baseUrl:wt}}async function Se(e,t,r){let n=`${e.baseUrl}${t}`,i=await fetch(n,{...r,headers:{...r?.headers,Authorization:`Bearer ${e.apiKey}`,"User-Agent":"generatesaas-cli/3.42.0"}});if(!i.ok){let s,o;try{o=await i.json(),s=o.error??`API ${i.status}: ${t}`}catch{s=`API ${i.status}: ${t}`}throw new M(i.status,s,o)}return i}import{existsSync as Vs,mkdirSync as Bs,readFileSync as Gs,writeFileSync as Ks}from"fs";import{dirname as Hs}from"path";import*as Pe from"@clack/prompts";function vt(){if(!Vs(me))return null;try{let e=JSON.parse(Gs(me,"utf-8"));return e.apiKey?e.apiKey:(e.token&&!e.apiKey&&Pe.log.warning(`Found old GitHub token in ${me}. Run 'generatesaas init' to set up your API key.`),null)}catch{return null}}function Ue(e){let t=process.env.GENERATESAAS_API_URL;t&&t.replace(/\/+$/,"")!==mr||(Bs(Hs(me),{recursive:!0}),Ks(me,`${JSON.stringify({apiKey:e},null," ")}
9
9
  `,{mode:384}))}async function at(e){if(e?.apiKey)return e.apiKey;let t=process.env.GENERATESAAS_API_KEY;if(t)return t;let r=vt();if(r)return r;if(!e?.prompt)throw new Error("API key not found. Set GENERATESAAS_API_KEY or run 'generatesaas init' to configure.");return kt()}async function kt(){let e=await Pe.text({message:"Enter your GenerateSaaS API key:",placeholder:"gs_live_...",validate:t=>{if(!t?.trim())return"API key is required."}});return Pe.isCancel(e)&&(Pe.cancel("Setup cancelled."),process.exit(0)),e.trim()}import{readFile as Ys}from"fs/promises";async function Ae(e){let t=process.env.GENERATESAAS_VERSION_INDEX;return t?JSON.parse(await Ys(t,"utf-8")):process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{latest:"0.0.0-ci",versions:[{version:"0.0.0-ci",date:new Date().toISOString(),breaking:!1}],entitlements:null}:await(await Se(e,"/versions")).json()}async function yn(e,t){if(process.env.GENERATESAAS_OFFLINE_LICENSE==="1")return null;try{return await(await Se(e,`/changelog/${encodeURIComponent(t)}`)).text()}catch(r){if(r instanceof M&&r.status===404)return null;throw r}}async function bn(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{skills:{"generatesaas-update":{skillMd:`# Offline skill stub
10
10
  `,scripts:{},references:{}}}}:await(await Se(e,`/skills/${encodeURIComponent(t)}`)).json()}function $t(e){if(!(e instanceof M)||e.status!==403)return null;let t=e.body;return!t||t.code!=="update_window_expired"?null:{message:e.message,lastAllowedVersion:t.lastAllowedVersion??null}}var gr="nextjs";function wn(e){return{frontend:gr,architecture:e.architecture,deployTarget:e.deploymentTarget,database:e.databaseProvider,cache:e.cacheProvider,payment:e.paymentProvider,email:e.emailProvider,multiTenancy:e.multiTenancy,blog:!0,docs:e.docs,desktop:e.desktop,mobile:e.mobile,runner:!1,credits:e.credits,revenueSharing:e.revenueSharing,currency:e.defaultCurrency}}async function yr(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{token:"offline-test-token",licenseId:"offline-test-license-id",installId:t.installId}:await(await Se(e,"/license/sign",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json()}async function vn(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{token:t.currentToken}:await(await Se(e,"/license/refresh",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json()}async function br(e,t){let r=await fetch(`${e}/license/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok)throw new Error(`Verification service returned ${r.status}`);return await r.json()}async function kn(e,t,r){let n=await fetch(`${e}/license/inspect`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(r)});if(!n.ok){let i=await n.json().catch(()=>null);throw new Error(i?.error??`Inspect endpoint returned ${n.status}`)}return await n.json()}var wr=new Set([".git","node_modules",".pnpm-store",".env",".env.test",".turbo",".data","dist",".next",".next-e2e-web",".next-e2e-desktop",".wrangler",".devcontainer","playwright-report","test-results",".drive-out",".mastra"]),vr=new Set(["pnpm-lock.yaml","widget-documents.generated.ts"]);function ct(e){if(kr(e))return!0;for(let t of e.split("/"))if(vr.has(t))return!0;return!1}var Ws=new Set(["data","references","scripts",".cursor",".agents",".codex",".generatesaas",".vscode",".mcp.json","vitest.config.ts","README.md","TODO.md","OVERVIEW.md"]),En=["scripts/docs-lint.ts"],zs=["docs/superpowers","packages/cli","packages/cli-api","packages/database/tests/no-migration-history.test.ts","infra/docker-compose.yml",".claude/commands",".claude/skills/web-port",".claude/skills/web-port-workspace",".claude/settings.local.json",".claude/worktrees"];function kr(e){let t=e.split("/");for(let r of t)if(wr.has(r))return!0;if(En.includes(e)||En.some(r=>r.startsWith(`${e}/`)))return!1;if(Ws.has(t[0]))return!0;for(let r of zs)if(e===r||e.startsWith(`${r}/`))return!0;return!1}async function jt(e,t,r){await qs(r,{recursive:!0});let n=process.env.GENERATESAAS_TEMPLATE_TARBALL_DIR;if(n){let a=Xs(n,`v${t}.tar.gz`);if(!Js(a))throw new Error(`GENERATESAAS_TEMPLATE_TARBALL_DIR is set but ${a} does not exist.`);await Er(Sn(a),Sr(r));return}let i=process.env.GENERATESAAS_TEMPLATE_TARBALL;if(i){await Er(Sn(i),Sr(r));return}let s=await Se(e,`/template/${encodeURIComponent(t)}`);if(!s.body)throw new Error("Empty response body");let o=Zs.fromWeb(s.body);await Er(o,Sr(r))}function Sr(e){return Qs({cwd:e,strip:1,filter:t=>{let r=t.replace(/^[^/]+\//,"");return r?!kr(r):!0},sync:!1})}import{readdir as Mt,readFile as lt,rm as An,rmdir as eo,writeFile as Et}from"fs/promises";import{join as K}from"path";async function In(e){let t;try{t=await Mt(e,{withFileTypes:!0})}catch{return!1}let r=!1;for(let n of t){let i=K(e,n.name);if(n.isDirectory()){await In(i)&&(r=!0);continue}if(n.name.startsWith("_")){r=!0;continue}await An(i,{force:!0})}return r||await eo(e).catch(()=>{}),r}async function Tn(e){let t=K(e,"packages/content"),r=[];try{r=(await Mt(t,{withFileTypes:!0})).filter(o=>o.isDirectory()).map(o=>o.name)}catch{return}let n=new Set;for(let o of r){let a=K(t,o),p;try{p=(await Mt(a,{withFileTypes:!0})).filter(h=>h.isDirectory())}catch{continue}for(let h of p)n.add(h.name),await In(K(a,h.name))}let i=await io(e),s=new Set([...n].filter(o=>i===void 0||i.has(o)));await Promise.all([...s].map(o=>An(K(e,"apps/web/public/images",o),{recursive:!0,force:!0}))),await oo(e,s)}var to="packages/config/src/index.ts",ro=/\bcontent:\s*\{[\s\S]*?\bsections:\s*\[([\s\S]*?)\]/,no=/\bslug:\s*"([^"]+)"/g;async function io(e){let t;try{t=await lt(K(e,to),"utf-8")}catch{return}let r=ro.exec(t)?.[1];if(r===void 0)return;let n=[...r.matchAll(no)].map(i=>i[1]).filter(i=>i!==void 0);return n.length>0?new Set(n):void 0}var so="packages/translate/.meta/mdx-translation-meta.json";async function oo(e,t){if(t.size===0)return;let r=K(e,so),n;try{n=JSON.parse(await lt(r,"utf-8"))}catch{return}if(typeof n!="object"||n===null)return;let i=n;if(typeof i.locales!="object"||i.locales===null)return;let s={};for(let[o,a]of Object.entries(i.locales)){if(typeof a!="object"||a===null)continue;let p={};for(let[h,g]of Object.entries(a)){let k=h.split("/"),w=k.length>1?k[0]:void 0,P=k[k.length-1]?.startsWith("_")===!0;w!==void 0&&t.has(w)&&!P||(p[h]=g)}s[o]=p}await Et(r,`${JSON.stringify({...i,locales:s},null," ")}
11
11
  `)}var ao="packages/config/src/blog.ts";async function Rn(e){let t=K(e,ao),r=await lt(t,"utf-8"),n=Pn(Pn(r,"blogCategories",t),"blogAuthors",t);await Et(t,n)}function Pn(e,t,r){let n=new RegExp(`(export const ${t}\\b[^=]*=\\s*)\\[[\\s\\S]*?\\];`);if(!n.test(e))throw new Error(`emptyBlogConfig: could not find the \`export const ${t} = [...]\` declaration in ${r}. The boilerplate blog config may have been renamed or restructured; update the CLI strip in cleanup.ts.`);return e.replace(n,"$1[];")}async function _n(e){let t=K(e,"packages/i18n/translations"),r;try{r=await Mt(t)}catch{return}for(let n of r){let i=K(t,n,"web.json"),s;try{s=await lt(i,"utf-8")}catch{continue}let o=JSON.parse(s);!o.content?.categories||o.content.categories.blog===void 0||(o.content.categories.blog={},await Et(i,`${JSON.stringify(o,null," ")}
@@ -78,7 +78,7 @@ To pull the latest boilerplate changes into this project, open it in your AI cod
78
78
  url: ${t}
79
79
  updaterCacheDirName: ${r}
80
80
  `)}function Fo(e){let t=e.split(".");return t.length>=3?t.slice(1).join("."):e}function Vo(e,t){let r=dr(e,"app");return{appId:`${t.split(".").reverse().join(".")}.${r.replace(/-/g,"")}`,productName:e,protocol:r}}function Bo(e){let t=e.toLowerCase().replace(/[^a-z0-9_]/g,"");return/^[a-z]/.test(t)?t:`app${t}`}function Go(e,t){let r=dr(e,"app");return{appName:e,slug:r,bundleId:[...t.split(".").reverse(),r.replace(/-/g,"")].map(Bo).join("."),scheme:/^[a-z]/.test(r)?r:`app-${r}`}}function Ko(e){let t=[" // PRESENCE IS THE SWITCH: reporting runs as soon as the credential below is non-empty. There"," // is no separate `enabled` flag to remember - pasting the key IS turning it on, and clearing it"," // is turning it off. These are PUBLISHABLE credentials: they only authorize SENDING events,"," // never reading them, which is why they live here rather than in env and why a packaged desktop"," // app can carry them. Server-side, SENTRY_DSN and POSTHOG_API_KEY override them."].join(`
81
- `),r=[];return e.includes("sentry")&&r.push(' sentry: { dsn: "" }'),e.includes("posthog")&&r.push([" // llmContent sends your users' prompts and completions to PostHog. Every number (tokens,"," // cost, latency, errors) is captured either way - turn it on only if your privacy policy"," // covers sending their message text to a third party.",' posthog: { publicKey: "", host: "https://us.i.posthog.com", llmContent: false }'].join(`
81
+ `),r=[];return e.includes("sentry")&&r.push(' sentry: { dsn: "" }'),e.includes("posthog")&&r.push([" // This one key turns on errors, LLM analytics AND product analytics (page views, autocapture,"," // identify). Add `analytics.posthog` only to override that: your own /ingest proxy, session"," // replay, surveys. POSTHOG_API_KEY overrides the key for server errors and LLM analytics only."," // llmContent sends your users' prompts and completions to PostHog. Every number (tokens,"," // cost, latency, errors) is captured either way - turn it on only if your privacy policy"," // covers sending their message text to a third party.",' posthog: { publicKey: "", host: "https://us.i.posthog.com", llmContent: false }'].join(`
82
82
  `)),r.length===0?[" // Error and product reporting is OFF: no provider was selected at init, so neither adapter",' // nor SDK was generated. To turn one on, add `"sentry"`, `"posthog"` or both to the'," // `observability` array in `.generatesaas/manifest.json`, then run `generatesaas update` -"," // which re-shapes the project and installs what it needs. Note that update stages nothing"," // while you are already on the latest version, so take the upgrade first if it reports no"," // changes."," observability: {},"].join(`
83
83
  `):`${t}
84
84
  observability: {
@@ -799,7 +799,8 @@ ${k},
799
799
  items: []
800
800
  }
801
801
  };
802
- `;await l(t,w)}var Wo={smtp:[{key:"SMTP_HOST",defaultValue:"127.0.0.1"},{key:"SMTP_PORT",defaultValue:"1025"},{key:"SMTP_USER"},{key:"SMTP_PASSWORD"}],ses:[{key:"AMAZON_SES_REGION",comment:"# TODO: Configure Amazon SES credentials (e.g. us-east-1)"},{key:"AMAZON_SES_KEY"},{key:"AMAZON_SES_SECRET"},{key:"AMAZON_SES_CONFIGURATION_SET",comment:"# Delivery events: configuration set -> SNS topic -> /webhooks/email/ses (see docs: Email)"},{key:"AMAZON_SES_SNS_TOPIC_ARN"}],resend:[{key:"RESEND_API_KEY",comment:"# TODO: Add your Resend API key"},{key:"RESEND_WEBHOOK_SECRET",comment:"# Delivery events: Resend webhook -> /webhooks/email/resend (see docs: Email)"}]},zo={stripe:[{key:"STRIPE_SECRET_KEY",comment:"# TODO: Add your Stripe keys"},{key:"STRIPE_WEBHOOK_SECRET"},{key:"STRIPE_API_BASE",comment:"# Point the Stripe SDK at another host - a local mock, or a proxy of your own. Unset means api.stripe.com."},{key:"STRIPE_PORTAL_GENERATION",comment:"# A number your deploy sets higher on every release (build timestamp, pipeline run number), so a new release retires the Stripe portal configurations an older one created. Unset, none are retired."}],polar:[{key:"POLAR_ACCESS_TOKEN",comment:"# TODO: Add your Polar keys"},{key:"POLAR_WEBHOOK_SECRET"}]};function Bt(e,t){return t?e.map(r=>{let n=t[r.key];return n?{...r,defaultValue:n,comment:void 0}:r}):e}function Pt(e,t){for(let r of e)r.comment&&t.push(r.comment),r.defaultValue!==void 0?t.push(`${r.key}=${r.defaultValue}`):t.push(`#${r.key}=`)}function Tr(e){return Array.from(crypto.getRandomValues(new Uint8Array(e))).map(t=>t.toString(16).padStart(2,"0")).join("")}function Rr(e){return e.architecture==="fullstack"?{apiUrl:"http://localhost:3000/api",baseUrl:"http://localhost:3000"}:{apiUrl:"http://localhost:3010",baseUrl:"http://localhost:3000"}}var Jo="https://your-app.example.com/api";function Gt(e,t,r,n){e.push(n==="example"?`${t}=`:`${t}=${r}`)}function Un(e,t){let r=t==="example"?void 0:e.credentials,{apiUrl:n,baseUrl:i}=Rr(e),s=[];e.architecture==="separate"?s.push("# API Configuration","# Standalone backend's own URL (the frontend reaches it via the public var above).",`API_URL=${n}`,`BASE_URL=${i}`):s.push("# App","# (API_URL is derived from the frontend's *_PUBLIC_API_URL by the runtime env schema.)",`BASE_URL=${i}`),s.push("","# Client IP (production)","# The backend rate-limits by client IP and stamps it on audit entries. YOU ALMOST","# CERTAINLY DO NOT NEED THIS: it detects Vercel, Fly.io, Render, Railway, Netlify and","# Coolify from their own env vars, and treats a private connection peer (Docker, compose,","# Kubernetes, Dokploy, an nginx/Traefik/Caddy on the same host) as proof that something is","# forwarding to it. A forwarded header is trusted only in those cases, never on a server","# exposed directly - there, a caller could have sent it themselves."),e.architecture==="fullstack"?s.push("# This build runs the API in the frontend's route handler, which has no connection","# address, so on a host the backend does not recognise there is nothing to fall back on","# and every caller shares ONE rate-limit bucket: the 10/min sign-in limit applies to","# your whole app rather than per person, and audit entries record no address."):s.push("# This build reads the connection peer, so a server exposed directly identifies its","# callers correctly with nothing set here."),s.push("# SET IT when nothing above can see your topology - the common case is a CDN in front of a","# directly exposed server, where connections arrive from a public CDN address:","# Cloudflare -> TRUSTED_PROXY=cf-connecting-ip","# another proxy in front -> TRUSTED_PROXY=1 (the number of proxies)","# Whatever you set wins over detection; `false` turns detection off and trusts nothing.","# TRUSTED_PROXY=1"),s.push("","# Auth rate limits","# Raises every Better Auth rate limit by a whole number (1-50). Unset = 1 = the","# shipped limits. No value disables them: 0, empty or unparseable fails at boot.","# You almost certainly want the default. The reason to raise it is an automated suite,","# which drives ONE address and so shares one bucket - and the e2e config already sets","# its own value, so it needs nothing here.","# AUTH_RATE_LIMIT_MULTIPLIER=1"),s.push("","# Database"),Pt(Bt(Ce[e.databaseProvider].envVars,r),s),s.push("","# Cache"),Pt(Bt(Le[e.cacheProvider].envVars,r),s),e.cacheProvider==="redis"&&s.push("# Optional prefix on every Redis key the app writes. Set it when several deployments share","# one Redis instance, or to keep a load test out of the live keyspace.","# Set it once, before first boot. Changing it on a running deployment orphans in-flight","# auto-top-up claims and distributed locks (autotopup:pending:*, withMutex) - drain or use","# a maintenance window first.","#REDIS_KEY_PREFIX="),s.push("","# Authentication"),t==="example"&&s.push("# Generate a strong secret, e.g. `openssl rand -hex 32`"),Gt(s,"BETTER_AUTH_SECRET",crypto.randomUUID(),t),s.push("","# Content API (random secret; required when contentApi feature is enabled in @repo/config)"),Gt(s,"CONTENT_API_KEY",Tr(32),t),s.push("","# Job Queue - Inngest","INNGEST_APP_ID=api"),Gt(s,"INNGEST_EVENT_KEY",Tr(32),t),s.push("# REQUIRED in production: it is how the /inngest endpoint tells Inngest from anyone else who","# finds the URL. The app refuses to boot without it unless INNGEST_DEV is set (local dev server).","# Take the real value from the Inngest dashboard."),Gt(s,"INNGEST_SIGNING_KEY",Tr(32),t),s.push("# The local Inngest dev server (pnpm dev:inngest). In production on Inngest Cloud leave this UNSET:","# Cloud takes events and registration on two hosts, which no single URL can name. Set it only for a","# self-hosted Inngest, to its one host.","INNGEST_BASE_URL=http://127.0.0.1:8288"),e.architecture==="separate"&&(s.push("","# API Port (standalone backend)","API_PORT=3010"),s.push("","# CORS + cross-subdomain cookies (production only - leave unset for local dev)","# TRUSTED_ORIGINS=https://your-app.example.com","# AUTH_COOKIE_DOMAIN=.example.com"));let o=Wo[e.emailProvider];if(o&&(s.push("","# Email"),Pt(Bt(o,r),s)),e.paymentProvider!=="none"){let p=zo[e.paymentProvider];p&&(s.push("","# Payment"),Pt(Bt(p,r),s))}s.push("","# Storage - S3 Compatible (required for uploads: avatars, files)","# Works with AWS S3, Cloudflare R2, MinIO, and other S3-compatible services.","# Uploads fail until these are set - storage is enabled in @repo/config by default.","#STORAGE_REGION=us-east-1","#STORAGE_ENDPOINT=https://your-account.r2.cloudflarestorage.com","#STORAGE_ACCESS_KEY_ID=","#STORAGE_SECRET_ACCESS_KEY=","# Two buckets: one publicly readable (avatars, assets), one credentials-only (private","# uploads served through the app). The bucket boundary is the privacy guarantee.","#STORAGE_PUBLIC_BUCKET=","#STORAGE_PRIVATE_BUCKET=",'# Public base URL for the public bucket. Public file URLs are STORAGE_PUBLIC_URL + "/" + key.',"#STORAGE_PUBLIC_URL=https://cdn.example.com","","# Storage - Local Filesystem (optional overrides)","# Defaults work out of the box; override for Docker volume mounts.","#STORAGE_LOCAL_PATH=/data","#STORAGE_LOCAL_PUBLIC_URL=https://cdn.example.com/files"),s.push("","# Admin Notifications (optional)","# Real-time notifications when business events occur (signups, purchases, etc.).","# Each provider is auto-enabled when its env vars are set.","#DISCORD_WEBHOOK_URL=https://discord.com/api/webhooks/...","#SLACK_WEBHOOK_URL=https://hooks.slack.com/services/...","#TELEGRAM_BOT_TOKEN=123456789:ABCdefGHIjklMNOpqrsTUVwxyz","#TELEGRAM_CHAT_ID=-1001234567890","#TELEGRAM_TOPIC_ID=123"),s.push("","# Social sign-in (optional)","# Enable the matching provider in @repo/config, then set its pair here.","#GOOGLE_CLIENT_ID=","#GOOGLE_CLIENT_SECRET=","#GITHUB_CLIENT_ID=","#GITHUB_CLIENT_SECRET=","# Apple: APPLE_TEAM_ID + APPLE_KEY_ID + APPLE_PRIVATE_KEY are the signing key. Add APPLE_CLIENT_ID",'# (a Service ID) for the web button, and list "apple" in config.auth.socialProviders.',"#APPLE_CLIENT_ID=","#APPLE_TEAM_ID=","#APPLE_KEY_ID=","#APPLE_PRIVATE_KEY="),s.push("","# SMS - Twilio (optional)","#TWILIO_ACCOUNT_SID=ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx","#TWILIO_AUTH_TOKEN=","#TWILIO_PHONE_NUMBER=+1234567890"),s.push("","# Newsletter (optional)","#RESEND_AUDIENCE_ID=","#LISTMONK_URL=https://listmonk.yourdomain.com","#LISTMONK_API_USER=admin","#LISTMONK_API_TOKEN=","#LISTMONK_LIST_ID=1"),e.demo&&s.push("","# Support chat - Chatwoot identity validation (optional)","# The website inbox's HMAC token (Inbox -> Settings -> Configuration -> Identity validation).","# Server-only: the backend signs the signed-in user's id with it so the inbox can enforce","# identity validation. Never expose it to the browser.","#CHATWOOT_HMAC_TOKEN="),s.push("","# Translations - OpenRouter (optional)","# Set to auto-translate en/* into your other locales with `pnpm translate`.","# The pre-commit hook runs it on commit; without a key it skips and untranslated","# locales fall back to the default locale. Get a key: https://openrouter.ai/keys","#OPENROUTER_API_KEY=");let a=[];return e.observability.includes("sentry")&&a.push({key:"SENTRY_DSN",comment:"# Overrides config.observability.sentry.dsn for the server only."}),e.observability.includes("posthog")&&a.push({key:"POSTHOG_API_KEY",comment:`# Overrides config.observability.posthog.publicKey for the server only (host stays in config).
802
+ `;await l(t,w)}var Wo={smtp:[{key:"SMTP_HOST",defaultValue:"127.0.0.1"},{key:"SMTP_PORT",defaultValue:"1025"},{key:"SMTP_USER"},{key:"SMTP_PASSWORD"}],ses:[{key:"AMAZON_SES_REGION",comment:"# TODO: Configure Amazon SES credentials (e.g. us-east-1)"},{key:"AMAZON_SES_KEY"},{key:"AMAZON_SES_SECRET"},{key:"AMAZON_SES_CONFIGURATION_SET",comment:"# Delivery events: configuration set -> SNS topic -> /webhooks/email/ses (see docs: Email)"},{key:"AMAZON_SES_SNS_TOPIC_ARN"}],resend:[{key:"RESEND_API_KEY",comment:"# TODO: Add your Resend API key"},{key:"RESEND_WEBHOOK_SECRET",comment:"# Delivery events: Resend webhook -> /webhooks/email/resend (see docs: Email)"}]},zo={stripe:[{key:"STRIPE_SECRET_KEY",comment:"# TODO: Add your Stripe keys"},{key:"STRIPE_WEBHOOK_SECRET"},{key:"STRIPE_API_BASE",comment:"# Point the Stripe SDK at another host - a local mock, or a proxy of your own. Unset means api.stripe.com."},{key:"STRIPE_PORTAL_GENERATION",comment:"# A number your deploy sets higher on every release (build timestamp, pipeline run number), so a new release retires the Stripe portal configurations an older one created. Unset, none are retired."}],polar:[{key:"POLAR_ACCESS_TOKEN",comment:"# TODO: Add your Polar keys"},{key:"POLAR_WEBHOOK_SECRET"}]};function Bt(e,t){return t?e.map(r=>{let n=t[r.key];return n?{...r,defaultValue:n,comment:void 0}:r}):e}function Pt(e,t){for(let r of e)r.comment&&t.push(r.comment),r.defaultValue!==void 0?t.push(`${r.key}=${r.defaultValue}`):t.push(`#${r.key}=`)}function Tr(e){return Array.from(crypto.getRandomValues(new Uint8Array(e))).map(t=>t.toString(16).padStart(2,"0")).join("")}function Rr(e){return e.architecture==="fullstack"?{apiUrl:"http://localhost:3000/api",baseUrl:"http://localhost:3000"}:{apiUrl:"http://localhost:3010",baseUrl:"http://localhost:3000"}}var Jo="https://your-app.example.com/api";function Gt(e,t,r,n){e.push(n==="example"?`${t}=`:`${t}=${r}`)}function Un(e,t){let r=t==="example"?void 0:e.credentials,{apiUrl:n,baseUrl:i}=Rr(e),s=[];e.architecture==="separate"?s.push("# API Configuration","# Standalone backend's own URL (the frontend reaches it via the public var above).",`API_URL=${n}`,`BASE_URL=${i}`):s.push("# App","# (API_URL is derived from the frontend's *_PUBLIC_API_URL by the runtime env schema.)",`BASE_URL=${i}`),s.push("","# Client IP (production)","# The backend rate-limits by client IP and stamps it on audit entries. YOU ALMOST","# CERTAINLY DO NOT NEED THIS: it detects Vercel, Fly.io, Render, Railway, Netlify and","# Coolify from their own env vars, and treats a private connection peer (Docker, compose,","# Kubernetes, Dokploy, an nginx/Traefik/Caddy on the same host) as proof that something is","# forwarding to it. A forwarded header is trusted only in those cases, never on a server","# exposed directly - there, a caller could have sent it themselves."),e.architecture==="fullstack"?s.push("# This build runs the API in the frontend's route handler, which has no connection","# address, so on a host the backend does not recognise there is nothing to fall back on","# and every caller shares ONE rate-limit bucket: the 10/min sign-in limit applies to","# your whole app rather than per person, and audit entries record no address."):s.push("# This build reads the connection peer, so a server exposed directly identifies its","# callers correctly with nothing set here."),s.push("# SET IT when nothing above can see your topology - the common case is a CDN in front of a","# directly exposed server, where connections arrive from a public CDN address:","# Cloudflare -> TRUSTED_PROXY=cf-connecting-ip","# another proxy in front -> TRUSTED_PROXY=1 (the number of proxies)","# Whatever you set wins over detection; `false` turns detection off and trusts nothing.","# TRUSTED_PROXY=1"),s.push("","# Auth rate limits","# Raises every Better Auth rate limit by a whole number (1-50). Unset = 1 = the","# shipped limits. No value disables them: 0, empty or unparseable fails at boot.","# You almost certainly want the default. The reason to raise it is an automated suite,","# which drives ONE address and so shares one bucket - and the e2e config already sets","# its own value, so it needs nothing here.","# AUTH_RATE_LIMIT_MULTIPLIER=1"),s.push("","# Database"),Pt(Bt(Ce[e.databaseProvider].envVars,r),s),s.push("","# Cache"),Pt(Bt(Le[e.cacheProvider].envVars,r),s),e.cacheProvider==="redis"&&s.push("# Optional prefix on every Redis key the app writes. Set it when several deployments share","# one Redis instance, or to keep a load test out of the live keyspace.","# Set it once, before first boot. Changing it on a running deployment orphans in-flight","# auto-top-up claims and distributed locks (autotopup:pending:*, withMutex) - drain or use","# a maintenance window first.","#REDIS_KEY_PREFIX="),s.push("","# Authentication"),t==="example"&&s.push("# Generate a strong secret, e.g. `openssl rand -hex 32`"),Gt(s,"BETTER_AUTH_SECRET",crypto.randomUUID(),t),s.push("","# Content API (random secret; required when contentApi feature is enabled in @repo/config)"),Gt(s,"CONTENT_API_KEY",Tr(32),t),s.push("","# Job Queue - Inngest","INNGEST_APP_ID=api"),Gt(s,"INNGEST_EVENT_KEY",Tr(32),t),s.push("# REQUIRED in production: it is how the /inngest endpoint tells Inngest from anyone else who","# finds the URL. The app refuses to boot without it unless INNGEST_DEV is set (local dev server).","# Take the real value from the Inngest dashboard."),Gt(s,"INNGEST_SIGNING_KEY",Tr(32),t),s.push("# The local Inngest dev server (pnpm dev:inngest). In production on Inngest Cloud leave this UNSET:","# Cloud takes events and registration on two hosts, which no single URL can name. Set it only for a","# self-hosted Inngest, to its one host.","INNGEST_BASE_URL=http://127.0.0.1:8288"),e.architecture==="separate"&&(s.push("","# API Port (standalone backend)","API_PORT=3010"),s.push("","# CORS + cross-subdomain cookies (production only - leave unset for local dev)","# TRUSTED_ORIGINS=https://your-app.example.com","# AUTH_COOKIE_DOMAIN=.example.com"));let o=Wo[e.emailProvider];if(o&&(s.push("","# Email"),Pt(Bt(o,r),s)),e.paymentProvider!=="none"){let p=zo[e.paymentProvider];p&&(s.push("","# Payment"),Pt(Bt(p,r),s))}s.push("","# Storage - S3 Compatible (required for uploads: avatars, files)","# Works with AWS S3, Cloudflare R2, MinIO, and other S3-compatible services.","# Uploads fail until these are set - storage is enabled in @repo/config by default.","#STORAGE_REGION=us-east-1","#STORAGE_ENDPOINT=https://your-account.r2.cloudflarestorage.com","#STORAGE_ACCESS_KEY_ID=","#STORAGE_SECRET_ACCESS_KEY=","# Two buckets: one publicly readable (avatars, assets), one credentials-only (private","# uploads served through the app). The bucket boundary is the privacy guarantee.","#STORAGE_PUBLIC_BUCKET=","#STORAGE_PRIVATE_BUCKET=",'# Public base URL for the public bucket. Public file URLs are STORAGE_PUBLIC_URL + "/" + key.',"#STORAGE_PUBLIC_URL=https://cdn.example.com","","# Storage - Local Filesystem (optional overrides)","# Defaults work out of the box; override for Docker volume mounts.","#STORAGE_LOCAL_PATH=/data","#STORAGE_LOCAL_PUBLIC_URL=https://cdn.example.com/files"),s.push("","# Admin Notifications (optional)","# Real-time notifications when business events occur (signups, purchases, etc.).","# Each provider is auto-enabled when its env vars are set.","#DISCORD_WEBHOOK_URL=https://discord.com/api/webhooks/...","#SLACK_WEBHOOK_URL=https://hooks.slack.com/services/...","#TELEGRAM_BOT_TOKEN=123456789:ABCdefGHIjklMNOpqrsTUVwxyz","#TELEGRAM_CHAT_ID=-1001234567890","#TELEGRAM_TOPIC_ID=123"),s.push("","# Social sign-in (optional)","# Enable the matching provider in @repo/config, then set its pair here.","#GOOGLE_CLIENT_ID=","#GOOGLE_CLIENT_SECRET=","#GITHUB_CLIENT_ID=","#GITHUB_CLIENT_SECRET=","# Apple: APPLE_TEAM_ID + APPLE_KEY_ID + APPLE_PRIVATE_KEY are the signing key. Add APPLE_CLIENT_ID",'# (a Service ID) for the web button, and list "apple" in config.auth.socialProviders.',"#APPLE_CLIENT_ID=","#APPLE_TEAM_ID=","#APPLE_KEY_ID=","#APPLE_PRIVATE_KEY="),s.push("","# SMS - Twilio (optional)","#TWILIO_ACCOUNT_SID=ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx","#TWILIO_AUTH_TOKEN=","#TWILIO_PHONE_NUMBER=+1234567890"),s.push("","# Newsletter (optional)","#RESEND_AUDIENCE_ID=","#LISTMONK_URL=https://listmonk.yourdomain.com","#LISTMONK_API_USER=admin","#LISTMONK_API_TOKEN=","#LISTMONK_LIST_ID=1"),e.demo&&s.push("","# Support chat - Chatwoot identity validation (optional)","# The website inbox's HMAC token (Inbox -> Settings -> Configuration -> Identity validation).","# Server-only: the backend signs the signed-in user's id with it so the inbox can enforce","# identity validation. Never expose it to the browser.","#CHATWOOT_HMAC_TOKEN="),s.push("","# Translations - OpenRouter (optional)","# Set to auto-translate en/* into your other locales with `pnpm translate`.","# The pre-commit hook runs it on commit; without a key it skips and untranslated","# locales fall back to the default locale. Get a key: https://openrouter.ai/keys","#OPENROUTER_API_KEY=");let a=[];return e.observability.includes("sentry")&&a.push({key:"SENTRY_DSN",comment:"# Overrides config.observability.sentry.dsn for the server only."}),e.observability.includes("posthog")&&a.push({key:"POSTHOG_API_KEY",comment:`# Overrides config.observability.posthog.publicKey for the server only (host stays in config),
803
+ # for errors and LLM analytics; product analytics always uses the committed key.
803
804
  # Set but EMPTY switches every server-side PostHog report off (the e2e harness does this). Leave it
804
805
  # unset in production: the committed key is used, and only the deployment reports.`}),a.length>0&&(s.push("","# Error and product reporting (optional)"),Pt(a,s)),s.push("","# Release (optional)","# The release this deployment runs (a version, tag or commit), set by your deploy pipeline.","# Product feedback records it beside each item. Unset records none.","#APP_VERSION=","","# ChatGPT plugin directory (optional)","# The domain-verification token the OpenAI Plugins dashboard gives you when you list the MCP","# server. Served at /.well-known/openai-apps-challenge while config.mcpServer is on; unset","# answers 404.","#OPENAI_APPS_CHALLENGE="),s.push("","# AI base (optional)","# Enable config.ai in packages/config. Built-in AI resolves through OpenRouter only,","# so OPENROUTER_API_KEY above is the only MODEL provider key the backend reads.","# BYOK is per-user and never an env var: users paste their own key in the app and it","# is stored encrypted in the database.","# Override the OpenRouter API base - a gateway or a proxy of your own. It must carry the","# /api/v1 suffix. Unset uses the hosted API.","#OPENROUTER_BASE_URL=https://openrouter.ai/api/v1","","# AI web tools (optional)","# Give the assistant its own web access, on chat (on by default), the desktop app-tools","# lane, automations and the MCP server. A key's presence is the whole switch: set one","# and the model gets its tools, set none and chat is unchanged. config.ai.webSearch:","# false switches every lane off.","# ANY one key alone covers both capabilities. With several set, auto-detection takes the","# CHEAPEST first - TinyFish, then Firecrawl, then Parallel - per capability; naming","# config.ai.webTools.searchEngine or .extractEngine wins over that order, and a named","# engine whose key is missing ships no tool at all.","# WHAT A CALL COSTS THE USER: the vendor price x credits.creditsPerUsd x the","# webSearch/webExtract markup (shipped at 100, so twice cost). Override the vendor price","# with config.ai.webTools.searchCostUsd / .extractCostUsd.","# TinyFish (the auto-detect default) - both tools at a $0 list price, so a call debits","# nothing, writes no ledger row and is never refused for an empty balance. Rate-limited","# instead (30 searches and 150 pages a minute per API key by default, shared by every","# user), so set a price on a busy app. Note its terms include a license to train on","# submitted content.","# https://agent.tinyfish.ai/","#TINYFISH_API_KEY=","# Firecrawl (the recommended PAID engine) - `web_search` AND `web_extract` (reads one","# page) from one signup, and the only vendor here whose terms carry no license over what","# you submit.","# https://firecrawl.dev/","#FIRECRAWL_API_KEY=","# Parallel (optional) - both tools, cheaper than Firecrawl on each, at high quality;","# extract is slower on a page it has not already indexed. Note its customer terms","# include a license to train on submitted queries.","# https://platform.parallel.ai/","#PARALLEL_API_KEY="),e.desktop&&s.push("","# Desktop app (optional)","# Base URL the marketing download page reads the release feed from.","# Unset uses config.desktop.autoUpdate.url.","#DESKTOP_FEED_BASE_URL="),e.mobile&&(s.push("","# Mobile app","# The bundle identifier the native Sign in with Apple token is issued to - it joins","# APPLE_CLIENT_ID in the audience the backend accepts. With the three Apple signing values","# and no APPLE_CLIENT_ID, it alone turns on native-only Sign in with Apple: the iOS app shows","# Apple beside Google (it reads that at runtime) and the web shows no Apple button.","#APPLE_APP_BUNDLE_IDENTIFIER=","# Comma-separated Android signing certificate SHA-256 fingerprints. They feed","# .well-known/assetlinks.json (which verifies your universal links) and the passkey","# Android origins.","#MOBILE_ANDROID_SHA256_FINGERPRINTS=","# Optional. An Expo access token turns on enhanced security for push sends.","#EXPO_ACCESS_TOKEN="),e.mobilePurchases==="revenuecat"&&s.push("","# Mobile store purchases - RevenueCat (server)","# The first two verify incoming webhooks; the third is read by the sync route and the","# nightly reconcile pass.","#REVENUECAT_WEBHOOK_SECRET=","#REVENUECAT_AUTH_HEADER=","#REVENUECAT_API_KEY=")),s.push("","# Build output (optional)","# Next's distDir for apps/web. Unset uses .next; the e2e harness sets its own so a test","# build never overwrites a dev server's.","#NEXT_DIST_DIR="),s.push(""),s.join(`
805
806
  `)}var Fn="NEXT_PUBLIC_API_URL";function qo(e){let{apiUrl:t}=Rr(e),r=["# API Configuration",`${Fn}=${t}`];return e.architecture==="separate"&&r.push("","# Production (uncomment and replace with your deployed hostnames):",`# ${Fn}=${Jo}`),r.push(""),r.join(`
@@ -1737,7 +1738,7 @@ function posthogConfigured(): boolean {
1737
1738
  ${k}`:o.message))}else i()})})}async function ss(e){if(!Re("pnpm"))return _.log.warn("pnpm not found. Skipping lockfile regeneration."),!1;try{return await Te("pnpm",["install","--lockfile-only","--no-frozen-lockfile"],e),!0}catch(t){let r=t instanceof Error?t.message:String(t);return _.log.warn(`Lockfile regeneration failed: ${r}`),_.log.warn("Deploys using --frozen-lockfile may fail."),!1}}async function os(e){if(!Re("pnpm"))return _.log.warn("pnpm not found. Skipping dependency installation."),_.log.info("Install pnpm: https://pnpm.io/installation"),!1;let t=_.spinner();t.start("Installing dependencies (this may take a minute)...");try{return await Te("pnpm",["install"],e),t.stop("Dependencies installed."),!0}catch(r){t.stop("Dependency installation failed.");let n=r instanceof Error?r.message:String(r);return _.log.warn(`pnpm install failed: ${n}`),_.log.warn("You can run it manually later."),!1}}async function as(e){if(!Re("pnpm"))return!1;let t=_.spinner();t.start("Generating baseline database migration...");try{return await Te("pnpm",["-F","@repo/database","generate"],e),t.stop("Baseline migration generated."),!0}catch(r){t.stop("Baseline migration generation failed.");let n=r instanceof Error?r.message:String(r);return _.log.warn(`Could not generate baseline migration: ${n}`),_.log.warn("Run 'pnpm -F @repo/database generate' before your first deploy."),!1}}async function cs(e){if(!Re("pnpm"))return!1;try{await Kr(rr(e,"packages/mcp-widgets"))}catch{return!1}let t=_.spinner();t.start("Building the MCP widgets...");try{return await Te("pnpm",["-F","@repo/mcp-widgets","widgets:build"],e),t.stop("MCP widgets built."),!0}catch(r){t.stop("MCP widget build failed.");let n=r instanceof Error?r.message:String(r);return _.log.warn(`Could not build the MCP widgets: ${n}`),_.log.warn("Run 'pnpm -F @repo/mcp-widgets widgets:build' and commit the result."),!1}}async function ls(e){try{return await Kr(rr(e,".git")),_.log.info("Git repository already exists, skipping init."),!0}catch{}if(!Re("git"))return _.log.warn("git not found. Skipping repository initialization."),!1;let t=_.spinner();t.start("Initializing git repository...");try{return await Te("git",["init"],e),await Te("git",["add","-A"],e),await Te("git",["commit","--no-verify","-m","Initial commit from GenerateSaaS"],e),t.stop("Git repository initialized."),!0}catch{return t.stop("Git initialization failed."),_.log.warn("You can run git init manually later."),!1}}async function ps(e){if(!Re("pnpm"))return!1;try{await Kr(rr(e,".git"))}catch{return!1}try{let t=JSON.parse(await hp(rr(e,"package.json"),"utf-8")),r=!!t.devDependencies?.["simple-git-hooks"],n=!!t["simple-git-hooks"];if(!r||!n)return!1}catch{return!1}try{return await Te("pnpm",["exec","simple-git-hooks"],e),!0}catch{return _.log.warn("Could not install git hooks. Run 'pnpm exec simple-git-hooks' manually."),!1}}import*as Je from"@clack/prompts";import H from"picocolors";function ds(e,t){let r=rt(e);t.dockerAvailable||Je.log.warn("Docker not found. Install Docker to run local services: https://docs.docker.com/get-docker/"),t.baselineMigrationMissing&&Je.log.warn("No database migration was generated (the install did not complete). Run `pnpm install` then `pnpm --filter @repo/database generate` and commit the result BEFORE deploying - otherwise your first deploy pushes the schema untracked.");let n=[];n.push(`cd ${e.projectDir}`),t.pnpmInstalled||n.push("pnpm install"),t.mcpWidgetsUnbuilt&&n.push(`pnpm -F @repo/mcp-widgets widgets:build ${H.dim("# then commit the rebuilt widget document")}`),n.push(`pnpm infra ${H.dim(`# ${r.map(a=>en[a].label).join(", ")}`)}`),n.push(`pnpm dev ${H.dim("# http://localhost:3000")}`),t.skippedCredentials.length>0&&(n.push(""),n.push(H.dim("Fill in remaining TODO values in .env"))),Je.note(n.join(`
1738
1739
  `),H.yellow("Start Development"));let i=[];i.push(`App ${H.cyan("http://localhost:3000")}`),e.architecture==="separate"&&i.push(`API ${H.cyan("http://localhost:3010")}`),r.includes("mailpit")&&i.push(`Mailpit ${H.cyan("http://localhost:8025")}`),r.includes("inngest")&&i.push(`Inngest ${H.cyan("http://localhost:8288")}`),Je.note(i.join(`
1739
1740
  `),H.yellow("Dev Tools"));let s=[],o=fp(e);o.length>0&&s.push(`Set in production: ${H.dim(o.join(", "))}`),s.push("pnpm db:setup # Apply the database schema"),s.push(gp(e)),Je.note(s.join(`
1740
- `),H.yellow("Deployment"))}function fp(e){let t=["DATABASE_URL","BETTER_AUTH_SECRET","INNGEST_APP_ID","INNGEST_EVENT_KEY","INNGEST_SIGNING_KEY"];return e.cacheProvider==="upstash"?t.push("UPSTASH_REDIS_REST_URL","UPSTASH_REDIS_REST_TOKEN"):t.push("REDIS_URL"),e.paymentProvider==="stripe"?t.push("STRIPE_SECRET_KEY","STRIPE_WEBHOOK_SECRET"):e.paymentProvider==="polar"&&t.push("POLAR_ACCESS_TOKEN","POLAR_WEBHOOK_SECRET"),e.emailProvider==="ses"?t.push("AMAZON_SES_REGION","AMAZON_SES_KEY","AMAZON_SES_SECRET"):e.emailProvider==="resend"?t.push("RESEND_API_KEY"):t.push("SMTP_HOST","SMTP_PORT"),t}function gp(e){switch(e.deploymentTarget){case"node":return"Deploy with Docker or your preferred Node.js host";case"vercel":return"vercel deploy # Deploy to Vercel"}}function ht(e){let r=(e.startsWith("v")?e.slice(1):e).match(/^(\d+)\.(\d+)\.(\d+)$/);return r?[Number(r[1]),Number(r[2]),Number(r[3])]:null}function _e(e,t){let r=ht(e),n=ht(t);if(!r||!n)return 0;for(let i=0;i<3;i++)if(r[i]!==n[i])return r[i]-n[i];return 0}function nr(e,t){return e.versions.find(r=>r.version===t)?.cli}function us(e){return process.env.GENERATESAAS_TEMPLATE_TARBALL||process.env.GENERATESAAS_TEMPLATE_TARBALL_DIR||process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?!0:ht(e)===null}function ir(e,t,r="3.41.0"){if(us(r))return{ok:!0};let n=nr(e,e.latest);return!n||ht(n)===null?{ok:!0}:_e(r,n)>=0?{ok:!0}:{ok:!1,message:`Your installed generatesaas CLI (v${r}) is too old for template v${e.latest}, which needs CLI v${n} or newer. Run npx generatesaas@latest ${t} so npm fetches the current CLI. If the release happened minutes ago, npm may still be propagating it - retry shortly.`}}function ms(e,t,r="3.41.0"){if(us(r))return{ok:!0};let n=nr(e,t);return!n||ht(n)===null?{ok:!0}:_e(r,n)===0?{ok:!0}:{ok:!1,message:`Template v${t} must be scaffolded by CLI v${n} exactly (the CLI whose generators produced that release). Run npx generatesaas@${n} init.`}}import Ep from"picocolors";var Sp="a10a6fb9d7cadde32e37dad52059d17b5d2b916b08c76d8fbcc99982e9a3d87f";async function Pp(e){let t=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`generatesaas-demo:${e}`)),r=[...new Uint8Array(t).subarray(0,16)].map(n=>n.toString(16).padStart(2,"0")).join("");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20,32)}`}function hs(e){e.command("init").description("Scaffold a new GenerateSaaS project").argument("[apiKey]","license key (same as --api-key)").option("-n, --name <name>","project name (lowercase, hyphens, starts with letter)").option("--app-name <name>","display name for the app").option("-l, --location <path>","project directory (default: ./{name})").addOption(new ee("--architecture <type>","fullstack or separate").choices([...nt])).addOption(new ee("--payment <provider>","payment provider").choices([...it])).addOption(new ee("--email <provider>","email provider").choices([...st])).option("--org","enable multi-tenancy (organizations)").option("--no-org","disable multi-tenancy").option("--projects","enable projects (a switcher that scopes a user's work)").option("--no-projects","disable projects").option("--docs","include the docs app (apps/docs, Fumadocs)").option("--no-docs","exclude the docs app").option("--desktop","include the desktop app (apps/desktop, built with Electron)").option("--no-desktop","exclude the desktop app").option("--mobile","include the mobile app (apps/mobile, built with Expo)").option("--no-mobile","exclude the mobile app").addOption(new ee("--mobile-purchases <lane>","in-app purchases in the mobile app: revenuecat adds the store billing lane on top of your web payment provider, none keeps web billing only").choices([...je])).option("--ai","include the AI features (chat, models, automations, integrations)").option("--no-ai","exclude the AI features").option("--web-ai","show the AI features in the web app (the default)").option("--no-web-ai","desktop-first: keep the AI features out of the web app, which is reduced to account, login and billing - the desktop or mobile app is the AI product. Requires --desktop or --mobile, plus --ai").option("--revenue-sharing","enable revenue sharing").option("--no-revenue-sharing","disable revenue sharing").option("--credits","enable credits system").option("--no-credits","disable credits system (subscription-only)").addOption(new ee("--currency <code>","default currency for billing").choices([...ce])).addOption(new ee("--preset <preset>","infrastructure preset: serverless (Vercel + Neon + Upstash) or selfhost (Docker or Node + Postgres + Redis); --deploy/--database/--cache override it piecewise").choices([...$e])).addOption(new ee("--deploy <target>","deployment target").choices([...le])).addOption(new ee("--database <provider>","database provider").choices([...pe])).addOption(new ee("--cache <provider>","cache provider").choices([...de])).option("--observability <providers>",`comma-separated observability providers (${G.join(", ")}); anything unselected ships no SDK`).option("--api-key <key>","API key (skips interactive prompt)").option("--base-url <url>","public base URL (e.g. https://example.com) - bakes into canonical/og/sitemap").option("-y, --yes","accept defaults for unspecified options (non-interactive)").addOption(new ee("--demo","first-party demo build: keep sample content, mark site non-indexable - requires CI API key").hideHelp()).addOption(new ee("--no-db-migration","skip generating the baseline DB migration (internal: demos/CI/playground)").hideHelp()).action(async(t,r)=>{await Ap(t?{...r,apiKey:t}:r)})}async function Ap(e){let t=performance.now();Zr("3.41.0");let r;try{r=pn(e)}catch(v){E.cancel(N(v)),process.exit(1)}let n=E.spinner(),i;try{i=await at({apiKey:e.apiKey,prompt:!e.yes})}catch(v){E.cancel(N(v)),process.exit(1)}e.demo&&Fr(i)!==Sp&&(E.cancel("--demo is restricted to first-party demo deployments."),process.exit(1));let s=he(i),o,a=async()=>{o=await Ae(s);let v=ir(o,"init");if(!v.ok)throw new Error(v.message);return{latestVersion:o.latest,selectedVersion:o.latest,desktopAllowed:o.entitlements?.desktopAllowed??!0,mobileAllowed:o.entitlements?.mobileAllowed??!0}};n.start("Verifying access...");let p,h,g=!0,k=!0;try{({latestVersion:p,selectedVersion:h,desktopAllowed:g,mobileAllowed:k}=await a()),n.stop("Access verified."),Ue(i)}catch(v){if(n.stop("Access verification failed."),v instanceof M&&v.status===401){e.yes&&(E.cancel("Invalid API key. Cannot prompt in non-interactive mode."),process.exit(1)),E.log.warning("Invalid API key."),i=await kt(),s=he(i),n.start("Verifying access...");try{({latestVersion:p,selectedVersion:h,desktopAllowed:g,mobileAllowed:k}=await a()),n.stop("Access verified."),Ue(i)}catch(L){n.stop("Access verification failed."),E.cancel(L instanceof M&&L.status===401?"Invalid API key.":N(L)),process.exit(1)}}else E.cancel(N(v)),process.exit(1)}E.log.success(`Latest version: ${p}`),r.desktop===!0&&!g&&(E.cancel("The desktop app is available on the Pro plan and up. Upgrade your plan at generatesaas.com."),process.exit(1)),r.mobile===!0&&!k&&(E.cancel("The mobile app is available on the Pro plan and up. Upgrade your plan at generatesaas.com."),process.exit(1));let w;e.yes?w=dn({...r,...g?{}:{desktop:!1},...k?{}:{mobile:!1}}):w=await un(r,{desktopAllowed:g,mobileAllowed:k});let P;n.start("Activating license...");try{let v=e.demo&&w.baseUrl?await Pp(w.baseUrl):crypto.randomUUID(),L=()=>({frontend:gr,version:h,installId:v,projectName:w.projectName,options:wn(w)}),F;try{F=await yr(s,L())}catch(ve){let $=$t(ve);if(!$?.lastAllowedVersion||!o)throw ve;n.stop("License activation failed.");let W=ms(o,$.lastAllowedVersion);if(W.ok||(E.cancel(`${$.message} ${W.message}`),process.exit(1)),e.yes){let z=nr(o,$.lastAllowedVersion);E.cancel(`${$.message} Re-run ${z?`npx generatesaas@${z} init`:"init"} without --yes to continue with v${$.lastAllowedVersion} (the last version your license covers).`),process.exit(1)}let ke=await E.confirm({message:`Your update window has ended. Continue with v${$.lastAllowedVersion} (the last version your license covers)?`});(E.isCancel(ke)||!ke)&&(E.cancel("Setup cancelled."),process.exit(0)),h=$.lastAllowedVersion,n.start(`Activating license for v${h}...`),F=await yr(s,L())}P={token:F.token,keyHash:Fr(i),installId:F.installId??v},n.stop("License activated.")}catch(v){n.stop("License activation failed."),E.cancel(N(v)),process.exit(1)}let u=kp(w.projectDir);if(yp(u)&&bp(u).length>0)if(e.yes)E.log.info(`Directory ${u} is not empty. Merging (keeping existing files, overwriting conflicts).`);else{let L=await E.select({message:`Directory ${u} is not empty.`,options:[{value:"merge",label:"Merge",hint:"keep existing files, overwrite conflicts"},{value:"overwrite",label:"Overwrite",hint:"delete everything and start fresh"},{value:"cancel",label:"Cancel"}]});(E.isCancel(L)||L==="cancel")&&(E.cancel("Setup cancelled."),process.exit(0)),L==="overwrite"&&wp(u,{recursive:!0,force:!0})}let O={...w,projectDir:u,version:h,...e.demo?{docs:!1}:{}};n.start("Downloading template...");try{await jt(s,h,u),n.stop("Template downloaded.")}catch(v){n.stop("Download failed."),E.cancel(N(v)),process.exit(1)}n.start("Generating project files...");try{if(await Xt(O),!e.demo){let v=await mt(u);await l(vp(u,Ct),`${JSON.stringify(v,null," ")}
1741
+ `),H.yellow("Deployment"))}function fp(e){let t=["DATABASE_URL","BETTER_AUTH_SECRET","INNGEST_APP_ID","INNGEST_EVENT_KEY","INNGEST_SIGNING_KEY"];return e.cacheProvider==="upstash"?t.push("UPSTASH_REDIS_REST_URL","UPSTASH_REDIS_REST_TOKEN"):t.push("REDIS_URL"),e.paymentProvider==="stripe"?t.push("STRIPE_SECRET_KEY","STRIPE_WEBHOOK_SECRET"):e.paymentProvider==="polar"&&t.push("POLAR_ACCESS_TOKEN","POLAR_WEBHOOK_SECRET"),e.emailProvider==="ses"?t.push("AMAZON_SES_REGION","AMAZON_SES_KEY","AMAZON_SES_SECRET"):e.emailProvider==="resend"?t.push("RESEND_API_KEY"):t.push("SMTP_HOST","SMTP_PORT"),t}function gp(e){switch(e.deploymentTarget){case"node":return"Deploy with Docker or your preferred Node.js host";case"vercel":return"vercel deploy # Deploy to Vercel"}}function ht(e){let r=(e.startsWith("v")?e.slice(1):e).match(/^(\d+)\.(\d+)\.(\d+)$/);return r?[Number(r[1]),Number(r[2]),Number(r[3])]:null}function _e(e,t){let r=ht(e),n=ht(t);if(!r||!n)return 0;for(let i=0;i<3;i++)if(r[i]!==n[i])return r[i]-n[i];return 0}function nr(e,t){return e.versions.find(r=>r.version===t)?.cli}function us(e){return process.env.GENERATESAAS_TEMPLATE_TARBALL||process.env.GENERATESAAS_TEMPLATE_TARBALL_DIR||process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?!0:ht(e)===null}function ir(e,t,r="3.42.0"){if(us(r))return{ok:!0};let n=nr(e,e.latest);return!n||ht(n)===null?{ok:!0}:_e(r,n)>=0?{ok:!0}:{ok:!1,message:`Your installed generatesaas CLI (v${r}) is too old for template v${e.latest}, which needs CLI v${n} or newer. Run npx generatesaas@latest ${t} so npm fetches the current CLI. If the release happened minutes ago, npm may still be propagating it - retry shortly.`}}function ms(e,t,r="3.42.0"){if(us(r))return{ok:!0};let n=nr(e,t);return!n||ht(n)===null?{ok:!0}:_e(r,n)===0?{ok:!0}:{ok:!1,message:`Template v${t} must be scaffolded by CLI v${n} exactly (the CLI whose generators produced that release). Run npx generatesaas@${n} init.`}}import Ep from"picocolors";var Sp="a10a6fb9d7cadde32e37dad52059d17b5d2b916b08c76d8fbcc99982e9a3d87f";async function Pp(e){let t=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`generatesaas-demo:${e}`)),r=[...new Uint8Array(t).subarray(0,16)].map(n=>n.toString(16).padStart(2,"0")).join("");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20,32)}`}function hs(e){e.command("init").description("Scaffold a new GenerateSaaS project").argument("[apiKey]","license key (same as --api-key)").option("-n, --name <name>","project name (lowercase, hyphens, starts with letter)").option("--app-name <name>","display name for the app").option("-l, --location <path>","project directory (default: ./{name})").addOption(new ee("--architecture <type>","fullstack or separate").choices([...nt])).addOption(new ee("--payment <provider>","payment provider").choices([...it])).addOption(new ee("--email <provider>","email provider").choices([...st])).option("--org","enable multi-tenancy (organizations)").option("--no-org","disable multi-tenancy").option("--projects","enable projects (a switcher that scopes a user's work)").option("--no-projects","disable projects").option("--docs","include the docs app (apps/docs, Fumadocs)").option("--no-docs","exclude the docs app").option("--desktop","include the desktop app (apps/desktop, built with Electron)").option("--no-desktop","exclude the desktop app").option("--mobile","include the mobile app (apps/mobile, built with Expo)").option("--no-mobile","exclude the mobile app").addOption(new ee("--mobile-purchases <lane>","in-app purchases in the mobile app: revenuecat adds the store billing lane on top of your web payment provider, none keeps web billing only").choices([...je])).option("--ai","include the AI features (chat, models, automations, integrations)").option("--no-ai","exclude the AI features").option("--web-ai","show the AI features in the web app (the default)").option("--no-web-ai","desktop-first: keep the AI features out of the web app, which is reduced to account, login and billing - the desktop or mobile app is the AI product. Requires --desktop or --mobile, plus --ai").option("--revenue-sharing","enable revenue sharing").option("--no-revenue-sharing","disable revenue sharing").option("--credits","enable credits system").option("--no-credits","disable credits system (subscription-only)").addOption(new ee("--currency <code>","default currency for billing").choices([...ce])).addOption(new ee("--preset <preset>","infrastructure preset: serverless (Vercel + Neon + Upstash) or selfhost (Docker or Node + Postgres + Redis); --deploy/--database/--cache override it piecewise").choices([...$e])).addOption(new ee("--deploy <target>","deployment target").choices([...le])).addOption(new ee("--database <provider>","database provider").choices([...pe])).addOption(new ee("--cache <provider>","cache provider").choices([...de])).option("--observability <providers>",`comma-separated observability providers (${G.join(", ")}); anything unselected ships no SDK`).option("--api-key <key>","API key (skips interactive prompt)").option("--base-url <url>","public base URL (e.g. https://example.com) - bakes into canonical/og/sitemap").option("-y, --yes","accept defaults for unspecified options (non-interactive)").addOption(new ee("--demo","first-party demo build: keep sample content, mark site non-indexable - requires CI API key").hideHelp()).addOption(new ee("--no-db-migration","skip generating the baseline DB migration (internal: demos/CI/playground)").hideHelp()).action(async(t,r)=>{await Ap(t?{...r,apiKey:t}:r)})}async function Ap(e){let t=performance.now();Zr("3.42.0");let r;try{r=pn(e)}catch(v){E.cancel(N(v)),process.exit(1)}let n=E.spinner(),i;try{i=await at({apiKey:e.apiKey,prompt:!e.yes})}catch(v){E.cancel(N(v)),process.exit(1)}e.demo&&Fr(i)!==Sp&&(E.cancel("--demo is restricted to first-party demo deployments."),process.exit(1));let s=he(i),o,a=async()=>{o=await Ae(s);let v=ir(o,"init");if(!v.ok)throw new Error(v.message);return{latestVersion:o.latest,selectedVersion:o.latest,desktopAllowed:o.entitlements?.desktopAllowed??!0,mobileAllowed:o.entitlements?.mobileAllowed??!0}};n.start("Verifying access...");let p,h,g=!0,k=!0;try{({latestVersion:p,selectedVersion:h,desktopAllowed:g,mobileAllowed:k}=await a()),n.stop("Access verified."),Ue(i)}catch(v){if(n.stop("Access verification failed."),v instanceof M&&v.status===401){e.yes&&(E.cancel("Invalid API key. Cannot prompt in non-interactive mode."),process.exit(1)),E.log.warning("Invalid API key."),i=await kt(),s=he(i),n.start("Verifying access...");try{({latestVersion:p,selectedVersion:h,desktopAllowed:g,mobileAllowed:k}=await a()),n.stop("Access verified."),Ue(i)}catch(L){n.stop("Access verification failed."),E.cancel(L instanceof M&&L.status===401?"Invalid API key.":N(L)),process.exit(1)}}else E.cancel(N(v)),process.exit(1)}E.log.success(`Latest version: ${p}`),r.desktop===!0&&!g&&(E.cancel("The desktop app is available on the Pro plan and up. Upgrade your plan at generatesaas.com."),process.exit(1)),r.mobile===!0&&!k&&(E.cancel("The mobile app is available on the Pro plan and up. Upgrade your plan at generatesaas.com."),process.exit(1));let w;e.yes?w=dn({...r,...g?{}:{desktop:!1},...k?{}:{mobile:!1}}):w=await un(r,{desktopAllowed:g,mobileAllowed:k});let P;n.start("Activating license...");try{let v=e.demo&&w.baseUrl?await Pp(w.baseUrl):crypto.randomUUID(),L=()=>({frontend:gr,version:h,installId:v,projectName:w.projectName,options:wn(w)}),F;try{F=await yr(s,L())}catch(ve){let $=$t(ve);if(!$?.lastAllowedVersion||!o)throw ve;n.stop("License activation failed.");let W=ms(o,$.lastAllowedVersion);if(W.ok||(E.cancel(`${$.message} ${W.message}`),process.exit(1)),e.yes){let z=nr(o,$.lastAllowedVersion);E.cancel(`${$.message} Re-run ${z?`npx generatesaas@${z} init`:"init"} without --yes to continue with v${$.lastAllowedVersion} (the last version your license covers).`),process.exit(1)}let ke=await E.confirm({message:`Your update window has ended. Continue with v${$.lastAllowedVersion} (the last version your license covers)?`});(E.isCancel(ke)||!ke)&&(E.cancel("Setup cancelled."),process.exit(0)),h=$.lastAllowedVersion,n.start(`Activating license for v${h}...`),F=await yr(s,L())}P={token:F.token,keyHash:Fr(i),installId:F.installId??v},n.stop("License activated.")}catch(v){n.stop("License activation failed."),E.cancel(N(v)),process.exit(1)}let u=kp(w.projectDir);if(yp(u)&&bp(u).length>0)if(e.yes)E.log.info(`Directory ${u} is not empty. Merging (keeping existing files, overwriting conflicts).`);else{let L=await E.select({message:`Directory ${u} is not empty.`,options:[{value:"merge",label:"Merge",hint:"keep existing files, overwrite conflicts"},{value:"overwrite",label:"Overwrite",hint:"delete everything and start fresh"},{value:"cancel",label:"Cancel"}]});(E.isCancel(L)||L==="cancel")&&(E.cancel("Setup cancelled."),process.exit(0)),L==="overwrite"&&wp(u,{recursive:!0,force:!0})}let O={...w,projectDir:u,version:h,...e.demo?{docs:!1}:{}};n.start("Downloading template...");try{await jt(s,h,u),n.stop("Template downloaded.")}catch(v){n.stop("Download failed."),E.cancel(N(v)),process.exit(1)}n.start("Generating project files...");try{if(await Xt(O),!e.demo){let v=await mt(u);await l(vp(u,Ct),`${JSON.stringify(v,null," ")}
1741
1742
  `),await ts(u,u)}await is(u),await Qi(O,P),n.stop("Project files generated.")}catch(v){n.stop("Generation failed."),E.cancel(N(v)),process.exit(1)}!await ss(u)&&O.demo===!0&&(E.cancel("Lockfile regeneration failed on a demo build - refusing to ship a stale lockfile."),process.exit(1));let B=await os(u),oe=O.demo!==!0&&e.dbMigration!==!1,Oe=!1;oe&&B&&(await as(u),Oe=!0);let xe=B?await cs(u):!1;await ls(u),B&&await ps(u);let De=Re("docker"),Qe=ur(O).map(v=>v.key).filter(v=>!O.credentials?.[v]);ds(O,{pnpmInstalled:B,dockerAvailable:De,skippedCredentials:Qe,baselineMigrationMissing:oe&&!Oe,mcpWidgetsUnbuilt:O.ai&&!xe}),Qr(),E.log.info(Ep.dim(`Done in ${((performance.now()-t)/1e3).toFixed(1)}s`))}import{existsSync as sr}from"fs";import{readFile as vs}from"fs/promises";import{join as qe,resolve as Op}from"path";import*as b from"@clack/prompts";import C from"picocolors";import{mkdtemp as Ip,rm as Tp}from"fs/promises";import{tmpdir as Rp}from"os";import{join as _p}from"path";async function Hr(e,t,r,n,{olderRelease:i=!1}={}){let s=await Ip(_p(Rp(),"generatesaas-stage-"));try{await jt(e,t,s);let o=()=>Xt({...r,projectDir:s}),a=[];return i?a=await Qn(o):await o(),await Vr(s,n),a}finally{await Tp(s,{recursive:!0,force:!0})}}function fs(e){return e?"ON":"OFF"}var ft="packages/config/src/index.ts";function gs(e){let t=e.databaseProvider!==void 0&&e.databaseProvider!=="postgres",r=e.cacheProvider!==void 0&&e.cacheProvider!=="redis";return[...e.dockerServices??[]].filter(n=>!(n==="postgres"&&t)&&!(n==="redis"&&r)).sort()}function ys(e){return[...rt({databaseProvider:e.databaseProvider??"postgres",cacheProvider:e.cacheProvider??"redis",emailProvider:e.emailProvider??"smtp"})].sort()}var Yr=[{key:"errorTracking",severity:"warn",normalize:e=>{e.errorTracking===void 0||e.observability!==void 0||(e.observability=e.errorTracking==="none"?[]:[e.errorTracking])},preserved:()=>!0,describe:()=>"Retired option `errorTracking`: it is now `observability`, an array, because a project may run more than one provider at once. Your recorded choice was migrated across automatically."},{key:"companion",severity:"warn",normalize:e=>{e.companion===void 0||e.runner!==void 0||(e.runner=e.companion)},preserved:()=>!0,describe:()=>"Retired option `companion`: it was renamed to `runner`, and that lane has since been removed. Your recorded choice was migrated across automatically so the removal is reported under one name."},{key:"runner",severity:"warn",preserved:e=>e.runner!==!0,describe:()=>"Retired option `runner`: your project recorded the runner ON, and the paired-device lane is GONE - not moved to config, removed. This update deletes the pairing endpoint, the dispatch transport, the relay, the `/runner/*` routes and the Runners page from your project, so machines your users had paired are no longer reachable from it. Chat and automations keep running on your app's own AI backend (`config.ai`); nothing else about them changes."},{key:"companionSource",severity:"warn",preserved:()=>!1,describe:e=>`Retired option \`companionSource\`: your project recorded a \`${String(e.companionSource)}\` daemon source. The paired-device lane that daemon served has been removed from your project, so there is no daemon left to source.`},{key:"companionName",severity:"warn",preserved:()=>!1,describe:e=>`Retired option \`companionName\`: your project recorded a branded daemon called ${e.companionName}. The paired-device lane is gone, so your project no longer ships an install flow to brand. An existing install on a user's machine keeps running; it has nothing left to pair with here.`},{key:"companionRepoUrl",severity:"warn",preserved:()=>!1,describe:e=>`Retired option \`companionRepoUrl\`: your project pointed its install flow at ${e.companionRepoUrl}. The paired-device lane is gone, so there is no install flow left to point anywhere.`},{key:"companionLocalPath",severity:"warn",preserved:e=>(e.companionLocalPath??"").trim()==="",describe:e=>`Retired option \`companionLocalPath\`: your project recorded a local daemon checkout at ${e.companionLocalPath}. The option is gone, and so is the paired-device lane behind it - nothing in your project is built from a local daemon checkout any more.`},{key:"desktopAutoRelease",severity:"warn",applies:e=>e.desktop===!0,preserved:e=>e.desktopAutoRelease!==!0,describe:()=>"Retired option `desktopAutoRelease`: your project recorded automatic desktop releases, but the release trigger is no longer an option - cutting a release publishes signed installers from your repository and spends your Actions minutes, so it is always deliberate now. The staged `.github/workflows/desktop-release.yml` runs on `workflow_dispatch` only (the Actions tab). Add a `workflow_run` block to it if you want the CI-chained trigger back."},{key:"billingScope",severity:"ask",applies:e=>e.multiTenancy===!0,preserved:e=>e.billingScope!=="organization",describe:()=>"Retired option `billingScope`: your project recorded organization-scoped billing, and organization billing is GONE - not moved to config, removed. Money now lives only on a USER: an organization has no balance, no plan and no payment-provider customer of its own, and a workspace is funded by that organization's OWNER, whose personal balance every credit spent in it is drawn from. Payments already in flight are safe - a webhook arriving with old organization metadata is credited to that organization's owner rather than dropped - but a STORED balance is not: the `credits` and `plan` columns an organization holds them in are going away, and this update does NOT migrate them for you. MOVE every paying organization's credits and plan onto its owner BEFORE you take new checkouts, or that balance goes with the columns. How should this update proceed?"},{key:"socialProviders",severity:"warn",preserved:e=>(e.socialProviders??[]).length===0,describe:e=>`Retired option \`socialProviders\`: your project recorded ${(e.socialProviders??[]).join(", ")}, but it is now a plain config value that starts empty. Add those IDs back to \`config.auth.socialProviders\` in ${ft} or their sign-in buttons stop rendering.`},{key:"mcpServer",severity:"warn",preserved:e=>e.mcpServer!==!0||e.ai===!0,describe:()=>`Retired option \`mcpServer\`: your project recorded the outward MCP server ON, but its code now ships to every project behind a config gate generated OFF without AI. Set \`config.mcpServer.enabled\` to \`true\` in ${ft} to keep your /mcp endpoint and its settings tab.`},{key:"emailTracking",severity:"ask",preserved:e=>e.emailTracking!==!1,describe:()=>`Retired option \`emailTracking\`: your project recorded email open/click tracking OFF, but it is now a plain config value generated ON. Applying this update as-is starts tracking opens and clicks for every user you mail. Put it back by setting \`config.email.tracking.enabled\` to \`false\` in ${ft}. How should this update proceed?`},{key:"aiBuiltin",severity:"warn",normalize:e=>{e.aiBuiltin===void 0&&e.aiByok!==void 0&&(e.aiBuiltin=e.aiByok===!1)},applies:e=>e.ai===!0,preserved:e=>e.aiBuiltin===ne(e),describe:e=>`Retired option \`aiBuiltin\`: your project recorded built-in AI models ${fs(e.aiBuiltin)}, but it is now a plain config value generated ${fs(ne(e))} for a project ${ne(e)?"with":"without"} a payment provider. Set \`config.ai.builtin\` to \`${String(e.aiBuiltin===!0)}\` in ${ft} to keep your choice.`},{key:"aiByok",severity:"warn",applies:e=>e.ai===!0,preserved:e=>e.aiByok!==!1,describe:()=>`Retired option \`aiByok\`: your project recorded bring-your-own-key AI OFF, but it is now a plain config value generated ON. Set \`config.ai.byok\` to \`false\` in ${ft} to keep it off.`},{key:"dockerServices",severity:"warn",preserved:e=>gs(e).join(",")===ys(e).join(","),describe:e=>`Retired option \`dockerServices\`: your project recorded ${gs(e).join(", ")||"no services"}, but the local Docker services are now DERIVED from your stack - postgres when you self-host Postgres, redis when you self-host Redis, mailpit on SMTP, inngest always - so an inconsistent selection is no longer possible. Your regenerated \`infra/docker-compose.yml\` will contain ${ys(e).join(", ")}. Add any extra service back by hand; the file is yours to edit.`},{key:"aiTools",severity:"warn",preserved:e=>(e.aiTools??[]).length===rn.length,describe:e=>`Retired option \`aiTools\`: your project recorded ${(e.aiTools??[]).join(", ")||"no AI tools"}, but the \`generatesaas-update\` skill bundle now ships to every AI-tool root (${ze.join(", ")}) so it is there whichever assistant you switch to. Delete the roots you do not use - they are plain text files with no runtime path.`},{key:"blog",severity:"warn",preserved:e=>e.blog!==!1,describe:()=>`Retired option \`blog\`: your project recorded the blog OFF, but content is no longer an option. This update adds the \`/blog\`, \`/alternatives\` and \`/compare\` route code to your project; every one of them 404s until you add a file under \`packages/content/{locale}/{section}/\`, and none of them appears in your navbar, footer, sitemap or llms.txt while it is empty. Delete an entry from \`config.content.sections\` in ${ft} to drop a section for good.`}],rg=Yr.map(e=>e.key);function bs(e){for(let t of Yr)t.normalize?.(e)}function ws(e){let t=[];for(let r of Yr){if(r.normalize?.(e),e[r.key]===void 0)continue;(!r.applies||r.applies(e))&&!r.preserved(e)&&t.push({key:r.key,message:r.describe(e),severity:r.severity}),delete e[r.key]}return t}function ks(e){e.command("update").description("Update AI skill files and stage template updates").allowExcessArguments(!0).option("--cwd <path>","project directory (default: current directory)").option("--answer <id=choice>","answer a question that would otherwise prompt (repeatable), e.g. --answer desktop-migration=keep-ai",xp,[]).action(async(t,r)=>{r.args.length>0&&b.log.warn("`auto` is now the default and the argument is ignored.");let n=Dp(t.answer),i=Op(t.cwd??process.cwd()),s=qe(i,ue),o;try{o=JSON.parse(await vs(s,"utf-8"))}catch{b.cancel(".generatesaas/manifest.json not found. Run this from a GenerateSaaS project."),process.exit(1)}o.frontend===hr&&(b.cancel(`This project was generated on the Nuxt frontend (\`.generatesaas/manifest.json\` records \`frontend: "${hr}"\`).
1742
1743
 
1743
1744
  v${fr} is the last release that ships a Nuxt frontend, and this CLI cannot update or migrate a Nuxt project to Next.js.
@@ -1794,7 +1795,7 @@ ${k}`}).join(`
1794
1795
  `]},{file:"packages/api/src/routes/public/v1/health.ts",removals:[`import { manifest } from "../../../lib/manifest";
1795
1796
  `],replacements:[{from:'c.json({ status: "success" as const, version: manifest?.version })',to:'c.json({ status: "success" as const })'}]}];function td(){return[...ze,...Br].flatMap(e=>tr.map(t=>Xe(e,t)))}function zr(e){return or(e)?(Zp(e,{recursive:!0}),!0):!1}function rd(e,t,r=[]){if(!or(e))return!1;let n=Jr(e,"utf-8"),i=n;for(let s of t)i=i.replace(s,"");for(let{from:s,to:o}of r)i=i.replace(s,o);return i===n?!1:(Ds(e,i,"utf-8"),!0)}function nd(e){let t=Xe(e,".gitignore");if(!or(t))return!1;let r=Jr(t,"utf-8"),n=r.split(`
1796
1797
  `).filter(i=>!i.includes(".generatesaas")).join(`
1797
- `);return n===r?!1:(Ds(t,n,"utf-8"),!0)}function Ns(e){e.command("eject").description("Remove all GenerateSaaS ties - manifest, license, heartbeat, skills").action(async()=>{let t=process.cwd(),r=Xe(t,ue),n;try{n=JSON.parse(Jr(r,"utf-8"))}catch{U.cancel("No GenerateSaaS project found in this directory."),process.exit(1)}let i=await U.text({message:'Type "eject" to confirm (this cannot be undone):',validate:a=>{if(a!=="eject")return'Type "eject" to confirm, or press Ctrl+C to cancel.'}});if(U.isCancel(i)&&(U.cancel("Eject cancelled."),process.exit(0)),n.licenseToken)try{await fetch("https://generatesaas.com/api/v1/heartbeat",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n.licenseToken}`},body:JSON.stringify({event:"eject",version:n.version,frontend:n.frontend}),signal:AbortSignal.timeout(5e3)}),U.log.info("Recorded the opt-out with generatesaas.com (final event - nothing is sent after this).")}catch{U.log.warn("Could not reach generatesaas.com to record the opt-out. Ejecting anyway.")}let s=[],o=[];for(let a of td())zr(Xe(t,a))&&s.push(a);for(let a of Qp)zr(Xe(t,a))&&s.push(a);zr(Xe(t,J))&&s.push(`${J}/`);for(let a of ed){let p=Xe(t,a.file);rd(p,a.removals,a.replacements)?o.push(a.file):or(p)&&U.log.warn(`Could not auto-modify ${a.file} - manually remove license/heartbeat references.`)}nd(t)&&o.push(".gitignore");for(let a of s)U.log.info(`Deleted ${a}`);for(let a of o)U.log.info(`Modified ${a}`);U.log.success("Ejected successfully. This project is now fully standalone.")})}var Ze=new id().name("generatesaas").description("CLI for scaffolding and managing GenerateSaaS projects").version("3.41.0").addHelpText("after",`
1798
+ `);return n===r?!1:(Ds(t,n,"utf-8"),!0)}function Ns(e){e.command("eject").description("Remove all GenerateSaaS ties - manifest, license, heartbeat, skills").action(async()=>{let t=process.cwd(),r=Xe(t,ue),n;try{n=JSON.parse(Jr(r,"utf-8"))}catch{U.cancel("No GenerateSaaS project found in this directory."),process.exit(1)}let i=await U.text({message:'Type "eject" to confirm (this cannot be undone):',validate:a=>{if(a!=="eject")return'Type "eject" to confirm, or press Ctrl+C to cancel.'}});if(U.isCancel(i)&&(U.cancel("Eject cancelled."),process.exit(0)),n.licenseToken)try{await fetch("https://generatesaas.com/api/v1/heartbeat",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n.licenseToken}`},body:JSON.stringify({event:"eject",version:n.version,frontend:n.frontend}),signal:AbortSignal.timeout(5e3)}),U.log.info("Recorded the opt-out with generatesaas.com (final event - nothing is sent after this).")}catch{U.log.warn("Could not reach generatesaas.com to record the opt-out. Ejecting anyway.")}let s=[],o=[];for(let a of td())zr(Xe(t,a))&&s.push(a);for(let a of Qp)zr(Xe(t,a))&&s.push(a);zr(Xe(t,J))&&s.push(`${J}/`);for(let a of ed){let p=Xe(t,a.file);rd(p,a.removals,a.replacements)?o.push(a.file):or(p)&&U.log.warn(`Could not auto-modify ${a.file} - manually remove license/heartbeat references.`)}nd(t)&&o.push(".gitignore");for(let a of s)U.log.info(`Deleted ${a}`);for(let a of o)U.log.info(`Modified ${a}`);U.log.success("Ejected successfully. This project is now fully standalone.")})}var Ze=new id().name("generatesaas").description("CLI for scaffolding and managing GenerateSaaS projects").version("3.42.0").addHelpText("after",`
1798
1799
  Examples:
1799
1800
  $ generatesaas init Interactive setup
1800
1801
  $ generatesaas init -n my-app -y Quick setup with defaults
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "generatesaas",
3
- "version": "3.41.0",
3
+ "version": "3.42.0",
4
4
  "type": "module",
5
5
  "description": "CLI for scaffolding and managing GenerateSaaS projects",
6
6
  "license": "UNLICENSED",