generatesaas 3.39.0 → 3.41.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.
@@ -46,6 +46,7 @@ costly mistake made in this repo.
46
46
  - TypeScript strict - no `any`, no `as any` / `as unknown as`.
47
47
  - JSDoc on exported functions/utilities; no inline comments unless asked.
48
48
  - Prefer the shipped libs (Better Auth, Drizzle, Hono) over hand-rolling.
49
+ - **Screen = widget.** A new feature ships as AI capability tools first (`packages/api/src/ai/capabilities/`), with a kit widget (`defineKitCapability`) where widgets are on. Its dashboard screen, if it has one, reads the same service the tools call, and the capability test is its behaviour test.
49
50
 
50
51
  ## Tests
51
52
 
@@ -58,7 +59,7 @@ costly mistake made in this repo.
58
59
  - Read `@repo/config` for expectations instead of hardcoding values, so a config change moves the test with it.
59
60
  - No `skip` / `skipIf` / `only`: a case that does not apply to this build is not registered (`if (flag) { describe(...) }`).
60
61
  - Every new test must catch a real regression. One behavior test beats five that pin implementation details.
61
- - A new AI tool is tested once, through its capability's result. The API suite already holds every tool to what an MCP client needs (sign-in, listing, approvals, error shapes, Claude Code's 2,048-character cap on descriptions, a refresh entry for a write) - do not test it again over MCP.
62
+ - A new AI tool is tested once, through its capability's result. The API suite already holds every tool to what an MCP client needs (sign-in, listing, error shapes, Claude Code's 2,048-character cap on descriptions, a refresh entry for a write) - do not test it again over MCP.
62
63
 
63
64
  ## Don't modify
64
65
 
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). 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, 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(`
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.39.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.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," ")}
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," ")}
@@ -375,9 +375,11 @@ ${h}
375
375
  cap: 20,
376
376
  apiKeyCap: 20
377
377
  },
378
- // \`/chat\` page presentation. \`suggestions\` are prompt-starter chips shown on the empty chat;
379
- // empty by default (starters are product copy you write for your users).
378
+ // The in-app chat. Set enabled: false to hide it on web, desktop and mobile; the MCP server,
379
+ // automations and the desktop terminal stay. \`suggestions\` are prompt-starter chips shown on the
380
+ // empty chat; empty by default (starters are product copy you write for your users).
380
381
  chat: {
382
+ enabled: true,
381
383
  suggestions: []
382
384
  },
383
385
  // Your users can connect ANY HTTP API or MCP server out of the box, through the two built-in
@@ -390,8 +392,9 @@ ${h}
390
392
  desktop: desktopConfig,
391
393
  mobile: mobileConfig,
392
394
  // Outward MCP server exposing the capability layer to external agents. Its code ships with every
393
- // project, so \`enabled\` alone controls the /mcp endpoint and the MCP settings tab.${e.ai?"\n // `apps` serves the interactive widgets (MCP Apps) Claude or ChatGPT render for a tool that\n // links one; set it false to keep the tool list free of widget metadata.":""}
394
- mcpServer: { enabled: ${e.demo?"true":"false"}${e.ai?", apps: true":""} },
395
+ // project, so \`enabled\` alone controls the /mcp endpoint and the MCP settings tab. On with AI, so
396
+ // people can connect Claude or ChatGPT to the app from day one.${e.ai?"\n // `apps` serves the interactive widgets (MCP Apps) Claude or ChatGPT render for a tool that\n // links one; set it false to keep the tool list free of widget metadata.":""}
397
+ mcpServer: { enabled: ${e.demo||e.ai?"true":"false"}${e.ai?", apps: true":""} },
395
398
  // Revenue sharing: your answer at init, and yours to change here at any time. On, the daily
396
399
  // license heartbeat self-reports an aggregate revenue estimate (MRR, ARR, total and 30-day
397
400
  // revenue, active subscriptions). No customer data, but not anonymous either: the figures travel
@@ -454,6 +457,7 @@ export * from "./billing-fields";
454
457
  export * from "./social-providers";
455
458
  export * from "./blog";
456
459
  export * from "./cache";
460
+ export * from "./chat";
457
461
  export * from "./content";
458
462
  export * from "./credit-price";
459
463
  export * from "./feedback";
@@ -797,7 +801,7 @@ ${k},
797
801
  };
798
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).
799
803
  # Set but EMPTY switches every server-side PostHog report off (the e2e harness does this). Leave it
800
- # 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="),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(`
804
+ # 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(`
801
805
  `)}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(`
802
806
  `)}function Xo(e){let{apiUrl:t,baseUrl:r}=Rr(e),n=["# Expo reads env from THIS directory, never the monorepo root.","# Every EXPO_PUBLIC_* value is inlined into the app bundle - never put a secret here.","# Android emulator: replace localhost with 10.0.2.2; a physical device needs your machine's LAN IP","# EXPO_PUBLIC_API_URL is the value to fill first - without it the app throws at launch and names it.",`EXPO_PUBLIC_API_URL=${t}`,`EXPO_PUBLIC_WEB_URL=${r}`,"","# Native Google sign-in (optional)","#EXPO_PUBLIC_GOOGLE_WEB_CLIENT_ID=","#EXPO_PUBLIC_GOOGLE_IOS_CLIENT_ID="];e.mobilePurchases==="revenuecat"&&n.push("","# RevenueCat public SDK keys (optional until you create your products)","#EXPO_PUBLIC_REVENUECAT_IOS_KEY=","#EXPO_PUBLIC_REVENUECAT_ANDROID_KEY=");let i=[];return e.observability.includes("sentry")&&i.push("#EXPO_PUBLIC_SENTRY_DSN="),e.observability.includes("posthog")&&i.push("#EXPO_PUBLIC_POSTHOG_KEY="),i.length>0&&n.push("","# Observability (optional)",...i),n.push(""),n.join(`
803
807
  `)}async function Vn(e){let t=qo(e);if(await l(`${e.projectDir}/.env`,`${t}
@@ -1196,7 +1200,7 @@ export async function withMutex<T>(
1196
1200
  * \`generatesaas update\`: re-shaping brings that provider's half of this file, its SDK and its env
1197
1201
  * key back. Pasting the other provider's credential into \`config.observability\` on its own cannot -
1198
1202
  * the start it would need is not here.`}async function ni(e){if(!e.mobile)return;let t=e.projectDir,r=["sentry","posthog"].filter(s=>!e.observability.includes(s));e.observability.length===0&&await ga(He(t,ri),{force:!0});let n=e.observability.length===0?ti:[...ti,ri];for(let s of r)for(let o of n){let a=He(t,o);await l(a,Ge(await Cr(a,"utf-8"),o,`mobile-obs-${s}`,Ye))}if(e.observability.length===0)for(let s of ba){let o=He(t,s);await l(o,Ge(await Cr(o,"utf-8"),s,ya,Ye))}if(r.includes("sentry")){for(let s of va){let o=He(t,s);await l(o,Ge(await Cr(o,"utf-8"),s,"mobile-obs-sentry",Ye))}await A(He(t,"apps/mobile/app.config.ts"),wa,"","app.config.ts Sentry Expo plugin",Ye),await A(He(t,"apps/mobile/jest.config.js"),ka,"","jest.config.js Sentry transform allowance",Ye)}let i=He(t,"apps/mobile/lib/observability.ts");await A(i,Ea,Aa(e.observability),"lib/observability.ts dual-provider note",Ye),e.observability.length===0&&(await A(i,Sa,Pa,"lib/observability.ts privacy import",Ye),await ei(i))}var dt={"@upstash/redis":"^1.37.0","@upstash/lock":"^0.2.1","@neondatabase/serverless":"^1.0.1",postgres:"^3.4.7"};async function ie(e){let t=await ii(e,"utf-8");return JSON.parse(t)}async function se(e,t){let r=/\n([\t ]+)"/.exec(await ii(e,"utf-8"))?.[1]??" ";await l(e,`${JSON.stringify(t,null,r)}
1199
- `)}function X(e,t){for(let r of t)delete e.dependencies?.[r],delete e.devDependencies?.[r]}function Ta(e){e.dependencies&&Object.keys(e.dependencies).length===0&&delete e.dependencies,e.devDependencies&&Object.keys(e.devDependencies).length===0&&delete e.devDependencies}function We(e,t,r,n=!1){let i=n?"devDependencies":"dependencies";e[i]||(e[i]={}),e[i][t]=r}async function si(e){await _a(e),await Oa(e),await xa(e),await La(e),await $a(e),await Ka(e),await Ra(e)}async function Ra(e){if(!e.mobile){let t=j(e.projectDir,"packages/auth/package.json"),r=await ie(t);X(r,["@better-auth/expo"]),await se(t,r);let n=j(e.projectDir,"tooling/styles/package.json"),i=await ie(n);X(i,["tsx"]),Ta(i),await se(n,i)}if(e.mobile&&e.mobilePurchases!=="revenuecat"){let t=j(e.projectDir,"apps/mobile/package.json"),r=await ie(t);X(r,["react-native-purchases","react-native-purchases-ui"]),await se(t,r)}}async function _a(e){let t=j(e.projectDir,"packages/api/package.json"),r=await ie(t);X(r,["sharp","@types/sharp"]),e.cacheProvider==="upstash"&&(X(r,["ioredis"]),We(r,"@upstash/redis",dt["@upstash/redis"],!0),We(r,"@upstash/lock",dt["@upstash/lock"],!0)),await se(t,r)}async function Oa(e){let t=j(e.projectDir,"apps/web/package.json"),r=await ie(t);X(r,["@upstash/ratelimit","@upstash/redis"]),await se(t,r)}async function xa(e){let t=j(e.projectDir,"packages/runtime/package.json"),r=await ie(t);e.cacheProvider==="upstash"&&(X(r,["ioredis","rate-limit-redis","redis-semaphore"]),We(r,"@upstash/redis",dt["@upstash/redis"]),We(r,"@upstash/lock",dt["@upstash/lock"])),await se(t,r)}var Lr={sentry:["@sentry/node","@sentry/browser","@sentry/electron"],posthog:["posthog-node","posthog-js"]},Da=["@sentry/electron"],Na=[...Lr.sentry,...Lr.posthog],Ca=[...Ht.sentry,...Ht.posthog];async function La(e){let t=j(e.projectDir,"packages/observability/package.json"),r=await ie(t),n=new Set(e.observability.flatMap(a=>Lr[a]));if(!e.desktop)for(let a of Da)n.delete(a);if(X(r,Na.filter(a=>!n.has(a))),await se(t,r),!e.mobile)return;let i=j(e.projectDir,"apps/mobile/package.json"),s=await ie(i),o=new Set(e.observability.flatMap(a=>Ht[a]));X(s,Ca.filter(a=>!o.has(a))),await se(i,s)}async function $a(e){let t=j(e.projectDir,"packages/database/package.json"),r=await ie(t);e.databaseProvider==="neon"?(X(r,["pg","@types/pg"]),We(r,"@neondatabase/serverless",dt["@neondatabase/serverless"])):e.databaseProvider==="supabase"&&(X(r,["pg","@types/pg"]),We(r,"postgres",dt.postgres)),await se(t,r)}var ja=["app/.well-known/oauth-authorization-server/[[...path]]/route.ts","app/.well-known/oauth-protected-resource/[[...path]]/route.ts","app/.well-known/ai-catalog.json/route.ts"],Ma="app/.well-known/api-catalog/route.ts",Ua=`import { agentsConfig } from "@repo/config";
1203
+ `)}function X(e,t){for(let r of t)delete e.dependencies?.[r],delete e.devDependencies?.[r]}function Ta(e){e.dependencies&&Object.keys(e.dependencies).length===0&&delete e.dependencies,e.devDependencies&&Object.keys(e.devDependencies).length===0&&delete e.devDependencies}function We(e,t,r,n=!1){let i=n?"devDependencies":"dependencies";e[i]||(e[i]={}),e[i][t]=r}async function si(e){await _a(e),await Oa(e),await xa(e),await La(e),await $a(e),await Ka(e),await Ra(e)}async function Ra(e){if(!e.mobile){let t=j(e.projectDir,"packages/auth/package.json"),r=await ie(t);X(r,["@better-auth/expo"]),await se(t,r);let n=j(e.projectDir,"tooling/styles/package.json"),i=await ie(n);X(i,["tsx"]),Ta(i),await se(n,i)}if(e.mobile&&e.mobilePurchases!=="revenuecat"){let t=j(e.projectDir,"apps/mobile/package.json"),r=await ie(t);X(r,["react-native-purchases","react-native-purchases-ui"]),await se(t,r)}}async function _a(e){let t=j(e.projectDir,"packages/api/package.json"),r=await ie(t);X(r,["sharp","@types/sharp"]),e.cacheProvider==="upstash"&&(X(r,["ioredis"]),We(r,"@upstash/redis",dt["@upstash/redis"],!0),We(r,"@upstash/lock",dt["@upstash/lock"],!0)),await se(t,r)}async function Oa(e){let t=j(e.projectDir,"apps/web/package.json"),r=await ie(t);X(r,["@upstash/ratelimit","@upstash/redis"]),await se(t,r)}async function xa(e){let t=j(e.projectDir,"packages/runtime/package.json"),r=await ie(t);e.cacheProvider==="upstash"&&(X(r,["ioredis","rate-limit-redis","redis-semaphore"]),We(r,"@upstash/redis",dt["@upstash/redis"]),We(r,"@upstash/lock",dt["@upstash/lock"])),await se(t,r)}var Lr={sentry:["@sentry/node","@sentry/browser","@sentry/electron"],posthog:["posthog-node","posthog-js"]},Da=["@sentry/electron"],Na=[...Lr.sentry,...Lr.posthog],Ca=[...Ht.sentry,...Ht.posthog];async function La(e){let t=j(e.projectDir,"packages/observability/package.json"),r=await ie(t),n=new Set(e.observability.flatMap(a=>Lr[a]));if(!e.desktop)for(let a of Da)n.delete(a);if(X(r,Na.filter(a=>!n.has(a))),await se(t,r),!e.mobile)return;let i=j(e.projectDir,"apps/mobile/package.json"),s=await ie(i),o=new Set(e.observability.flatMap(a=>Ht[a]));X(s,Ca.filter(a=>!o.has(a))),await se(i,s)}async function $a(e){let t=j(e.projectDir,"packages/database/package.json"),r=await ie(t);e.databaseProvider==="neon"?(X(r,["pg","@types/pg"]),We(r,"@neondatabase/serverless",dt["@neondatabase/serverless"])):e.databaseProvider==="supabase"&&(X(r,["pg","@types/pg"]),We(r,"postgres",dt.postgres)),await se(t,r)}var ja=["app/.well-known/oauth-authorization-server/[[...path]]/route.ts","app/.well-known/oauth-protected-resource/[[...path]]/route.ts","app/.well-known/ai-catalog.json/route.ts","app/.well-known/openai-apps-challenge/route.ts"],Ma="app/.well-known/api-catalog/route.ts",Ua=`import { agentsConfig } from "@repo/config";
1200
1204
 
1201
1205
  /**
1202
1206
  * RFC 9727 API catalog. A client resolves \`/.well-known/*\` against the SITE ROOT; in this
@@ -1400,8 +1404,8 @@ vi.mock("@upstash/lock", () => {
1400
1404
  `)],fc=["apps/web/app/[locale]/(marketing)/download","apps/web/tests/routes/download-page.test.tsx"],gc=["cli","cli:clean","demo:bench","playground:regen","playground:test","playground:test:repo","playground:test:audit","playground:test:units","playground:test:e2e","playground:test:build","playground:test:mobile","check-types:scripts","ai:parity"];async function hi(e){let t=m(e.projectDir,".github/workflows"),r=await ut(t).catch(()=>[]);for(let n of r)nc.has(n)||await Ie(m(t,n),{recursive:!0,force:!0})}async function yc(e,t){let r=m(e,"package.json"),n=JSON.parse(await ge(r,"utf-8"));if(!n.scripts)return;let i=!1;for(let o of t)o in n.scripts&&(delete n.scripts[o],i=!0);if(!i)return;let s=/\n([\t ]+)"/.exec(await ge(r,"utf-8"))?.[1]??" ";await l(r,`${JSON.stringify(n,null,s)}
1401
1405
  `)}async function fi(e){await yc(e.projectDir,[...gc])}async function gi(e){let t=m(e.projectDir,"package.json"),r=await ge(t,"utf-8"),n=JSON.parse(r);!n.scripts||!("dev"in n.scripts)||(n.scripts.dev=e.architecture==="separate"?"turbo run dev --continue":"turbo run dev --continue --filter=!backend",await l(t,`${JSON.stringify(n,null," ")}
1402
1406
  `))}async function yi(e){let t=m(e.projectDir,"package.json"),r=JSON.parse(await ge(t,"utf-8")),n=r.scripts?.test;if(n!=="turbo run test --concurrency=2 && vitest run")throw new Error(`rewriteRootTestScript: expected the root test script to be "turbo run test --concurrency=2 && vitest run", got ${JSON.stringify(n)} (boilerplate drift).`);r.scripts.test="turbo run test --concurrency=2",await l(t,`${JSON.stringify(r,null," ")}
1403
- `)}async function bi(e){e.docs||await S(e.projectDir,"apps/docs","stripDocsApp")}async function wi(e){let t=m(e.projectDir,"docs/(platform)/meta.json"),r=JSON.parse(await ge(t,"utf-8"));if(r.title!=="GenerateSaaS")throw new Error(`stripUnusedDocsSilo: expected the feature-page group to be titled "GenerateSaaS", found ${JSON.stringify(r.title)} (boilerplate drift).`);r.title=e.appName,await Ke(t,r," ","stripUnusedDocsSilo"),e.desktop||await Ie(m(e.projectDir,"docs/desktop"),{recursive:!0,force:!0}),e.mobile||await Ie(m(e.projectDir,"docs/mobile"),{recursive:!0,force:!0}),await bc(e),await Sc(e)}async function V(e,t,r,n){let i=await Kt(e,t,n);i!==null&&await l(e,Ge(i,t,r,n))}async function bc(e){let t=e.projectDir,r="stripUnusedDocsSilo",n=m(t,"docs/(platform)/configuration.mdx"),i=e.desktop;e.desktop||(await A(n,"| Desktop app + device sign-in - see [desktop app](/desktop) |","| Desktop app + device sign-in |","configuration.mdx desktop config-table link",r),await V(n,"configuration.mdx desktop TRUSTED_ORIGINS callout","desktop-origins-docs",r),await A(m(t,"docs/cli/init.mdx"),"the [desktop app](/desktop), AI features","the desktop app, AI features","cli init.mdx desktop app link",r),await V(m(t,"docs/(platform)/payments/organizations.mdx"),"payments organizations.mdx desktop tenancy callout","desktop-tenancy-docs",r),await V(m(t,"docs/(platform)/projects.mdx"),"projects.mdx desktop scoping callout","desktop-projects-docs",r),await V(m(t,"docs/(platform)/client-architecture.mdx"),"client-architecture.mdx desktop card","desktop-architecture-docs",r),await V(m(t,"docs/(platform)/screens.mdx"),"screens.mdx desktop halves","screens-desktop-docs",r),await V(m(t,"docs/(platform)/testing/e2e.mdx"),"testing/e2e.mdx desktop e2e callout","desktop-testing-docs",r),await A(m(t,"docs/(platform)/index.mdx"),` <Card href="/desktop" title="Desktop app" description="Cross-platform desktop app with device sign-in and AI agents." />
1404
- `,"","index.mdx desktop app card",r),await V(m(t,"docs/(platform)/ai.mdx"),"ai.mdx automation lanes row + section","desktop-lanes-docs",r),await A(m(t,"docs/(platform)/ai.mdx"),"| Creating or changing an automation on the user's computer (desktop) | `create_local_automation`, an `update_local_automation` beyond a rename or a pause, `delete_local_automation` ([how](/desktop/ai#what-runs-and-where)) | No |\n","","ai.mdx device-automation approval row",r)),i||(await V(n,"configuration.mdx desktop-AI paragraph","desktop-ai-docs",r),await A(m(t,"docs/(platform)/navigation.mdx"),"gates the desktop app's Chat and Automations, see [desktop AI](/desktop/ai) |","gates the desktop app's Chat and Automations |","navigation.mdx sidebar-flag agents-row link",r))}async function vi(e){if(e.desktop)return;await S(e.projectDir,"apps/desktop","stripDesktopApp");let t=m(e.projectDir,"packages/i18n/translations");for(let i of await ut(t,{withFileTypes:!0}))i.isDirectory()&&await Ie(m(t,i.name,"desktop.json"),{force:!0});await S(e.projectDir,".github/workflows/desktop-release.yml","stripDesktopApp");for(let i of fc)await S(e.projectDir,i,"stripDesktopApp");await S(e.projectDir,"packages/utils/src/desktop-download.ts","stripDesktopApp"),await S(e.projectDir,"packages/utils/tests/desktop-download.test.ts","stripDesktopApp");let r=m(e.projectDir,"packages/utils/package.json"),n=JSON.parse(await ge(r,"utf-8"));if(!n.exports?.["./desktop-download"])throw new Error("stripDesktopApp: expected packages/utils/package.json to carry the ./desktop-download export");delete n.exports["./desktop-download"],await Ke(r,n," ","stripDesktopApp")}function wc(e){return e.desktop}async function ki(e){wc(e)||await S(e.projectDir,"packages/agent-core","stripDesktopAiRuntimePackages")}var vc=["packages/mcp-widgets","packages/api/src/ai/mcp-apps","packages/api/src/routes/internal/ai/widgets-router.ts","packages/api/tests/routes/mcp-apps.test.ts","packages/api/tests/ai/organization-widgets.test.ts","packages/api/tests/routes/widgets-router.test.ts","packages/app-core/src/mcp-app","packages/app-core/src/test-support/mcp-fake-host.ts","packages/app-core/tests/mcp-app","packages/ui/src/components/mcp-widgets","packages/ui/src/lib/mcp-widgets","packages/ui/src/components/ai/tool-widget.tsx","packages/ui/src/components/ai/tool-widget.test.tsx","packages/ui/src/components/ai/tool-widget-split.test.tsx","docs/(platform)/mcp-widgets.mdx"],$r="gsaas:mcp-apps-start";async function kc(e){let t=[];for(let r of await ut(m(e,"packages"),{withFileTypes:!0}))if(r.isDirectory())for(let n of["src","tests"]){let i=m(e,"packages",r.name,n);if(!rc(i))continue;let s=await q(i,i,o=>o.split("/").includes("node_modules"),o=>/\.(?:ts|tsx)$/.test(o));for(let o of s)(await ge(o,"utf-8")).includes($r)&&t.push(o)}return t.sort()}async function Ei(e){if(e.ai)return;let t="stripMcpApps",r=e.projectDir;for(let s of vc)await S(r,s,"stripMcpApps");let n=await kc(r);n.length===0&&pt(t,`${$r} regions`,`${t}: expected ${$r} regions under packages/<name>/src or tests, but found none (boilerplate drift).`);for(let s of n)await Tt(s,s,"mcp-apps",t);let i=m(r,"packages/i18n/translations");await S(r,"packages/i18n/translations/en/mcp-widgets.json","stripMcpApps");for(let s of await ut(i,{withFileTypes:!0}))s.isDirectory()&&await Ie(m(i,s.name,"mcp-widgets.json"),{force:!0});await A(m(r,"docs/(platform)/meta.json"),` "mcp-widgets",
1407
+ `)}async function bi(e){e.docs||await S(e.projectDir,"apps/docs","stripDocsApp")}async function wi(e){let t=m(e.projectDir,"docs/(platform)/meta.json"),r=JSON.parse(await ge(t,"utf-8"));if(r.title!=="GenerateSaaS")throw new Error(`stripUnusedDocsSilo: expected the feature-page group to be titled "GenerateSaaS", found ${JSON.stringify(r.title)} (boilerplate drift).`);r.title=e.appName,await Ke(t,r," ","stripUnusedDocsSilo"),e.desktop||await Ie(m(e.projectDir,"docs/desktop"),{recursive:!0,force:!0}),e.mobile||await Ie(m(e.projectDir,"docs/mobile"),{recursive:!0,force:!0}),await bc(e),await Sc(e)}async function V(e,t,r,n){let i=await Kt(e,t,n);i!==null&&await l(e,Ge(i,t,r,n))}async function bc(e){let t=e.projectDir,r="stripUnusedDocsSilo",n=m(t,"docs/(platform)/configuration.mdx"),i=e.desktop;e.desktop||(await A(n,"| Desktop app + device sign-in - see [desktop app](/desktop) |","| Desktop app + device sign-in |","configuration.mdx desktop config-table link",r),await V(n,"configuration.mdx desktop TRUSTED_ORIGINS callout","desktop-origins-docs",r),await A(m(t,"docs/cli/init.mdx"),"the [desktop app](/desktop), AI features","the desktop app, AI features","cli init.mdx desktop app link",r),await V(m(t,"docs/(platform)/payments/organizations.mdx"),"payments organizations.mdx desktop tenancy callout","desktop-tenancy-docs",r),await V(m(t,"docs/(platform)/projects/index.mdx"),"projects/index.mdx desktop scoping callout","desktop-projects-docs",r),await V(m(t,"docs/(platform)/client-architecture.mdx"),"client-architecture.mdx desktop card","desktop-architecture-docs",r),await V(m(t,"docs/(platform)/screens.mdx"),"screens.mdx desktop halves","screens-desktop-docs",r),await V(m(t,"docs/(platform)/testing/e2e.mdx"),"testing/e2e.mdx desktop e2e callout","desktop-testing-docs",r),await A(m(t,"docs/(platform)/index.mdx"),` <Card href="/desktop" title="Desktop app" description="Cross-platform desktop app with device sign-in and AI agents." />
1408
+ `,"","index.mdx desktop app card",r),await V(m(t,"docs/(platform)/ai.mdx"),"ai.mdx automation lanes row + section","desktop-lanes-docs",r),await A(m(t,"docs/(platform)/ai.mdx"),"| Deleting an automation on the user's computer (desktop) | `delete_local_automation` ([how](/desktop/ai#what-runs-and-where)) |\n","","ai.mdx device-automation confirm row",r)),i||(await V(n,"configuration.mdx desktop-AI paragraph","desktop-ai-docs",r),await A(m(t,"docs/(platform)/navigation.mdx"),"gates the desktop app's Chat and Automations, see [desktop AI](/desktop/ai) |","gates the desktop app's Chat and Automations |","navigation.mdx sidebar-flag agents-row link",r))}async function vi(e){if(e.desktop)return;await S(e.projectDir,"apps/desktop","stripDesktopApp");let t=m(e.projectDir,"packages/i18n/translations");for(let i of await ut(t,{withFileTypes:!0}))i.isDirectory()&&await Ie(m(t,i.name,"desktop.json"),{force:!0});await S(e.projectDir,".github/workflows/desktop-release.yml","stripDesktopApp");for(let i of fc)await S(e.projectDir,i,"stripDesktopApp");await S(e.projectDir,"packages/utils/src/desktop-download.ts","stripDesktopApp"),await S(e.projectDir,"packages/utils/tests/desktop-download.test.ts","stripDesktopApp");let r=m(e.projectDir,"packages/utils/package.json"),n=JSON.parse(await ge(r,"utf-8"));if(!n.exports?.["./desktop-download"])throw new Error("stripDesktopApp: expected packages/utils/package.json to carry the ./desktop-download export");delete n.exports["./desktop-download"],await Ke(r,n," ","stripDesktopApp")}function wc(e){return e.desktop}async function ki(e){wc(e)||await S(e.projectDir,"packages/agent-core","stripDesktopAiRuntimePackages")}var vc=["packages/mcp-widgets","packages/api/src/ai/mcp-apps","packages/api/src/routes/internal/ai/widgets-router.ts","packages/api/tests/routes/mcp-apps.test.ts","packages/api/tests/ai/organization-widgets.test.ts","packages/api/tests/routes/widgets-router.test.ts","packages/app-core/src/mcp-app","packages/app-core/src/test-support/mcp-fake-host.ts","packages/app-core/tests/mcp-app","packages/ui/src/components/mcp-widgets","packages/ui/src/lib/mcp-widgets","packages/ui/src/components/ai/tool-widget.tsx","packages/ui/src/components/ai/tool-widget.test.tsx","packages/ui/src/components/ai/tool-widget-split.test.tsx","docs/(platform)/mcp-widgets"],$r="gsaas:mcp-apps-start";async function kc(e){let t=[];for(let r of await ut(m(e,"packages"),{withFileTypes:!0}))if(r.isDirectory())for(let n of["src","tests"]){let i=m(e,"packages",r.name,n);if(!rc(i))continue;let s=await q(i,i,o=>o.split("/").includes("node_modules"),o=>/\.(?:ts|tsx)$/.test(o));for(let o of s)(await ge(o,"utf-8")).includes($r)&&t.push(o)}return t.sort()}async function Ei(e){if(e.ai)return;let t="stripMcpApps",r=e.projectDir;for(let s of vc)await S(r,s,"stripMcpApps");let n=await kc(r);n.length===0&&pt(t,`${$r} regions`,`${t}: expected ${$r} regions under packages/<name>/src or tests, but found none (boilerplate drift).`);for(let s of n)await Tt(s,s,"mcp-apps",t);let i=m(r,"packages/i18n/translations");await S(r,"packages/i18n/translations/en/mcp-widgets.json","stripMcpApps");for(let s of await ut(i,{withFileTypes:!0}))s.isDirectory()&&await Ie(m(i,s.name,"mcp-widgets.json"),{force:!0});await A(m(r,"docs/(platform)/meta.json"),` "mcp-widgets",
1405
1409
  `,"","platform meta.json mcp-widgets entry",t),await V(m(r,"docs/(platform)/external-agent-mcp.mdx"),"external-agent-mcp.mdx widgets paragraph","mcp-apps-docs",t),await V(m(r,"docs/(platform)/ai.mdx"),"ai.mdx widgets under tool rows section","mcp-apps-docs",t)}async function Ec(e,t,r,n){let i=await ut(e);for(let s of t){let o=i.filter(a=>a.startsWith(s));if(o.length===0)throw new Error(`${n}: expected ${r} to hold at least one ${s}* entry`);for(let a of o)await Ie(m(e,a),{recursive:!0})}}async function Tt(e,t,r,n){let i=await Kt(e,t,n);i!==null&&await l(e,Ge(i,t,r,n))}async function Sc(e){let t=e.projectDir,r="stripUnusedDocsSilo",n=e.mobile&&e.mobilePurchases==="revenuecat";e.mobile||(await A(m(t,"docs/(platform)/index.mdx"),` <Card href="/mobile" title="Mobile app" description="Cross-platform iOS and Android app with push, universal links, and store billing." />
1406
1410
  `,"","index.mdx mobile app card",r),await A(m(t,"docs/(platform)/configuration.mdx")," - see [mobile app](/mobile)","","configuration.mdx mobile config-table link",r),await A(m(t,"docs/(platform)/client-architecture.mdx"),` <Card href="/mobile" title="Mobile app">The Expo app - the third surface this client core serves.</Card>
1407
1411
  `,"","client-architecture.mdx mobile app card",r),await A(m(t,"docs/cli/init.mdx"),"The [mobile app](/mobile) (`apps/mobile`, built with Expo)","The mobile app (`apps/mobile`, built with Expo)","cli init.mdx mobile app link",r),await A(m(t,"docs/(platform)/notifications.mdx"),"- **On a phone too.** With the [mobile app](/mobile) shipped and `config.mobile.push.enabled` on, the same notification is delivered to the user's registered devices as a push - see [mobile notifications](/mobile/notifications).\n\n","","notifications.mdx mobile push bullet",r),await A(m(t,"docs/(platform)/authentication/social-oauth.mdx")," - the native flow adds `APPLE_APP_BUNDLE_IDENTIFIER`; without `APPLE_CLIENT_ID` it runs native-only (no web button), see [mobile auth](/mobile/auth) |"," |","social-oauth.mdx Apple native-flow tail",r),await A(m(t,"docs/(platform)/authentication/two-factor-and-passkeys.mdx"),"- **On the [mobile app](/mobile/auth)**, passkeys use the platform's own biometrics and are claimed by the same `.well-known` association files. The app's biometric **App lock** is a separate device gate, never a second factor.\n\n","","two-factor-and-passkeys.mdx mobile passkeys bullet",r),await A(m(t,"docs/(platform)/project-structure.mdx"),"the web, desktop and mobile apps","the web and desktop apps","project-structure.mdx surface list",r),await V(m(t,"docs/(platform)/testing/e2e.mdx"),"testing e2e.mdx mobile Maestro section","mobile-testing-docs",r),await V(m(t,"docs/(platform)/environment-variables/index.mdx"),"environment-variables mobile section","mobile-env-docs",r)),n||(await A(m(t,"docs/(platform)/payments/meta.json"),', "mobile-billing"',"","payments meta.json mobile-billing entry",r),await A(m(t,"docs/(platform)/payments/index.mdx"),` <Card href="/payments/mobile-billing" title="Mobile store billing" description="In-app purchases through RevenueCat, additive to your web provider." />
@@ -1733,8 +1737,8 @@ function posthogConfigured(): boolean {
1733
1737
  ${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(`
1734
1738
  `),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(`
1735
1739
  `),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(`
1736
- `),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.39.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.39.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.39.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," ")}
1737
- `),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,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. 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}"\`).
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
+ `),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}"\`).
1738
1742
 
1739
1743
  v${fr} is the last release that ships a Nuxt frontend, and this CLI cannot update or migrate a Nuxt project to Next.js.
1740
1744
 
@@ -1790,7 +1794,7 @@ ${k}`}).join(`
1790
1794
  `]},{file:"packages/api/src/routes/public/v1/health.ts",removals:[`import { manifest } from "../../../lib/manifest";
1791
1795
  `],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(`
1792
1796
  `).filter(i=>!i.includes(".generatesaas")).join(`
1793
- `);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.39.0").addHelpText("after",`
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",`
1794
1798
  Examples:
1795
1799
  $ generatesaas init Interactive setup
1796
1800
  $ 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.39.0",
3
+ "version": "3.41.0",
4
4
  "type": "module",
5
5
  "description": "CLI for scaffolding and managing GenerateSaaS projects",
6
6
  "license": "UNLICENSED",