generatesaas 3.29.0 → 3.31.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.
package/dist/index.js CHANGED
@@ -1,17 +1,17 @@
1
1
  #!/usr/bin/env node
2
- import{Command as Op}from"commander";import*as ks from"@clack/prompts";import{existsSync as Kl,readdirSync as Gl,rmSync as Hl}from"fs";import{join as Yl,resolve as Wl}from"path";import{Option as X}from"commander";import*as S from"@clack/prompts";import*as St from"@clack/prompts";import Qt from"picocolors";function Br(e){let t=e?` GenerateSaaS v${e} `:" GenerateSaaS ";St.intro(Qt.bgYellow(Qt.black(t)))}function Kr(){St.outro(Qt.yellow("Happy building!"))}import*as f from"@clack/prompts";import y from"picocolors";var ut={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)"}},Pt={stripe:{label:"Stripe"},polar:{label:"Polar"},none:{label:"None",hint:"disable payments"}},At={smtp:{label:"SMTP",hint:"Mailpit for local dev"},ses:{label:"Amazon SES"},resend:{label:"Resend"}},It={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"}},Gr={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 Oe={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 te={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}},xe={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"}]}},De={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"}]}},Ze=[{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."}],Qe=[{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)."}],le={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"}}},Ne=Object.keys(le);function er(e){let t=[];for(let r of Ze)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 Qe)e.deploymentTarget===r.target&&e.architecture===r.architecture&&t.push(`\`architecture: "${r.architecture}"\` with \`deploymentTarget: "${r.target}"\` - ${r.reason}`);return t}var Hr=["Local file storage (sharp, geoip-lite)","SMTP email (use Resend or SES instead)","Content API git integration"];function et(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 tt=["fullstack","separate"],rt=["stripe","polar","none"],nt=["smtp","ses","resend"];var Yr=["claude-code","cursor","codex","gemini-cli","windsurf"],pe=["USD","EUR","GBP","CAD","AUD","BRL","JPY"],de=["node","vercel"],ue=["postgres","neon","supabase"],me=["redis","upstash"],F=["sentry","posthog"],Ce=["revenuecat","none"];function re(e){return e.paymentProvider!==void 0&&e.paymentProvider!=="none"}var tr=[{key:"architecture",label:"Architecture",hint:"Fullstack (frontend hosts the API) or a standalone Hono backend.",category:"Infrastructure",kind:"enum",default:"fullstack",choices:tt,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:de,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:ue,adoptable:!1,impact:"config",shapesTree:!0},{key:"cacheProvider",label:"Cache provider",hint:"Self-hosted Redis or Upstash.",category:"Infrastructure",kind:"enum",default:"redis",choices:me,adoptable:!1,impact:"config",shapesTree:!0},{key:"paymentProvider",label:"Payment provider",hint:"Stripe, Polar, or none.",category:"Features",kind:"enum",default:"none",choices:rt,adoptable:!1,impact:"structural",shapesTree:!0},{key:"defaultCurrency",label:"Default currency",hint:"Billing and pricing currency.",category:"Features",kind:"enum",default:"USD",choices:pe,adoptable:!1,impact:"config",shapesTree:!1},{key:"emailProvider",label:"Email provider",hint:"SMTP, Amazon SES, or Resend.",category:"Features",kind:"enum",default:"smtp",choices:nt,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:F,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:Ce,adoptable:!0,impact:"structural",shapesTree:!0,requires:e=>e.mobile===!0&&re(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.",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=>re(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 Ss(e,t){return e[t]!==void 0}function Wr(e){return tr.filter(t=>t.adoptable&&!Ss(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 Ps(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 As(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 zr(e){let t=[];for(let r of tr){let n=e[r.key];n!==void 0&&(Ps(r,n)||t.push(`\`${r.key}\` is ${JSON.stringify(n)}, but it must be ${As(r)}.`))}return t}function qr(e){let t={};for(let r of tr)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 rr(e,t){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||t}function Tt(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Rt(e){return/^[a-z][a-z0-9-]*$/.test(e)}function N(e){return e instanceof Error?e.message:String(e)}function mt(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 ht(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 Jr(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 Xr(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`."),re(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 Zr(e){let t=Is(e,e.desktopAi);return delete e.desktopAi,t}function Is(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 Qr(e){let t={};if(e.name!==void 0){if(!Rt(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(!Ce.includes(e.mobilePurchases))throw new Error(`Invalid mobile purchases "${e.mobilePurchases}". Valid values: ${Ce.join(", ")}`);t.mobilePurchases=e.mobilePurchases}if(e.ai!==void 0&&(t.ai=e.ai),e.webAi!==void 0&&(t.webAi=e.webAi),mt(t),ht(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(!pe.includes(e.currency))throw new Error(`Invalid currency "${e.currency}". Valid values: ${pe.join(", ")}`);t.defaultCurrency=e.currency}if(e.deploy!==void 0){if(!de.includes(e.deploy))throw new Error(`Invalid deployment target "${e.deploy}". Valid values: ${de.join(", ")}`);t.deploymentTarget=e.deploy}if(e.database!==void 0){if(!ue.includes(e.database))throw new Error(`Invalid database provider "${e.database}". Valid values: ${ue.join(", ")}`);t.databaseProvider=e.database}if(e.cache!==void 0){if(!me.includes(e.cache))throw new Error(`Invalid cache provider "${e.cache}". Valid values: ${me.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=>!F.includes(i));if(n.length>0)throw new Error(`Invalid observability provider ${JSON.stringify(n.join(", "))}. Valid values: ${F.join(", ")}`);t.observability=r}if(e.preset!==void 0){if(!Ne.includes(e.preset))throw new Error(`Invalid preset "${e.preset}". Valid values: ${Ne.join(", ")}`);let r=le[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 it={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 en(e){let t=e.projectName??it.projectName,r=e.projectDir??`./${t}`,n=e.appName??Tt(t),i=e.deploymentTarget??it.deploymentTarget,o=te[i]?.edgeRuntime??!1,s=e.databaseProvider??(o?"neon":it.databaseProvider),a=e.cacheProvider??(o?"upstash":it.cacheProvider),d=e.emailProvider??(o?"resend":it.emailProvider),h={...it,...e,projectName:t,appName:n,projectDir:r,deploymentTarget:i,databaseProvider:s,cacheProvider:a,emailProvider:d};h.paymentProvider==="none"&&(h.credits=!1),(!h.mobile||h.paymentProvider==="none")&&(h.mobilePurchases="none"),mt(h);for(let g of Ze){if(h.deploymentTarget!==g.target)continue;let w=h.databaseProvider===g.provider?"database":"cache";if(h.databaseProvider===g.provider||h.cacheProvider===g.provider)throw new Error(`Incompatible: --deploy ${g.target} + --${w} ${g.provider}. ${g.reason}`)}for(let g of Qe)if(h.architecture===g.architecture&&h.deploymentTarget===g.target)throw new Error(`Incompatible: --architecture ${g.architecture} + --deploy ${g.target}. ${g.reason}`);return ht(h),h}function I(e){f.isCancel(e)&&(f.cancel("Setup cancelled."),process.exit(0))}function nr(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 tn(e,t){let r=!1;e&&mt(e),e&&ht(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:u=>{if(!u?.trim())return"Project name is required.";if(!Rt(u))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:Tt(n),validate:u=>{if(!u?.trim())return"App name is required."}});return I(c),c})(),o=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 s={};if(e?.deploymentTarget===void 0&&e?.databaseProvider===void 0&&e?.cacheProvider===void 0){r=!0;let c=await f.select({message:"Infrastructure:",options:[...Ne.map(u=>({value:u,label:le[u].label,hint:le[u].hint})),{value:"custom",label:"Customize",hint:"choose each piece yourself"}]});if(I(c),c!=="custom"){let u=le[c].values;s.deploymentTarget=u.deploymentTarget,s.databaseProvider=u.databaseProvider,s.cacheProvider=u.cacheProvider,f.log.info(`${le[c].label}: ${le[c].hint}.`)}}let a=e?.deploymentTarget??s.deploymentTarget??"node";if(e?.deploymentTarget===void 0&&s.deploymentTarget===void 0){r=!0;let c=await f.select({message:"Deployment target:",options:de.map(u=>({value:u,label:te[u].label,hint:te[u].hint}))});I(c),a=c}let d=e?.architecture?Qe.find(c=>c.architecture===e.architecture&&c.target===a):void 0;if(d)throw new Error(`Incompatible: --architecture ${d.architecture} + --deploy ${d.target}. ${d.reason}`);let h=new Set(Qe.filter(c=>c.target===a).map(c=>c.architecture)),g=tt.filter(c=>!h.has(c)),w=e?.architecture??await(async()=>{if(g.length===1){let u=g[0];return f.log.info(`Auto-selected ${ut[u].label} architecture (only compatible option for ${te[a].label}).`),u}r=!0;let c=await f.select({message:"Architecture:",options:g.map(u=>({value:u,label:ut[u].label,hint:ut[u].hint}))});return I(c),c})(),v=e?.databaseProvider??s.databaseProvider??await(async()=>{r=!0;let c=ue.filter(R=>!Ze.some(Se=>Se.target===a&&Se.provider===R));if(c.length===1){let R=c[0];return f.log.info(`Auto-selected ${xe[R].label} (only compatible option for ${te[a].label}).`),R}let u=await f.select({message:"Database provider:",options:c.map(R=>({value:R,label:xe[R].label,hint:xe[R].hint}))});return I(u),u})(),P=e?.cacheProvider??s.cacheProvider??await(async()=>{r=!0;let c=me.filter(R=>!Ze.some(Se=>Se.target===a&&Se.provider===R));if(c.length===1){let R=c[0];return f.log.info(`Auto-selected ${De[R].label} (only compatible option for ${te[a].label}).`),R}let u=await f.select({message:"Cache provider:",options:c.map(R=>({value:R,label:De[R].label,hint:De[R].hint}))});return I(u),u})();if(te[a]?.edgeRuntime){let c=Hr.map(u=>` - ${u}`).join(`
3
- `);f.note(c,"Unavailable on edge runtime")}f.log.info(y.bold("Features"));let m=e?.paymentProvider??await(async()=>{r=!0;let c=await f.select({message:"Payment provider:",options:rt.map(u=>({value:u,label:Pt[u].label,hint:Pt[u].hint}))});return I(c),c})(),D=e?.defaultCurrency??await(async()=>{if(m==="none")return"USD";r=!0;let c=await f.select({message:"Default currency:",options:pe.map(u=>({value:u,label:u,hint:Oe[u].name}))});return I(c),c})(),we=e?.emailProvider??await(async()=>{r=!0;let c=await f.select({message:"Email provider:",options:nt.map(u=>({value:u,label:At[u].label,hint:At[u].hint}))});return I(c),c})(),K=e?.observability??await(async()=>{r=!0;let c=await f.multiselect({message:"Observability (space to select, enter to confirm):",required:!1,initialValues:[],options:F.map(u=>({value:u,label:It[u].label,hint:It[u].hint}))});return I(c),c})(),ae=e?.multiTenancy??await(async()=>{r=!0;let c=await f.confirm({message:"Enable multi-tenancy (organizations)?",initialValue:!1});return I(c),c})(),Re=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})(),_e=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})(),Xe=t?.desktopAllowed!==!1,ce=e?.desktop??(Xe?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)),E=t?.mobileAllowed!==!1,_=e?.mobile??(E?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)),Q=!_||m==="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})();mt({mobile:_,mobilePurchases:Q,paymentProvider:m});let G=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})(),M=e?.webAi??((ce||_)&&G?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);ht({webAi:M,ai:G,desktop:ce,mobile:_});let ee=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})(),H=m==="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,Ee=nr({databaseProvider:v,cacheProvider:P,paymentProvider:m,emailProvider:we,demo:ke}),A={};if(Ee.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 Ee)if(r=!0,c.secret){let u=await f.password({message:c.message,mask:"*"});I(u),typeof u=="string"&&u.trim()&&(A[c.key]=u.trim())}else{let u=await f.text({message:c.message,placeholder:c.placeholder});I(u),typeof u=="string"&&u.trim()&&(A[c.key]=u.trim())}}if(r){let c=[` Name: ${y.cyan(n)}`,` App name: ${y.cyan(i)}`,` Location: ${y.cyan(o)}`,` Architecture: ${y.cyan(ut[w].label)}`].join(`
4
- `),u=[` Deploy target: ${y.cyan(te[a]?.label??"Node.js / Docker")}`,` Database: ${y.cyan(xe[v].label)}`,` Cache: ${y.cyan(De[P].label)}`].filter(Boolean).join(`
5
- `),R=[m!=="none"?` Payment: ${y.cyan(Pt[m].label)} (${D})`:` Payment: ${y.dim("none")}`,` Credits: ${H?y.cyan("Yes"):y.dim("No")}`,` AI features: ${G?y.cyan("Yes"):y.dim("No")}`,...M?[]:[` Web AI: ${y.dim("No")} (app-first)`],` Email: ${y.cyan(At[we].label)}`,` Observability: ${K.length===0?y.dim("none"):y.cyan(K.map(Zt=>It[Zt].label).join(", "))}`,` Multi-tenancy: ${ae?y.cyan("Yes"):y.dim("No")}`,` Projects: ${Re?y.cyan("Yes"):y.dim("No")}`,` Docs app: ${_e?y.cyan("Yes"):y.dim("No")}`,` Desktop app: ${ce?y.cyan("Yes"):y.dim("No")}`,` Mobile app: ${_?y.cyan("Yes"):y.dim("No")}`,...Q==="none"?[]:[` In-app purch.: ${y.cyan("RevenueCat")}`],` Rev. sharing: ${ee?y.cyan("Yes"):y.dim("No")}`].join(`
6
- `),Se=[y.bold("Project"),c,"",y.bold("Infrastructure"),u,"",y.bold("Features"),R];if(Ee.length>0){let Zt=Ee.map(Vr=>{let Es=A[Vr.key]?y.green("provided"):y.dim("skipped");return` ${Vr.key}: ${Es}`}).join(`
7
- `);Se.push("",y.bold("Credentials"),Zt)}f.note(Se.join(`
8
- `),"Summary");let Fr=await f.confirm({message:"Proceed with these settings?"});(f.isCancel(Fr)||!Fr)&&(f.cancel("Setup cancelled."),process.exit(0))}return{projectName:n,appName:i,projectDir:o,architecture:w,deploymentTarget:a,databaseProvider:v,cacheProvider:P,paymentProvider:m,emailProvider:we,observability:K,multiTenancy:ae,projects:Re,docs:_e,desktop:ce,mobile:_,mobilePurchases:Q,ai:G,webAi:M,revenueSharing:ee,credits:H,defaultCurrency:D,...Object.keys(A).length>0?{credentials:A}:{},...e?.baseUrl!==void 0?{baseUrl:e.baseUrl}:{},...ke!==void 0?{demo:ke}:{}}}import{createReadStream as mn,existsSync as $s}from"fs";import{mkdir as js}from"fs/promises";import{join as Ms}from"path";import{Readable as Us}from"stream";import{pipeline as ur}from"stream/promises";import{extract as Fs}from"tar";import{join as Le}from"path";import{homedir as Ts}from"os";var ft=process.env.GENERATESAAS_API_URL??"https://cli.generatesaas.com",Y=".generatesaas",he=Le(Y,"manifest.json"),rn="nextjs",ir="nuxt",sr="2.4.1",nn=Le(Y,"hashes.json"),_t=Le(Y,"template-hashes.json"),Ot=Le(Y,"template"),sn=Le(Y,"staging"),on=Le(Y,"staging.json"),fe=Le(Ts(),".generatesaas");var $=class extends Error{constructor(r,n,i){super(n);this.status=r;this.body=i}status;body;name="ApiError"};function ge(e){return{apiKey:e,baseUrl:ft}}async function Pe(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.29.0"}});if(!i.ok){let o,s;try{s=await i.json(),o=s.error??`API ${i.status}: ${t}`}catch{o=`API ${i.status}: ${t}`}throw new $(i.status,o,s)}return i}import{existsSync as Rs,mkdirSync as _s,readFileSync as Os,writeFileSync as xs}from"fs";import{dirname as Ds}from"path";import*as Ae from"@clack/prompts";function gt(){if(!Rs(fe))return null;try{let e=JSON.parse(Os(fe,"utf-8"));return e.apiKey?e.apiKey:(e.token&&!e.apiKey&&Ae.log.warning(`Found old GitHub token in ${fe}. Run 'generatesaas init' to set up your API key.`),null)}catch{return null}}function $e(e){_s(Ds(fe),{recursive:!0}),xs(fe,`${JSON.stringify({apiKey:e},null," ")}
9
- `,{mode:384})}async function st(e){if(e?.apiKey)return e.apiKey;let t=process.env.GENERATESAAS_API_KEY;if(t)return t;let r=gt();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 yt()}async function yt(){let e=await Ae.text({message:"Enter your GenerateSaaS API key:",placeholder:"gs_live_...",validate:t=>{if(!t?.trim())return"API key is required."}});return Ae.isCancel(e)&&(Ae.cancel("Setup cancelled."),process.exit(0)),e.trim()}import{readFile as Ns}from"fs/promises";async function Ie(e){let t=process.env.GENERATESAAS_VERSION_INDEX;return t?JSON.parse(await Ns(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 Pe(e,"/versions")).json()}async function an(e,t){if(process.env.GENERATESAAS_OFFLINE_LICENSE==="1")return null;try{return await(await Pe(e,`/changelog/${encodeURIComponent(t)}`)).text()}catch(r){if(r instanceof $&&r.status===404)return null;throw r}}async function cn(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{skills:{"generatesaas-update":{skillMd:`# Offline skill stub
10
- `,scripts:{},references:{}}}}:await(await Pe(e,`/skills/${encodeURIComponent(t)}`)).json()}function xt(e){if(!(e instanceof $)||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 or="nextjs";function ln(e){return{frontend:or,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 ar(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{token:"offline-test-token",licenseId:"offline-test-license-id",installId:t.installId}:await(await Pe(e,"/license/sign",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json()}async function pn(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{token:t.currentToken}:await(await Pe(e,"/license/refresh",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json()}async function cr(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 dn(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 lr=new Set([".git","node_modules",".pnpm-store",".env",".env.test",".turbo",".data","dist",".next",".next-e2e-web",".next-e2e-desktop",".svelte-kit",".wrangler",".devcontainer","playwright-report","test-results",".drive-out",".mastra"]),pr=new Set(["pnpm-lock.yaml"]);function ot(e){if(dr(e))return!0;for(let t of e.split("/"))if(pr.has(t))return!0;return!1}var Cs=new Set(["data","mksaas","references","scripts",".cursor",".agents",".codex",".generatesaas",".vscode",".mcp.json","vitest.config.ts","README.md","TODO.md","OVERVIEW.md","HANDOFF.md"]),un=["scripts/docs-lint.ts"],Ls=["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 dr(e){let t=e.split("/");for(let r of t)if(lr.has(r))return!0;if(un.includes(e)||un.some(r=>r.startsWith(`${e}/`)))return!1;if(Cs.has(t[0]))return!0;for(let r of Ls)if(e===r||e.startsWith(`${r}/`))return!0;return!1}async function Dt(e,t,r){await js(r,{recursive:!0});let n=process.env.GENERATESAAS_TEMPLATE_TARBALL_DIR;if(n){let a=Ms(n,`v${t}.tar.gz`);if(!$s(a))throw new Error(`GENERATESAAS_TEMPLATE_TARBALL_DIR is set but ${a} does not exist.`);await ur(mn(a),mr(r));return}let i=process.env.GENERATESAAS_TEMPLATE_TARBALL;if(i){await ur(mn(i),mr(r));return}let o=await Pe(e,`/template/${encodeURIComponent(t)}`);if(!o.body)throw new Error("Empty response body");let s=Us.fromWeb(o.body);await ur(s,mr(r))}function mr(e){return Fs({cwd:e,strip:1,filter:t=>{let r=t.replace(/^[^/]+\//,"");return r?!dr(r):!0},sync:!1})}import{readdir as Nt,readFile as at,rm as fn,rmdir as Vs,writeFile as bt}from"fs/promises";import{join as V}from"path";async function gn(e){let t;try{t=await Nt(e,{withFileTypes:!0})}catch{return!1}let r=!1;for(let n of t){let i=V(e,n.name);if(n.isDirectory()){await gn(i)&&(r=!0);continue}if(n.name.startsWith("_")){r=!0;continue}await fn(i,{force:!0})}return r||await Vs(e).catch(()=>{}),r}async function yn(e){let t=V(e,"packages/content"),r=[];try{r=(await Nt(t,{withFileTypes:!0})).filter(s=>s.isDirectory()).map(s=>s.name)}catch{return}let n=new Set;for(let s of r){let a=V(t,s),d;try{d=(await Nt(a,{withFileTypes:!0})).filter(h=>h.isDirectory())}catch{continue}for(let h of d)n.add(h.name),await gn(V(a,h.name))}let i=await Hs(e),o=new Set([...n].filter(s=>i===void 0||i.has(s)));await Promise.all([...o].map(s=>fn(V(e,"apps/web/public/images",s),{recursive:!0,force:!0}))),await Ws(e,o)}var Bs="packages/config/src/index.ts",Ks=/\bcontent:\s*\{[\s\S]*?\bsections:\s*\[([\s\S]*?)\]/,Gs=/\bslug:\s*"([^"]+)"/g;async function Hs(e){let t;try{t=await at(V(e,Bs),"utf-8")}catch{return}let r=Ks.exec(t)?.[1];if(r===void 0)return;let n=[...r.matchAll(Gs)].map(i=>i[1]).filter(i=>i!==void 0);return n.length>0?new Set(n):void 0}var Ys="packages/translate/.meta/mdx-translation-meta.json";async function Ws(e,t){if(t.size===0)return;let r=V(e,Ys),n;try{n=JSON.parse(await at(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 o={};for(let[s,a]of Object.entries(i.locales)){if(typeof a!="object"||a===null)continue;let d={};for(let[h,g]of Object.entries(a)){let w=h.split("/"),v=w.length>1?w[0]:void 0,P=w[w.length-1]?.startsWith("_")===!0;v!==void 0&&t.has(v)&&!P||(d[h]=g)}o[s]=d}await bt(r,`${JSON.stringify({...i,locales:o},null," ")}
11
- `)}var zs="packages/config/src/blog.ts";async function bn(e){let t=V(e,zs),r=await at(t,"utf-8"),n=hn(hn(r,"blogCategories",t),"blogAuthors",t);await bt(t,n)}function hn(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 vn(e){let t=V(e,"packages/i18n/translations"),r;try{r=await Nt(t)}catch{return}for(let n of r){let i=V(t,n,"web.json"),o;try{o=await at(i,"utf-8")}catch{continue}let s=JSON.parse(o);!s.content?.categories||s.content.categories.blog===void 0||(s.content.categories.blog={},await bt(i,`${JSON.stringify(s,null," ")}
12
- `))}}var qs="packages/config/src/ai/tasks.ts",Js="The array carries a SINGLE INERT DEMO task: the CLI strips it for buyer builds (leaving an empty\n * `aiTasks`, which hides the Tasks tab) and keeps it for `--demo` builds.",Xs="The array starts EMPTY, which hides the Tasks tab until you declare your first task.";async function wn(e){let t=V(e,qs),r=await at(t,"utf-8"),n=r.replace(/\n?[\t ]*\/\/ gsaas:demo-ai-task-start[\s\S]*?\/\/ gsaas:demo-ai-task-end/,"");if(n===r)throw new Error(`removeDemoAiTasks: could not find the \`gsaas:demo-ai-task\` markers in ${t}. The boilerplate AI tasks config may have been renamed or restructured; update the CLI strip in cleanup.ts.`);let i=n.replace(Js,Xs);if(i===n)throw new Error(`removeDemoAiTasks: the demo-task paragraph in ${t} did not match, so the shipped file would describe a demo task it no longer carries (boilerplate drift).`);await bt(t,i)}async function kn(e){let t=V(e,".claude","settings.json"),r;try{r=await at(t,"utf8")}catch{return}let n=JSON.parse(r);delete n.alwaysThinkingEnabled,delete n.enableAllProjectMcpServers,n.env&&(delete n.env.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS,Object.keys(n.env).length===0&&delete n.env),n.permissions?.allow&&(n.permissions.allow=n.permissions.allow.filter(Zs)),await bt(t,`${JSON.stringify(n,null," ")}
13
- `)}function Zs(e){return!(e.startsWith("mcp__")||e.includes("nuxt"))}import{readFileSync as co}from"fs";import{dirname as lo,join as Sn}from"path";import{fileURLToPath as po}from"url";import{existsSync as Qs}from"fs";import{join as En}from"path";function Ct(e,t,r){let n=En(e,...t);return Qs(n)?n:En(e,r)}import{mkdir as eo,writeFile as to,readdir as ro,rm as no,rmdir as io}from"fs/promises";import{dirname as Lt,join as so,relative as oo,sep as ao}from"path";function je(e){return e.split(ao).join("/")}async function $t(e){await eo(e,{recursive:!0})}async function l(e,t){await $t(Lt(e)),await to(e,t,"utf-8")}async function Me(e,t){await no(e,{force:!0});let r=Lt(e);for(;r!==t&&r!==Lt(r);){try{await io(r)}catch{return}r=Lt(r)}}async function ye(e,t,r,n){let i=[],o=await ro(e,{withFileTypes:!0});for(let s of o){let a=so(e,s.name),d=je(oo(t,a));r(d)||(s.isDirectory()?i.push(...await ye(a,t,r,n)):s.isFile()&&(n===void 0||n(d))&&i.push(a))}return i}var uo={postgres:"Postgres",neon:"Neon (managed Postgres)",supabase:"Supabase (managed Postgres)"},mo={resend:"Resend",ses:"Amazon SES",smtp:"SMTP"},ho={redis:"Redis",upstash:"Upstash Redis"},fo={node:"Node.js / Docker",vercel:"Vercel"},hr="apps/web",go="Next.js 16",yo="`app/` routes, `components/`, `lib/`",bo={stripe:"Stripe",polar:"Polar"};function vo(e){let t=e.architecture==="fullstack",r=t?"(fullstack - Hono API mounted inside the app)":"(separate - standalone Hono backend)",n=t?`Mounted inside \`${hr}\`. A standalone \`apps/backend\` is also kept (inert) so you can switch to separate later.`:"Runs from `apps/backend`; the frontend reaches it over HTTP.",i=ho[e.cacheProvider],o=fo[e.deploymentTarget],s=e.paymentProvider==="none"?"":`
14
- - **Payments:** ${bo[e.paymentProvider]}`,a=e.desktop?e.mobile?", the desktop app (built with Electron) under `docs/desktop/` and the mobile app (built with Expo) under `docs/mobile/`":", and the desktop app (built with Electron) under `docs/desktop/`":e.mobile?", and the mobile app (built with Expo) under `docs/mobile/`":"",d=e.desktop?" With the desktop app on, both shells render the same body, so one change lands in both.":"",h=`\`useTranslations()\` from \`next-intl\` in components; messages are loaded in \`${hr}/i18n/request.ts\`.`;return ko({archSuffix:r,apiLocation:n,databaseName:uo[e.databaseProvider],cacheName:i,paymentLine:s,emailName:mo[e.emailProvider],deployName:o,appDocsRef:a,sharedScreensBothShells:d,i18nRule:h,webAppDir:hr,webAppName:go,webAppLayout:yo})}function wo(){return Ct(lo(po(import.meta.url)),["generators","content"],"content")}function ko(e){let t=co(Sn(wo(),"AGENTS.template.md"),"utf-8"),r=new Map(Object.entries(e)),n=t.replace(/\{\{(\w+)\}\}/g,(o,s)=>{let a=r.get(s);if(a===void 0)throw new Error(`AGENTS.template.md uses unknown token {{${s}}}`);return a}),i=/\{\{[^}]*\}\}/.exec(n);if(i)throw new Error(`AGENTS.template.md carries an unrendered token: ${i[0]}`);return n}async function Pn(e){await l(Sn(e.projectDir,"AGENTS.md"),vo(e))}import{join as Eo}from"path";var An="apps/web",fr="Next.js 16",So={postgres:"Postgres (self-hosted)",neon:"Neon (managed Postgres)",supabase:"Supabase (managed Postgres)"};function Po(e){let t=e.appName.trim()||e.projectName,r=So[e.databaseProvider],n=e.architecture==="fullstack"?`${fr} app at \`${An}/\` with the Hono API mounted inside it. A standalone \`apps/backend/\` is also included (inert in this fullstack setup) so you can split the API into a separate service later without re-scaffolding.`:`${fr} app at \`${An}/\` and a separate Hono backend at \`apps/backend/\`.`,i=e.architecture==="fullstack"?`- App + API: http://localhost:3000
2
+ import{Command as $p}from"commander";import*as Ps from"@clack/prompts";import{existsSync as ql,readdirSync as Jl,rmSync as Xl}from"fs";import{join as Zl,resolve as Ql}from"path";import{Option as ee}from"commander";import*as S from"@clack/prompts";import*as At from"@clack/prompts";import er from"picocolors";function Kr(e){let t=e?` GenerateSaaS v${e} `:" GenerateSaaS ";At.intro(er.bgYellow(er.black(t)))}function Gr(){At.outro(er.yellow("Happy building!"))}import*as f from"@clack/prompts";import y from"picocolors";var mt={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)"}},It={stripe:{label:"Stripe"},polar:{label:"Polar"},none:{label:"None",hint:"disable payments"}},Tt={smtp:{label:"SMTP",hint:"Mailpit for local dev"},ses:{label:"Amazon SES"},resend:{label:"Resend"}},Rt={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"}},Hr={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 De={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}},Ne={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"}]}},Ce={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"}]}},Ze=[{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."}],Qe=[{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)."}],ce={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"}}},Le=Object.keys(ce);function tr(e){let t=[];for(let r of Ze)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 Qe)e.deploymentTarget===r.target&&e.architecture===r.architecture&&t.push(`\`architecture: "${r.architecture}"\` with \`deploymentTarget: "${r.target}"\` - ${r.reason}`);return t}var Yr=["Local file storage (sharp, geoip-lite)","SMTP email (use Resend or SES instead)","Content API git integration"];function et(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 tt=["fullstack","separate"],rt=["stripe","polar","none"],nt=["smtp","ses","resend"];var Wr=["claude-code","cursor","codex","gemini-cli","windsurf"],le=["USD","EUR","GBP","CAD","AUD","BRL","JPY"],pe=["node","vercel"],de=["postgres","neon","supabase"],ue=["redis","upstash"],K=["sentry","posthog"],$e=["revenuecat","none"];function ne(e){return e.paymentProvider!==void 0&&e.paymentProvider!=="none"}var rr=[{key:"architecture",label:"Architecture",hint:"Fullstack (frontend hosts the API) or a standalone Hono backend.",category:"Infrastructure",kind:"enum",default:"fullstack",choices:tt,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:pe,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:de,adoptable:!1,impact:"config",shapesTree:!0},{key:"cacheProvider",label:"Cache provider",hint:"Self-hosted Redis or Upstash.",category:"Infrastructure",kind:"enum",default:"redis",choices:ue,adoptable:!1,impact:"config",shapesTree:!0},{key:"paymentProvider",label:"Payment provider",hint:"Stripe, Polar, or none.",category:"Features",kind:"enum",default:"none",choices:rt,adoptable:!1,impact:"structural",shapesTree:!0},{key:"defaultCurrency",label:"Default currency",hint:"Billing and pricing currency.",category:"Features",kind:"enum",default:"USD",choices:le,adoptable:!1,impact:"config",shapesTree:!1},{key:"emailProvider",label:"Email provider",hint:"SMTP, Amazon SES, or Resend.",category:"Features",kind:"enum",default:"smtp",choices:nt,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:K,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:$e,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 Is(e,t){return e[t]!==void 0}function zr(e){return rr.filter(t=>t.adoptable&&!Is(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 Ts(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 Rs(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 qr(e){let t=[];for(let r of rr){let n=e[r.key];n!==void 0&&(Ts(r,n)||t.push(`\`${r.key}\` is ${JSON.stringify(n)}, but it must be ${Rs(r)}.`))}return t}function Jr(e){let t={};for(let r of rr)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 nr(e,t){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||t}function _t(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Ot(e){return/^[a-z][a-z0-9-]*$/.test(e)}function N(e){return e instanceof Error?e.message:String(e)}function ht(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 ft(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 Xr(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 Zr(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 Qr(e){let t=_s(e,e.desktopAi);return delete e.desktopAi,t}function _s(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 en(e){let t={};if(e.name!==void 0){if(!Ot(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(!$e.includes(e.mobilePurchases))throw new Error(`Invalid mobile purchases "${e.mobilePurchases}". Valid values: ${$e.join(", ")}`);t.mobilePurchases=e.mobilePurchases}if(e.ai!==void 0&&(t.ai=e.ai),e.webAi!==void 0&&(t.webAi=e.webAi),ht(t),ft(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(!le.includes(e.currency))throw new Error(`Invalid currency "${e.currency}". Valid values: ${le.join(", ")}`);t.defaultCurrency=e.currency}if(e.deploy!==void 0){if(!pe.includes(e.deploy))throw new Error(`Invalid deployment target "${e.deploy}". Valid values: ${pe.join(", ")}`);t.deploymentTarget=e.deploy}if(e.database!==void 0){if(!de.includes(e.database))throw new Error(`Invalid database provider "${e.database}". Valid values: ${de.join(", ")}`);t.databaseProvider=e.database}if(e.cache!==void 0){if(!ue.includes(e.cache))throw new Error(`Invalid cache provider "${e.cache}". Valid values: ${ue.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=>!K.includes(i));if(n.length>0)throw new Error(`Invalid observability provider ${JSON.stringify(n.join(", "))}. Valid values: ${K.join(", ")}`);t.observability=r}if(e.preset!==void 0){if(!Le.includes(e.preset))throw new Error(`Invalid preset "${e.preset}". Valid values: ${Le.join(", ")}`);let r=ce[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 it={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 tn(e){let t=e.projectName??it.projectName,r=e.projectDir??`./${t}`,n=e.appName??_t(t),i=e.deploymentTarget??it.deploymentTarget,o=re[i]?.edgeRuntime??!1,s=e.databaseProvider??(o?"neon":it.databaseProvider),a=e.cacheProvider??(o?"upstash":it.cacheProvider),d=e.emailProvider??(o?"resend":it.emailProvider),h={...it,...e,projectName:t,appName:n,projectDir:r,deploymentTarget:i,databaseProvider:s,cacheProvider:a,emailProvider:d};h.paymentProvider==="none"&&(h.credits=!1),(!h.mobile||h.paymentProvider==="none")&&(h.mobilePurchases="none"),ht(h);for(let g of Ze){if(h.deploymentTarget!==g.target)continue;let E=h.databaseProvider===g.provider?"database":"cache";if(h.databaseProvider===g.provider||h.cacheProvider===g.provider)throw new Error(`Incompatible: --deploy ${g.target} + --${E} ${g.provider}. ${g.reason}`)}for(let g of Qe)if(h.architecture===g.architecture&&h.deploymentTarget===g.target)throw new Error(`Incompatible: --architecture ${g.architecture} + --deploy ${g.target}. ${g.reason}`);return ft(h),h}function T(e){f.isCancel(e)&&(f.cancel("Setup cancelled."),process.exit(0))}function ir(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 rn(e,t){let r=!1;e&&ht(e),e&&ft(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:u=>{if(!u?.trim())return"Project name is required.";if(!Ot(u))return"Use lowercase letters, numbers, and hyphens only. Must start with a letter."}});return T(c),c})(),i=e?.appName??await(async()=>{r=!0;let c=await f.text({message:"App name:",initialValue:_t(n),validate:u=>{if(!u?.trim())return"App name is required."}});return T(c),c})(),o=e?.projectDir??await(async()=>{r=!0;let c=await f.text({message:"Project location:",initialValue:`./${n}`});return T(c),c==="."?process.cwd():c})();f.log.info(y.bold("Infrastructure"));let s={};if(e?.deploymentTarget===void 0&&e?.databaseProvider===void 0&&e?.cacheProvider===void 0){r=!0;let c=await f.select({message:"Infrastructure:",options:[...Le.map(u=>({value:u,label:ce[u].label,hint:ce[u].hint})),{value:"custom",label:"Customize",hint:"choose each piece yourself"}]});if(T(c),c!=="custom"){let u=ce[c].values;s.deploymentTarget=u.deploymentTarget,s.databaseProvider=u.databaseProvider,s.cacheProvider=u.cacheProvider,f.log.info(`${ce[c].label}: ${ce[c].hint}.`)}}let a=e?.deploymentTarget??s.deploymentTarget??"node";if(e?.deploymentTarget===void 0&&s.deploymentTarget===void 0){r=!0;let c=await f.select({message:"Deployment target:",options:pe.map(u=>({value:u,label:re[u].label,hint:re[u].hint}))});T(c),a=c}let d=e?.architecture?Qe.find(c=>c.architecture===e.architecture&&c.target===a):void 0;if(d)throw new Error(`Incompatible: --architecture ${d.architecture} + --deploy ${d.target}. ${d.reason}`);let h=new Set(Qe.filter(c=>c.target===a).map(c=>c.architecture)),g=tt.filter(c=>!h.has(c)),E=e?.architecture??await(async()=>{if(g.length===1){let u=g[0];return f.log.info(`Auto-selected ${mt[u].label} architecture (only compatible option for ${re[a].label}).`),u}r=!0;let c=await f.select({message:"Architecture:",options:g.map(u=>({value:u,label:mt[u].label,hint:mt[u].hint}))});return T(c),c})(),w=e?.databaseProvider??s.databaseProvider??await(async()=>{r=!0;let c=de.filter(R=>!Ze.some(Ee=>Ee.target===a&&Ee.provider===R));if(c.length===1){let R=c[0];return f.log.info(`Auto-selected ${Ne[R].label} (only compatible option for ${re[a].label}).`),R}let u=await f.select({message:"Database provider:",options:c.map(R=>({value:R,label:Ne[R].label,hint:Ne[R].hint}))});return T(u),u})(),P=e?.cacheProvider??s.cacheProvider??await(async()=>{r=!0;let c=ue.filter(R=>!Ze.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 u=await f.select({message:"Cache provider:",options:c.map(R=>({value:R,label:Ce[R].label,hint:Ce[R].hint}))});return T(u),u})();if(re[a]?.edgeRuntime){let c=Yr.map(u=>` - ${u}`).join(`
3
+ `);f.note(c,"Unavailable on edge runtime")}f.log.info(y.bold("Features"));let m=e?.paymentProvider??await(async()=>{r=!0;let c=await f.select({message:"Payment provider:",options:rt.map(u=>({value:u,label:It[u].label,hint:It[u].hint}))});return T(c),c})(),O=e?.defaultCurrency??await(async()=>{if(m==="none")return"USD";r=!0;let c=await f.select({message:"Default currency:",options:le.map(u=>({value:u,label:u,hint:De[u].name}))});return T(c),c})(),be=e?.emailProvider??await(async()=>{r=!0;let c=await f.select({message:"Email provider:",options:nt.map(u=>({value:u,label:Tt[u].label,hint:Tt[u].hint}))});return T(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:K.map(u=>({value:u,label:Rt[u].label,hint:Rt[u].hint}))});return T(c),c})(),ae=e?.multiTenancy??await(async()=>{r=!0;let c=await f.confirm({message:"Enable multi-tenancy (organizations)?",initialValue:!1});return T(c),c})(),_e=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 T(c),c})(),Oe=e?.docs??await(async()=>{r=!0;let c=await f.confirm({message:"Include docs app? (self-hosted Fumadocs documentation site)",initialValue:!1});return T(c),c})(),xe=t?.desktopAllowed!==!1,we=e?.desktop??(xe?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 T(c),c})():(f.log.info(y.dim("Desktop app: available on the Pro plan and up - skipped.")),!1)),Xe=t?.mobileAllowed!==!1,v=e?.mobile??(Xe?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 T(c),c})():(f.log.info(y.dim("Mobile app: available on the Pro plan and up - skipped.")),!1)),L=!v||m==="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 T(R),R})();ht({mobile:v,mobilePurchases:L,paymentProvider:m});let F=e?.ai??await(async()=>{r=!0;let c=await f.confirm({message:"Add AI features? (chat, models, automations, integrations)",initialValue:!1});return T(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 T(c),c})():!0);ft({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 T(c),c})(),W=m==="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 T(c),c})(),ke=e?.demo,z=ir({databaseProvider:w,cacheProvider:P,paymentProvider:m,emailProvider:be,demo:ke}),I={};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 u=await f.password({message:c.message,mask:"*"});T(u),typeof u=="string"&&u.trim()&&(I[c.key]=u.trim())}else{let u=await f.text({message:c.message,placeholder:c.placeholder});T(u),typeof u=="string"&&u.trim()&&(I[c.key]=u.trim())}}if(r){let c=[` Name: ${y.cyan(n)}`,` App name: ${y.cyan(i)}`,` Location: ${y.cyan(o)}`,` Architecture: ${y.cyan(mt[E].label)}`].join(`
4
+ `),u=[` Deploy target: ${y.cyan(re[a]?.label??"Node.js / Docker")}`,` Database: ${y.cyan(Ne[w].label)}`,` Cache: ${y.cyan(Ce[P].label)}`].filter(Boolean).join(`
5
+ `),R=[m!=="none"?` Payment: ${y.cyan(It[m].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(Tt[be].label)}`,` Observability: ${B.length===0?y.dim("none"):y.cyan(B.map(Qt=>Rt[Qt].label).join(", "))}`,` Multi-tenancy: ${ae?y.cyan("Yes"):y.dim("No")}`,` Projects: ${_e?y.cyan("Yes"):y.dim("No")}`,` Docs app: ${Oe?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
+ `),Ee=[y.bold("Project"),c,"",y.bold("Infrastructure"),u,"",y.bold("Features"),R];if(z.length>0){let Qt=z.map(Br=>{let As=I[Br.key]?y.green("provided"):y.dim("skipped");return` ${Br.key}: ${As}`}).join(`
7
+ `);Ee.push("",y.bold("Credentials"),Qt)}f.note(Ee.join(`
8
+ `),"Summary");let Vr=await f.confirm({message:"Proceed with these settings?"});(f.isCancel(Vr)||!Vr)&&(f.cancel("Setup cancelled."),process.exit(0))}return{projectName:n,appName:i,projectDir:o,architecture:E,deploymentTarget:a,databaseProvider:w,cacheProvider:P,paymentProvider:m,emailProvider:be,observability:B,multiTenancy:ae,projects:_e,docs:Oe,desktop:we,mobile:v,mobilePurchases:L,ai:F,webAi:ve,revenueSharing:$,credits:W,defaultCurrency:O,...Object.keys(I).length>0?{credentials:I}:{},...e?.baseUrl!==void 0?{baseUrl:e.baseUrl}:{},...ke!==void 0?{demo:ke}:{}}}import{createReadStream as hn,existsSync as Us}from"fs";import{mkdir as Fs}from"fs/promises";import{join as Vs}from"path";import{Readable as Bs}from"stream";import{pipeline as mr}from"stream/promises";import{extract as Ks}from"tar";import{join as je}from"path";import{homedir as Os}from"os";var gt=process.env.GENERATESAAS_API_URL??"https://cli.generatesaas.com",q=".generatesaas",me=je(q,"manifest.json"),nn="nextjs",sr="nuxt",or="2.4.1",sn=je(q,"hashes.json"),xt=je(q,"template-hashes.json"),Dt=je(q,"template"),on=je(q,"staging"),an=je(q,"staging.json"),he=je(Os(),".generatesaas");var j=class extends Error{constructor(r,n,i){super(n);this.status=r;this.body=i}status;body;name="ApiError"};function fe(e){return{apiKey:e,baseUrl:gt}}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.31.0"}});if(!i.ok){let o,s;try{s=await i.json(),o=s.error??`API ${i.status}: ${t}`}catch{o=`API ${i.status}: ${t}`}throw new j(i.status,o,s)}return i}import{existsSync as xs,mkdirSync as Ds,readFileSync as Ns,writeFileSync as Cs}from"fs";import{dirname as Ls}from"path";import*as Pe from"@clack/prompts";function yt(){if(!xs(he))return null;try{let e=JSON.parse(Ns(he,"utf-8"));return e.apiKey?e.apiKey:(e.token&&!e.apiKey&&Pe.log.warning(`Found old GitHub token in ${he}. Run 'generatesaas init' to set up your API key.`),null)}catch{return null}}function Me(e){Ds(Ls(he),{recursive:!0}),Cs(he,`${JSON.stringify({apiKey:e},null," ")}
9
+ `,{mode:384})}async function st(e){if(e?.apiKey)return e.apiKey;let t=process.env.GENERATESAAS_API_KEY;if(t)return t;let r=yt();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 bt()}async function bt(){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 $s}from"fs/promises";async function Ae(e){let t=process.env.GENERATESAAS_VERSION_INDEX;return t?JSON.parse(await $s(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 cn(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 j&&r.status===404)return null;throw r}}async function ln(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{skills:{"generatesaas-update":{skillMd:`# Offline skill stub
10
+ `,scripts:{},references:{}}}}:await(await Se(e,`/skills/${encodeURIComponent(t)}`)).json()}function Nt(e){if(!(e instanceof j)||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 ar="nextjs";function pn(e){return{frontend:ar,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 cr(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 dn(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 lr(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 un(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 pr=new Set([".git","node_modules",".pnpm-store",".env",".env.test",".turbo",".data","dist",".next",".next-e2e-web",".next-e2e-desktop",".svelte-kit",".wrangler",".devcontainer","playwright-report","test-results",".drive-out",".mastra"]),dr=new Set(["pnpm-lock.yaml","widget-documents.generated.ts"]);function ot(e){if(ur(e))return!0;for(let t of e.split("/"))if(dr.has(t))return!0;return!1}var js=new Set(["data","mksaas","references","scripts",".cursor",".agents",".codex",".generatesaas",".vscode",".mcp.json","vitest.config.ts","README.md","TODO.md","OVERVIEW.md","HANDOFF.md"]),mn=["scripts/docs-lint.ts"],Ms=["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 ur(e){let t=e.split("/");for(let r of t)if(pr.has(r))return!0;if(mn.includes(e)||mn.some(r=>r.startsWith(`${e}/`)))return!1;if(js.has(t[0]))return!0;for(let r of Ms)if(e===r||e.startsWith(`${r}/`))return!0;return!1}async function Ct(e,t,r){await Fs(r,{recursive:!0});let n=process.env.GENERATESAAS_TEMPLATE_TARBALL_DIR;if(n){let a=Vs(n,`v${t}.tar.gz`);if(!Us(a))throw new Error(`GENERATESAAS_TEMPLATE_TARBALL_DIR is set but ${a} does not exist.`);await mr(hn(a),hr(r));return}let i=process.env.GENERATESAAS_TEMPLATE_TARBALL;if(i){await mr(hn(i),hr(r));return}let o=await Se(e,`/template/${encodeURIComponent(t)}`);if(!o.body)throw new Error("Empty response body");let s=Bs.fromWeb(o.body);await mr(s,hr(r))}function hr(e){return Ks({cwd:e,strip:1,filter:t=>{let r=t.replace(/^[^/]+\//,"");return r?!ur(r):!0},sync:!1})}import{readdir as Lt,readFile as at,rm as gn,rmdir as Gs,writeFile as wt}from"fs/promises";import{join as G}from"path";async function yn(e){let t;try{t=await Lt(e,{withFileTypes:!0})}catch{return!1}let r=!1;for(let n of t){let i=G(e,n.name);if(n.isDirectory()){await yn(i)&&(r=!0);continue}if(n.name.startsWith("_")){r=!0;continue}await gn(i,{force:!0})}return r||await Gs(e).catch(()=>{}),r}async function bn(e){let t=G(e,"packages/content"),r=[];try{r=(await Lt(t,{withFileTypes:!0})).filter(s=>s.isDirectory()).map(s=>s.name)}catch{return}let n=new Set;for(let s of r){let a=G(t,s),d;try{d=(await Lt(a,{withFileTypes:!0})).filter(h=>h.isDirectory())}catch{continue}for(let h of d)n.add(h.name),await yn(G(a,h.name))}let i=await zs(e),o=new Set([...n].filter(s=>i===void 0||i.has(s)));await Promise.all([...o].map(s=>gn(G(e,"apps/web/public/images",s),{recursive:!0,force:!0}))),await Js(e,o)}var Hs="packages/config/src/index.ts",Ys=/\bcontent:\s*\{[\s\S]*?\bsections:\s*\[([\s\S]*?)\]/,Ws=/\bslug:\s*"([^"]+)"/g;async function zs(e){let t;try{t=await at(G(e,Hs),"utf-8")}catch{return}let r=Ys.exec(t)?.[1];if(r===void 0)return;let n=[...r.matchAll(Ws)].map(i=>i[1]).filter(i=>i!==void 0);return n.length>0?new Set(n):void 0}var qs="packages/translate/.meta/mdx-translation-meta.json";async function Js(e,t){if(t.size===0)return;let r=G(e,qs),n;try{n=JSON.parse(await at(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 o={};for(let[s,a]of Object.entries(i.locales)){if(typeof a!="object"||a===null)continue;let d={};for(let[h,g]of Object.entries(a)){let E=h.split("/"),w=E.length>1?E[0]:void 0,P=E[E.length-1]?.startsWith("_")===!0;w!==void 0&&t.has(w)&&!P||(d[h]=g)}o[s]=d}await wt(r,`${JSON.stringify({...i,locales:o},null," ")}
11
+ `)}var Xs="packages/config/src/blog.ts";async function wn(e){let t=G(e,Xs),r=await at(t,"utf-8"),n=fn(fn(r,"blogCategories",t),"blogAuthors",t);await wt(t,n)}function fn(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 vn(e){let t=G(e,"packages/i18n/translations"),r;try{r=await Lt(t)}catch{return}for(let n of r){let i=G(t,n,"web.json"),o;try{o=await at(i,"utf-8")}catch{continue}let s=JSON.parse(o);!s.content?.categories||s.content.categories.blog===void 0||(s.content.categories.blog={},await wt(i,`${JSON.stringify(s,null," ")}
12
+ `))}}var Zs="packages/config/src/ai/tasks.ts",Qs="The array carries a SINGLE INERT DEMO task: the CLI strips it for buyer builds (leaving an empty\n * `aiTasks`, which hides the Tasks tab) and keeps it for `--demo` builds.",eo="The array starts EMPTY, which hides the Tasks tab until you declare your first task.";async function kn(e){let t=G(e,Zs),r=await at(t,"utf-8"),n=r.replace(/\n?[\t ]*\/\/ gsaas:demo-ai-task-start[\s\S]*?\/\/ gsaas:demo-ai-task-end/,"");if(n===r)throw new Error(`removeDemoAiTasks: could not find the \`gsaas:demo-ai-task\` markers in ${t}. The boilerplate AI tasks config may have been renamed or restructured; update the CLI strip in cleanup.ts.`);let i=n.replace(Qs,eo);if(i===n)throw new Error(`removeDemoAiTasks: the demo-task paragraph in ${t} did not match, so the shipped file would describe a demo task it no longer carries (boilerplate drift).`);await wt(t,i)}async function En(e){let t=G(e,".claude","settings.json"),r;try{r=await at(t,"utf8")}catch{return}let n=JSON.parse(r);delete n.alwaysThinkingEnabled,delete n.enableAllProjectMcpServers,n.env&&(delete n.env.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS,Object.keys(n.env).length===0&&delete n.env),n.permissions?.allow&&(n.permissions.allow=n.permissions.allow.filter(to)),await wt(t,`${JSON.stringify(n,null," ")}
13
+ `)}function to(e){return!(e.startsWith("mcp__")||e.includes("nuxt"))}import{readFileSync as uo}from"fs";import{dirname as mo,join as Pn}from"path";import{fileURLToPath as ho}from"url";import{existsSync as ro}from"fs";import{join as Sn}from"path";function $t(e,t,r){let n=Sn(e,...t);return ro(n)?n:Sn(e,r)}import{mkdir as no,writeFile as io,readdir as so,rm as oo,rmdir as ao}from"fs/promises";import{dirname as jt,join as co,relative as lo,sep as po}from"path";function Ue(e){return e.split(po).join("/")}async function Mt(e){await no(e,{recursive:!0})}async function l(e,t){await Mt(jt(e)),await io(e,t,"utf-8")}async function Fe(e,t){await oo(e,{force:!0});let r=jt(e);for(;r!==t&&r!==jt(r);){try{await ao(r)}catch{return}r=jt(r)}}async function J(e,t,r,n){let i=[],o=await so(e,{withFileTypes:!0});for(let s of o){let a=co(e,s.name),d=Ue(lo(t,a));r(d)||(s.isDirectory()?i.push(...await J(a,t,r,n)):s.isFile()&&(n===void 0||n(d))&&i.push(a))}return i}var fo={postgres:"Postgres",neon:"Neon (managed Postgres)",supabase:"Supabase (managed Postgres)"},go={resend:"Resend",ses:"Amazon SES",smtp:"SMTP"},yo={redis:"Redis",upstash:"Upstash Redis"},bo={node:"Node.js / Docker",vercel:"Vercel"},fr="apps/web",wo="Next.js 16",vo="`app/` routes, `components/`, `lib/`",ko={stripe:"Stripe",polar:"Polar"};function Eo(e){let t=e.architecture==="fullstack",r=t?"(fullstack - Hono API mounted inside the app)":"(separate - standalone Hono backend)",n=t?`Mounted inside \`${fr}\`. A standalone \`apps/backend\` is also kept (inert) so you can switch to separate later.`:"Runs from `apps/backend`; the frontend reaches it over HTTP.",i=yo[e.cacheProvider],o=bo[e.deploymentTarget],s=e.paymentProvider==="none"?"":`
14
+ - **Payments:** ${ko[e.paymentProvider]}`,a=e.desktop?e.mobile?", the desktop app (built with Electron) under `docs/desktop/` and the mobile app (built with Expo) under `docs/mobile/`":", and the desktop app (built with Electron) under `docs/desktop/`":e.mobile?", and the mobile app (built with Expo) under `docs/mobile/`":"",d=e.desktop?" With the desktop app on, both shells render the same body, so one change lands in both.":"",h=`\`useTranslations()\` from \`next-intl\` in components; messages are loaded in \`${fr}/i18n/request.ts\`.`;return Po({archSuffix:r,apiLocation:n,databaseName:fo[e.databaseProvider],cacheName:i,paymentLine:s,emailName:go[e.emailProvider],deployName:o,appDocsRef:a,sharedScreensBothShells:d,i18nRule:h,webAppDir:fr,webAppName:wo,webAppLayout:vo})}function So(){return $t(mo(ho(import.meta.url)),["generators","content"],"content")}function Po(e){let t=uo(Pn(So(),"AGENTS.template.md"),"utf-8"),r=new Map(Object.entries(e)),n=t.replace(/\{\{(\w+)\}\}/g,(o,s)=>{let a=r.get(s);if(a===void 0)throw new Error(`AGENTS.template.md uses unknown token {{${s}}}`);return a}),i=/\{\{[^}]*\}\}/.exec(n);if(i)throw new Error(`AGENTS.template.md carries an unrendered token: ${i[0]}`);return n}async function An(e){await l(Pn(e.projectDir,"AGENTS.md"),Eo(e))}import{join as Ao}from"path";var In="apps/web",gr="Next.js 16",Io={postgres:"Postgres (self-hosted)",neon:"Neon (managed Postgres)",supabase:"Supabase (managed Postgres)"};function To(e){let t=e.appName.trim()||e.projectName,r=Io[e.databaseProvider],n=e.architecture==="fullstack"?`${gr} app at \`${In}/\` with the Hono API mounted inside it. A standalone \`apps/backend/\` is also included (inert in this fullstack setup) so you can split the API into a separate service later without re-scaffolding.`:`${gr} app at \`${In}/\` and a separate Hono backend at \`apps/backend/\`.`,i=e.architecture==="fullstack"?`- App + API: http://localhost:3000
15
15
  - Inngest dev server: http://127.0.0.1:8288`:`- App: http://localhost:3000
16
16
  - API: http://localhost:3010
17
17
  - Inngest dev server: http://127.0.0.1:8288`,o=e.ai?`pnpm mastra:studio # optional: inspect the AI assistant and its memory (localhost:4111)
@@ -22,7 +22,7 @@ ${n}
22
22
 
23
23
  ## Stack
24
24
 
25
- - **Frontend:** ${fr}
25
+ - **Frontend:** ${gr}
26
26
  - **Backend:** Hono (TypeScript, RPC-typed)
27
27
  - **Auth:** Better Auth
28
28
  - **ORM / DB:** Drizzle + ${r}
@@ -74,27 +74,27 @@ pnpm dlx generatesaas eject
74
74
  ## Updates
75
75
 
76
76
  To pull the latest boilerplate changes into this project, open it in your AI coding agent and ask: \`update my GenerateSaaS project\`.
77
- `}async function In(e){await l(Eo(e.projectDir,"README.md"),Po(e))}import{access as Ao}from"fs/promises";import{join as vt}from"path";async function Io(e,t,r){let n=vt(e,"apps/desktop/dev-app-update.yml");try{await Ao(n)}catch{throw new Error(`Cannot neutralize the desktop dev update feed: ${n} is missing (boilerplate drift).`)}await l(n,`provider: generic
77
+ `}async function Tn(e){await l(Ao(e.projectDir,"README.md"),To(e))}import{access as Ro}from"fs/promises";import{join as vt}from"path";async function _o(e,t,r){let n=vt(e,"apps/desktop/dev-app-update.yml");try{await Ro(n)}catch{throw new Error(`Cannot neutralize the desktop dev update feed: ${n} is missing (boilerplate drift).`)}await l(n,`provider: generic
78
78
  url: ${t}
79
79
  updaterCacheDirName: ${r}
80
- `)}function To(e){let t=e.split(".");return t.length>=3?t.slice(1).join("."):e}function Ro(e,t){let r=rr(e,"app");return{appId:`${t.split(".").reverse().join(".")}.${r.replace(/-/g,"")}`,productName:e,protocol:r}}function _o(e){let t=e.toLowerCase().replace(/[^a-z0-9_]/g,"");return/^[a-z]/.test(t)?t:`app${t}`}function Oo(e,t){let r=rr(e,"app");return{appName:e,slug:r,bundleId:[...t.split(".").reverse(),r.replace(/-/g,"")].map(_o).join("."),scheme:/^[a-z]/.test(r)?r:`app-${r}`}}function xo(e){let t=[" // PRESENCE IS THE SWITCH: reporting runs as soon as the credential below is non-empty. There"," // is no separate `enabled` flag to remember - pasting the key IS turning it on, and clearing it"," // is turning it off. These are PUBLISHABLE credentials: they only authorize SENDING events,"," // never reading them, which is why they live here rather than in env and why a packaged desktop"," // app can carry them. Server-side, SENTRY_DSN and POSTHOG_API_KEY override them."].join(`
80
+ `)}function Oo(e){let t=e.split(".");return t.length>=3?t.slice(1).join("."):e}function xo(e,t){let r=nr(e,"app");return{appId:`${t.split(".").reverse().join(".")}.${r.replace(/-/g,"")}`,productName:e,protocol:r}}function Do(e){let t=e.toLowerCase().replace(/[^a-z0-9_]/g,"");return/^[a-z]/.test(t)?t:`app${t}`}function No(e,t){let r=nr(e,"app");return{appName:e,slug:r,bundleId:[...t.split(".").reverse(),r.replace(/-/g,"")].map(Do).join("."),scheme:/^[a-z]/.test(r)?r:`app-${r}`}}function Co(e){let t=[" // PRESENCE IS THE SWITCH: reporting runs as soon as the credential below is non-empty. There"," // is no separate `enabled` flag to remember - pasting the key IS turning it on, and clearing it"," // is turning it off. These are PUBLISHABLE credentials: they only authorize SENDING events,"," // never reading them, which is why they live here rather than in env and why a packaged desktop"," // app can carry them. Server-side, SENTRY_DSN and POSTHOG_API_KEY override them."].join(`
81
81
  `),r=[];return e.includes("sentry")&&r.push(' sentry: { dsn: "" }'),e.includes("posthog")&&r.push([" // llmContent sends your users' prompts and completions to PostHog. Every number (tokens,"," // cost, latency, errors) is captured either way - turn it on only if your privacy policy"," // covers sending their message text to a third party.",' posthog: { publicKey: "", host: "https://us.i.posthog.com", llmContent: false }'].join(`
82
82
  `)),r.length===0?[" // Error and product reporting is OFF: no provider was selected at init, so neither adapter",' // nor SDK was generated. To turn one on, add `"sentry"`, `"posthog"` or both to the'," // `observability` array in `.generatesaas/manifest.json`, then run `generatesaas update` -"," // which re-shapes the project and installs what it needs. Note that update stages nothing"," // while you are already on the latest version, so take the upgrade first if it reports no"," // changes."," observability: {},"].join(`
83
83
  `):`${t}
84
84
  observability: {
85
85
  ${r.join(`,
86
86
  `)}
87
- },`}async function Tn(e){let t=e.appName.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),r=e.paymentProvider!=="none",n=e.baseUrl??"http://localhost:3000",i=e.baseUrl?new URL(e.baseUrl).hostname:"example.com",o=To(i),s=e.demo?"false":"true",a=e.multiTenancy?`{
87
+ },`}async function Rn(e){let t=e.appName.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),r=e.paymentProvider!=="none",n=e.baseUrl??"http://localhost:3000",i=e.baseUrl?new URL(e.baseUrl).hostname:"example.com",o=Oo(i),s=e.demo?"false":"true",a=e.multiTenancy?`{
88
88
  multiTenant: true,
89
89
  organizationLimit: 5,
90
90
  defaultOrganizationName: "{name}'s workspace"
91
- }`:"{ multiTenant: false }",d=e.projects?"{ enabled: true, seedDefault: true }":"{ enabled: false, seedDefault: true }",h=xo(e.observability),g=e.demo?`{
91
+ }`:"{ multiTenant: false }",d=e.projects?"{ enabled: true, seedDefault: true }":"{ enabled: false, seedDefault: true }",h=Co(e.observability),g=e.demo?`{
92
92
  enableInDev: true,
93
93
  chatwoot: {
94
94
  baseUrl: "https://support.alexchelan.com",
95
95
  websiteToken: "1uWvJLHkhWLihkK2bxLaj2Fg"
96
96
  }
97
- }`:"{}",w=e.architecture==="fullstack"?"false":"true",v=Ro(t,o),P=`https://cdn.${o}/desktop`,m=Oo(t,o),D=` // Store purchases (RevenueCat) for the mobile app - ADDITIVE to the web provider, never a
97
+ }`:"{}",E=e.architecture==="fullstack"?"false":"true",w=xo(t,o),P=`https://cdn.${o}/desktop`,m=No(t,o),O=` // Store purchases (RevenueCat) for the mobile app - ADDITIVE to the web provider, never a
98
98
  // replacement: store rules require digital goods to be sold through in-app purchase.
99
99
  mobile: {
100
100
  enabled: ${e.mobilePurchases==="revenuecat"},
@@ -103,7 +103,7 @@ ${r.join(`,
103
103
  grantCreditsToFamilyShare: false,
104
104
  externalPurchaseLinks: "off",
105
105
  customerCenter: true
106
- }`,we=`import type { AgentsConfig, AppConfig } from "@repo/config/types";
106
+ }`,be=`import type { AgentsConfig, AppConfig } from "@repo/config/types";
107
107
  import { resolveAgentsConfig } from "./agents";
108
108
  import { desktopConfig } from "./desktop.mjs";
109
109
  import { mobileConfig } from "./mobile.mjs";
@@ -187,10 +187,10 @@ export const config: AppConfig = {
187
187
  enabled: true,
188
188
  provider: "${e.paymentProvider}",
189
189
  bannedCountries: ["BY", "CU", "IR", "KP", "RU", "SY"],
190
- ${D}
190
+ ${O}
191
191
  }`:`{
192
192
  enabled: false,
193
- ${D}
193
+ ${O}
194
194
  }`},
195
195
  sms: { enabled: false },
196
196
  newsletter: { enabled: false },
@@ -201,7 +201,7 @@ ${D}
201
201
  maxCreatesPerDay: 20
202
202
  },
203
203
  apiDocs: true,
204
- performanceMonitor: { enabled: ${w} },
204
+ performanceMonitor: { enabled: ${E} },
205
205
  // Open pages re-read what changed elsewhere, over one coalesced signal; see docs/live-updates.
206
206
  liveUpdates: { enabled: true },
207
207
  ${h}
@@ -248,7 +248,7 @@ ${h}
248
248
  }`:`{
249
249
  base: "${e.defaultCurrency}",
250
250
  list: [
251
- { symbol: "${Oe[e.defaultCurrency].symbol}", name: "${Oe[e.defaultCurrency].name}", code: "${e.defaultCurrency}", place: "${Oe[e.defaultCurrency].place}", space: ${Oe[e.defaultCurrency].space} }
251
+ { symbol: "${De[e.defaultCurrency].symbol}", name: "${De[e.defaultCurrency].name}", code: "${e.defaultCurrency}", place: "${De[e.defaultCurrency].place}", space: ${De[e.defaultCurrency].space} }
252
252
  ],
253
253
  countryMap: {
254
254
  default: "${e.defaultCurrency}"
@@ -384,8 +384,8 @@ ${h}
384
384
  desktop: desktopConfig,
385
385
  mobile: mobileConfig,
386
386
  // Outward MCP server exposing the capability layer to external agents. Its code ships with every
387
- // project, so \`enabled\` alone controls the /mcp endpoint and the MCP settings tab.
388
- mcpServer: { enabled: ${e.demo?"true":"false"} },
387
+ // 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.":""}
388
+ mcpServer: { enabled: ${e.demo?"true":"false"}${e.ai?", apps: true":""} },
389
389
  // Revenue sharing: your answer at init, and yours to change here at any time. On, the daily
390
390
  // license heartbeat self-reports an aggregate revenue estimate (MRR, ARR, total and 30-day
391
391
  // revenue, active subscriptions). No customer data, but not anonymous either: the figures travel
@@ -462,7 +462,7 @@ export * from "./robots";
462
462
  export * from "./roles";
463
463
  export * from "./section-tabs";
464
464
  export * from "./tenancy";
465
- `,K=vt(e.projectDir,"packages/config/src/index.ts");await l(K,we),await l(vt(e.projectDir,"packages/config/src/support.ts"),`import type { SupportConfig } from "@repo/config/types";
465
+ `,B=vt(e.projectDir,"packages/config/src/index.ts");await l(B,be),await l(vt(e.projectDir,"packages/config/src/support.ts"),`import type { SupportConfig } from "@repo/config/types";
466
466
 
467
467
  /**
468
468
  * Live-chat (support widget) configuration, re-exported by the config index as
@@ -483,9 +483,9 @@ export const supportConfig: SupportConfig = ${g};
483
483
 
484
484
  export const desktopConfig = {
485
485
  enabled: ${e.desktop},
486
- appId: "${v.appId}",
487
- productName: "${v.productName}",
488
- protocol: "${v.protocol}",
486
+ appId: "${w.appId}",
487
+ productName: "${w.productName}",
488
+ protocol: "${w.protocol}",
489
489
  baseUrl: "${n}",
490
490
  // Public base URL the release workflow uploads to; electron-updater polls
491
491
  // \`<url>/latest-mac.yml\` (\`latest.yml\` on Windows, \`latest-linux.yml\` on Linux) plus
@@ -639,9 +639,9 @@ export const SETTINGS_PRIVACY_PATH = "/settings/privacy";
639
639
  export const SETTINGS_APP_LOCK_PATH = "/settings/app-lock";
640
640
  /** app/(app)/settings/about.tsx - version, legal links and support. */
641
641
  export const SETTINGS_ABOUT_PATH = "/settings/about";
642
- `),e.desktop&&await Io(e.projectDir,P,`${v.protocol}-updater`)}import{join as Do}from"path";function No(e,t){let r=[e==="stripe"?' stripePriceId: "",':' polarProductId: "",'];return t&&r.push(' appleProductId: "",',' googleProductId: "",'," storeAmounts: {},"),r.join(`
643
- `)}function gr(e){let t=[];return e.withCredits&&(t.push(`credits: ${e.credits}`),e.recurring!==!1&&t.push("creditInterval: 30")),t.push(`apiRateLimit: { maxRequests: ${e.rateLimit} }`),e.maxConcurrentRuns!==void 0&&t.push(`maxConcurrentRuns: ${e.maxConcurrentRuns}`),e.automationMinutesPerMonth!==void 0&&t.push(`automationMinutesPerMonth: ${e.automationMinutesPerMonth}`),t.map(r=>` ${r}`).join(`,
644
- `)}async function Rn(e){let t=Do(e.projectDir,"packages/config/src/pricing.ts"),r=e.defaultCurrency;if(e.paymentProvider==="none"){let P=`import type { PricingConfig } from "@repo/config/types";
642
+ `),e.desktop&&await _o(e.projectDir,P,`${w.protocol}-updater`)}import{join as Lo}from"path";function $o(e,t){let r=[e==="stripe"?' stripePriceId: "",':' polarProductId: "",'];return t&&r.push(' appleProductId: "",',' googleProductId: "",'," storeAmounts: {},"),r.join(`
643
+ `)}function yr(e){let t=[];return e.withCredits&&(t.push(`credits: ${e.credits}`),e.recurring!==!1&&t.push("creditInterval: 30")),t.push(`apiRateLimit: { maxRequests: ${e.rateLimit} }`),e.maxConcurrentRuns!==void 0&&t.push(`maxConcurrentRuns: ${e.maxConcurrentRuns}`),e.automationMinutesPerMonth!==void 0&&t.push(`automationMinutesPerMonth: ${e.automationMinutesPerMonth}`),t.map(r=>` ${r}`).join(`,
644
+ `)}async function _n(e){let t=Lo(e.projectDir,"packages/config/src/pricing.ts"),r=e.defaultCurrency;if(e.paymentProvider==="none"){let P=`import type { PricingConfig } from "@repo/config/types";
645
645
 
646
646
  export const pricingConfig: PricingConfig = {
647
647
  defaultPlan: "free",
@@ -670,7 +670,7 @@ export const pricingConfig: PricingConfig = {
670
670
  credits: { enabled: false },
671
671
  products: { enabled: false, items: [] }
672
672
  };
673
- `;await l(t,P);return}let n=e.paymentProvider,i=No(n,e.mobilePurchases==="revenuecat"),o=e.credits,s=!!e.ai,a=gr({credits:5,rateLimit:100,withCredits:o,recurring:!1,...s&&{maxConcurrentRuns:2,automationMinutesPerMonth:60}}),d=gr({credits:10,rateLimit:1e3,withCredits:o,...s&&{maxConcurrentRuns:5,automationMinutesPerMonth:600}}),h=gr({credits:40,rateLimit:5e3,withCredits:o,...s&&{maxConcurrentRuns:10,automationMinutesPerMonth:3e3}}),g=r==="USD"?"":` // !! ${r} pricing WARNING: creditsPerUsd anchors credit cost to USD (AI providers bill in
673
+ `;await l(t,P);return}let n=e.paymentProvider,i=$o(n,e.mobilePurchases==="revenuecat"),o=e.credits,s=!!e.ai,a=yr({credits:5,rateLimit:100,withCredits:o,recurring:!1,...s&&{maxConcurrentRuns:2,automationMinutesPerMonth:60}}),d=yr({credits:10,rateLimit:1e3,withCredits:o,...s&&{maxConcurrentRuns:5,automationMinutesPerMonth:600}}),h=yr({credits:40,rateLimit:5e3,withCredits:o,...s&&{maxConcurrentRuns:10,automationMinutesPerMonth:3e3}}),g=r==="USD"?"":` // !! ${r} pricing WARNING: creditsPerUsd anchors credit cost to USD (AI providers bill in
674
674
  // !! USD), but your plan prices and credit purchases are denominated in ${r}. Verify that the
675
675
  // !! ${r} amounts above cover the USD cost per credit (~0.50 USD at creditsPerUsd 1 with the
676
676
  // !! 100% markup) - and raise prices or creditsPerUsd if they do not.
@@ -679,7 +679,7 @@ export const pricingConfig: PricingConfig = {
679
679
  !! plan prices and credit purchases are denominated in ${r}. At the shipped economics 1 credit
680
680
  !! carries ~0.50 USD of AI cost - verify every ${r} price still covers it (see the comment on the
681
681
  !! credits block in packages/config/src/pricing.ts), or raise prices / creditsPerUsd.
682
- `);let w=o?` // creditsPerUsd scales USD cost -> credits (1 = 1 credit carries ~0.50 USD of cost after the
682
+ `);let E=o?` // creditsPerUsd scales USD cost -> credits (1 = 1 credit carries ~0.50 USD of cost after the
683
683
  // 100% markup); markupPercent is the DEFAULT margin for everything that debits credits (AI,
684
684
  // external APIs, your own features), and credits.markupByCategory overrides it per metered
685
685
  // service ("ai", "webSearch", "webExtract"). Two optional knobs shape each debit's size:
@@ -698,7 +698,7 @@ ${g} credits: {
698
698
  // priced explicitly at twice cost instead of inheriting the global rate by accident. A free
699
699
  // engine still debits nothing - twice zero is zero.
700
700
  markupByCategory: { webSearch: 100, webExtract: 100 }
701
- }`:" credits: { enabled: false }",v=`import type { PricingConfig } from "@repo/config/types";
701
+ }`:" credits: { enabled: false }",w=`import type { PricingConfig } from "@repo/config/types";
702
702
 
703
703
  export const pricingConfig: PricingConfig = {
704
704
  defaultPlan: "free",
@@ -782,22 +782,22 @@ ${i}
782
782
  ${h}
783
783
  }
784
784
  ],
785
- ${w},
785
+ ${E},
786
786
  products: {
787
787
  enabled: false,
788
788
  items: []
789
789
  }
790
790
  };
791
- `;await l(t,v)}var Co={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)"}]},Lo={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 jt(e,t){return t?e.map(r=>{let n=t[r.key];return n?{...r,defaultValue:n,comment:void 0}:r}):e}function wt(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 yr(e){return Array.from(crypto.getRandomValues(new Uint8Array(e))).map(t=>t.toString(16).padStart(2,"0")).join("")}function br(e){return e.architecture==="fullstack"?{apiUrl:"http://localhost:3000/api",baseUrl:"http://localhost:3000"}:{apiUrl:"http://localhost:3010",baseUrl:"http://localhost:3000"}}var $o="https://your-app.example.com/api";function Mt(e,t,r,n){e.push(n==="example"?`${t}=`:`${t}=${r}`)}function _n(e,t){let r=t==="example"?void 0:e.credentials,{apiUrl:n,baseUrl:i}=br(e),o=[];e.architecture==="separate"?o.push("# API Configuration","# Standalone backend's own URL (the frontend reaches it via the public var above).",`API_URL=${n}`,`BASE_URL=${i}`):o.push("# App","# (API_URL is derived from the frontend's *_PUBLIC_API_URL by the runtime env schema.)",`BASE_URL=${i}`),o.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"?o.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."):o.push("# This build reads the connection peer, so a server exposed directly identifies its","# callers correctly with nothing set here."),o.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"),o.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"),o.push("","# Database"),wt(jt(xe[e.databaseProvider].envVars,r),o),o.push("","# Cache"),wt(jt(De[e.cacheProvider].envVars,r),o),e.cacheProvider==="redis"&&o.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="),o.push("","# Authentication"),t==="example"&&o.push("# Generate a strong secret, e.g. `openssl rand -hex 32`"),Mt(o,"BETTER_AUTH_SECRET",crypto.randomUUID(),t),o.push("","# Content API (random secret; required when contentApi feature is enabled in @repo/config)"),Mt(o,"CONTENT_API_KEY",yr(32),t),o.push("","# Job Queue - Inngest","INNGEST_APP_ID=api"),Mt(o,"INNGEST_EVENT_KEY",yr(32),t),o.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."),Mt(o,"INNGEST_SIGNING_KEY",yr(32),t),o.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"&&(o.push("","# API Port (standalone backend)","API_PORT=3010"),o.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 s=Co[e.emailProvider];if(s&&(o.push("","# Email"),wt(jt(s,r),o)),e.paymentProvider!=="none"){let d=Lo[e.paymentProvider];d&&(o.push("","# Payment"),wt(jt(d,r),o))}o.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"),o.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"),o.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="),o.push("","# SMS - Twilio (optional)","#TWILIO_ACCOUNT_SID=ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx","#TWILIO_AUTH_TOKEN=","#TWILIO_PHONE_NUMBER=+1234567890"),o.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&&o.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="),o.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).
791
+ `;await l(t,w)}var jo={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)"}]},Mo={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 Ut(e,t){return t?e.map(r=>{let n=t[r.key];return n?{...r,defaultValue:n,comment:void 0}:r}):e}function kt(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 br(e){return Array.from(crypto.getRandomValues(new Uint8Array(e))).map(t=>t.toString(16).padStart(2,"0")).join("")}function wr(e){return e.architecture==="fullstack"?{apiUrl:"http://localhost:3000/api",baseUrl:"http://localhost:3000"}:{apiUrl:"http://localhost:3010",baseUrl:"http://localhost:3000"}}var Uo="https://your-app.example.com/api";function Ft(e,t,r,n){e.push(n==="example"?`${t}=`:`${t}=${r}`)}function On(e,t){let r=t==="example"?void 0:e.credentials,{apiUrl:n,baseUrl:i}=wr(e),o=[];e.architecture==="separate"?o.push("# API Configuration","# Standalone backend's own URL (the frontend reaches it via the public var above).",`API_URL=${n}`,`BASE_URL=${i}`):o.push("# App","# (API_URL is derived from the frontend's *_PUBLIC_API_URL by the runtime env schema.)",`BASE_URL=${i}`),o.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"?o.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."):o.push("# This build reads the connection peer, so a server exposed directly identifies its","# callers correctly with nothing set here."),o.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"),o.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"),o.push("","# Database"),kt(Ut(Ne[e.databaseProvider].envVars,r),o),o.push("","# Cache"),kt(Ut(Ce[e.cacheProvider].envVars,r),o),e.cacheProvider==="redis"&&o.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="),o.push("","# Authentication"),t==="example"&&o.push("# Generate a strong secret, e.g. `openssl rand -hex 32`"),Ft(o,"BETTER_AUTH_SECRET",crypto.randomUUID(),t),o.push("","# Content API (random secret; required when contentApi feature is enabled in @repo/config)"),Ft(o,"CONTENT_API_KEY",br(32),t),o.push("","# Job Queue - Inngest","INNGEST_APP_ID=api"),Ft(o,"INNGEST_EVENT_KEY",br(32),t),o.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."),Ft(o,"INNGEST_SIGNING_KEY",br(32),t),o.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"&&(o.push("","# API Port (standalone backend)","API_PORT=3010"),o.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 s=jo[e.emailProvider];if(s&&(o.push("","# Email"),kt(Ut(s,r),o)),e.paymentProvider!=="none"){let d=Mo[e.paymentProvider];d&&(o.push("","# Payment"),kt(Ut(d,r),o))}o.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"),o.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"),o.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="),o.push("","# SMS - Twilio (optional)","#TWILIO_ACCOUNT_SID=ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx","#TWILIO_AUTH_TOKEN=","#TWILIO_PHONE_NUMBER=+1234567890"),o.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&&o.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="),o.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).
792
792
  # Set but EMPTY switches every server-side PostHog report off (the e2e harness does this). Leave it
793
- # unset in production: the committed key is used, and only the deployment reports.`}),a.length>0&&(o.push("","# Error and product reporting (optional)"),wt(a,o)),o.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&&o.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&&(o.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"&&o.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=")),o.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="),o.push(""),o.join(`
794
- `)}var On="NEXT_PUBLIC_API_URL";function jo(e){let{apiUrl:t}=br(e),r=["# API Configuration",`${On}=${t}`];return e.architecture==="separate"&&r.push("","# Production (uncomment and replace with your deployed hostnames):",`# ${On}=${$o}`),r.push(""),r.join(`
795
- `)}function Mo(e){let{apiUrl:t,baseUrl:r}=br(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(`
796
- `)}async function xn(e){let t=jo(e);if(await l(`${e.projectDir}/.env`,`${t}
797
- ${_n(e,"env")}`),await l(`${e.projectDir}/.env.example`,`${t}
798
- ${_n(e,"example")}`),e.mobile){let r=Mo(e);await l(`${e.projectDir}/apps/mobile/.env`,r),await l(`${e.projectDir}/apps/mobile/.env.example`,r)}}import{join as Uo}from"path";var Fo=`# Every port is published on 127.0.0.1 only: these development services run with fixed credentials
793
+ # unset in production: the committed key is used, and only the deployment reports.`}),a.length>0&&(o.push("","# Error and product reporting (optional)"),kt(a,o)),o.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&&o.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&&(o.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"&&o.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=")),o.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="),o.push(""),o.join(`
794
+ `)}var xn="NEXT_PUBLIC_API_URL";function Fo(e){let{apiUrl:t}=wr(e),r=["# API Configuration",`${xn}=${t}`];return e.architecture==="separate"&&r.push("","# Production (uncomment and replace with your deployed hostnames):",`# ${xn}=${Uo}`),r.push(""),r.join(`
795
+ `)}function Vo(e){let{apiUrl:t,baseUrl:r}=wr(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(`
796
+ `)}async function Dn(e){let t=Fo(e);if(await l(`${e.projectDir}/.env`,`${t}
797
+ ${On(e,"env")}`),await l(`${e.projectDir}/.env.example`,`${t}
798
+ ${On(e,"example")}`),e.mobile){let r=Vo(e);await l(`${e.projectDir}/apps/mobile/.env`,r),await l(`${e.projectDir}/apps/mobile/.env.example`,r)}}import{join as Bo}from"path";var Ko=`# Every port is published on 127.0.0.1 only: these development services run with fixed credentials
799
799
  # or none, so nothing else on your network should reach them.
800
- `;async function Dn(e){let t=et(e),r=[],n=[];if(t.includes("postgres")&&(r.push(` postgres:
800
+ `;async function Nn(e){let t=et(e),r=[],n=[];if(t.includes("postgres")&&(r.push(` postgres:
801
801
  image: postgres:18-alpine
802
802
  restart: unless-stopped
803
803
  ports:
@@ -833,10 +833,15 @@ ${_n(e,"example")}`),e.mobile){let r=Mo(e);await l(`${e.projectDir}/apps/mobile/
833
833
  environment:
834
834
  MP_SMTP_AUTH_ACCEPT_ANY: 1
835
835
  MP_SMTP_AUTH_ALLOW_INSECURE: 1`),t.includes("inngest")){let s=e.architecture==="separate"?"http://host.docker.internal:3010/inngest":"http://host.docker.internal:3000/api/inngest";r.push(` inngest:
836
- image: inngest/inngest:v1.17.9
836
+ image: inngest/inngest:v1.46.0
837
837
  restart: unless-stopped
838
838
  ports:
839
839
  - "127.0.0.1:\${INNGEST_PORT:-8288}:8288"
840
+ healthcheck:
841
+ test: ["CMD", "inngest", "alpha", "doctor", "healthcheck"]
842
+ interval: 10s
843
+ timeout: 5s
844
+ retries: 5
840
845
  # \`-u\` is load-bearing, not tuning. Without it \`inngest dev\` AUTO-DISCOVERS, and it scans its own
841
846
  # container's localhost - where nothing is listening. It then registers zero apps and silently
842
847
  # runs no functions, so on a stock stack NOTHING that goes through Inngest is ever delivered: no
@@ -851,7 +856,7 @@ ${_n(e,"example")}`),e.mobile){let r=Mo(e);await l(`${e.projectDir}/apps/mobile/
851
856
  extra_hosts:
852
857
  - "host.docker.internal:host-gateway"`)}let o=`name: ${`${e.projectName}-infra`}
853
858
 
854
- ${Fo}services:
859
+ ${Ko}services:
855
860
  ${r.join(`
856
861
 
857
862
  `)}
@@ -859,22 +864,22 @@ ${r.join(`
859
864
  volumes:
860
865
  ${n.join(`
861
866
  `)}
862
- `),await l(Uo(e.projectDir,"infra/docker-compose.yml"),o)}import{join as Vo}from"path";var kt="Next.js";function Bo(e){let t=[];if(t.push({type:"node-terminal",request:"launch",name:"Dev",command:"pnpm dev",cwd:"${workspaceFolder}",skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development"}}),e.architecture==="separate"&&t.push({type:"node-terminal",request:"launch",name:"Backend",command:"pnpm dev",cwd:"${workspaceFolder}/apps/backend",skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development"}}),t.push({type:"node-terminal",request:"launch",name:kt,command:"pnpm dev",cwd:"${workspaceFolder}/apps/web",skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development"}}),e.docs&&t.push({type:"node-terminal",request:"launch",name:"Docs",command:"pnpm dev",cwd:"${workspaceFolder}/apps/docs",skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development"}}),e.desktop){let r=e.architecture==="separate"?"http://localhost:3010":"http://localhost:3000/api";t.push({type:"node-terminal",request:"launch",name:"Desktop",command:"pnpm dev",cwd:"${workspaceFolder}/apps/desktop",skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development",BASE_URL:"http://localhost:3000",PUBLIC_API_URL:r}})}if(t.push({type:"node-terminal",request:"launch",name:"Inngest",command:"pnpm dev:inngest",cwd:"${workspaceFolder}",skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development"}}),t.push({type:"node-terminal",request:"launch",name:"Mail",command:"pnpm dev:mail",cwd:"${workspaceFolder}",skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development"}}),e.paymentProvider==="stripe"){let r=e.architecture==="separate"?"localhost:3010/auth/stripe/webhook":"localhost:3000/api/auth/stripe/webhook";t.push({type:"node-terminal",request:"launch",name:"Stripe",command:`stripe listen --forward-to ${r}`,cwd:"${workspaceFolder}",skipFiles:["<node_internals>/**"]})}return t}function Ko(e){let t=[];return e.architecture==="separate"?t.push({name:`Dev (${kt} + Backend + Inngest)`,configurations:["Backend",kt,"Inngest"]}):t.push({name:`Dev (${kt} + Inngest)`,configurations:[kt,"Inngest"]}),t}async function Nn(e){let t={version:"0.2.0",configurations:Bo(e),compounds:Ko(e)};await l(Vo(e.projectDir,".vscode/launch.json"),`${JSON.stringify(t,null," ")}
863
- `)}import{readFile as Ln}from"fs/promises";import{join as $n}from"path";var vr='import { drizzle } from "drizzle-orm/node-postgres";',wr=`export const db = drizzle(parsed.data.DATABASE_URL, { schema });
864
- export const pool = db.$client;`,Go={postgres:{importLine:vr,instantiation:wr},neon:{importLine:`import { Pool } from "@neondatabase/serverless";
867
+ `),await l(Bo(e.projectDir,"infra/docker-compose.yml"),o)}import{join as Go}from"path";var Et="Next.js";function Ho(e){let t=[];if(t.push({type:"node-terminal",request:"launch",name:"Dev",command:"pnpm dev",cwd:"${workspaceFolder}",skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development"}}),e.architecture==="separate"&&t.push({type:"node-terminal",request:"launch",name:"Backend",command:"pnpm dev",cwd:"${workspaceFolder}/apps/backend",skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development"}}),t.push({type:"node-terminal",request:"launch",name:Et,command:"pnpm dev",cwd:"${workspaceFolder}/apps/web",skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development"}}),e.docs&&t.push({type:"node-terminal",request:"launch",name:"Docs",command:"pnpm dev",cwd:"${workspaceFolder}/apps/docs",skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development"}}),e.desktop){let r=e.architecture==="separate"?"http://localhost:3010":"http://localhost:3000/api";t.push({type:"node-terminal",request:"launch",name:"Desktop",command:"pnpm dev",cwd:"${workspaceFolder}/apps/desktop",skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development",BASE_URL:"http://localhost:3000",PUBLIC_API_URL:r}})}if(t.push({type:"node-terminal",request:"launch",name:"Inngest",command:"pnpm dev:inngest",cwd:"${workspaceFolder}",skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development"}}),t.push({type:"node-terminal",request:"launch",name:"Mail",command:"pnpm dev:mail",cwd:"${workspaceFolder}",skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development"}}),e.paymentProvider==="stripe"){let r=e.architecture==="separate"?"localhost:3010/auth/stripe/webhook":"localhost:3000/api/auth/stripe/webhook";t.push({type:"node-terminal",request:"launch",name:"Stripe",command:`stripe listen --forward-to ${r}`,cwd:"${workspaceFolder}",skipFiles:["<node_internals>/**"]})}return t}function Yo(e){let t=[];return e.architecture==="separate"?t.push({name:`Dev (${Et} + Backend + Inngest)`,configurations:["Backend",Et,"Inngest"]}):t.push({name:`Dev (${Et} + Inngest)`,configurations:[Et,"Inngest"]}),t}async function Cn(e){let t={version:"0.2.0",configurations:Ho(e),compounds:Yo(e)};await l(Go(e.projectDir,".vscode/launch.json"),`${JSON.stringify(t,null," ")}
868
+ `)}import{readFile as $n}from"fs/promises";import{join as jn}from"path";var vr='import { drizzle } from "drizzle-orm/node-postgres";',kr=`export const db = drizzle(parsed.data.DATABASE_URL, { schema });
869
+ export const pool = db.$client;`,Wo={postgres:{importLine:vr,instantiation:kr},neon:{importLine:`import { Pool } from "@neondatabase/serverless";
865
870
  import { drizzle } from "drizzle-orm/neon-serverless";`,instantiation:`const pool = new Pool({ connectionString: parsed.data.DATABASE_URL });
866
871
  export const db = drizzle(pool, { schema });`},supabase:{importLine:`import { drizzle } from "drizzle-orm/postgres-js";
867
872
  import postgres from "postgres";`,instantiation:`const client = postgres(parsed.data.DATABASE_URL);
868
- export const db = drizzle(client, { schema });`}};async function jn(e){let t=$n(e.projectDir,"packages/database/src/index.ts"),r=await Ln(t,"utf-8");if(!r.includes(vr)||!r.includes(wr))throw new Error("generateDbDriver: boilerplate packages/database/src/index.ts is missing the node-postgres driver anchors (the import line or the `db` instantiation block); the boilerplate drifted.");let n=Go[e.databaseProvider],i=r.replace(vr,n.importLine).replace(wr,n.instantiation);await l(t,i),await Yo(e)}var Cn='import { Client } from "pg";',kr=` const client = new Client({ connectionString });
873
+ export const db = drizzle(client, { schema });`}};async function Mn(e){let t=jn(e.projectDir,"packages/database/src/index.ts"),r=await $n(t,"utf-8");if(!r.includes(vr)||!r.includes(kr))throw new Error("generateDbDriver: boilerplate packages/database/src/index.ts is missing the node-postgres driver anchors (the import line or the `db` instantiation block); the boilerplate drifted.");let n=Wo[e.databaseProvider],i=r.replace(vr,n.importLine).replace(kr,n.instantiation);await l(t,i),await qo(e)}var Ln='import { Client } from "pg";',Er=` const client = new Client({ connectionString });
869
874
  await client.connect();
870
875
  return {
871
876
  query: async (text) => ({ rows: (await client.query<LiveColumnRow>(text)).rows }),
872
877
  end: () => client.end()
873
- };`,Ho={postgres:null,neon:{importLine:'import { Client } from "@neondatabase/serverless";',open:kr},supabase:{importLine:'import postgres from "postgres";',open:` const sql = postgres(connectionString, { prepare: false });
878
+ };`,zo={postgres:null,neon:{importLine:'import { Client } from "@neondatabase/serverless";',open:Er},supabase:{importLine:'import postgres from "postgres";',open:` const sql = postgres(connectionString, { prepare: false });
874
879
  return {
875
880
  query: async (text) => ({ rows: await sql.unsafe(text) }),
876
881
  end: () => sql.end()
877
- };`}};async function Yo(e){let t=Ho[e.databaseProvider];if(!t)return;let r=$n(e.projectDir,"packages/database/src/db-verify.ts"),n=await Ln(r,"utf-8");if(!n.includes(Cn)||!n.includes(kr))throw new Error("generateDbDriver: boilerplate packages/database/src/db-verify.ts is missing the node-postgres verifier anchors (the import line or the openVerifyClient body); the boilerplate drifted.");await l(r,n.replace(Cn,t.importLine).replace(kr,t.open))}import{join as Mn}from"path";async function Un(e){e.cacheProvider==="upstash"&&(await Wo(e),await zo(e))}async function Wo(e){await l(Mn(e.projectDir,"packages/runtime/src/redis.ts"),`import { Redis } from "@upstash/redis";
882
+ };`}};async function qo(e){let t=zo[e.databaseProvider];if(!t)return;let r=jn(e.projectDir,"packages/database/src/db-verify.ts"),n=await $n(r,"utf-8");if(!n.includes(Ln)||!n.includes(Er))throw new Error("generateDbDriver: boilerplate packages/database/src/db-verify.ts is missing the node-postgres verifier anchors (the import line or the openVerifyClient body); the boilerplate drifted.");await l(r,n.replace(Ln,t.importLine).replace(Er,t.open))}import{join as Un}from"path";async function Fn(e){e.cacheProvider==="upstash"&&(await Jo(e),await Xo(e))}async function Jo(e){await l(Un(e.projectDir,"packages/runtime/src/redis.ts"),`import { Redis } from "@upstash/redis";
878
883
  import type { Store } from "hono-rate-limiter";
879
884
  import { env } from "./env";
880
885
 
@@ -1086,7 +1091,7 @@ export function subscribeRedisChannel(
1086
1091
 
1087
1092
  /** No persistent connection to close with Upstash REST. */
1088
1093
  export async function closeRedis(): Promise<void> {}
1089
- `)}async function zo(e){await l(Mn(e.projectDir,"packages/runtime/src/mutex.ts"),`import { Lock } from "@upstash/lock";
1094
+ `)}async function Xo(e){await l(Un(e.projectDir,"packages/runtime/src/mutex.ts"),`import { Lock } from "@upstash/lock";
1090
1095
  import { redis } from "./redis";
1091
1096
 
1092
1097
  export class MutexTimeoutError extends Error {
@@ -1164,18 +1169,18 @@ export async function withMutex<T>(
1164
1169
  });
1165
1170
  }
1166
1171
  }
1167
- `)}import{readFile as qo}from"fs/promises";import{join as Jo}from"path";var Fn=" REDIS_URL: z.string(),",Xo=` UPSTASH_REDIS_REST_URL: z.string(),
1168
- UPSTASH_REDIS_REST_TOKEN: z.string(),`;async function Vn(e){let t=Jo(e.projectDir,"packages/runtime/src/env.ts"),r=await qo(t,"utf-8");if(!r.includes(Fn))throw new Error("generateEnvSchema: boilerplate packages/runtime/src/env.ts is missing the REDIS_URL cache binding anchor; the boilerplate drifted.");let n=e.cacheProvider==="upstash"?r.replace(Fn,Xo):r;await l(t,n)}import{readFile as Yn}from"fs/promises";import{join as j}from"path";import{readFile as Sr,rm as ea}from"fs/promises";import{join as Ve}from"path";import{readFile as Er}from"fs/promises";function Zo(e){return new RegExp(`^[ \\t]*(?:\\/\\/|\\{\\/\\*|\\*) gsaas:${e}-start(?: \\*\\/\\})?[ \\t]*\\r?\\n[\\s\\S]*?^[ \\t]*(?:\\/\\/|\\{\\/\\*|\\*) gsaas:${e}-end(?: \\*\\/\\})?[ \\t]*\\r?\\n`,"gm")}function Ue(e,t,r,n){let i=Zo(r);if(e.match(i)===null)throw new Error(`${n}: expected gsaas ${r} markers in ${t}, but found none (boilerplate drift).`);let o=e.replace(i,"");if(o.includes(`gsaas:${r}-start`)||o.includes(`gsaas:${r}-end`))throw new Error(`${n}: an unbalanced gsaas ${r} marker is left in ${t} (boilerplate drift).`);return o.replace(/\n{3,}/g,`
1172
+ `)}import{readFile as Zo}from"fs/promises";import{join as Qo}from"path";var Vn=" REDIS_URL: z.string(),",ea=` UPSTASH_REDIS_REST_URL: z.string(),
1173
+ UPSTASH_REDIS_REST_TOKEN: z.string(),`;async function Bn(e){let t=Qo(e.projectDir,"packages/runtime/src/env.ts"),r=await Zo(t,"utf-8");if(!r.includes(Vn))throw new Error("generateEnvSchema: boilerplate packages/runtime/src/env.ts is missing the REDIS_URL cache binding anchor; the boilerplate drifted.");let n=e.cacheProvider==="upstash"?r.replace(Vn,ea):r;await l(t,n)}import{readFile as Wn}from"fs/promises";import{join as M}from"path";import{readFile as Pr,rm as na}from"fs/promises";import{join as Ke}from"path";import{readFile as Sr}from"fs/promises";function ta(e){return new RegExp(`^[ \\t]*(?:\\/\\/|\\{\\/\\*|\\*) gsaas:${e}-start(?: \\*\\/\\})?[ \\t]*\\r?\\n[\\s\\S]*?^[ \\t]*(?:\\/\\/|\\{\\/\\*|\\*) gsaas:${e}-end(?: \\*\\/\\})?[ \\t]*\\r?\\n`,"gm")}function Ve(e,t,r,n){let i=ta(r);if(e.match(i)===null)throw new Error(`${n}: expected gsaas ${r} markers in ${t}, but found none (boilerplate drift).`);let o=e.replace(i,"");if(o.includes(`gsaas:${r}-start`)||o.includes(`gsaas:${r}-end`))throw new Error(`${n}: an unbalanced gsaas ${r} marker is left in ${t} (boilerplate drift).`);return o.replace(/\n{3,}/g,`
1169
1174
 
1170
- `).replace(/,(\r?\n[ \t]*[\]})])/g,"$1")}async function T(e,t,r,n,i){let o=await Er(e,"utf-8"),s=o.indexOf(t);if(s===-1)throw new Error(`${i}: expected to find the ${n} seam, but it was missing (boilerplate drift).`);if(o.includes(t,s+t.length))throw new Error(`${i}: the ${n} seam appears more than once (boilerplate drift).`);await l(e,o.slice(0,s)+r+o.slice(s+t.length))}async function Fe(e,t,r,n){let i=/\n([\t ]+)"/.exec(await Er(e,"utf-8"))?.[1];if(i!==r){let o=s=>s===" "?"tab":`${s.length}-space`;throw new Error(`${n}: expected ${e} to be ${o(r)}-indented, but it is ${i===void 0?"not indented":o(i)}-indented (boilerplate drift). Re-serializing it with the wrong indent would reformat the whole file.`)}await l(e,`${JSON.stringify(t,null,r)}
1171
- `)}function Qo(e){let t="",r=0;for(;r<e.length;){let n=e[r],i=e[r+1];if(n==="/"&&i==="/"){for(;r<e.length&&e[r]!==`
1175
+ `).replace(/,(\r?\n[ \t]*[\]})])/g,"$1")}async function A(e,t,r,n,i){let o=await Sr(e,"utf-8"),s=o.indexOf(t);if(s===-1)throw new Error(`${i}: expected to find the ${n} seam, but it was missing (boilerplate drift).`);if(o.includes(t,s+t.length))throw new Error(`${i}: the ${n} seam appears more than once (boilerplate drift).`);await l(e,o.slice(0,s)+r+o.slice(s+t.length))}async function Be(e,t,r,n){let i=/\n([\t ]+)"/.exec(await Sr(e,"utf-8"))?.[1];if(i!==r){let o=s=>s===" "?"tab":`${s.length}-space`;throw new Error(`${n}: expected ${e} to be ${o(r)}-indented, but it is ${i===void 0?"not indented":o(i)}-indented (boilerplate drift). Re-serializing it with the wrong indent would reformat the whole file.`)}await l(e,`${JSON.stringify(t,null,r)}
1176
+ `)}function ra(e){let t="",r=0;for(;r<e.length;){let n=e[r],i=e[r+1];if(n==="/"&&i==="/"){for(;r<e.length&&e[r]!==`
1172
1177
  `;)r++;continue}if(n==="/"&&i==="*"){for(r+=2;r<e.length&&!(e[r]==="*"&&e[r+1]==="/");)e[r]===`
1173
1178
  `&&(t+=`
1174
1179
  `),r++;r+=2;continue}if(n==='"'||n==="'"||n==="`"){let o=n;for(r++;r<e.length&&e[r]!==o;)e[r]==="\\"?r++:e[r]===`
1175
1180
  `&&(t+=`
1176
- `),r++;r++;continue}t+=n,r++}return t}async function Bn(e){let t=`import { config } from "@repo/config";
1177
- `,r=await Er(e,"utf-8");if(!r.includes(t))return;let n=r.replace(t,""),i=Qo(n);/\bconfig\b/.test(i)||await l(e,n)}var Be="stripMobileObservability",Kn=["apps/mobile/lib/observability.ts","apps/mobile/types/env.d.ts","apps/mobile/tests/settings-privacy-screen.test.tsx"],Gn="apps/mobile/tests/observability.test.ts",ta="mobile-obs-any",ra=["apps/mobile/tests/settings-privacy-screen.test.tsx"],Ut={sentry:["@sentry/react-native","@sentry/cli"],posthog:["posthog-react-native"]},na=`,
1178
- ...sentryExpoPlugin()`,ia=["apps/mobile/app.config.ts"],sa="|@sentry/react-native",oa=` * DUAL-PROVIDER, the way \`packages/observability\` is. This repo carries the Sentry and the PostHog
1181
+ `),r++;r++;continue}t+=n,r++}return t}async function Kn(e){let t=`import { config } from "@repo/config";
1182
+ `,r=await Sr(e,"utf-8");if(!r.includes(t))return;let n=r.replace(t,""),i=ra(n);/\bconfig\b/.test(i)||await l(e,n)}var Ge="stripMobileObservability",Gn=["apps/mobile/lib/observability.ts","apps/mobile/types/env.d.ts","apps/mobile/tests/settings-privacy-screen.test.tsx"],Hn="apps/mobile/tests/observability.test.ts",ia="mobile-obs-any",sa=["apps/mobile/tests/settings-privacy-screen.test.tsx"],Vt={sentry:["@sentry/react-native","@sentry/cli"],posthog:["posthog-react-native"]},oa=`,
1183
+ ...sentryExpoPlugin()`,aa=["apps/mobile/app.config.ts"],ca="|@sentry/react-native",la=` * DUAL-PROVIDER, the way \`packages/observability\` is. This repo carries the Sentry and the PostHog
1179
1184
  * halves at once so dev and the test suite exercise both. A generated project carries only the
1180
1185
  * providers its \`observability\` manifest option names: the CLI removes the other one's marked region
1181
1186
  * from this file, its SDK from \`apps/mobile/package.json\` and, for Sentry, its Expo config plugin
@@ -1186,7 +1191,7 @@ export async function withMutex<T>(
1186
1191
  * cross-provider \`{@link}\` and every paragraph about one provider's credentials sits INSIDE that
1187
1192
  * provider's own region, and what is left between them is provider-neutral - the {@link PROVIDERS}
1188
1193
  * list and the two exported entry points that walk it, which is what a project generated with
1189
- * \`observability: []\` keeps and starts nothing with.`,aa='import { readPrivacySettings, type PrivacySettings } from "@/lib/privacy";',ca='import type { PrivacySettings } from "@/lib/privacy";';function la(e){let t=e.map(n=>n==="sentry"?"Sentry":"PostHog").join(" and ");return`${e.length===0?` * Your project was generated with observability OFF, so this app received no reporting adapter
1194
+ * \`observability: []\` keeps and starts nothing with.`,pa='import { readPrivacySettings, type PrivacySettings } from "@/lib/privacy";',da='import type { PrivacySettings } from "@/lib/privacy";';function ua(e){let t=e.map(n=>n==="sentry"?"Sentry":"PostHog").join(" and ");return`${e.length===0?` * Your project was generated with observability OFF, so this app received no reporting adapter
1190
1195
  * and no reporting SDK: {@link PROVIDERS} is empty, and both functions below are no-ops that load
1191
1196
  * nothing and send nothing.`:` * This app reports to ${t}. No other provider's start, SDK or Expo config plugin was
1192
1197
  * generated, so there is nothing here for Metro to fold away and nothing for pnpm to install.`}
@@ -1194,9 +1199,9 @@ export async function withMutex<T>(
1194
1199
  * To change providers, edit \`observability\` in .generatesaas/manifest.json and run
1195
1200
  * \`generatesaas update\`: re-shaping brings that provider's half of this file, its SDK and its env
1196
1201
  * key back. Pasting the other provider's credential into \`config.observability\` on its own cannot -
1197
- * the start it would need is not here.`}async function Hn(e){if(!e.mobile)return;let t=e.projectDir,r=["sentry","posthog"].filter(o=>!e.observability.includes(o));e.observability.length===0&&await ea(Ve(t,Gn),{force:!0});let n=e.observability.length===0?Kn:[...Kn,Gn];for(let o of r)for(let s of n){let a=Ve(t,s);await l(a,Ue(await Sr(a,"utf-8"),s,`mobile-obs-${o}`,Be))}if(e.observability.length===0)for(let o of ra){let s=Ve(t,o);await l(s,Ue(await Sr(s,"utf-8"),o,ta,Be))}if(r.includes("sentry")){for(let o of ia){let s=Ve(t,o);await l(s,Ue(await Sr(s,"utf-8"),o,"mobile-obs-sentry",Be))}await T(Ve(t,"apps/mobile/app.config.ts"),na,"","app.config.ts Sentry Expo plugin",Be),await T(Ve(t,"apps/mobile/jest.config.js"),sa,"","jest.config.js Sentry transform allowance",Be)}let i=Ve(t,"apps/mobile/lib/observability.ts");await T(i,oa,la(e.observability),"lib/observability.ts dual-provider note",Be),e.observability.length===0&&(await T(i,aa,ca,"lib/observability.ts privacy import",Be),await Bn(i))}var ct={"@upstash/redis":"^1.37.0","@upstash/lock":"^0.2.1","@neondatabase/serverless":"^1.0.1",postgres:"^3.4.7"};async function ne(e){let t=await Yn(e,"utf-8");return JSON.parse(t)}async function ie(e,t){let r=/\n([\t ]+)"/.exec(await Yn(e,"utf-8"))?.[1]??" ";await l(e,`${JSON.stringify(t,null,r)}
1198
- `)}function W(e,t){for(let r of t)delete e.dependencies?.[r],delete e.devDependencies?.[r]}function pa(e){e.dependencies&&Object.keys(e.dependencies).length===0&&delete e.dependencies,e.devDependencies&&Object.keys(e.devDependencies).length===0&&delete e.devDependencies}function Ke(e,t,r,n=!1){let i=n?"devDependencies":"dependencies";e[i]||(e[i]={}),e[i][t]=r}async function Wn(e){await ua(e),await ma(e),await ha(e),await ba(e),await va(e),await Pa(e),await da(e)}async function da(e){if(!e.mobile){let t=j(e.projectDir,"packages/auth/package.json"),r=await ne(t);W(r,["@better-auth/expo"]),await ie(t,r);let n=j(e.projectDir,"tooling/styles/package.json"),i=await ne(n);W(i,["tsx"]),pa(i),await ie(n,i)}if(e.mobile&&e.mobilePurchases!=="revenuecat"){let t=j(e.projectDir,"apps/mobile/package.json"),r=await ne(t);W(r,["react-native-purchases","react-native-purchases-ui"]),await ie(t,r)}}async function ua(e){let t=j(e.projectDir,"packages/api/package.json"),r=await ne(t);W(r,["sharp","@types/sharp"]),e.cacheProvider==="upstash"&&(W(r,["ioredis"]),Ke(r,"@upstash/redis",ct["@upstash/redis"],!0),Ke(r,"@upstash/lock",ct["@upstash/lock"],!0)),await ie(t,r)}async function ma(e){let t=j(e.projectDir,"apps/web/package.json"),r=await ne(t);W(r,["@upstash/ratelimit","@upstash/redis"]),await ie(t,r)}async function ha(e){let t=j(e.projectDir,"packages/runtime/package.json"),r=await ne(t);e.cacheProvider==="upstash"&&(W(r,["ioredis","rate-limit-redis","redis-semaphore"]),Ke(r,"@upstash/redis",ct["@upstash/redis"]),Ke(r,"@upstash/lock",ct["@upstash/lock"])),await ie(t,r)}var Pr={sentry:["@sentry/node","@sentry/browser","@sentry/electron"],posthog:["posthog-node","posthog-js"]},fa=["@sentry/electron"],ga=[...Pr.sentry,...Pr.posthog],ya=[...Ut.sentry,...Ut.posthog];async function ba(e){let t=j(e.projectDir,"packages/observability/package.json"),r=await ne(t),n=new Set(e.observability.flatMap(a=>Pr[a]));if(!e.desktop)for(let a of fa)n.delete(a);if(W(r,ga.filter(a=>!n.has(a))),await ie(t,r),!e.mobile)return;let i=j(e.projectDir,"apps/mobile/package.json"),o=await ne(i),s=new Set(e.observability.flatMap(a=>Ut[a]));W(o,ya.filter(a=>!s.has(a))),await ie(i,o)}async function va(e){let t=j(e.projectDir,"packages/database/package.json"),r=await ne(t);e.databaseProvider==="neon"?(W(r,["pg","@types/pg"]),Ke(r,"@neondatabase/serverless",ct["@neondatabase/serverless"])):e.databaseProvider==="supabase"&&(W(r,["pg","@types/pg"]),Ke(r,"postgres",ct.postgres)),await ie(t,r)}var wa=["app/.well-known/oauth-authorization-server/[[...path]]/route.ts","app/.well-known/oauth-protected-resource/[[...path]]/route.ts"];async function ka(e){let t=await ne(e),r=t.dependencies?.["@repo/api"];r&&(delete t.dependencies?.["@repo/api"],Ke(t,"@repo/api",r,!0),await ie(e,t))}var Ea=["instrumentation.ts","tests/instrumentation.test.ts"],Sa="tests/api-trailing-slash.test.ts";async function Pa(e){if(e.architecture!=="separate")return;let t=j(e.projectDir,"apps/web");await Me(j(t,"app/api/[[...rest]]/route.ts"),t),await Me(j(t,Sa),t);for(let r of wa)await Me(j(t,r),t);for(let r of Ea)await Me(j(t,r),t);await ka(j(t,"package.json"))}import{readFile as Aa}from"fs/promises";import{join as Ia}from"path";var Ta=["base.json","node.json","next.json"],zn="GenerateSaaS ";async function qn(e){if(!e.demo)for(let t of Ta){let r=Ia(e.projectDir,"tooling/typescript",t),n;try{n=await Aa(r,"utf-8")}catch{continue}let i=JSON.parse(n);typeof i.display!="string"||!i.display.startsWith(zn)||(i.display=i.display.slice(zn.length),await l(r,`${JSON.stringify(i,null," ")}
1199
- `))}}import{readFile as Zn,rm as Ra}from"fs/promises";import{join as Et}from"path";async function Qn(e){e.cacheProvider==="upstash"&&(await Promise.all([Jn(Et(e.projectDir,"packages/runtime/tests/setup.ts")),Jn(Et(e.projectDir,"packages/mail/tests/setup.ts")),Oa(e.projectDir),Ra(Et(e.projectDir,"packages/runtime/tests/redis.test.ts"),{force:!0})]),await _a(e.projectDir))}async function _a(e){await l(Et(e,"packages/runtime/tests/redis.test.ts"),`import { beforeEach, describe, expect, it, vi } from "vitest";
1202
+ * the start it would need is not here.`}async function Yn(e){if(!e.mobile)return;let t=e.projectDir,r=["sentry","posthog"].filter(o=>!e.observability.includes(o));e.observability.length===0&&await na(Ke(t,Hn),{force:!0});let n=e.observability.length===0?Gn:[...Gn,Hn];for(let o of r)for(let s of n){let a=Ke(t,s);await l(a,Ve(await Pr(a,"utf-8"),s,`mobile-obs-${o}`,Ge))}if(e.observability.length===0)for(let o of sa){let s=Ke(t,o);await l(s,Ve(await Pr(s,"utf-8"),o,ia,Ge))}if(r.includes("sentry")){for(let o of aa){let s=Ke(t,o);await l(s,Ve(await Pr(s,"utf-8"),o,"mobile-obs-sentry",Ge))}await A(Ke(t,"apps/mobile/app.config.ts"),oa,"","app.config.ts Sentry Expo plugin",Ge),await A(Ke(t,"apps/mobile/jest.config.js"),ca,"","jest.config.js Sentry transform allowance",Ge)}let i=Ke(t,"apps/mobile/lib/observability.ts");await A(i,la,ua(e.observability),"lib/observability.ts dual-provider note",Ge),e.observability.length===0&&(await A(i,pa,da,"lib/observability.ts privacy import",Ge),await Kn(i))}var ct={"@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 Wn(e,"utf-8");return JSON.parse(t)}async function se(e,t){let r=/\n([\t ]+)"/.exec(await Wn(e,"utf-8"))?.[1]??" ";await l(e,`${JSON.stringify(t,null,r)}
1203
+ `)}function X(e,t){for(let r of t)delete e.dependencies?.[r],delete e.devDependencies?.[r]}function ma(e){e.dependencies&&Object.keys(e.dependencies).length===0&&delete e.dependencies,e.devDependencies&&Object.keys(e.devDependencies).length===0&&delete e.devDependencies}function He(e,t,r,n=!1){let i=n?"devDependencies":"dependencies";e[i]||(e[i]={}),e[i][t]=r}async function zn(e){await fa(e),await ga(e),await ya(e),await ka(e),await Ea(e),await Ta(e),await ha(e)}async function ha(e){if(!e.mobile){let t=M(e.projectDir,"packages/auth/package.json"),r=await ie(t);X(r,["@better-auth/expo"]),await se(t,r);let n=M(e.projectDir,"tooling/styles/package.json"),i=await ie(n);X(i,["tsx"]),ma(i),await se(n,i)}if(e.mobile&&e.mobilePurchases!=="revenuecat"){let t=M(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 fa(e){let t=M(e.projectDir,"packages/api/package.json"),r=await ie(t);X(r,["sharp","@types/sharp"]),e.cacheProvider==="upstash"&&(X(r,["ioredis"]),He(r,"@upstash/redis",ct["@upstash/redis"],!0),He(r,"@upstash/lock",ct["@upstash/lock"],!0)),await se(t,r)}async function ga(e){let t=M(e.projectDir,"apps/web/package.json"),r=await ie(t);X(r,["@upstash/ratelimit","@upstash/redis"]),await se(t,r)}async function ya(e){let t=M(e.projectDir,"packages/runtime/package.json"),r=await ie(t);e.cacheProvider==="upstash"&&(X(r,["ioredis","rate-limit-redis","redis-semaphore"]),He(r,"@upstash/redis",ct["@upstash/redis"]),He(r,"@upstash/lock",ct["@upstash/lock"])),await se(t,r)}var Ar={sentry:["@sentry/node","@sentry/browser","@sentry/electron"],posthog:["posthog-node","posthog-js"]},ba=["@sentry/electron"],wa=[...Ar.sentry,...Ar.posthog],va=[...Vt.sentry,...Vt.posthog];async function ka(e){let t=M(e.projectDir,"packages/observability/package.json"),r=await ie(t),n=new Set(e.observability.flatMap(a=>Ar[a]));if(!e.desktop)for(let a of ba)n.delete(a);if(X(r,wa.filter(a=>!n.has(a))),await se(t,r),!e.mobile)return;let i=M(e.projectDir,"apps/mobile/package.json"),o=await ie(i),s=new Set(e.observability.flatMap(a=>Vt[a]));X(o,va.filter(a=>!s.has(a))),await se(i,o)}async function Ea(e){let t=M(e.projectDir,"packages/database/package.json"),r=await ie(t);e.databaseProvider==="neon"?(X(r,["pg","@types/pg"]),He(r,"@neondatabase/serverless",ct["@neondatabase/serverless"])):e.databaseProvider==="supabase"&&(X(r,["pg","@types/pg"]),He(r,"postgres",ct.postgres)),await se(t,r)}var Sa=["app/.well-known/oauth-authorization-server/[[...path]]/route.ts","app/.well-known/oauth-protected-resource/[[...path]]/route.ts"];async function Pa(e){let t=await ie(e),r=t.dependencies?.["@repo/api"];r&&(delete t.dependencies?.["@repo/api"],He(t,"@repo/api",r,!0),await se(e,t))}var Aa=["instrumentation.ts","tests/instrumentation.test.ts"],Ia="tests/api-trailing-slash.test.ts";async function Ta(e){if(e.architecture!=="separate")return;let t=M(e.projectDir,"apps/web");await Fe(M(t,"app/api/[[...rest]]/route.ts"),t),await Fe(M(t,Ia),t);for(let r of Sa)await Fe(M(t,r),t);for(let r of Aa)await Fe(M(t,r),t);await Pa(M(t,"package.json"))}import{readFile as Ra}from"fs/promises";import{join as _a}from"path";var Oa=["base.json","node.json","next.json"],qn="GenerateSaaS ";async function Jn(e){if(!e.demo)for(let t of Oa){let r=_a(e.projectDir,"tooling/typescript",t),n;try{n=await Ra(r,"utf-8")}catch{continue}let i=JSON.parse(n);typeof i.display!="string"||!i.display.startsWith(qn)||(i.display=i.display.slice(qn.length),await l(r,`${JSON.stringify(i,null," ")}
1204
+ `))}}import{readFile as Qn,rm as xa}from"fs/promises";import{join as St}from"path";async function ei(e){e.cacheProvider==="upstash"&&(await Promise.all([Xn(St(e.projectDir,"packages/runtime/tests/setup.ts")),Xn(St(e.projectDir,"packages/mail/tests/setup.ts")),Na(e.projectDir),xa(St(e.projectDir,"packages/runtime/tests/redis.test.ts"),{force:!0})]),await Da(e.projectDir))}async function Da(e){await l(St(e,"packages/runtime/tests/redis.test.ts"),`import { beforeEach, describe, expect, it, vi } from "vitest";
1200
1205
 
1201
1206
  /**
1202
1207
  * Regression guards for the Upstash-backed cache layer in src/redis.ts.
@@ -1329,9 +1334,9 @@ describe("pub/sub", () => {
1329
1334
  expect(() => stop()).not.toThrow();
1330
1335
  });
1331
1336
  });
1332
- `)}async function Jn(e){let t;try{t=await Zn(e,"utf-8")}catch{throw new Error(`pruneCacheTests: expected ${e} for the Upstash cache swap (boilerplate drift).`)}let r=t.replace(/\tREDIS_URL:\s*"[^"]*",?\n/,` UPSTASH_REDIS_REST_URL: "https://test.upstash.io",
1337
+ `)}async function Xn(e){let t;try{t=await Qn(e,"utf-8")}catch{throw new Error(`pruneCacheTests: expected ${e} for the Upstash cache swap (boilerplate drift).`)}let r=t.replace(/\tREDIS_URL:\s*"[^"]*",?\n/,` UPSTASH_REDIS_REST_URL: "https://test.upstash.io",
1333
1338
  UPSTASH_REDIS_REST_TOKEN: "test-token",
1334
- `);if(r===t){if(t.includes("UPSTASH_REDIS_REST_URL"))return;throw new Error(`pruneCacheTests: found no REDIS_URL default to swap in ${e} (boilerplate drift).`)}await l(e,r)}var be="ioredisCounters",Xn="COUNT_UNDER_LIMIT_SCRIPT";async function Oa(e){let t=Et(e,"packages/api/tests/setup.ts"),r;try{r=await Zn(t,"utf-8")}catch{throw new Error(`pruneCacheTests: expected ${t} for the Upstash cache swap (boilerplate drift).`)}let n=r;n=n.replace(/\tREDIS_URL:\s*"[^"]*",?\n/g,` UPSTASH_REDIS_REST_URL: "https://test.upstash.io",
1339
+ `);if(r===t){if(t.includes("UPSTASH_REDIS_REST_URL"))return;throw new Error(`pruneCacheTests: found no REDIS_URL default to swap in ${e} (boilerplate drift).`)}await l(e,r)}var ge="ioredisCounters",Zn="COUNT_UNDER_LIMIT_SCRIPT";async function Na(e){let t=St(e,"packages/api/tests/setup.ts"),r;try{r=await Qn(t,"utf-8")}catch{throw new Error(`pruneCacheTests: expected ${t} for the Upstash cache swap (boilerplate drift).`)}let n=r;n=n.replace(/\tREDIS_URL:\s*"[^"]*",?\n/g,` UPSTASH_REDIS_REST_URL: "https://test.upstash.io",
1335
1340
  UPSTASH_REDIS_REST_TOKEN: "test-token",
1336
1341
  `),n=n.replace(/vi\.mock\("ioredis"[\s\S]*?\n\}\);\n\n?/,""),n=n.replace(/vi\.mock\("rate-limit-redis"[\s\S]*?\n\}\);\n\n?/,""),n=n.replace(/\t\t\tREDIS_URL:\s*"[^"]*",?\n/,` UPSTASH_REDIS_REST_URL: "https://test.upstash.io",
1337
1342
  UPSTASH_REDIS_REST_TOKEN: "test-token",
@@ -1340,15 +1345,15 @@ describe("pub/sub", () => {
1340
1345
  get = vi.fn().mockResolvedValue(null);
1341
1346
  mget = vi.fn().mockResolvedValue([]);
1342
1347
  set = vi.fn().mockResolvedValue("OK");
1343
- del = vi.fn(async (key: string) => (${be}.delete(key) ? 1 : 0));
1348
+ del = vi.fn(async (key: string) => (${ge}.delete(key) ? 1 : 0));
1344
1349
  incr = vi.fn(async (key: string) => {
1345
- const next = (${be}.get(key) ?? 0) + 1;
1346
- ${be}.set(key, next);
1350
+ const next = (${ge}.get(key) ?? 0) + 1;
1351
+ ${ge}.set(key, next);
1347
1352
  return next;
1348
1353
  });
1349
1354
  decr = vi.fn(async (key: string) => {
1350
- const next = (${be}.get(key) ?? 0) - 1;
1351
- ${be}.set(key, next);
1355
+ const next = (${ge}.get(key) ?? 0) - 1;
1356
+ ${ge}.set(key, next);
1352
1357
  return next;
1353
1358
  });
1354
1359
  expire = vi.fn().mockResolvedValue(1);
@@ -1356,12 +1361,12 @@ describe("pub/sub", () => {
1356
1361
  pttl = vi.fn().mockResolvedValue(-1);
1357
1362
  scan = vi.fn().mockResolvedValue(["0", []]);
1358
1363
  eval = vi.fn(async (script: string, keys: string[], args: (string | number)[]) => {
1359
- if (script !== ${Xn}) return null;
1364
+ if (script !== ${Zn}) return null;
1360
1365
  const key = String(keys[0]);
1361
1366
  const limit = Number(args[0]);
1362
- const next = (${be}.get(key) ?? 0) + 1;
1367
+ const next = (${ge}.get(key) ?? 0) + 1;
1363
1368
  if (next > limit) return -1;
1364
- ${be}.set(key, next);
1369
+ ${ge}.set(key, next);
1365
1370
  return next;
1366
1371
  });
1367
1372
  }
@@ -1376,32 +1381,33 @@ vi.mock("@upstash/lock", () => {
1376
1381
  return { Lock };
1377
1382
  });
1378
1383
 
1379
- `;if(n=n.replace(/(^vi\.mock\("@repo\/runtime")/m,`${i}$1`),n===r){if(r.includes("UPSTASH_REDIS_REST_URL"))return;throw new Error(`pruneCacheTests: nothing to rewrite in ${t} for the Upstash swap (boilerplate drift).`)}for(let o of['vi.mock("ioredis"','vi.mock("rate-limit-redis"',"REDIS_URL:"])if(n.includes(o))throw new Error(`pruneCacheTests: ${t} still contains ${o} after the Upstash swap (boilerplate drift).`);for(let o of[`const ${be} = new Map`,`${Xn},`,`${be}.clear()`])if(!n.includes(o))throw new Error(`pruneCacheTests: ${t} no longer contains ${o}, which the Upstash mock relies on (boilerplate drift).`);await l(t,n)}import{readFile as xa}from"fs/promises";var Da=/^[ \t]*(?:\/\/|\{\/\*|\*) gsaas:[a-z0-9-]+-(?:start|end)(?: \*\/\})?[ \t]*\r?\n/gm,Na=new Set([".ts",".tsx",".vue",".mjs",".js",".jsx",".md",".mdx"]),ei=32;function Ca(e){let t=e.lastIndexOf(".");return t>=0&&Na.has(e.slice(t))}async function La(e){let t=await xa(e,"utf-8");if(!t.includes("gsaas:"))return;let r=t.replace(Da,"");r!==t&&await l(e,r)}async function ti(e){let t=await ye(e.projectDir,e.projectDir,r=>r==="node_modules"||r.startsWith("node_modules/")||r===".git"||r.startsWith(".git/"),Ca);for(let r=0;r<t.length;r+=ei)await Promise.all(t.slice(r,r+ei).map(La))}import{readdir as Vt,readFile as se,rm as k}from"fs/promises";import{join as p}from"path";var $a=new Set(["ci.yml","desktop-release.yml","mobile-release.yml"]),ja=["apps/web/app/.well-known/apple-app-site-association/route.ts","apps/web/app/.well-known/assetlinks.json/route.ts","apps/web/tests/routes/apple-app-site-association.test.ts","apps/web/tests/routes/assetlinks.test.ts"],Ma=["packages/auth/src/config.ts","packages/api/src/routes/internal/index.ts","packages/api/src/index.ts"],Ua=["packages/api/src/routes/internal/index.ts","packages/api/src/routes/inngest.ts","packages/notifications/src/index.ts","packages/config/src/cache.ts"],Fa=["packages/notifications/src/push","packages/notifications/tests/push","packages/api/src/routes/internal/push.ts","packages/api/tests/routes/push.test.ts","packages/api/src/functions/notifications/push-dispatch.ts","packages/api/src/functions/notifications/push-receipts.ts","packages/api/src/functions/notifications/push-sink.ts","packages/api/tests/functions/push-dispatch.test.ts","packages/api/tests/functions/push-receipts.test.ts","packages/api/tests/functions/push-sink.test.ts","packages/api/tests/unit/push-store.test.ts","packages/api/tests/routes/push-registry.test.ts","packages/config/tests/push-cache-keys.test.ts"],Va=["packages/payments/src/store","packages/payments/tests/store","packages/payments/tests/helpers/clock.ts","packages/payments/tests/lib/store-claim-ids.test.ts","packages/api/src/routes/internal/webhooks/revenuecat.ts","packages/api/tests/routes/revenuecat-webhook.test.ts","packages/api/tests/routes/revenuecat-webhook-limiter.test.ts","packages/api/tests/routes/revenuecat-interleavings.test.ts","packages/api/tests/lib/revenuecat-claim-recovery.test.ts","packages/api/src/routes/internal/billing-mobile.ts","packages/api/tests/routes/billing-mobile-sync.test.ts","packages/api/tests/routes/billing-mobile-mount.test.ts","packages/api/src/functions/billing/revenuecat-reconcile.ts","packages/api/src/functions/billing/revenuecat-reconcile-entity.ts","packages/api/tests/functions/revenuecat-reconcile.test.ts"],Ba=["packages/api/src/routes/internal/index.ts","packages/api/src/routes/inngest.ts","packages/api/src/index.ts","packages/payments/src/index.ts","packages/config/src/cache.ts"],Ka=["apps/mobile/lib/purchases","apps/mobile/app/(app)/settings/billing/paywall.tsx","apps/mobile/e2e/flows/billing-paywall.yaml","apps/mobile/e2e/flows/billing-purchase.yaml","apps/mobile/e2e/flows/billing-restore.yaml"],Ga=[{dir:"apps/mobile/components/billing",prefixes:["paywall","credit-packs","store-"]},{dir:"apps/mobile/tests",prefixes:["purchases-"]}],Ha=["apps/mobile/app.config.ts","apps/mobile/app/_layout.tsx","apps/mobile/app/delete-account.tsx","apps/mobile/app/(app)/settings/billing/index.tsx","apps/mobile/components/home/plan-cards.tsx","apps/mobile/lib/api-client.ts","apps/mobile/lib/auth/sign-out.ts","apps/mobile/types/env.d.ts","apps/mobile/tests/api-client.test.ts","apps/mobile/tests/feature-seams.test.ts","apps/mobile/tests/root-layout.test.tsx","apps/mobile/tests/route-manifest.test.ts","apps/mobile/tests/sign-out.test.ts"],Ya=[","," {",' file: "billing-paywall.yaml",',' tags: ["purchases"],',' title: "The paywall renders sandbox offerings"'," },"," {",' file: "billing-purchase.yaml",',' tags: ["purchases"],',' title: "A sandbox purchase updates the plan card through the sync route"'," },",' { file: "billing-restore.yaml", tags: ["purchases"], title: "Restore purchases" }',""].join(`
1380
- `),Wa=[["## Billing (store purchases)","","#### Paywall (`billing-paywall.yaml`)","","| `testID` | Element | Flow |","| --- | --- | --- |","| `settings-paywall-screen` | The paywall route's screen root | `billing-paywall.yaml` |","| `billing-paywall-loading` | The offering read's skeleton | `billing-paywall.yaml` |","| `billing-paywall-status-error` | The offering read failed | `billing-paywall.yaml` |","| `billing-paywall-status-retry` | Retry the offering read | `billing-paywall.yaml` |","| `billing-paywall-list` | The list of purchasable packages | `billing-paywall.yaml` |","| `billing-paywall-row-<productId>` | One package row, keyed by store product id | `billing-paywall.yaml` |","| `billing-paywall-row-<productId>-action` | That row's buy control | `billing-purchase.yaml` |","| `billing-paywall-restore` | Restore purchases, from the paywall | `billing-restore.yaml` |","",""].join(`
1384
+ `;if(n=n.replace(/(^vi\.mock\("@repo\/runtime")/m,`${i}$1`),n===r){if(r.includes("UPSTASH_REDIS_REST_URL"))return;throw new Error(`pruneCacheTests: nothing to rewrite in ${t} for the Upstash swap (boilerplate drift).`)}for(let o of['vi.mock("ioredis"','vi.mock("rate-limit-redis"',"REDIS_URL:"])if(n.includes(o))throw new Error(`pruneCacheTests: ${t} still contains ${o} after the Upstash swap (boilerplate drift).`);for(let o of[`const ${ge} = new Map`,`${Zn},`,`${ge}.clear()`])if(!n.includes(o))throw new Error(`pruneCacheTests: ${t} no longer contains ${o}, which the Upstash mock relies on (boilerplate drift).`);await l(t,n)}import{readFile as Ca}from"fs/promises";var La=/^[ \t]*(?:\/\/|\{\/\*|\*) gsaas:[a-z0-9-]+-(?:start|end)(?: \*\/\})?[ \t]*\r?\n/gm,$a=new Set([".ts",".tsx",".vue",".mjs",".js",".jsx",".md",".mdx"]),ti=32;function ja(e){let t=e.lastIndexOf(".");return t>=0&&$a.has(e.slice(t))}async function Ma(e){let t=await Ca(e,"utf-8");if(!t.includes("gsaas:"))return;let r=t.replace(La,"");r!==t&&await l(e,r)}async function ri(e){let t=await J(e.projectDir,e.projectDir,r=>r==="node_modules"||r.startsWith("node_modules/")||r===".git"||r.startsWith(".git/"),ja);for(let r=0;r<t.length;r+=ti)await Promise.all(t.slice(r,r+ti).map(Ma))}import{existsSync as Ua}from"fs";import{readdir as lt,readFile as Z,rm as k}from"fs/promises";import{join as p}from"path";var Fa=new Set(["ci.yml","desktop-release.yml","mobile-release.yml"]),Va=["apps/web/app/.well-known/apple-app-site-association/route.ts","apps/web/app/.well-known/assetlinks.json/route.ts","apps/web/tests/routes/apple-app-site-association.test.ts","apps/web/tests/routes/assetlinks.test.ts"],Ba=["packages/auth/src/config.ts","packages/api/src/routes/internal/index.ts","packages/api/src/index.ts"],Ka=["packages/api/src/routes/internal/index.ts","packages/api/src/routes/inngest.ts","packages/notifications/src/index.ts","packages/config/src/cache.ts"],Ga=["packages/notifications/src/push","packages/notifications/tests/push","packages/api/src/routes/internal/push.ts","packages/api/tests/routes/push.test.ts","packages/api/src/functions/notifications/push-dispatch.ts","packages/api/src/functions/notifications/push-receipts.ts","packages/api/src/functions/notifications/push-sink.ts","packages/api/tests/functions/push-dispatch.test.ts","packages/api/tests/functions/push-receipts.test.ts","packages/api/tests/functions/push-sink.test.ts","packages/api/tests/unit/push-store.test.ts","packages/api/tests/routes/push-registry.test.ts","packages/config/tests/push-cache-keys.test.ts"],Ha=["packages/payments/src/store","packages/payments/tests/store","packages/payments/tests/helpers/clock.ts","packages/payments/tests/lib/store-claim-ids.test.ts","packages/api/src/routes/internal/webhooks/revenuecat.ts","packages/api/tests/routes/revenuecat-webhook.test.ts","packages/api/tests/routes/revenuecat-webhook-limiter.test.ts","packages/api/tests/routes/revenuecat-interleavings.test.ts","packages/api/tests/lib/revenuecat-claim-recovery.test.ts","packages/api/src/routes/internal/billing-mobile.ts","packages/api/tests/routes/billing-mobile-sync.test.ts","packages/api/tests/routes/billing-mobile-mount.test.ts","packages/api/src/functions/billing/revenuecat-reconcile.ts","packages/api/src/functions/billing/revenuecat-reconcile-entity.ts","packages/api/tests/functions/revenuecat-reconcile.test.ts"],Ya=["packages/api/src/routes/internal/index.ts","packages/api/src/routes/inngest.ts","packages/api/src/index.ts","packages/payments/src/index.ts","packages/config/src/cache.ts"],Wa=["apps/mobile/lib/purchases","apps/mobile/app/(app)/settings/billing/paywall.tsx","apps/mobile/e2e/flows/billing-paywall.yaml","apps/mobile/e2e/flows/billing-purchase.yaml","apps/mobile/e2e/flows/billing-restore.yaml"],za=[{dir:"apps/mobile/components/billing",prefixes:["paywall","credit-packs","store-"]},{dir:"apps/mobile/tests",prefixes:["purchases-"]}],qa=["apps/mobile/app.config.ts","apps/mobile/app/_layout.tsx","apps/mobile/app/delete-account.tsx","apps/mobile/app/(app)/settings/billing/index.tsx","apps/mobile/components/home/plan-cards.tsx","apps/mobile/lib/api-client.ts","apps/mobile/lib/auth/sign-out.ts","apps/mobile/types/env.d.ts","apps/mobile/tests/api-client.test.ts","apps/mobile/tests/feature-seams.test.ts","apps/mobile/tests/root-layout.test.tsx","apps/mobile/tests/route-manifest.test.ts","apps/mobile/tests/sign-out.test.ts"],Ja=[","," {",' file: "billing-paywall.yaml",',' tags: ["purchases"],',' title: "The paywall renders sandbox offerings"'," },"," {",' file: "billing-purchase.yaml",',' tags: ["purchases"],',' title: "A sandbox purchase updates the plan card through the sync route"'," },",' { file: "billing-restore.yaml", tags: ["purchases"], title: "Restore purchases" }',""].join(`
1385
+ `),Xa=[["## Billing (store purchases)","","#### Paywall (`billing-paywall.yaml`)","","| `testID` | Element | Flow |","| --- | --- | --- |","| `settings-paywall-screen` | The paywall route's screen root | `billing-paywall.yaml` |","| `billing-paywall-loading` | The offering read's skeleton | `billing-paywall.yaml` |","| `billing-paywall-status-error` | The offering read failed | `billing-paywall.yaml` |","| `billing-paywall-status-retry` | Retry the offering read | `billing-paywall.yaml` |","| `billing-paywall-list` | The list of purchasable packages | `billing-paywall.yaml` |","| `billing-paywall-row-<productId>` | One package row, keyed by store product id | `billing-paywall.yaml` |","| `billing-paywall-row-<productId>-action` | That row's buy control | `billing-purchase.yaml` |","| `billing-paywall-restore` | Restore purchases, from the paywall | `billing-restore.yaml` |","",""].join(`
1381
1386
  `),["#### Purchase and restore controls (`billing-purchase.yaml`, `billing-restore.yaml`)","","| `testID` | Element | Flow |","| --- | --- | --- |",'| `billing-upgrade` | The plan card\'s "See plans" link into the paywall | `billing-purchase.yaml` |',"| `billing-restore` | Restore purchases, on the billing page | `billing-restore.yaml` |",'| `billing-restore-lead` | The "Already subscribed?" lead beside it | `billing-restore.yaml` |',"| `billing-manage` | Manage subscription (Customer Center or the store page) | `billing-purchase.yaml` |","| `billing-external-link` | The external purchase link, when the disclosure sheet ships | `billing-purchase.yaml` |","| `billing-external-link-disclosure` | That link's disclosure sheet | `billing-purchase.yaml` |","",""].join(`
1382
1387
  `),["#### Credit packs (`billing-purchase.yaml`)","","| `testID` | Element | Flow |","| --- | --- | --- |","| `billing-credit-packs` | The credit packs card | `billing-purchase.yaml` |","| `billing-credit-packs-list` | The pack list | `billing-purchase.yaml` |","| `billing-credit-packs-row-<storeProductId>` | One pack row | `billing-purchase.yaml` |","| `billing-credit-packs-row-<storeProductId>-action` | That pack's buy control | `billing-purchase.yaml` |","| `billing-credit-packs-empty` | No pack is available on this plan | `billing-purchase.yaml` |","| `billing-credit-packs-unavailable` | The store listed none of the configured ids | `billing-purchase.yaml` |","",""].join(`
1383
- `)],za=["apps/web/app/[locale]/(marketing)/download","apps/web/tests/routes/download-page.test.tsx"],qa=["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 ri(e){let t=p(e.projectDir,".github/workflows"),r=await Vt(t).catch(()=>[]);for(let n of r)$a.has(n)||await k(p(t,n),{recursive:!0,force:!0})}async function Ja(e,t){let r=p(e,"package.json"),n=JSON.parse(await se(r,"utf-8"));if(!n.scripts)return;let i=!1;for(let s of t)s in n.scripts&&(delete n.scripts[s],i=!0);if(!i)return;let o=/\n([\t ]+)"/.exec(await se(r,"utf-8"))?.[1]??" ";await l(r,`${JSON.stringify(n,null,o)}
1384
- `)}async function ni(e){await Ja(e.projectDir,[...qa])}async function ii(e){let t=p(e.projectDir,"package.json"),r=await se(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," ")}
1385
- `))}async function si(e){let t=p(e.projectDir,"package.json"),r=JSON.parse(await se(t,"utf-8")),n=r.scripts?.test;if(n!=="turbo run test --concurrency=4 && vitest run")throw new Error(`rewriteRootTestScript: expected the root test script to be "turbo run test --concurrency=4 && vitest run", got ${JSON.stringify(n)} (boilerplate drift).`);r.scripts.test="turbo run test --concurrency=4",await l(t,`${JSON.stringify(r,null," ")}
1386
- `)}async function oi(e){e.docs||await k(p(e.projectDir,"apps/docs"),{recursive:!0})}async function ai(e){let t=p(e.projectDir,"docs/(platform)/meta.json"),r=JSON.parse(await se(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 Fe(t,r," ","stripUnusedDocsSilo"),e.desktop||await k(p(e.projectDir,"docs/desktop"),{recursive:!0,force:!0}),e.mobile||await k(p(e.projectDir,"docs/mobile"),{recursive:!0,force:!0}),await Xa(e),await ec(e)}async function z(e,t,r,n){await l(e,Ue(await se(e,"utf-8"),t,r,n))}async function Xa(e){let t=e.projectDir,r="stripUnusedDocsSilo",n=p(t,"docs/(platform)/configuration.mdx"),i=e.desktop;e.desktop||(await T(n,"| Desktop app + device sign-in - see [desktop app](/desktop) |","| Desktop app + device sign-in |","configuration.mdx desktop config-table link",r),await z(n,"configuration.mdx desktop TRUSTED_ORIGINS callout","desktop-origins-docs",r),await T(p(t,"docs/cli/init.mdx"),"the [desktop app](/desktop), AI features","the desktop app, AI features","cli init.mdx desktop app link",r),await z(p(t,"docs/(platform)/payments/organizations.mdx"),"payments organizations.mdx desktop tenancy callout","desktop-tenancy-docs",r),await z(p(t,"docs/(platform)/projects.mdx"),"projects.mdx desktop scoping callout","desktop-projects-docs",r),await z(p(t,"docs/(platform)/client-architecture.mdx"),"client-architecture.mdx desktop card","desktop-architecture-docs",r),await z(p(t,"docs/(platform)/screens.mdx"),"screens.mdx desktop halves","screens-desktop-docs",r),await z(p(t,"docs/(platform)/testing/e2e.mdx"),"testing/e2e.mdx desktop e2e callout","desktop-testing-docs",r),await T(p(t,"docs/(platform)/index.mdx"),` <Card href="/desktop" title="Desktop app" description="Cross-platform desktop app with device sign-in and AI agents." />
1387
- `,"","index.mdx desktop app card",r),await z(p(t,"docs/(platform)/ai.mdx"),"ai.mdx automation lanes row + section","desktop-lanes-docs",r)),i||(await z(n,"configuration.mdx desktop-AI paragraph","desktop-ai-docs",r),await T(p(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 ci(e){if(e.desktop)return;await k(p(e.projectDir,"apps/desktop"),{recursive:!0});let t=p(e.projectDir,"packages/i18n/translations");for(let i of await Vt(t,{withFileTypes:!0}))i.isDirectory()&&await k(p(t,i.name,"desktop.json"),{force:!0});await k(p(e.projectDir,".github/workflows/desktop-release.yml"));for(let i of za)await k(p(e.projectDir,i),{recursive:!0});await k(p(e.projectDir,"packages/utils/src/desktop-download.ts")),await k(p(e.projectDir,"packages/utils/tests/desktop-download.test.ts"));let r=p(e.projectDir,"packages/utils/package.json"),n=JSON.parse(await se(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 Fe(r,n," ","stripDesktopApp")}function Za(e){return e.desktop}async function li(e){Za(e)||await k(p(e.projectDir,"packages/agent-core"),{recursive:!0})}async function Qa(e,t,r,n){let i=await Vt(e);for(let o of t){let s=i.filter(a=>a.startsWith(o));if(s.length===0)throw new Error(`${n}: expected ${r} to hold at least one ${o}* entry`);for(let a of s)await k(p(e,a),{recursive:!0})}}async function Ft(e,t,r,n){await l(e,Ue(await se(e,"utf-8"),t,r,n))}async function ec(e){let t=e.projectDir,r="stripUnusedDocsSilo",n=e.mobile&&e.mobilePurchases==="revenuecat";e.mobile||(await T(p(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." />
1388
- `,"","index.mdx mobile app card",r),await T(p(t,"docs/(platform)/configuration.mdx")," - see [mobile app](/mobile)","","configuration.mdx mobile config-table link",r),await T(p(t,"docs/(platform)/client-architecture.mdx"),` <Card href="/mobile" title="Mobile app">The Expo app - the third surface this client core serves.</Card>
1389
- `,"","client-architecture.mdx mobile app card",r),await T(p(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 T(p(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 T(p(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 T(p(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 T(p(t,"docs/(platform)/project-structure.mdx"),"the web, desktop and mobile apps","the web and desktop apps","project-structure.mdx surface list",r),await z(p(t,"docs/(platform)/testing/e2e.mdx"),"testing e2e.mdx mobile Maestro section","mobile-testing-docs",r),await z(p(t,"docs/(platform)/environment-variables/index.mdx"),"environment-variables mobile section","mobile-env-docs",r)),n||(await T(p(t,"docs/(platform)/payments/meta.json"),', "mobile-billing"',"","payments meta.json mobile-billing entry",r),await T(p(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." />
1390
- `,"","payments index.mdx mobile store billing card",r),await k(p(t,"docs/(platform)/payments/mobile-billing.mdx"))),e.mobile&&!n&&(await T(p(t,"docs/mobile/meta.json"),', "billing"',"","mobile meta.json billing entry",r),await T(p(t,"docs/mobile/index.mdx"),` <Card href="/mobile/billing" title="Billing" description="Store purchases through RevenueCat, and the web-billing shape." />
1391
- `,"","mobile index.mdx billing card",r),await z(p(t,"docs/mobile/index.mdx"),"mobile index.mdx store-purchases block","mobile-purchases-docs",r),await k(p(t,"docs/mobile/billing"),{recursive:!0,force:!0}))}async function pi(e){if(e.mobile)return;await k(p(e.projectDir,"apps/mobile"),{recursive:!0});let t=p(e.projectDir,"packages/i18n/translations");for(let i of await Vt(t,{withFileTypes:!0}))i.isDirectory()&&await k(p(t,i.name,"mobile.json"),{force:!0});await k(p(e.projectDir,"packages/i18n/tests/mobile-notification-labels.test.ts")),await k(p(e.projectDir,"packages/i18n/tests/mobile-brand-literals.test.ts")),await k(p(e.projectDir,"packages/i18n/tests/mobile-shared-merge.test.ts")),await k(p(e.projectDir,"packages/auth/tests/expo-plugin.test.ts")),await k(p(e.projectDir,"packages/auth/tests/expo-authorization-allowlist.test.ts")),await k(p(e.projectDir,"packages/auth/src/expo-authorization-allowlist.ts")),await k(p(e.projectDir,".github/workflows/mobile-release.yml")),await k(p(e.projectDir,"tooling/styles/scripts/build-mobile-css.ts"));let r=p(e.projectDir,"tooling/styles/package.json"),n=JSON.parse(await se(r,"utf-8"));if(!n.scripts?.["mobile-css"])throw new Error("stripMobileApp: expected tooling/styles/package.json to carry the mobile-css script");delete n.scripts["mobile-css"],Object.keys(n.scripts).length===0&&delete n.scripts,await Fe(r,n," ","stripMobileApp");for(let i of ja)await Me(p(e.projectDir,i),p(e.projectDir,"apps/web"));await k(p(e.projectDir,"packages/api/src/routes/internal/well-known.ts")),await k(p(e.projectDir,"packages/api/tests/routes/well-known-mobile.test.ts")),await k(p(e.projectDir,"packages/api/src/routes/internal/mobile-auth.ts")),await k(p(e.projectDir,"packages/api/tests/routes/mobile-auth.test.ts")),await k(p(e.projectDir,"apps/web/public/images/stores"),{recursive:!0});for(let i of Ma)await Ft(p(e.projectDir,i),i,"mobile-auth","stripMobileApp");for(let i of Ua)await Ft(p(e.projectDir,i),i,"mobile-push","stripMobileApp");for(let i of Fa)await k(p(e.projectDir,i),{recursive:!0})}async function di(e){if(e.mobile&&e.mobilePurchases==="revenuecat")return;for(let n of Va)await k(p(e.projectDir,n),{recursive:!0});let t=p(e.projectDir,"packages/payments/package.json"),r=JSON.parse(await se(t,"utf-8"));if(!r.sideEffects?.includes("./src/store/revenuecat/index.ts"))throw new Error("stripMobilePurchases: expected packages/payments/package.json to list the store lane in sideEffects");r.sideEffects=r.sideEffects.filter(n=>n!=="./src/store/revenuecat/index.ts"),await Fe(t,r," ","stripMobilePurchases");for(let n of Ba)await Ft(p(e.projectDir,n),n,"mobile-purchases","stripMobilePurchases");if(e.mobile){for(let n of Ka)await k(p(e.projectDir,n),{recursive:!0});for(let{dir:n,prefixes:i}of Ga)await Qa(p(e.projectDir,n),i,n,"stripMobilePurchases");for(let n of Ha)await Ft(p(e.projectDir,n),n,"mobile-purchases","stripMobilePurchases");for(let n of Wa)await T(p(e.projectDir,"apps/mobile/e2e/README.md"),n,"","e2e README purchases row block","stripMobilePurchases");await T(p(e.projectDir,"apps/mobile/e2e/tags.ts"),Ya,`
1392
- `,"e2e tags.ts purchases inventory entries","stripMobilePurchases")}}import{readFile as tc}from"fs/promises";import{join as rc}from"path";var ui=`on:
1388
+ `)],Za=["apps/web/app/[locale]/(marketing)/download","apps/web/tests/routes/download-page.test.tsx"],Qa=["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 ni(e){let t=p(e.projectDir,".github/workflows"),r=await lt(t).catch(()=>[]);for(let n of r)Fa.has(n)||await k(p(t,n),{recursive:!0,force:!0})}async function ec(e,t){let r=p(e,"package.json"),n=JSON.parse(await Z(r,"utf-8"));if(!n.scripts)return;let i=!1;for(let s of t)s in n.scripts&&(delete n.scripts[s],i=!0);if(!i)return;let o=/\n([\t ]+)"/.exec(await Z(r,"utf-8"))?.[1]??" ";await l(r,`${JSON.stringify(n,null,o)}
1389
+ `)}async function ii(e){await ec(e.projectDir,[...Qa])}async function si(e){let t=p(e.projectDir,"package.json"),r=await Z(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," ")}
1390
+ `))}async function oi(e){let t=p(e.projectDir,"package.json"),r=JSON.parse(await Z(t,"utf-8")),n=r.scripts?.test;if(n!=="turbo run test --concurrency=4 && vitest run")throw new Error(`rewriteRootTestScript: expected the root test script to be "turbo run test --concurrency=4 && vitest run", got ${JSON.stringify(n)} (boilerplate drift).`);r.scripts.test="turbo run test --concurrency=4",await l(t,`${JSON.stringify(r,null," ")}
1391
+ `)}async function ai(e){e.docs||await k(p(e.projectDir,"apps/docs"),{recursive:!0})}async function ci(e){let t=p(e.projectDir,"docs/(platform)/meta.json"),r=JSON.parse(await Z(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 Be(t,r," ","stripUnusedDocsSilo"),e.desktop||await k(p(e.projectDir,"docs/desktop"),{recursive:!0,force:!0}),e.mobile||await k(p(e.projectDir,"docs/mobile"),{recursive:!0,force:!0}),await tc(e),await oc(e)}async function V(e,t,r,n){await l(e,Ve(await Z(e,"utf-8"),t,r,n))}async function tc(e){let t=e.projectDir,r="stripUnusedDocsSilo",n=p(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(p(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(p(t,"docs/(platform)/payments/organizations.mdx"),"payments organizations.mdx desktop tenancy callout","desktop-tenancy-docs",r),await V(p(t,"docs/(platform)/projects.mdx"),"projects.mdx desktop scoping callout","desktop-projects-docs",r),await V(p(t,"docs/(platform)/client-architecture.mdx"),"client-architecture.mdx desktop card","desktop-architecture-docs",r),await V(p(t,"docs/(platform)/screens.mdx"),"screens.mdx desktop halves","screens-desktop-docs",r),await V(p(t,"docs/(platform)/testing/e2e.mdx"),"testing/e2e.mdx desktop e2e callout","desktop-testing-docs",r),await A(p(t,"docs/(platform)/index.mdx"),` <Card href="/desktop" title="Desktop app" description="Cross-platform desktop app with device sign-in and AI agents." />
1392
+ `,"","index.mdx desktop app card",r),await V(p(t,"docs/(platform)/ai.mdx"),"ai.mdx automation lanes row + section","desktop-lanes-docs",r),await A(p(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(p(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 li(e){if(e.desktop)return;await k(p(e.projectDir,"apps/desktop"),{recursive:!0});let t=p(e.projectDir,"packages/i18n/translations");for(let i of await lt(t,{withFileTypes:!0}))i.isDirectory()&&await k(p(t,i.name,"desktop.json"),{force:!0});await k(p(e.projectDir,".github/workflows/desktop-release.yml"));for(let i of Za)await k(p(e.projectDir,i),{recursive:!0});await k(p(e.projectDir,"packages/utils/src/desktop-download.ts")),await k(p(e.projectDir,"packages/utils/tests/desktop-download.test.ts"));let r=p(e.projectDir,"packages/utils/package.json"),n=JSON.parse(await Z(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 Be(r,n," ","stripDesktopApp")}function rc(e){return e.desktop}async function pi(e){rc(e)||await k(p(e.projectDir,"packages/agent-core"),{recursive:!0})}var nc=["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"],di="gsaas:mcp-apps-start";async function ic(e){let t=[];for(let r of await lt(p(e,"packages"),{withFileTypes:!0}))if(r.isDirectory())for(let n of["src","tests"]){let i=p(e,"packages",r.name,n);if(!Ua(i))continue;let o=await J(i,i,s=>s.split("/").includes("node_modules"),s=>/\.(?:ts|tsx)$/.test(s));for(let s of o)(await Z(s,"utf-8")).includes(di)&&t.push(s)}return t.sort()}async function ui(e){if(e.ai)return;let t="stripMcpApps",r=e.projectDir;for(let o of nc)await k(p(r,o),{recursive:!0});let n=await ic(r);if(n.length===0)throw new Error(`${t}: expected ${di} regions under packages/<name>/src or tests, but found none (boilerplate drift).`);for(let o of n)await Pt(o,o,"mcp-apps",t);let i=p(r,"packages/i18n/translations");await k(p(i,"en/mcp-widgets.json"));for(let o of await lt(i,{withFileTypes:!0}))o.isDirectory()&&await k(p(i,o.name,"mcp-widgets.json"),{force:!0});await A(p(r,"docs/(platform)/meta.json"),` "mcp-widgets",
1393
+ `,"","platform meta.json mcp-widgets entry",t),await V(p(r,"docs/(platform)/external-agent-mcp.mdx"),"external-agent-mcp.mdx widgets paragraph","mcp-apps-docs",t),await V(p(r,"docs/(platform)/ai.mdx"),"ai.mdx widgets under tool rows section","mcp-apps-docs",t)}async function sc(e,t,r,n){let i=await lt(e);for(let o of t){let s=i.filter(a=>a.startsWith(o));if(s.length===0)throw new Error(`${n}: expected ${r} to hold at least one ${o}* entry`);for(let a of s)await k(p(e,a),{recursive:!0})}}async function Pt(e,t,r,n){await l(e,Ve(await Z(e,"utf-8"),t,r,n))}async function oc(e){let t=e.projectDir,r="stripUnusedDocsSilo",n=e.mobile&&e.mobilePurchases==="revenuecat";e.mobile||(await A(p(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." />
1394
+ `,"","index.mdx mobile app card",r),await A(p(t,"docs/(platform)/configuration.mdx")," - see [mobile app](/mobile)","","configuration.mdx mobile config-table link",r),await A(p(t,"docs/(platform)/client-architecture.mdx"),` <Card href="/mobile" title="Mobile app">The Expo app - the third surface this client core serves.</Card>
1395
+ `,"","client-architecture.mdx mobile app card",r),await A(p(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(p(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(p(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(p(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(p(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(p(t,"docs/(platform)/testing/e2e.mdx"),"testing e2e.mdx mobile Maestro section","mobile-testing-docs",r),await V(p(t,"docs/(platform)/environment-variables/index.mdx"),"environment-variables mobile section","mobile-env-docs",r)),n||(await A(p(t,"docs/(platform)/payments/meta.json"),', "mobile-billing"',"","payments meta.json mobile-billing entry",r),await A(p(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." />
1396
+ `,"","payments index.mdx mobile store billing card",r),await k(p(t,"docs/(platform)/payments/mobile-billing.mdx"))),e.mobile&&!n&&(await A(p(t,"docs/mobile/meta.json"),', "billing"',"","mobile meta.json billing entry",r),await A(p(t,"docs/mobile/index.mdx"),` <Card href="/mobile/billing" title="Billing" description="Store purchases through RevenueCat, and the web-billing shape." />
1397
+ `,"","mobile index.mdx billing card",r),await V(p(t,"docs/mobile/index.mdx"),"mobile index.mdx store-purchases block","mobile-purchases-docs",r),await k(p(t,"docs/mobile/billing"),{recursive:!0,force:!0}))}async function mi(e){if(e.mobile)return;await k(p(e.projectDir,"apps/mobile"),{recursive:!0});let t=p(e.projectDir,"packages/i18n/translations");for(let i of await lt(t,{withFileTypes:!0}))i.isDirectory()&&await k(p(t,i.name,"mobile.json"),{force:!0});await k(p(e.projectDir,"packages/i18n/tests/mobile-notification-labels.test.ts")),await k(p(e.projectDir,"packages/i18n/tests/mobile-brand-literals.test.ts")),await k(p(e.projectDir,"packages/i18n/tests/mobile-shared-merge.test.ts")),await k(p(e.projectDir,"packages/auth/tests/expo-plugin.test.ts")),await k(p(e.projectDir,"packages/auth/tests/expo-authorization-allowlist.test.ts")),await k(p(e.projectDir,"packages/auth/src/expo-authorization-allowlist.ts")),await k(p(e.projectDir,".github/workflows/mobile-release.yml")),await k(p(e.projectDir,"tooling/styles/scripts/build-mobile-css.ts"));let r=p(e.projectDir,"tooling/styles/package.json"),n=JSON.parse(await Z(r,"utf-8"));if(!n.scripts?.["mobile-css"])throw new Error("stripMobileApp: expected tooling/styles/package.json to carry the mobile-css script");delete n.scripts["mobile-css"],Object.keys(n.scripts).length===0&&delete n.scripts,await Be(r,n," ","stripMobileApp");for(let i of Va)await Fe(p(e.projectDir,i),p(e.projectDir,"apps/web"));await k(p(e.projectDir,"packages/api/src/routes/internal/well-known.ts")),await k(p(e.projectDir,"packages/api/tests/routes/well-known-mobile.test.ts")),await k(p(e.projectDir,"packages/api/src/routes/internal/mobile-auth.ts")),await k(p(e.projectDir,"packages/api/tests/routes/mobile-auth.test.ts")),await k(p(e.projectDir,"apps/web/public/images/stores"),{recursive:!0});for(let i of Ba)await Pt(p(e.projectDir,i),i,"mobile-auth","stripMobileApp");for(let i of Ka)await Pt(p(e.projectDir,i),i,"mobile-push","stripMobileApp");for(let i of Ga)await k(p(e.projectDir,i),{recursive:!0})}async function hi(e){if(e.mobile&&e.mobilePurchases==="revenuecat")return;for(let n of Ha)await k(p(e.projectDir,n),{recursive:!0});let t=p(e.projectDir,"packages/payments/package.json"),r=JSON.parse(await Z(t,"utf-8"));if(!r.sideEffects?.includes("./src/store/revenuecat/index.ts"))throw new Error("stripMobilePurchases: expected packages/payments/package.json to list the store lane in sideEffects");r.sideEffects=r.sideEffects.filter(n=>n!=="./src/store/revenuecat/index.ts"),await Be(t,r," ","stripMobilePurchases");for(let n of Ya)await Pt(p(e.projectDir,n),n,"mobile-purchases","stripMobilePurchases");if(e.mobile){for(let n of Wa)await k(p(e.projectDir,n),{recursive:!0});for(let{dir:n,prefixes:i}of za)await sc(p(e.projectDir,n),i,n,"stripMobilePurchases");for(let n of qa)await Pt(p(e.projectDir,n),n,"mobile-purchases","stripMobilePurchases");for(let n of Xa)await A(p(e.projectDir,"apps/mobile/e2e/README.md"),n,"","e2e README purchases row block","stripMobilePurchases");await A(p(e.projectDir,"apps/mobile/e2e/tags.ts"),Ja,`
1398
+ `,"e2e tags.ts purchases inventory entries","stripMobilePurchases")}}import{readFile as ac}from"fs/promises";import{join as cc}from"path";var fi=`on:
1393
1399
  workflow_run:
1394
1400
  workflows: ["Tag Release"]
1395
1401
  branches: [main]
1396
1402
  types: [completed]
1397
- workflow_dispatch:`,nc=`on:
1398
- workflow_dispatch:`;async function mi(e){if(!e.desktop)return;let t=rc(e.projectDir,".github/workflows/desktop-release.yml"),r=await tc(t,"utf8");if(!r.includes(ui))throw new Error(`Cannot configure the desktop release trigger: the expected workflow_run block was not found in ${t}. The boilerplate workflow may have drifted.`);await l(t,r.replace(ui,nc))}import{readFile as ic}from"fs/promises";import{join as sc}from"path";var hi=`on:
1403
+ workflow_dispatch:`,lc=`on:
1404
+ workflow_dispatch:`;async function gi(e){if(!e.desktop)return;let t=cc(e.projectDir,".github/workflows/desktop-release.yml"),r=await ac(t,"utf8");if(!r.includes(fi))throw new Error(`Cannot configure the desktop release trigger: the expected workflow_run block was not found in ${t}. The boilerplate workflow may have drifted.`);await l(t,r.replace(fi,lc))}import{readFile as pc}from"fs/promises";import{join as dc}from"path";var yi=`on:
1399
1405
  workflow_run:
1400
1406
  workflows: ["Tag Release"]
1401
1407
  branches: [main]
1402
1408
  types: [completed]
1403
- workflow_dispatch:`,oc=`on:
1404
- workflow_dispatch:`;async function fi(e){if(!e.mobile)return;let t=sc(e.projectDir,".github/workflows/mobile-release.yml"),r=await ic(t,"utf8");if(!r.includes(hi))throw new Error(`Cannot configure the mobile release trigger: the expected workflow_run block was not found in ${t}. The boilerplate workflow may have drifted.`);await l(t,r.replace(hi,oc))}import{join as ac}from"path";async function bi(e){let t=cc(e);await l(ac(e.projectDir,".github/workflows/ci.yml"),t)}function gi(e){return e.databaseProvider!=="neon"&&e.cacheProvider!=="upstash"}function yi(e,t,r){return` - uses: actions/upload-artifact@v4
1409
+ workflow_dispatch:`,uc=`on:
1410
+ workflow_dispatch:`;async function bi(e){if(!e.mobile)return;let t=dc(e.projectDir,".github/workflows/mobile-release.yml"),r=await pc(t,"utf8");if(!r.includes(yi))throw new Error(`Cannot configure the mobile release trigger: the expected workflow_run block was not found in ${t}. The boilerplate workflow may have drifted.`);await l(t,r.replace(yi,uc))}import{join as mc}from"path";async function ki(e){let t=hc(e);await l(mc(e.projectDir,".github/workflows/ci.yml"),t)}function wi(e){return e.databaseProvider!=="neon"&&e.cacheProvider!=="upstash"}function vi(e,t,r){return` - uses: actions/upload-artifact@v4
1405
1411
  if: \${{ ${r} }}
1406
1412
  with:
1407
1413
  name: playwright-report-${e}
@@ -1410,7 +1416,7 @@ vi.mock("@upstash/lock", () => {
1410
1416
  ${t}/test-results
1411
1417
  if-no-files-found: ignore
1412
1418
  retention-days: 7
1413
- `}function cc(e){let t=e.cacheProvider==="upstash",r=t?"":` redis:
1419
+ `}function hc(e){let t=e.cacheProvider==="upstash",r=t?"":` redis:
1414
1420
  image: redis:8-alpine
1415
1421
  ports:
1416
1422
  - 6379:6379
@@ -1453,8 +1459,8 @@ ${r} mailpit:
1453
1459
  # No \`-u\`: the harness registers the app by PUTting its own /api/inngest endpoint, and the
1454
1460
  # suite's port is derived per checkout - a baked URL would name a port nothing serves.
1455
1461
  - name: Start Inngest
1456
- run: docker run -d --name inngest --network host inngest/inngest:v1.17.9 inngest dev
1457
- `,d=gi(e)?`
1462
+ run: docker run -d --name inngest --network host inngest/inngest:v1.46.0 inngest dev
1463
+ `,d=wi(e)?`
1458
1464
  # The end-to-end suite, on a manual "Run workflow" dispatch only - it builds the app in production
1459
1465
  # mode and drives it with Playwright, too slow to pay for on every PR. It needs no keys and no
1460
1466
  # internet: the harness preflights the services below, builds and starts the app itself, provisions
@@ -1489,7 +1495,7 @@ ${a}
1489
1495
  env:
1490
1496
  NODE_OPTIONS: --max-old-space-size=6144
1491
1497
 
1492
- ${yi("web","apps/web","!cancelled()")}`:"\n # No end-to-end job: this project's stack cannot run one in CI without credentials.\n # - a `neon` database talks over a serverless websocket that only reaches a managed endpoint,\n # so a Postgres service container is unreachable from the app;\n # - an `upstash` cache is a hosted REST endpoint, and this file carries no secrets.\n # The suite itself works locally: `pnpm infra` for a project on self-hosted Postgres and Redis,\n # then `pnpm e2e:ci`. To run it here, add a job with those services plus your own credentials as\n # repository secrets, or point a second CI environment at a disposable managed instance.\n",g=e.desktop&&gi(e)?`
1498
+ ${vi("web","apps/web","!cancelled()")}`:"\n # No end-to-end job: this project's stack cannot run one in CI without credentials.\n # - a `neon` database talks over a serverless websocket that only reaches a managed endpoint,\n # so a Postgres service container is unreachable from the app;\n # - an `upstash` cache is a hosted REST endpoint, and this file carries no secrets.\n # The suite itself works locally: `pnpm infra` for a project on self-hosted Postgres and Redis,\n # then `pnpm e2e:ci`. To run it here, add a job with those services plus your own credentials as\n # repository secrets, or point a second CI environment at a disposable managed instance.\n",g=e.desktop&&wi(e)?`
1493
1499
  # The DESKTOP end-to-end suite, on a manual "Run workflow" dispatch only: it builds the Electron
1494
1500
  # bundles AND a Next production build, which is too slow to pay for on every push. It has its own
1495
1501
  # port and its own build directory, so it can never collide with the web job above.
@@ -1523,18 +1529,18 @@ ${a}
1523
1529
  env:
1524
1530
  NODE_OPTIONS: --max-old-space-size=6144
1525
1531
 
1526
- ${yi("desktop","apps/desktop","failure()")}`:"",w=e.databaseProvider==="neon"?`
1532
+ ${vi("desktop","apps/desktop","failure()")}`:"",E=e.databaseProvider==="neon"?`
1527
1533
  # Required for neon: the api suite's embedded Postgres is TCP-only and the neon
1528
1534
  # websocket driver cannot reach it. Add this repository secret (any Postgres this
1529
1535
  # suite may CREATE DATABASE on - a Neon branch works).
1530
- GENERATESAAS_TEST_DATABASE_ADMIN_URL: \${{ secrets.GENERATESAAS_TEST_DATABASE_ADMIN_URL }}`:"",v=t?`
1536
+ GENERATESAAS_TEST_DATABASE_ADMIN_URL: \${{ secrets.GENERATESAAS_TEST_DATABASE_ADMIN_URL }}`:"",w=t?`
1531
1537
  UPSTASH_REDIS_REST_URL: https://test.upstash.io
1532
1538
  UPSTASH_REDIS_REST_TOKEN: test-token`:`
1533
1539
  REDIS_URL: redis://localhost:6379`,P=(()=>{switch(e.paymentProvider){case"stripe":return`
1534
1540
  STRIPE_SECRET_KEY: test
1535
1541
  STRIPE_WEBHOOK_SECRET: test`;case"polar":return`
1536
1542
  POLAR_ACCESS_TOKEN: test
1537
- POLAR_WEBHOOK_SECRET: test`;case"none":return"";default:{let D=e.paymentProvider;throw new Error(`buildCiYaml: unhandled payment provider "${String(D)}"`)}}})();return`# CI policy - a push runs NOTHING here. Your host (Vercel, Coolify, etc.) auto-deploys the push;
1543
+ POLAR_WEBHOOK_SECRET: test`;case"none":return"";default:{let O=e.paymentProvider;throw new Error(`buildCiYaml: unhandled payment provider "${String(O)}"`)}}})();return`# CI policy - a push runs NOTHING here. Your host (Vercel, Coolify, etc.) auto-deploys the push;
1538
1544
  # CI is a quality gate, not on a deploy's critical path. A pull request runs the Checks job (lint,
1539
1545
  # type-check, unit tests). The FULL set - Checks plus the end-to-end jobs - runs only on a manual
1540
1546
  # dispatch: open the Actions tab, pick "CI", and press "Run workflow". Run that full set and confirm
@@ -1568,7 +1574,7 @@ jobs:
1568
1574
  # "cancelled", which reads as a mystery rather than as a timeout. 40 is roughly double that.
1569
1575
  timeout-minutes: 40
1570
1576
  ${n} env:
1571
- CONTENT_API_KEY: test-contentapi-key-16chars${w}${v}${P}
1577
+ CONTENT_API_KEY: test-contentapi-key-16chars${E}${w}${P}
1572
1578
  STORAGE_REGION: test
1573
1579
  STORAGE_ENDPOINT: http://test
1574
1580
  STORAGE_ACCESS_KEY_ID: test
@@ -1584,22 +1590,22 @@ ${n} env:
1584
1590
  - run: pnpm check-types
1585
1591
 
1586
1592
  - run: pnpm test
1587
- ${d}${g}`}import{readFile as vi}from"fs/promises";import{existsSync as lc}from"fs";import{join as Ar}from"path";var wi="@repo/database";function pc(e){return e?"pnpm -F @repo/database reset && pnpm -F @repo/database run deploy -- --push":"pnpm -F @repo/database run deploy"}function dc(e){switch(e){case"fullstack":return"web";case"separate":return"backend";default:{let t=e;throw new Error(`schemaOwnerApp: unhandled architecture "${String(t)}"`)}}}async function uc(e,t,r){let n=await vi(e,"utf-8"),i=JSON.parse(n),o=i.scripts?.[t];if(!o)throw new Error(`Cannot prepend to missing script "${t}" in ${e}`);o.includes(wi)||(i.scripts={...i.scripts,[t]:`${r} && ${o}`},await l(e,`${JSON.stringify(i,null," ")}
1588
- `))}async function mc(e,t){let r=lc(e)?JSON.parse(await vi(e,"utf-8")):{$schema:"https://openapi.vercel.sh/vercel.json"},n=r.buildCommand?.trim()||"pnpm build";n.includes(wi)||(r.buildCommand=`${t} && ${n}`,await l(e,`${JSON.stringify(r,null," ")}
1589
- `))}async function ki(e){let t=pc(e.demo===!0),r=dc(e.architecture),n=Ar(e.projectDir,"apps",r);switch(e.deploymentTarget){case"node":await uc(Ar(n,"package.json"),"start",t);return;case"vercel":await mc(Ar(n,"vercel.json"),t);return;default:{let i=e.deploymentTarget;throw new Error(`generateDeployScripts: unhandled deployment target "${String(i)}"`)}}}import{readFile as hc}from"fs/promises";import{existsSync as fc}from"fs";import{join as Bt}from"path";var Ei=["stripe","polar"],gc=[...Ei,"none"];async function Si(e){let t=Bt(e.projectDir,"packages/payments/src"),r=e.paymentProvider,i=`// Active payment provider. To switch, change the path below to
1590
- // ${gc.filter(o=>o!==r).map(o=>`"./${o}/index"`).join(" or ")} (other folders are kept in place).
1593
+ ${d}${g}`}import{readFile as Ei}from"fs/promises";import{existsSync as fc}from"fs";import{join as Ir}from"path";var Si="@repo/database";function gc(e){return e?"pnpm -F @repo/database reset && pnpm -F @repo/database run deploy -- --push":"pnpm -F @repo/database run deploy"}function yc(e){switch(e){case"fullstack":return"web";case"separate":return"backend";default:{let t=e;throw new Error(`schemaOwnerApp: unhandled architecture "${String(t)}"`)}}}async function bc(e,t,r){let n=await Ei(e,"utf-8"),i=JSON.parse(n),o=i.scripts?.[t];if(!o)throw new Error(`Cannot prepend to missing script "${t}" in ${e}`);o.includes(Si)||(i.scripts={...i.scripts,[t]:`${r} && ${o}`},await l(e,`${JSON.stringify(i,null," ")}
1594
+ `))}async function wc(e,t){let r=fc(e)?JSON.parse(await Ei(e,"utf-8")):{$schema:"https://openapi.vercel.sh/vercel.json"},n=r.buildCommand?.trim()||"pnpm build";n.includes(Si)||(r.buildCommand=`${t} && ${n}`,await l(e,`${JSON.stringify(r,null," ")}
1595
+ `))}async function Pi(e){let t=gc(e.demo===!0),r=yc(e.architecture),n=Ir(e.projectDir,"apps",r);switch(e.deploymentTarget){case"node":await bc(Ir(n,"package.json"),"start",t);return;case"vercel":await wc(Ir(n,"vercel.json"),t);return;default:{let i=e.deploymentTarget;throw new Error(`generateDeployScripts: unhandled deployment target "${String(i)}"`)}}}import{readFile as vc}from"fs/promises";import{existsSync as kc}from"fs";import{join as Bt}from"path";var Ai=["stripe","polar"],Ec=[...Ai,"none"];async function Ii(e){let t=Bt(e.projectDir,"packages/payments/src"),r=e.paymentProvider,i=`// Active payment provider. To switch, change the path below to
1596
+ // ${Ec.filter(o=>o!==r).map(o=>`"./${o}/index"`).join(" or ")} (other folders are kept in place).
1591
1597
  export { ops } from "./${r}/index";
1592
- `;await l(Bt(t,"providers/index.ts"),i),await l(Bt(t,"index.ts"),await yc(t,r))}async function yc(e,t){let r=Bt(e,"index.ts");if(!fc(r))throw new Error(`generatePaymentBarrel: expected ${r} to exist - did packages/payments move?`);let n=await hc(r,"utf-8"),i=Ei.filter(s=>s!==t);return n.split(`
1598
+ `;await l(Bt(t,"providers/index.ts"),i),await l(Bt(t,"index.ts"),await Sc(t,r))}async function Sc(e,t){let r=Bt(e,"index.ts");if(!kc(r))throw new Error(`generatePaymentBarrel: expected ${r} to exist - did packages/payments move?`);let n=await vc(r,"utf-8"),i=Ai.filter(s=>s!==t);return n.split(`
1593
1599
  `).filter(s=>!i.some(a=>s.includes(`./providers/${a}/`))).join(`
1594
- `)}import{access as bc,readFile as Ht,rm as Kt}from"fs/promises";import{join as q}from"path";var Ri=["sentry","posthog"],Ir={sentry:"src/providers/sentry",posthog:"src/providers/posthog"},Gt={sentry:["tests/sentry-load-guard.test.ts","tests/sentry-browser-scrub.test.ts"],posthog:["tests/posthog-load-guard.test.ts","tests/llm-analytics.test.ts"]},vc=["tests/resolution.test.ts","tests/export-isolation.test.ts"],wc=["src/providers/sentry/desktop-main.ts","src/providers/sentry/desktop-renderer.ts","src/resolve-desktop-main.ts","src/resolve-desktop-renderer.ts"],kc=["./desktop-main","./desktop-renderer"],Ec=[`vi.mock("@sentry/electron/main", sdk.factories["@sentry/electron/main"]);
1600
+ `)}import{access as Pc,readFile as Ht,rm as Kt}from"fs/promises";import{join as Q}from"path";var xi=["sentry","posthog"],Tr={sentry:"src/providers/sentry",posthog:"src/providers/posthog"},Gt={sentry:["tests/sentry-load-guard.test.ts","tests/sentry-browser-scrub.test.ts"],posthog:["tests/posthog-load-guard.test.ts","tests/llm-analytics.test.ts"]},Ac=["tests/resolution.test.ts","tests/export-isolation.test.ts"],Ic=["src/providers/sentry/desktop-main.ts","src/providers/sentry/desktop-renderer.ts","src/resolve-desktop-main.ts","src/resolve-desktop-renderer.ts"],Tc=["./desktop-main","./desktop-renderer"],Rc=[`vi.mock("@sentry/electron/main", sdk.factories["@sentry/electron/main"]);
1595
1601
  `,`vi.mock("@sentry/electron/renderer", sdk.factories["@sentry/electron/renderer"]);
1596
- `],Sc=[' describeGate("desktop main", "electronMain", async () => {',' describeGate("desktop renderer", "electronRenderer", async () => {',' describe("the desktop main init options", () => {',' describe("the desktop renderer init", () => {'],Pi=`
1602
+ `],_c=[' describeGate("desktop main", "electronMain", async () => {',' describeGate("desktop renderer", "electronRenderer", async () => {',' describe("the desktop main init options", () => {',' describe("the desktop renderer init", () => {'],Ti=`
1597
1603
  });
1598
- `,Pc=" ";async function _i(e){let t=q(e.projectDir,"packages/observability");await Ai(t,"packages/observability");let r=e.observability,n=r.filter(s=>!F.includes(s));if(n.length>0)throw new Error(`observability names ${JSON.stringify(n)}, which is not a reporting provider. Every entry must be one of: ${F.join(", ")}. Shaping stops here so the project is not left half-stripped.`);for(let s of r)await Ai(q(t,Ir[s]),`packages/observability/${Ir[s]}`);let i=e.desktop?[...Ti,...gl]:Ti,o=new Map;for(let s of i)o.set(s.file,await Ht(q(t,s.file),"utf-8"));for(let s of Cc(r,e.desktop))await Lc(t,s);for(let s of Ri)if(!r.includes(s)){await Kt(q(t,Ir[s]),{recursive:!0,force:!0});for(let a of Gt[s])await Kt(q(t,a),{force:!0})}for(let s of vc)await Kt(q(t,s),{force:!0});e.desktop||await Ac(t,r);for(let s of i){let a=o.get(s.file);a!==void 0&&await l(q(t,s.file),Rc(a,s,r))}}async function Ai(e,t){try{await bc(e)}catch{throw new Error(`generateObservabilityProvider: expected ${t} to exist - did the observability package move?`)}}async function Ac(e,t){for(let i of wc)await Kt(q(e,i),{force:!0});t.includes("sentry")&&await Ic(e);let r=q(e,"package.json"),n=JSON.parse(await Ht(r,"utf-8"));for(let i of kc){if(!n.exports?.[i])throw new Error(`generateObservabilityProvider: expected packages/observability/package.json to carry the ${i} export`);delete n.exports[i]}await Fe(r,n," ","generateObservabilityProvider")}async function Ic(e){let t=q(e,Gt.sentry[0]),r=await Ht(t,"utf-8");r=Tr(r,Ec.map(n=>({find:n,replace:""})),Gt.sentry[0]);for(let n of Sc)r=Tc(r,n,Gt.sentry[0]);await l(t,r)}function Tc(e,t,r){let n=e.indexOf(t),i=n===-1?-1:e.indexOf(Pi,n);if(n===-1||i===-1)throw new Error(`generateObservabilityProvider: ${r} no longer contains the block this strip removes - re-point the anchor. Missing: ${t.trim()}`);if(e.includes(t,n+t.length))throw new Error(`generateObservabilityProvider: ${r} now opens more than one block with the same line, so this strip cannot tell which one to remove - re-point the anchor. Block: ${t.trim()}`);let o=e.slice(n+t.length,i).split(`
1599
- `).find(a=>a.trim().length>0&&!a.startsWith(`${Pc} `));if(o!==void 0)throw new Error(`generateObservabilityProvider: ${r} no longer closes the block this strip removes at its own indent - re-point the anchor. Block: ${t.trim()}; first line inside it that is not part of its body: ${o.trim()}`);let s=i+Pi.length;return e[s]===`
1600
- `&&(s+=1),e.slice(0,n)+e.slice(s)}function Rc(e,t,r){let n=Ri.filter(s=>!r.includes(s)),i=e,o=[];for(let s of n){let a=_c(i,s);i=a.source,o.push(...a.bindings)}t.dualMode!==!1&&(i=Tr(i,[{find:xc,replace:Dc(r)}],t.file)),i=Tr(i,t.edits(r),t.file);for(let s of n)if(i.includes(`./providers/${s}`))throw new Error(`generateObservabilityProvider: ${t.file} still reaches providers/${s} after the strip - the boilerplate grew an import shape the drop does not know.`);for(let s of o)if(new RegExp(String.raw`\b${s}\b`).test(i))throw new Error(`generateObservabilityProvider: ${t.file} still names ${s}, whose import the strip removed - the boilerplate grew a use the pinned rewrites do not cover.`);return i}function Tr(e,t,r){let n=e;for(let i of t){let o=n.indexOf(i.find);if(o===-1)throw new Error(`generateObservabilityProvider: ${r} no longer contains the text this strip rewrites - re-point the anchor. Missing: ${i.find.split(`
1604
+ `,Oc=" ";async function Di(e){let t=Q(e.projectDir,"packages/observability");await Ri(t,"packages/observability");let r=e.observability,n=r.filter(s=>!K.includes(s));if(n.length>0)throw new Error(`observability names ${JSON.stringify(n)}, which is not a reporting provider. Every entry must be one of: ${K.join(", ")}. Shaping stops here so the project is not left half-stripped.`);for(let s of r)await Ri(Q(t,Tr[s]),`packages/observability/${Tr[s]}`);let i=e.desktop?[...Oi,...El]:Oi,o=new Map;for(let s of i)o.set(s.file,await Ht(Q(t,s.file),"utf-8"));for(let s of Fc(r,e.desktop))await Vc(t,s);for(let s of xi)if(!r.includes(s)){await Kt(Q(t,Tr[s]),{recursive:!0,force:!0});for(let a of Gt[s])await Kt(Q(t,a),{force:!0})}for(let s of Ac)await Kt(Q(t,s),{force:!0});e.desktop||await xc(t,r);for(let s of i){let a=o.get(s.file);a!==void 0&&await l(Q(t,s.file),Cc(a,s,r))}}async function Ri(e,t){try{await Pc(e)}catch{throw new Error(`generateObservabilityProvider: expected ${t} to exist - did the observability package move?`)}}async function xc(e,t){for(let i of Ic)await Kt(Q(e,i),{force:!0});t.includes("sentry")&&await Dc(e);let r=Q(e,"package.json"),n=JSON.parse(await Ht(r,"utf-8"));for(let i of Tc){if(!n.exports?.[i])throw new Error(`generateObservabilityProvider: expected packages/observability/package.json to carry the ${i} export`);delete n.exports[i]}await Be(r,n," ","generateObservabilityProvider")}async function Dc(e){let t=Q(e,Gt.sentry[0]),r=await Ht(t,"utf-8");r=Rr(r,Rc.map(n=>({find:n,replace:""})),Gt.sentry[0]);for(let n of _c)r=Nc(r,n,Gt.sentry[0]);await l(t,r)}function Nc(e,t,r){let n=e.indexOf(t),i=n===-1?-1:e.indexOf(Ti,n);if(n===-1||i===-1)throw new Error(`generateObservabilityProvider: ${r} no longer contains the block this strip removes - re-point the anchor. Missing: ${t.trim()}`);if(e.includes(t,n+t.length))throw new Error(`generateObservabilityProvider: ${r} now opens more than one block with the same line, so this strip cannot tell which one to remove - re-point the anchor. Block: ${t.trim()}`);let o=e.slice(n+t.length,i).split(`
1605
+ `).find(a=>a.trim().length>0&&!a.startsWith(`${Oc} `));if(o!==void 0)throw new Error(`generateObservabilityProvider: ${r} no longer closes the block this strip removes at its own indent - re-point the anchor. Block: ${t.trim()}; first line inside it that is not part of its body: ${o.trim()}`);let s=i+Ti.length;return e[s]===`
1606
+ `&&(s+=1),e.slice(0,n)+e.slice(s)}function Cc(e,t,r){let n=xi.filter(s=>!r.includes(s)),i=e,o=[];for(let s of n){let a=Lc(i,s);i=a.source,o.push(...a.bindings)}t.dualMode!==!1&&(i=Rr(i,[{find:jc,replace:Mc(r)}],t.file)),i=Rr(i,t.edits(r),t.file);for(let s of n)if(i.includes(`./providers/${s}`))throw new Error(`generateObservabilityProvider: ${t.file} still reaches providers/${s} after the strip - the boilerplate grew an import shape the drop does not know.`);for(let s of o)if(new RegExp(String.raw`\b${s}\b`).test(i))throw new Error(`generateObservabilityProvider: ${t.file} still names ${s}, whose import the strip removed - the boilerplate grew a use the pinned rewrites do not cover.`);return i}function Rr(e,t,r){let n=e;for(let i of t){let o=n.indexOf(i.find);if(o===-1)throw new Error(`generateObservabilityProvider: ${r} no longer contains the text this strip rewrites - re-point the anchor. Missing: ${i.find.split(`
1601
1607
  `)[0]}`);if(i.all!==!0&&n.includes(i.find,o+i.find.length))throw new Error(`generateObservabilityProvider: ${r} now contains the text this strip rewrites more than once, so rewriting the first would leave the rest in the buyer's copy - make the anchor unique or mark the edit \`all\`. Ambiguous: ${i.find.split(`
1602
- `)[0]}`);n=i.all===!0?n.replaceAll(i.find,i.replace):n.replace(i.find,i.replace)}return n}function _c(e,t){let r=new RegExp(String.raw`^import[^;]*?from "\./providers/${t}/[^"]*";\n`,"gm"),n=[];return{source:e.replace(r,o=>(n.push(...Oc(o)),"")),bindings:n}}function Oc(e){let t=/^import\s+(?:type\s+)?(\S(?:[\s\S]*?\S)?)\s+from\s/.exec(e)?.[1]??"",r=[],n=/\{([\s\S]*?)\}/.exec(t);n?.[1]&&r.push(...n[1].split(",").map(s=>s.trim().replace(/^type\s+/,"")).map(s=>s.split(/\s+as\s+/).at(-1)??"").filter(s=>s.length>0));let i=t.replace(/\{[\s\S]*?\}/,"").replace(/,/g," ").trim(),o=/^\*\s+as\s+([A-Za-z_$][\w$]*)$/.exec(i);return o?.[1]?r.push(o[1]):/^[A-Z_$][\w$]*$/i.test(i)&&r.push(i),r}var xc=" * DUAL-MODE, exactly as `packages/payments/src/providers/index.ts` does it. This repo resolves the\n * provider at RUNTIME so dev and the test suite exercise every one of them. A generated project has\n * exactly one provider, so the CLI overwrites this file with a direct re-export of it and the rest\n * become unreachable and are pruned; the generator is the observability twin of\n * `packages/cli/src/generators/payment-barrel.ts` and lands with the manifest option.";function Dc(e){let t=e.map(n=>n==="sentry"?"Sentry":"PostHog").join(" and ");return`${e.length===0?` * Your project was generated with observability OFF, so no provider adapter and no reporting
1608
+ `)[0]}`);n=i.all===!0?n.replaceAll(i.find,i.replace):n.replace(i.find,i.replace)}return n}function Lc(e,t){let r=new RegExp(String.raw`^import[^;]*?from "\./providers/${t}/[^"]*";\n`,"gm"),n=[];return{source:e.replace(r,o=>(n.push(...$c(o)),"")),bindings:n}}function $c(e){let t=/^import\s+(?:type\s+)?(\S(?:[\s\S]*?\S)?)\s+from\s/.exec(e)?.[1]??"",r=[],n=/\{([\s\S]*?)\}/.exec(t);n?.[1]&&r.push(...n[1].split(",").map(s=>s.trim().replace(/^type\s+/,"")).map(s=>s.split(/\s+as\s+/).at(-1)??"").filter(s=>s.length>0));let i=t.replace(/\{[\s\S]*?\}/,"").replace(/,/g," ").trim(),o=/^\*\s+as\s+([A-Za-z_$][\w$]*)$/.exec(i);return o?.[1]?r.push(o[1]):/^[A-Z_$][\w$]*$/i.test(i)&&r.push(i),r}var jc=" * DUAL-MODE, exactly as `packages/payments/src/providers/index.ts` does it. This repo resolves the\n * provider at RUNTIME so dev and the test suite exercise every one of them. A generated project has\n * exactly one provider, so the CLI overwrites this file with a direct re-export of it and the rest\n * become unreachable and are pruned; the generator is the observability twin of\n * `packages/cli/src/generators/payment-barrel.ts` and lands with the manifest option.";function Mc(e){let t=e.map(n=>n==="sentry"?"Sentry":"PostHog").join(" and ");return`${e.length===0?` * Your project was generated with observability OFF, so no provider adapter and no reporting
1603
1609
  * SDK were shipped: this file is the whole layer, and every call is a no-op that loads nothing.`:` * Your project reports to ${t}. No other provider's adapter or SDK was generated, so
1604
1610
  * there is nothing here for a bundler to fold away and nothing for pnpm to install.`}
1605
1611
  *
@@ -1607,28 +1613,28 @@ export { ops } from "./${r}/index";
1607
1613
  * run \`generatesaas update\`: re-shaping brings that provider's adapter and its dependency back. The
1608
1614
  * update stages nothing while you are already on the latest version, so the switch lands with the
1609
1615
  * next release. Pasting the other provider's credential into \`config.observability\` on its own
1610
- * cannot: the adapter it would need is not here.`}var Ii={source:"src/providers/sentry/browser.ts",name:"SentryBrowserInitOptions",fields:["environment: string;"]},Nc={source:"src/providers/sentry/desktop-main.ts",name:"SentryDesktopMainInitOptions",fields:["environment: string;","appIsReady: boolean;"]};function Cc(e,t){return e.includes("sentry")?[]:t?[Ii,Nc]:[Ii]}async function Lc(e,t){let r=await Ht(q(e,t.source),"utf-8"),n=`export interface ${t.name} {
1616
+ * cannot: the adapter it would need is not here.`}var _i={source:"src/providers/sentry/browser.ts",name:"SentryBrowserInitOptions",fields:["environment: string;"]},Uc={source:"src/providers/sentry/desktop-main.ts",name:"SentryDesktopMainInitOptions",fields:["environment: string;","appIsReady: boolean;"]};function Fc(e,t){return e.includes("sentry")?[]:t?[_i,Uc]:[_i]}async function Vc(e,t){let r=await Ht(Q(e,t.source),"utf-8"),n=`export interface ${t.name} {
1611
1617
  `,i=r.indexOf(n),o=r.indexOf(`
1612
1618
  }
1613
1619
  `,i);if(i===-1||o===-1)throw new Error(`generateObservabilityProvider: ${t.source} no longer exports ${t.name} - the stand-in this strip emits for a project without Sentry has nothing left to track.`);let s=r.slice(i+n.length,o).split(`
1614
- `).map(a=>a.trim()).filter(a=>/^[A-Z_$][\w$]*\??: .+;$/i.test(a));if(s.join(" ")!==t.fields.join(" "))throw new Error(`generateObservabilityProvider: ${t.name} now declares [${s.join(" ")}] but the stand-in emitted for a project without Sentry declares [${t.fields.join(" ")}] - update the stand-in so switching providers on an update cannot break a buyer's call site.`)}var $c=" into every browser bundle. `tests/export-isolation.test.ts` walks the real module graph to keep\n * that from ever landing quietly.",jc=` if (resolveSentryDsn(observability, process.env.SENTRY_DSN)) ops.push(sentryServerOps);
1615
- `,Mc=` if (resolveServerPosthogCredentials(observability, process.env)) {
1620
+ `).map(a=>a.trim()).filter(a=>/^[A-Z_$][\w$]*\??: .+;$/i.test(a));if(s.join(" ")!==t.fields.join(" "))throw new Error(`generateObservabilityProvider: ${t.name} now declares [${s.join(" ")}] but the stand-in emitted for a project without Sentry declares [${t.fields.join(" ")}] - update the stand-in so switching providers on an update cannot break a buyer's call site.`)}var Bc=" into every browser bundle. `tests/export-isolation.test.ts` walks the real module graph to keep\n * that from ever landing quietly.",Kc=` if (resolveSentryDsn(observability, process.env.SENTRY_DSN)) ops.push(sentryServerOps);
1621
+ `,Gc=` if (resolveServerPosthogCredentials(observability, process.env)) {
1616
1622
  ops.push(posthogServerOps);
1617
1623
  }
1618
- `,Uc=` if (resolveSentryDsn(config.observability, process.env.SENTRY_DSN)) {
1624
+ `,Hc=` if (resolveSentryDsn(config.observability, process.env.SENTRY_DSN)) {
1619
1625
  await initSentryServer();
1620
1626
  }
1621
- `,Fc=` if (observability?.sentry?.dsn) ops.push(sentryBrowserOps);
1622
- `,Vc=` if (observability?.posthog?.publicKey) ops.push(posthogBrowserOps);
1623
- `,Bc=` if (config.observability?.sentry?.dsn) await initSentryBrowser(options);
1624
- `,Kc=` if (observability?.posthog?.publicKey && !observability?.sentry?.dsn) {
1627
+ `,Yc=` if (observability?.sentry?.dsn) ops.push(sentryBrowserOps);
1628
+ `,Wc=` if (observability?.posthog?.publicKey) ops.push(posthogBrowserOps);
1629
+ `,zc=` if (config.observability?.sentry?.dsn) await initSentryBrowser(options);
1630
+ `,qc=` if (observability?.posthog?.publicKey && !observability?.sentry?.dsn) {
1625
1631
  announceMissingDesktopSdk("posthog");
1626
1632
  }
1627
- `,Gc=` // PostHog ships no desktop SDK, so a project configured ONLY for PostHog reports nothing here -
1633
+ `,Jc=` // PostHog ships no desktop SDK, so a project configured ONLY for PostHog reports nothing here -
1628
1634
  // announced rather than silent, because a desktop build that quietly drops every error looks
1629
1635
  // identical to one with reporting off.
1630
- `,Hc=`import { createProviderGapAnnouncer } from "./announce";
1631
- `,Yc=`/**
1636
+ `,Xc=`import { createProviderGapAnnouncer } from "./announce";
1637
+ `,Zc=`/**
1632
1638
  * Say once that the selected provider cannot report from the desktop main process.
1633
1639
  *
1634
1640
  * A WARNING and never an error: PostHog ships no Electron SDK, and a buyer running PostHog on the
@@ -1646,7 +1652,7 @@ const announceMissingDesktopSdk = createProviderGapAnnouncer({
1646
1652
  remedy: "Select sentry to report errors from the desktop app."
1647
1653
  });
1648
1654
 
1649
- `,Wc=`/**
1655
+ `,Qc=`/**
1650
1656
  * Say once that the selected provider cannot report from the desktop renderer.
1651
1657
  *
1652
1658
  * A WARNING and never an error: PostHog ships no Electron SDK, and a buyer running PostHog on the
@@ -1660,33 +1666,33 @@ const announceMissingDesktopSdk = createProviderGapAnnouncer({
1660
1666
  remedy: "Select sentry to report errors from the desktop app."
1661
1667
  });
1662
1668
 
1663
- `,zc=` const observability = config.observability;
1664
- `,qc=`import { config } from "@repo/config";
1665
- `,Jc=` // No error-reporting adapter was generated for this project, so there is nothing to arm.
1666
- `,Xc="export type BrowserReportingOptions = SentryBrowserInitOptions;",Zc=`export interface BrowserReportingOptions {
1669
+ `,el=` const observability = config.observability;
1670
+ `,tl=`import { config } from "@repo/config";
1671
+ `,rl=` // No error-reporting adapter was generated for this project, so there is nothing to arm.
1672
+ `,nl="export type BrowserReportingOptions = SentryBrowserInitOptions;",il=`export interface BrowserReportingOptions {
1667
1673
  /** The deployment environment reports are tagged with. */
1668
1674
  environment: string;
1669
- }`,Qc=` return observability?.sentry?.dsn ? [sentryDesktopMainOps] : [];
1670
- `,el=` if (observability?.sentry?.dsn) await initSentryDesktopMain(options);
1671
- `,tl="export type DesktopMainReportingOptions = SentryDesktopMainInitOptions;",rl=`export interface DesktopMainReportingOptions {
1675
+ }`,sl=` return observability?.sentry?.dsn ? [sentryDesktopMainOps] : [];
1676
+ `,ol=` if (observability?.sentry?.dsn) await initSentryDesktopMain(options);
1677
+ `,al="export type DesktopMainReportingOptions = SentryDesktopMainInitOptions;",cl=`export interface DesktopMainReportingOptions {
1672
1678
  /** The deployment environment reports are tagged with. */
1673
1679
  environment: string;
1674
1680
  /** Whether Electron's \`app\` has emitted \`ready\` yet. */
1675
1681
  appIsReady: boolean;
1676
- }`,nl=` return observability?.sentry?.dsn ? [sentryDesktopRendererOps] : [];
1677
- `,il=` if (observability?.sentry?.dsn) await initSentryDesktopRenderer();
1678
- `;function Oi(e,t){let r=[];return e.includes("sentry")||r.push({find:t.sentry,replace:""}),e.includes("posthog")||r.push({find:t.posthog,replace:""}),r}function sl(e){let t=[{find:$c,replace:" into every browser bundle."},...Oi(e,{sentry:jc,posthog:Mc})];return e.includes("sentry")||t.push({find:Uc,replace:""}),t}function ol(e){let t=[...Oi(e,{sentry:Fc,posthog:Vc})];return e.includes("sentry")||t.push({find:Bc,replace:""},al),t}var al={find:Xc,replace:Zc};function cl(e){let t=[...xi(e,Yc)];return e.includes("sentry")||t.push({find:Qc,replace:` return [];
1679
- `},{find:el,replace:Ni(e)},{find:tl,replace:rl}),t.push(...Di(e)),t}function ll(e){let t=[...xi(e,Wc)];return e.includes("sentry")||t.push({find:nl,replace:` return [];
1680
- `},{find:il,replace:Ni(e)}),t.push(...Di(e)),t}function xi(e,t){return e.includes("posthog")?[]:[{find:Gc,replace:""},{find:Kc,replace:"",all:!0},{find:t,replace:""},{find:Hc,replace:""}]}function Di(e){return e.length>0?[]:[{find:zc,replace:"",all:!0},{find:qc,replace:""}]}function Ni(e){return e.length>0?"":Jc}var pl=` if (!posthogConfigured()) return;
1682
+ }`,ll=` return observability?.sentry?.dsn ? [sentryDesktopRendererOps] : [];
1683
+ `,pl=` if (observability?.sentry?.dsn) await initSentryDesktopRenderer();
1684
+ `;function Ni(e,t){let r=[];return e.includes("sentry")||r.push({find:t.sentry,replace:""}),e.includes("posthog")||r.push({find:t.posthog,replace:""}),r}function dl(e){let t=[{find:Bc,replace:" into every browser bundle."},...Ni(e,{sentry:Kc,posthog:Gc})];return e.includes("sentry")||t.push({find:Hc,replace:""}),t}function ul(e){let t=[...Ni(e,{sentry:Yc,posthog:Wc})];return e.includes("sentry")||t.push({find:zc,replace:""},ml),t}var ml={find:nl,replace:il};function hl(e){let t=[...Ci(e,Zc)];return e.includes("sentry")||t.push({find:sl,replace:` return [];
1685
+ `},{find:ol,replace:$i(e)},{find:al,replace:cl}),t.push(...Li(e)),t}function fl(e){let t=[...Ci(e,Qc)];return e.includes("sentry")||t.push({find:ll,replace:` return [];
1686
+ `},{find:pl,replace:$i(e)}),t.push(...Li(e)),t}function Ci(e,t){return e.includes("posthog")?[]:[{find:Jc,replace:""},{find:qc,replace:"",all:!0},{find:t,replace:""},{find:Xc,replace:""}]}function Li(e){return e.length>0?[]:[{find:el,replace:"",all:!0},{find:tl,replace:""}]}function $i(e){return e.length>0?"":rl}var gl=` if (!posthogConfigured()) return;
1681
1687
  try {
1682
1688
  const { captureAiGeneration: capture } = await import("./providers/posthog/llm");
1683
1689
  await capture(event);
1684
1690
  } catch (reportingError) {
1685
1691
  logReportingFailure("[observability] failed to report an AI generation", reportingError);
1686
1692
  }
1687
- `,dl=` // No PostHog adapter was generated for this project, so there is nothing to report to.
1688
- `,ul=` // No PostHog adapter was generated for this project, so there is nothing queued to drain.
1689
- `,ml=`/**
1693
+ `,yl=` // No PostHog adapter was generated for this project, so there is nothing to report to.
1694
+ `,bl=` // No PostHog adapter was generated for this project, so there is nothing queued to drain.
1695
+ `,wl=`/**
1690
1696
  * Whether PostHog is configured on this server AND this process is the deployment, without touching
1691
1697
  * the PostHog folder. The second half is the same \`serverReportingAllowed\` the adapter's own gate
1692
1698
  * asks, so a test run or a local build never even loads the SDK to find out it must stay silent.
@@ -1698,84 +1704,84 @@ function posthogConfigured(): boolean {
1698
1704
  return Boolean(process.env.POSTHOG_API_KEY || config.observability?.posthog?.publicKey);
1699
1705
  }
1700
1706
 
1701
- `,hl=` if (!posthogConfigured()) return;
1707
+ `,vl=` if (!posthogConfigured()) return;
1702
1708
  try {
1703
1709
  const { flushAiGenerations: flush } = await import("./providers/posthog/llm");
1704
1710
  await flush();
1705
1711
  } catch (reportingError) {
1706
1712
  logReportingFailure("[observability] failed to flush queued AI generations", reportingError);
1707
1713
  }
1708
- `;function fl(e){return e.includes("posthog")?[]:[{find:pl,replace:dl},{find:hl,replace:ul},{find:ml,replace:""},{find:`import { logReportingFailure } from "./logger";
1714
+ `;function kl(e){return e.includes("posthog")?[]:[{find:gl,replace:yl},{find:vl,replace:bl},{find:wl,replace:""},{find:`import { logReportingFailure } from "./logger";
1709
1715
  `,replace:""},{find:`import { config } from "@repo/config";
1710
1716
  `,replace:""},{find:`import { serverReportingAllowed } from "@repo/utils/reporting";
1711
- `,replace:""},{find:"export async function captureAiGeneration(event: AiGenerationEvent): Promise<void> {",replace:"export async function captureAiGeneration(_event: AiGenerationEvent): Promise<void> {"},{find:" * @param event - The call to record.",replace:" * @param _event - Ignored: no PostHog adapter was generated for this project."}]}var Ti=[{file:"src/resolve-server.ts",edits:sl},{file:"src/resolve-browser.ts",edits:ol},{file:"src/llm-analytics.ts",edits:fl,dualMode:!1}],gl=[{file:"src/resolve-desktop-main.ts",edits:cl},{file:"src/resolve-desktop-renderer.ts",edits:ll}];import{readdir as yl,readFile as bl}from"fs/promises";import{join as Ci}from"path";async function Li(e){if(e.demo)return;let t=e.appName.trim()||e.projectName,r=JSON.stringify(t).slice(1,-1),n=Ci(e.projectDir,"packages/i18n/translations"),i;try{i=await yl(n)}catch{return}for(let o of i){let s=Ci(n,o,"web.json"),a;try{a=await bl(s,"utf-8")}catch{continue}let d=a.replaceAll("GenerateSaaS",()=>r);d!==a&&await l(s,d)}}async function Yt(e){let t=e.projectDir;e.demo||(await yn(t),await bn(t),await vn(t),await wn(t)),await kn(t),await Pn(e),await In(e),await Tn(e),e.demo||await Rn(e),await xn(e),await Dn(e),await Nn(e),await jn(e),await Un(e),await Vn(e),await Wn(e),await qn(e),await Qn(e),await ri(e),await bi(e),await ni(e),await ii(e),await si(e),await oi(e),await ai(e),await ci(e),await li(e),await mi(e),await pi(e),await di(e),await fi(e),await ki(e),await Si(e),await _i(e),await Hn(e),await Li(e),await ti(e)}import{basename as ji,join as Mi,relative as wl}from"path";import{createHash as $i}from"crypto";import{readFile as vl}from"fs/promises";async function Wt(e){let t=await vl(e);return $i("sha256").update(t).digest("hex")}function Rr(e){return $i("sha256").update(e).digest("hex")}var kl=new Set(["data",Y]);function El(e){let t=e.split("/");for(let r of t)if(lr.has(r)||pr.has(r)||kl.has(r)||r.startsWith(".env")&&!r.includes("example"))return!0;return!1}function Ui(e,t){return{projectName:e.projectName??ji(t),appName:e.appName??e.projectName??ji(t),projectDir:t,architecture:e.architecture??"fullstack",paymentProvider:e.paymentProvider??"none",emailProvider:e.emailProvider??"smtp",multiTenancy:e.multiTenancy??!1,projects:e.projects??!1,docs:e.docs??!1,desktop:e.desktop??!1,mobile:e.mobile??!1,mobilePurchases:e.mobilePurchases??"none",ai:e.ai??!1,webAi:e.webAi??!0,revenueSharing:e.revenueSharing??!1,credits:e.credits??!1,defaultCurrency:e.defaultCurrency??"USD",deploymentTarget:e.deploymentTarget??"node",databaseProvider:e.databaseProvider??"postgres",cacheProvider:e.cacheProvider??"redis",observability:e.observability??[],version:e.version,baseUrl:e.baseUrl,credentials:{},demo:!1}}function Sl(e,t){return{version:e.version,initialVersion:e.version,appName:e.appName,projectName:e.projectName,frontend:rn,architecture:e.architecture,paymentProvider:e.paymentProvider,emailProvider:e.emailProvider,multiTenancy:e.multiTenancy,projects:e.projects,docs:e.docs,desktop:e.desktop,mobile:e.mobile,...e.mobile&&re(e)?{mobilePurchases:e.mobilePurchases}:{},ai:e.ai,webAi:e.webAi,credits:e.credits,revenueSharing:e.revenueSharing,defaultCurrency:e.defaultCurrency,deploymentTarget:e.deploymentTarget,databaseProvider:e.databaseProvider,cacheProvider:e.cacheProvider,observability:e.observability,...e.baseUrl?{baseUrl:e.baseUrl}:{},...t&&{licenseToken:t.token,licenseKeyHash:t.keyHash,installId:t.installId}}}async function Fi(e,t){let n=(await ye(e.projectDir,e.projectDir,El)).sort(),i=await Promise.all(n.map(async a=>[je(wl(e.projectDir,a)),await Wt(a)])),o=Object.fromEntries(i),s=Sl(e,t);await l(Mi(e.projectDir,he),`${JSON.stringify(s,null," ")}
1712
- `),await l(Mi(e.projectDir,nn),`${JSON.stringify(o,null," ")}
1713
- `)}import{relative as Pl}from"path";async function lt(e){let r=(await ye(e,e,ot)).sort(),n=await Promise.all(r.map(async i=>[je(Pl(e,i)),await Wt(i)]));return Object.fromEntries(n)}import{copyFile as Al,mkdir as Il,rm as Tl}from"fs/promises";import{dirname as Rl,join as Vi,relative as _l}from"path";import{existsSync as Ol}from"fs";async function _r(e,t){Ol(t)&&await Tl(t,{recursive:!0,force:!0});let n=(await ye(e,e,ot)).map(i=>({file:i,dest:Vi(t,je(_l(e,i)))}));await Promise.all([...new Set(n.map(({dest:i})=>Rl(i)))].map(i=>Il(i,{recursive:!0}))),await Promise.all(n.map(({file:i,dest:o})=>Al(i,o)))}async function Bi(e,t){await _r(e,Vi(t,Ot))}import{readdir as xl,readFile as Gi}from"fs/promises";import{existsSync as Dl}from"fs";import{dirname as Nl,join as oe,resolve as Or,sep as xr}from"path";import{fileURLToPath as Cl}from"url";var Ll={"claude-code":".claude/skills",cursor:".cursor/skills",codex:".agents/skills","gemini-cli":".gemini/skills",windsurf:".windsurf/skills"},Ge=Object.values(Ll),Dr=["generatesaas-update","generatesaas-translate"],$l=Nl(Cl(import.meta.url));function jl(){return Ct($l,["skill","content"],"content")}async function Nr(e,t){for(let r of Ge){let n=oe(e,r);for(let[i,o]of Object.entries(t)){let s=Or(n,i);if(!s.startsWith(n+xr))continue;let a=oe(s,"scripts"),d=oe(s,"references");await $t(a),await $t(d),await l(oe(s,"SKILL.md"),o.skillMd.replaceAll("__SKILL_ROOT__",r));for(let[g,w]of Object.entries(o.scripts)){let v=Or(a,g);v.startsWith(a+xr)&&await l(v,w)}let h=Object.entries(o.references);h.length===0&&await l(oe(d,".gitkeep"),"");for(let[g,w]of h){let v=Or(d,g);v.startsWith(d+xr)&&await l(v,w)}}}}async function Ki(e){if(!Dl(e))return{};let t={};for(let r of await xl(e))r!==".gitkeep"&&(t[r]=await Gi(oe(e,r),"utf-8"));return t}async function Hi(e){let t=jl(),r={};for(let n of Dr){let i=oe(t,n);r[n]={skillMd:await Gi(oe(i,"SKILL.md"),"utf-8"),scripts:await Ki(oe(i,"scripts")),references:await Ki(oe(i,"references"))}}await Nr(e,r)}import{execFile as Ml,execFileSync as Ul}from"child_process";import{access as Yi,readFile as Fl}from"fs/promises";import{join as Cr}from"path";import*as C from"@clack/prompts";function Ye(e){try{let t=process.platform==="win32"?"where":"which";return Ul(t,[e],{stdio:"ignore"}),!0}catch{return!1}}function He(e,t,r,n=3e5){return new Promise((i,o)=>{Ml(e,t,{cwd:r,timeout:n,maxBuffer:50*1024*1024},(s,a,d)=>{if(s){let h=String(a||"").trim(),w=[String(d||"").trim(),h].filter(Boolean).join(`
1714
- `);o(new Error(w?`${s.message}
1715
- ${w}`:s.message))}else i()})})}async function Wi(e){if(!Ye("pnpm"))return C.log.warn("pnpm not found. Skipping lockfile regeneration."),!1;try{return await He("pnpm",["install","--lockfile-only","--no-frozen-lockfile"],e),!0}catch(t){let r=t instanceof Error?t.message:String(t);return C.log.warn(`Lockfile regeneration failed: ${r}`),C.log.warn("Deploys using --frozen-lockfile may fail."),!1}}async function zi(e){if(!Ye("pnpm"))return C.log.warn("pnpm not found. Skipping dependency installation."),C.log.info("Install pnpm: https://pnpm.io/installation"),!1;let t=C.spinner();t.start("Installing dependencies (this may take a minute)...");try{return await He("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 C.log.warn(`pnpm install failed: ${n}`),C.log.warn("You can run it manually later."),!1}}async function qi(e){if(!Ye("pnpm"))return!1;let t=C.spinner();t.start("Generating baseline database migration...");try{return await He("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 C.log.warn(`Could not generate baseline migration: ${n}`),C.log.warn("Run 'pnpm -F @repo/database generate' before your first deploy."),!1}}async function Ji(e){try{return await Yi(Cr(e,".git")),C.log.info("Git repository already exists, skipping init."),!0}catch{}if(!Ye("git"))return C.log.warn("git not found. Skipping repository initialization."),!1;let t=C.spinner();t.start("Initializing git repository...");try{return await He("git",["init"],e),await He("git",["add","-A"],e),await He("git",["commit","--no-verify","-m","Initial commit from GenerateSaaS"],e),t.stop("Git repository initialized."),!0}catch{return t.stop("Git initialization failed."),C.log.warn("You can run git init manually later."),!1}}async function Xi(e){if(!Ye("pnpm"))return!1;try{await Yi(Cr(e,".git"))}catch{return!1}try{let t=JSON.parse(await Fl(Cr(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 He("pnpm",["exec","simple-git-hooks"],e),!0}catch{return C.log.warn("Could not install git hooks. Run 'pnpm exec simple-git-hooks' manually."),!1}}import*as We from"@clack/prompts";import J from"picocolors";function Zi(e,t){let r=et(e);t.dockerAvailable||We.log.warn("Docker not found. Install Docker to run local services: https://docs.docker.com/get-docker/"),t.baselineMigrationMissing&&We.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"),n.push(`pnpm infra ${J.dim(`# ${r.map(a=>Gr[a].label).join(", ")}`)}`),n.push(`pnpm dev ${J.dim("# http://localhost:3000")}`),t.skippedCredentials.length>0&&(n.push(""),n.push(J.dim("Fill in remaining TODO values in .env"))),We.note(n.join(`
1716
- `),J.yellow("Start Development"));let i=[];i.push(`App ${J.cyan("http://localhost:3000")}`),e.architecture==="separate"&&i.push(`API ${J.cyan("http://localhost:3010")}`),r.includes("mailpit")&&i.push(`Mailpit ${J.cyan("http://localhost:8025")}`),r.includes("inngest")&&i.push(`Inngest ${J.cyan("http://localhost:8288")}`),We.note(i.join(`
1717
- `),J.yellow("Dev Tools"));let o=[],s=Vl(e);s.length>0&&o.push(`Set in production: ${J.dim(s.join(", "))}`),o.push("pnpm db:setup # Apply the database schema"),o.push(Bl(e)),We.note(o.join(`
1718
- `),J.yellow("Deployment"))}function Vl(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 Bl(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 pt(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 Te(e,t){let r=pt(e),n=pt(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 zt(e,t){return e.versions.find(r=>r.version===t)?.cli}function Qi(e){return process.env.GENERATESAAS_TEMPLATE_TARBALL||process.env.GENERATESAAS_TEMPLATE_TARBALL_DIR||process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?!0:pt(e)===null}function qt(e,t,r="3.29.0"){if(Qi(r))return{ok:!0};let n=zt(e,e.latest);return!n||pt(n)===null?{ok:!0}:Te(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 es(e,t,r="3.29.0"){if(Qi(r))return{ok:!0};let n=zt(e,t);return!n||pt(n)===null?{ok:!0}:Te(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 zl from"picocolors";var ql="a10a6fb9d7cadde32e37dad52059d17b5d2b916b08c76d8fbcc99982e9a3d87f";async function Jl(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 ts(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 X("--architecture <type>","fullstack or separate").choices([...tt])).addOption(new X("--payment <provider>","payment provider").choices([...rt])).addOption(new X("--email <provider>","email provider").choices([...nt])).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 X("--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([...Ce])).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 X("--currency <code>","default currency for billing").choices([...pe])).addOption(new X("--preset <preset>","infrastructure preset: serverless (Vercel + Neon + Upstash) or selfhost (Docker or Node + Postgres + Redis); --deploy/--database/--cache override it piecewise").choices([...Ne])).addOption(new X("--deploy <target>","deployment target").choices([...de])).addOption(new X("--database <provider>","database provider").choices([...ue])).addOption(new X("--cache <provider>","cache provider").choices([...me])).option("--observability <providers>",`comma-separated observability providers (${F.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 X("--demo","first-party demo build: keep sample content, mark site non-indexable - requires CI API key").hideHelp()).addOption(new X("--no-db-migration","skip generating the baseline DB migration (internal: demos/CI/playground)").hideHelp()).action(async(t,r)=>{await Xl(t?{...r,apiKey:t}:r)})}async function Xl(e){let t=performance.now();Br("3.29.0");let r;try{r=Qr(e)}catch(E){S.cancel(N(E)),process.exit(1)}let n=S.spinner(),i;try{i=await st({apiKey:e.apiKey,prompt:!e.yes})}catch(E){S.cancel(N(E)),process.exit(1)}e.demo&&Rr(i)!==ql&&(S.cancel("--demo is restricted to first-party demo deployments."),process.exit(1));let o=ge(i),s,a=async()=>{s=await Ie(o);let E=qt(s,"init");if(!E.ok)throw new Error(E.message);return{latestVersion:s.latest,selectedVersion:s.latest,desktopAllowed:s.entitlements?.desktopAllowed??!0,mobileAllowed:s.entitlements?.mobileAllowed??!0}};n.start("Verifying access...");let d,h,g=!0,w=!0;try{({latestVersion:d,selectedVersion:h,desktopAllowed:g,mobileAllowed:w}=await a()),n.stop("Access verified."),$e(i)}catch(E){if(n.stop("Access verification failed."),E instanceof $&&E.status===401){e.yes&&(S.cancel("Invalid API key. Cannot prompt in non-interactive mode."),process.exit(1)),S.log.warning("Invalid API key."),i=await yt(),o=ge(i),n.start("Verifying access...");try{({latestVersion:d,selectedVersion:h,desktopAllowed:g,mobileAllowed:w}=await a()),n.stop("Access verified."),$e(i)}catch(_){n.stop("Access verification failed."),S.cancel(_ instanceof $&&_.status===401?"Invalid API key.":N(_)),process.exit(1)}}else S.cancel(N(E)),process.exit(1)}S.log.success(`Latest version: ${d}`),r.desktop===!0&&!g&&(S.cancel("The desktop app is available on the Pro plan and up. Upgrade your plan at generatesaas.com."),process.exit(1)),r.mobile===!0&&!w&&(S.cancel("The mobile app is available on the Pro plan and up. Upgrade your plan at generatesaas.com."),process.exit(1));let v;e.yes?v=en({...r,...g?{}:{desktop:!1},...w?{}:{mobile:!1}}):v=await tn(r,{desktopAllowed:g,mobileAllowed:w});let P;n.start("Activating license...");try{let E=e.demo&&v.baseUrl?await Jl(v.baseUrl):crypto.randomUUID(),_=()=>({frontend:or,version:h,installId:E,projectName:v.projectName,options:ln(v)}),Q;try{Q=await ar(o,_())}catch(G){let M=xt(G);if(!M?.lastAllowedVersion||!s)throw G;n.stop("License activation failed.");let ee=es(s,M.lastAllowedVersion);if(ee.ok||(S.cancel(`${M.message} ${ee.message}`),process.exit(1)),e.yes){let ke=zt(s,M.lastAllowedVersion);S.cancel(`${M.message} Re-run ${ke?`npx generatesaas@${ke} init`:"init"} without --yes to continue with v${M.lastAllowedVersion} (the last version your license covers).`),process.exit(1)}let H=await S.confirm({message:`Your update window has ended. Continue with v${M.lastAllowedVersion} (the last version your license covers)?`});(S.isCancel(H)||!H)&&(S.cancel("Setup cancelled."),process.exit(0)),h=M.lastAllowedVersion,n.start(`Activating license for v${h}...`),Q=await ar(o,_())}P={token:Q.token,keyHash:Rr(i),installId:Q.installId??E},n.stop("License activated.")}catch(E){n.stop("License activation failed."),S.cancel(N(E)),process.exit(1)}let m=Wl(v.projectDir);if(Kl(m)&&Gl(m).length>0)if(e.yes)S.log.info(`Directory ${m} is not empty. Merging (keeping existing files, overwriting conflicts).`);else{let _=await S.select({message:`Directory ${m} 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"}]});(S.isCancel(_)||_==="cancel")&&(S.cancel("Setup cancelled."),process.exit(0)),_==="overwrite"&&Hl(m,{recursive:!0,force:!0})}let D={...v,projectDir:m,version:h,...e.demo?{docs:!1}:{}};n.start("Downloading template...");try{await Dt(o,h,m),n.stop("Template downloaded.")}catch(E){n.stop("Download failed."),S.cancel(N(E)),process.exit(1)}n.start("Generating project files...");try{if(await Yt(D),!e.demo){let E=await lt(m);await l(Yl(m,_t),`${JSON.stringify(E,null," ")}
1719
- `),await Bi(m,m)}await Hi(m),await Fi(D,P),n.stop("Project files generated.")}catch(E){n.stop("Generation failed."),S.cancel(N(E)),process.exit(1)}!await Wi(m)&&D.demo===!0&&(S.cancel("Lockfile regeneration failed on a demo build - refusing to ship a stale lockfile."),process.exit(1));let K=await zi(m),ae=D.demo!==!0&&e.dbMigration!==!1,Re=!1;ae&&K&&(await qi(m),Re=!0),await Ji(m),K&&await Xi(m);let _e=Ye("docker"),ce=nr(D).map(E=>E.key).filter(E=>!D.credentials?.[E]);Zi(D,{pnpmInstalled:K,dockerAvailable:_e,skippedCredentials:ce,baselineMigrationMissing:ae&&!Re}),Kr(),S.log.info(zl.dim(`Done in ${((performance.now()-t)/1e3).toFixed(1)}s`))}import{existsSync as Jt}from"fs";import{readFile as as}from"fs/promises";import{join as ze,resolve as rp}from"path";import*as b from"@clack/prompts";import L from"picocolors";import{mkdtemp as Zl,rm as Ql}from"fs/promises";import{tmpdir as ep}from"os";import{join as tp}from"path";async function Lr(e,t,r,n){let i=await Zl(tp(ep(),"generatesaas-stage-"));try{await Dt(e,t,i),await Yt({...r,projectDir:i}),await _r(i,n)}finally{await Ql(i,{recursive:!0,force:!0})}}function rs(e){return e?"ON":"OFF"}var dt="packages/config/src/index.ts";function ns(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 is(e){return[...et({databaseProvider:e.databaseProvider??"postgres",cacheProvider:e.cacheProvider??"redis",emailProvider:e.emailProvider??"smtp"})].sort()}var $r=[{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 ${dt} 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 ${dt} 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 ${dt}. 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===re(e),describe:e=>`Retired option \`aiBuiltin\`: your project recorded built-in AI models ${rs(e.aiBuiltin)}, but it is now a plain config value generated ${rs(re(e))} for a project ${re(e)?"with":"without"} a payment provider. Set \`config.ai.builtin\` to \`${String(e.aiBuiltin===!0)}\` in ${dt} 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 ${dt} to keep it off.`},{key:"dockerServices",severity:"warn",preserved:e=>ns(e).join(",")===is(e).join(","),describe:e=>`Retired option \`dockerServices\`: your project recorded ${ns(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 ${is(e).join(", ")}. Add any extra service back by hand; the file is yours to edit.`},{key:"aiTools",severity:"warn",preserved:e=>(e.aiTools??[]).length===Yr.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 (${Ge.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 ${dt} to drop a section for good.`}],bf=$r.map(e=>e.key);function ss(e){for(let t of $r)t.normalize?.(e)}function os(e){let t=[];for(let r of $r){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 cs(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",np,[]).action(async(t,r)=>{r.args.length>0&&b.log.warn("`auto` is now the default and the argument is ignored.");let n=ip(t.answer),i=rp(t.cwd??process.cwd()),o=ze(i,he),s;try{s=JSON.parse(await as(o,"utf-8"))}catch{b.cancel(".generatesaas/manifest.json not found. Run this from a GenerateSaaS project."),process.exit(1)}s.frontend===ir&&(b.cancel(`This project was generated on the Nuxt frontend (\`.generatesaas/manifest.json\` records \`frontend: "${ir}"\`).
1717
+ `,replace:""},{find:"export async function captureAiGeneration(event: AiGenerationEvent): Promise<void> {",replace:"export async function captureAiGeneration(_event: AiGenerationEvent): Promise<void> {"},{find:" * @param event - The call to record.",replace:" * @param _event - Ignored: no PostHog adapter was generated for this project."}]}var Oi=[{file:"src/resolve-server.ts",edits:dl},{file:"src/resolve-browser.ts",edits:ul},{file:"src/llm-analytics.ts",edits:kl,dualMode:!1}],El=[{file:"src/resolve-desktop-main.ts",edits:hl},{file:"src/resolve-desktop-renderer.ts",edits:fl}];import{readdir as Sl,readFile as Pl}from"fs/promises";import{join as ji}from"path";async function Mi(e){if(e.demo)return;let t=e.appName.trim()||e.projectName,r=JSON.stringify(t).slice(1,-1),n=ji(e.projectDir,"packages/i18n/translations"),i;try{i=await Sl(n)}catch{return}for(let o of i){let s=ji(n,o,"web.json"),a;try{a=await Pl(s,"utf-8")}catch{continue}let d=a.replaceAll("GenerateSaaS",()=>r);d!==a&&await l(s,d)}}async function Yt(e){let t=e.projectDir;e.demo||(await bn(t),await wn(t),await vn(t),await kn(t)),await En(t),await An(e),await Tn(e),await Rn(e),e.demo||await _n(e),await Dn(e),await Nn(e),await Cn(e),await Mn(e),await Fn(e),await Bn(e),await zn(e),await Jn(e),await ei(e),await ni(e),await ki(e),await ii(e),await si(e),await oi(e),await ai(e),await ci(e),await li(e),await pi(e),await ui(e),await gi(e),await mi(e),await hi(e),await bi(e),await Pi(e),await Ii(e),await Di(e),await Yn(e),await Mi(e),await ri(e)}import{basename as Fi,join as Vi,relative as Il}from"path";import{createHash as Ui}from"crypto";import{readFile as Al}from"fs/promises";async function Wt(e){let t=await Al(e);return Ui("sha256").update(t).digest("hex")}function _r(e){return Ui("sha256").update(e).digest("hex")}var Tl=new Set(["data",q]);function Rl(e){let t=e.split("/");for(let r of t)if(pr.has(r)||dr.has(r)||Tl.has(r)||r.startsWith(".env")&&!r.includes("example"))return!0;return!1}function Bi(e,t){return{projectName:e.projectName??Fi(t),appName:e.appName??e.projectName??Fi(t),projectDir:t,architecture:e.architecture??"fullstack",paymentProvider:e.paymentProvider??"none",emailProvider:e.emailProvider??"smtp",multiTenancy:e.multiTenancy??!1,projects:e.projects??!1,docs:e.docs??!1,desktop:e.desktop??!1,mobile:e.mobile??!1,mobilePurchases:e.mobilePurchases??"none",ai:e.ai??!1,webAi:e.webAi??!0,revenueSharing:e.revenueSharing??!1,credits:e.credits??!1,defaultCurrency:e.defaultCurrency??"USD",deploymentTarget:e.deploymentTarget??"node",databaseProvider:e.databaseProvider??"postgres",cacheProvider:e.cacheProvider??"redis",observability:e.observability??[],version:e.version,baseUrl:e.baseUrl,credentials:{},demo:!1}}function _l(e,t){return{version:e.version,initialVersion:e.version,appName:e.appName,projectName:e.projectName,frontend:nn,architecture:e.architecture,paymentProvider:e.paymentProvider,emailProvider:e.emailProvider,multiTenancy:e.multiTenancy,projects:e.projects,docs:e.docs,desktop:e.desktop,mobile:e.mobile,...e.mobile&&ne(e)?{mobilePurchases:e.mobilePurchases}:{},ai:e.ai,webAi:e.webAi,credits:e.credits,revenueSharing:e.revenueSharing,defaultCurrency:e.defaultCurrency,deploymentTarget:e.deploymentTarget,databaseProvider:e.databaseProvider,cacheProvider:e.cacheProvider,observability:e.observability,...e.baseUrl?{baseUrl:e.baseUrl}:{},...t&&{licenseToken:t.token,licenseKeyHash:t.keyHash,installId:t.installId}}}async function Ki(e,t){let n=(await J(e.projectDir,e.projectDir,Rl)).sort(),i=await Promise.all(n.map(async a=>[Ue(Il(e.projectDir,a)),await Wt(a)])),o=Object.fromEntries(i),s=_l(e,t);await l(Vi(e.projectDir,me),`${JSON.stringify(s,null," ")}
1718
+ `),await l(Vi(e.projectDir,sn),`${JSON.stringify(o,null," ")}
1719
+ `)}import{relative as Ol}from"path";async function pt(e){let r=(await J(e,e,ot)).sort(),n=await Promise.all(r.map(async i=>[Ue(Ol(e,i)),await Wt(i)]));return Object.fromEntries(n)}import{copyFile as xl,mkdir as Dl,rm as Nl}from"fs/promises";import{dirname as Cl,join as Gi,relative as Ll}from"path";import{existsSync as $l}from"fs";async function Or(e,t){$l(t)&&await Nl(t,{recursive:!0,force:!0});let n=(await J(e,e,ot)).map(i=>({file:i,dest:Gi(t,Ue(Ll(e,i)))}));await Promise.all([...new Set(n.map(({dest:i})=>Cl(i)))].map(i=>Dl(i,{recursive:!0}))),await Promise.all(n.map(({file:i,dest:o})=>xl(i,o)))}async function Hi(e,t){await Or(e,Gi(t,Dt))}import{readdir as jl,readFile as Wi}from"fs/promises";import{existsSync as Ml}from"fs";import{dirname as Ul,join as oe,resolve as xr,sep as Dr}from"path";import{fileURLToPath as Fl}from"url";var Vl={"claude-code":".claude/skills",cursor:".cursor/skills",codex:".agents/skills","gemini-cli":".gemini/skills",windsurf:".windsurf/skills"},Ye=Object.values(Vl),Nr=["generatesaas-update","generatesaas-translate","generatesaas-og-image","generatesaas-landing-animations"],Bl=Ul(Fl(import.meta.url));function Kl(){return $t(Bl,["skill","content"],"content")}async function Cr(e,t){for(let r of Ye){let n=oe(e,r);for(let[i,o]of Object.entries(t)){let s=xr(n,i);if(!s.startsWith(n+Dr))continue;let a=oe(s,"scripts"),d=oe(s,"references");await Mt(a),await Mt(d),await l(oe(s,"SKILL.md"),o.skillMd.replaceAll("__SKILL_ROOT__",r));for(let[g,E]of Object.entries(o.scripts)){let w=xr(a,g);w.startsWith(a+Dr)&&await l(w,E)}let h=Object.entries(o.references);h.length===0&&await l(oe(d,".gitkeep"),"");for(let[g,E]of h){let w=xr(d,g);w.startsWith(d+Dr)&&await l(w,E)}}}}async function Yi(e){if(!Ml(e))return{};let t={};for(let r of await jl(e))r!==".gitkeep"&&(t[r]=await Wi(oe(e,r),"utf-8"));return t}async function zi(e){let t=Kl(),r={};for(let n of Nr){let i=oe(t,n);r[n]={skillMd:await Wi(oe(i,"SKILL.md"),"utf-8"),scripts:await Yi(oe(i,"scripts")),references:await Yi(oe(i,"references"))}}await Cr(e,r)}import{execFile as Gl,execFileSync as Hl}from"child_process";import{access as Lr,readFile as Yl}from"fs/promises";import{join as zt}from"path";import*as _ from"@clack/prompts";function Te(e){try{let t=process.platform==="win32"?"where":"which";return Hl(t,[e],{stdio:"ignore"}),!0}catch{return!1}}function Ie(e,t,r,n=3e5){return new Promise((i,o)=>{Gl(e,t,{cwd:r,timeout:n,maxBuffer:50*1024*1024},(s,a,d)=>{if(s){let h=String(a||"").trim(),E=[String(d||"").trim(),h].filter(Boolean).join(`
1720
+ `);o(new Error(E?`${s.message}
1721
+ ${E}`:s.message))}else i()})})}async function qi(e){if(!Te("pnpm"))return _.log.warn("pnpm not found. Skipping lockfile regeneration."),!1;try{return await Ie("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 Ji(e){if(!Te("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 Ie("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 Xi(e){if(!Te("pnpm"))return!1;let t=_.spinner();t.start("Generating baseline database migration...");try{return await Ie("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 Zi(e){if(!Te("pnpm"))return!1;try{await Lr(zt(e,"packages/mcp-widgets"))}catch{return!1}let t=_.spinner();t.start("Building the MCP widgets...");try{return await Ie("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 Qi(e){try{return await Lr(zt(e,".git")),_.log.info("Git repository already exists, skipping init."),!0}catch{}if(!Te("git"))return _.log.warn("git not found. Skipping repository initialization."),!1;let t=_.spinner();t.start("Initializing git repository...");try{return await Ie("git",["init"],e),await Ie("git",["add","-A"],e),await Ie("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 es(e){if(!Te("pnpm"))return!1;try{await Lr(zt(e,".git"))}catch{return!1}try{let t=JSON.parse(await Yl(zt(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 Ie("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 We from"@clack/prompts";import H from"picocolors";function ts(e,t){let r=et(e);t.dockerAvailable||We.log.warn("Docker not found. Install Docker to run local services: https://docs.docker.com/get-docker/"),t.baselineMigrationMissing&&We.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=>Hr[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"))),We.note(n.join(`
1722
+ `),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")}`),We.note(i.join(`
1723
+ `),H.yellow("Dev Tools"));let o=[],s=Wl(e);s.length>0&&o.push(`Set in production: ${H.dim(s.join(", "))}`),o.push("pnpm db:setup # Apply the database schema"),o.push(zl(e)),We.note(o.join(`
1724
+ `),H.yellow("Deployment"))}function Wl(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 zl(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 dt(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 Re(e,t){let r=dt(e),n=dt(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 qt(e,t){return e.versions.find(r=>r.version===t)?.cli}function rs(e){return process.env.GENERATESAAS_TEMPLATE_TARBALL||process.env.GENERATESAAS_TEMPLATE_TARBALL_DIR||process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?!0:dt(e)===null}function Jt(e,t,r="3.31.0"){if(rs(r))return{ok:!0};let n=qt(e,e.latest);return!n||dt(n)===null?{ok:!0}:Re(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 ns(e,t,r="3.31.0"){if(rs(r))return{ok:!0};let n=qt(e,t);return!n||dt(n)===null?{ok:!0}:Re(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 tp="a10a6fb9d7cadde32e37dad52059d17b5d2b916b08c76d8fbcc99982e9a3d87f";async function rp(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 is(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([...tt])).addOption(new ee("--payment <provider>","payment provider").choices([...rt])).addOption(new ee("--email <provider>","email provider").choices([...nt])).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([...$e])).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([...le])).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([...Le])).addOption(new ee("--deploy <target>","deployment target").choices([...pe])).addOption(new ee("--database <provider>","database provider").choices([...de])).addOption(new ee("--cache <provider>","cache provider").choices([...ue])).option("--observability <providers>",`comma-separated observability providers (${K.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 np(t?{...r,apiKey:t}:r)})}async function np(e){let t=performance.now();Kr("3.31.0");let r;try{r=en(e)}catch(v){S.cancel(N(v)),process.exit(1)}let n=S.spinner(),i;try{i=await st({apiKey:e.apiKey,prompt:!e.yes})}catch(v){S.cancel(N(v)),process.exit(1)}e.demo&&_r(i)!==tp&&(S.cancel("--demo is restricted to first-party demo deployments."),process.exit(1));let o=fe(i),s,a=async()=>{s=await Ae(o);let v=Jt(s,"init");if(!v.ok)throw new Error(v.message);return{latestVersion:s.latest,selectedVersion:s.latest,desktopAllowed:s.entitlements?.desktopAllowed??!0,mobileAllowed:s.entitlements?.mobileAllowed??!0}};n.start("Verifying access...");let d,h,g=!0,E=!0;try{({latestVersion:d,selectedVersion:h,desktopAllowed:g,mobileAllowed:E}=await a()),n.stop("Access verified."),Me(i)}catch(v){if(n.stop("Access verification failed."),v instanceof j&&v.status===401){e.yes&&(S.cancel("Invalid API key. Cannot prompt in non-interactive mode."),process.exit(1)),S.log.warning("Invalid API key."),i=await bt(),o=fe(i),n.start("Verifying access...");try{({latestVersion:d,selectedVersion:h,desktopAllowed:g,mobileAllowed:E}=await a()),n.stop("Access verified."),Me(i)}catch(L){n.stop("Access verification failed."),S.cancel(L instanceof j&&L.status===401?"Invalid API key.":N(L)),process.exit(1)}}else S.cancel(N(v)),process.exit(1)}S.log.success(`Latest version: ${d}`),r.desktop===!0&&!g&&(S.cancel("The desktop app is available on the Pro plan and up. Upgrade your plan at generatesaas.com."),process.exit(1)),r.mobile===!0&&!E&&(S.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=tn({...r,...g?{}:{desktop:!1},...E?{}:{mobile:!1}}):w=await rn(r,{desktopAllowed:g,mobileAllowed:E});let P;n.start("Activating license...");try{let v=e.demo&&w.baseUrl?await rp(w.baseUrl):crypto.randomUUID(),L=()=>({frontend:ar,version:h,installId:v,projectName:w.projectName,options:pn(w)}),F;try{F=await cr(o,L())}catch(ve){let $=Nt(ve);if(!$?.lastAllowedVersion||!s)throw ve;n.stop("License activation failed.");let W=ns(s,$.lastAllowedVersion);if(W.ok||(S.cancel(`${$.message} ${W.message}`),process.exit(1)),e.yes){let z=qt(s,$.lastAllowedVersion);S.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 S.confirm({message:`Your update window has ended. Continue with v${$.lastAllowedVersion} (the last version your license covers)?`});(S.isCancel(ke)||!ke)&&(S.cancel("Setup cancelled."),process.exit(0)),h=$.lastAllowedVersion,n.start(`Activating license for v${h}...`),F=await cr(o,L())}P={token:F.token,keyHash:_r(i),installId:F.installId??v},n.stop("License activated.")}catch(v){n.stop("License activation failed."),S.cancel(N(v)),process.exit(1)}let m=Ql(w.projectDir);if(ql(m)&&Jl(m).length>0)if(e.yes)S.log.info(`Directory ${m} is not empty. Merging (keeping existing files, overwriting conflicts).`);else{let L=await S.select({message:`Directory ${m} 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"}]});(S.isCancel(L)||L==="cancel")&&(S.cancel("Setup cancelled."),process.exit(0)),L==="overwrite"&&Xl(m,{recursive:!0,force:!0})}let O={...w,projectDir:m,version:h,...e.demo?{docs:!1}:{}};n.start("Downloading template...");try{await Ct(o,h,m),n.stop("Template downloaded.")}catch(v){n.stop("Download failed."),S.cancel(N(v)),process.exit(1)}n.start("Generating project files...");try{if(await Yt(O),!e.demo){let v=await pt(m);await l(Zl(m,xt),`${JSON.stringify(v,null," ")}
1725
+ `),await Hi(m,m)}await zi(m),await Ki(O,P),n.stop("Project files generated.")}catch(v){n.stop("Generation failed."),S.cancel(N(v)),process.exit(1)}!await qi(m)&&O.demo===!0&&(S.cancel("Lockfile regeneration failed on a demo build - refusing to ship a stale lockfile."),process.exit(1));let B=await Ji(m),ae=O.demo!==!0&&e.dbMigration!==!1,_e=!1;ae&&B&&(await Xi(m),_e=!0);let Oe=B?await Zi(m):!1;await Qi(m),B&&await es(m);let xe=Te("docker"),Xe=ir(O).map(v=>v.key).filter(v=>!O.credentials?.[v]);ts(O,{pnpmInstalled:B,dockerAvailable:xe,skippedCredentials:Xe,baselineMigrationMissing:ae&&!_e,mcpWidgetsUnbuilt:O.ai&&!Oe}),Gr(),S.log.info(ep.dim(`Done in ${((performance.now()-t)/1e3).toFixed(1)}s`))}import{existsSync as Xt}from"fs";import{readFile as ps}from"fs/promises";import{join as ze,resolve as cp}from"path";import*as b from"@clack/prompts";import C from"picocolors";import{mkdtemp as ip,rm as sp}from"fs/promises";import{tmpdir as op}from"os";import{join as ap}from"path";async function $r(e,t,r,n){let i=await ip(ap(op(),"generatesaas-stage-"));try{await Ct(e,t,i),await Yt({...r,projectDir:i}),await Or(i,n)}finally{await sp(i,{recursive:!0,force:!0})}}function ss(e){return e?"ON":"OFF"}var ut="packages/config/src/index.ts";function os(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 as(e){return[...et({databaseProvider:e.databaseProvider??"postgres",cacheProvider:e.cacheProvider??"redis",emailProvider:e.emailProvider??"smtp"})].sort()}var jr=[{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 ${ut} 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 ${ut} 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 ${ut}. 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 ${ss(e.aiBuiltin)}, but it is now a plain config value generated ${ss(ne(e))} for a project ${ne(e)?"with":"without"} a payment provider. Set \`config.ai.builtin\` to \`${String(e.aiBuiltin===!0)}\` in ${ut} 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 ${ut} to keep it off.`},{key:"dockerServices",severity:"warn",preserved:e=>os(e).join(",")===as(e).join(","),describe:e=>`Retired option \`dockerServices\`: your project recorded ${os(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 ${as(e).join(", ")}. Add any extra service back by hand; the file is yours to edit.`},{key:"aiTools",severity:"warn",preserved:e=>(e.aiTools??[]).length===Wr.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 (${Ye.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 ${ut} to drop a section for good.`}],Af=jr.map(e=>e.key);function cs(e){for(let t of jr)t.normalize?.(e)}function ls(e){let t=[];for(let r of jr){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 ds(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",lp,[]).action(async(t,r)=>{r.args.length>0&&b.log.warn("`auto` is now the default and the argument is ignored.");let n=pp(t.answer),i=cp(t.cwd??process.cwd()),o=ze(i,me),s;try{s=JSON.parse(await ps(o,"utf-8"))}catch{b.cancel(".generatesaas/manifest.json not found. Run this from a GenerateSaaS project."),process.exit(1)}s.frontend===sr&&(b.cancel(`This project was generated on the Nuxt frontend (\`.generatesaas/manifest.json\` records \`frontend: "${sr}"\`).
1720
1726
 
1721
- v${sr} is the last release that ships a Nuxt frontend, and this CLI cannot update or migrate a Nuxt project to Next.js.
1727
+ v${or} is the last release that ships a Nuxt frontend, and this CLI cannot update or migrate a Nuxt project to Next.js.
1722
1728
 
1723
- Your project keeps working exactly as it is - stay on v${sr}, or start a fresh project on Next.js with ${L.cyan("generatesaas init")} when you are ready to move.`),process.exit(1));let a=zr(s);a.length>0&&(b.cancel(`.generatesaas/manifest.json carries a value this CLI cannot shape a project from:
1729
+ Your project keeps working exactly as it is - stay on v${or}, or start a fresh project on Next.js with ${C.cyan("generatesaas init")} when you are ready to move.`),process.exit(1));let a=qr(s);a.length>0&&(b.cancel(`.generatesaas/manifest.json carries a value this CLI cannot shape a project from:
1724
1730
 
1725
1731
  ${a.map(m=>` - ${m}`).join(`
1726
1732
  `)}
1727
1733
 
1728
- Correct it there, then run ${L.cyan("generatesaas update")} again.`),process.exit(1)),ss(s);let d=er(s);d.length>0&&(b.cancel(`.generatesaas/manifest.json records a combination this project cannot run:
1734
+ Correct it there, then run ${C.cyan("generatesaas update")} again.`),process.exit(1)),cs(s);let d=tr(s);d.length>0&&(b.cancel(`.generatesaas/manifest.json records a combination this project cannot run:
1729
1735
 
1730
1736
  ${d.map(m=>` - ${m}`).join(`
1731
1737
  `)}
1732
1738
 
1733
- Correct it there, then run ${L.cyan("generatesaas update")} again.`),process.exit(1));let h=Jr(s);h.length>0&&(b.cancel(`.generatesaas/manifest.json turns the web AI surface off (\`webAi: false\`) in a project that cannot run without it:
1739
+ Correct it there, then run ${C.cyan("generatesaas update")} again.`),process.exit(1));let h=Xr(s);h.length>0&&(b.cancel(`.generatesaas/manifest.json turns the web AI surface off (\`webAi: false\`) in a project that cannot run without it:
1734
1740
 
1735
1741
  ${h.map(m=>` - ${m}`).join(`
1736
1742
  `)}
1737
1743
 
1738
- Correct it there, then run ${L.cyan("generatesaas update")} again.`),process.exit(1));let g=Xr(s);g.length>0&&(b.cancel(`.generatesaas/manifest.json turns on mobile store purchases (\`mobilePurchases: "revenuecat"\`) in a project that cannot run them:
1744
+ Correct it there, then run ${C.cyan("generatesaas update")} again.`),process.exit(1));let g=Zr(s);g.length>0&&(b.cancel(`.generatesaas/manifest.json turns on mobile store purchases (\`mobilePurchases: "revenuecat"\`) in a project that cannot run them:
1739
1745
 
1740
1746
  ${g.map(m=>` - ${m}`).join(`
1741
1747
  `)}
1742
1748
 
1743
- Correct it there, then run ${L.cyan("generatesaas update")} again.`),process.exit(1));let w;try{w=await st()}catch(m){b.cancel(N(m)),process.exit(1)}let v=ge(w),P=b.spinner();try{P.start("Verifying access...");let m;try{m=await Ie(v)}catch(A){throw A instanceof $&&A.status===401?new Error("Your saved API key was rejected. Run `generatesaas auth` to update it, or set GENERATESAAS_API_KEY."):A}let D=qt(m,"update");if(!D.ok)throw new Error(D.message);P.stop("Access verified."),$e(w),P.start("Fetching latest skill files...");let we=await cn(v,m.latest);await Nr(i,we.skills);let K=Ge;if(P.stop("Skills updated."),b.log.success(`Skill files installed to ${L.cyan(K.length.toString())} locations.`),s.version===m.latest){b.log.info(`Already on the latest version (${s.version}).`);return}Te(s.version,m.latest)>0&&(b.cancel(`This project is on ${s.version}, which is newer than the latest release (${m.latest}). Updating would stage the older template over it. Check that your API key points at the right account, or correct \`version\` in ${he}.`),process.exit(1));let ae=m.entitlements;ae&&(s.desktop&&!ae.desktopAllowed&&(b.cancel("This project includes the desktop app, which is available on the Pro plan and up. Upgrade your plan at generatesaas.com to keep updating it."),process.exit(1)),s.mobile&&ae.mobileAllowed===!1&&(b.cancel("This project includes the mobile app, which is available on the Pro plan and up. Upgrade your plan at generatesaas.com to keep updating it."),process.exit(1)));let Re=JSON.stringify(s);await sp(s,Zr(s),n),await op(os(s),n);let _e=Wr(s),Xe=qr(s),ce=er(Xe);ce.length>0&&(b.cancel(`.generatesaas/manifest.json is missing a provider key, and its default would create a combination this project cannot run:
1749
+ Correct it there, then run ${C.cyan("generatesaas update")} again.`),process.exit(1));let E;try{E=await st()}catch(m){b.cancel(N(m)),process.exit(1)}let w=fe(E),P=b.spinner();try{P.start("Verifying access...");let m;try{m=await Ae(w)}catch(I){throw I instanceof j&&I.status===401?new Error("Your saved API key was rejected. Run `generatesaas auth` to update it, or set GENERATESAAS_API_KEY."):I}let O=Jt(m,"update");if(!O.ok)throw new Error(O.message);P.stop("Access verified."),Me(E),P.start("Fetching latest skill files...");let be=await ln(w,m.latest);await Cr(i,be.skills);let B=Ye;if(P.stop("Skills updated."),b.log.success(`Skill files installed to ${C.cyan(B.length.toString())} locations.`),s.version===m.latest){b.log.info(`Already on the latest version (${s.version}).`);return}Re(s.version,m.latest)>0&&(b.cancel(`This project is on ${s.version}, which is newer than the latest release (${m.latest}). Updating would stage the older template over it. Check that your API key points at the right account, or correct \`version\` in ${me}.`),process.exit(1));let ae=m.entitlements;ae&&(s.desktop&&!ae.desktopAllowed&&(b.cancel("This project includes the desktop app, which is available on the Pro plan and up. Upgrade your plan at generatesaas.com to keep updating it."),process.exit(1)),s.mobile&&ae.mobileAllowed===!1&&(b.cancel("This project includes the mobile app, which is available on the Pro plan and up. Upgrade your plan at generatesaas.com to keep updating it."),process.exit(1)));let _e=JSON.stringify(s);await dp(s,Qr(s),n),await up(ls(s),n);let Oe=zr(s),xe=Jr(s),we=tr(xe);we.length>0&&(b.cancel(`.generatesaas/manifest.json is missing a provider key, and its default would create a combination this project cannot run:
1744
1750
 
1745
- ${ce.map(A=>` - ${A}`).join(`
1751
+ ${we.map(I=>` - ${I}`).join(`
1746
1752
  `)}
1747
1753
 
1748
- Add the key to .generatesaas/manifest.json with a value your deployment target supports, then run ${L.cyan("generatesaas update")} again.`),process.exit(1));let E=JSON.stringify(Xe)!==Re;if(s=Xe,s.licenseToken)try{let A=await pn(v,{currentToken:s.licenseToken,newVersion:m.latest});s.licenseToken=A.token,A.licenseKeyHash&&(s.licenseKeyHash=A.licenseKeyHash),await l(o,`${JSON.stringify(s,null," ")}
1749
- `),E=!1,b.log.success("License refreshed.")}catch(A){let c=xt(A);c&&(b.cancel(c.message),process.exit(1)),b.log.warn("License refresh skipped.")}E&&await l(o,`${JSON.stringify(s,null," ")}
1750
- `);let _=Ui(s,i),Q=ze(i,sn);P.start(`Staging v${m.latest} (shaped for your config)...`),await Lr(v,m.latest,_,Q),P.stop("Template staged.");let{text:G,title:M}=await lp(v,m,s.version);G&&b.note(G,M);let ee=ze(i,_t),H=ze(i,Ot),ke=!Jt(H),Ee=!Jt(ee);if(ke){if(P.start("Building baseline template (one-time migration)..."),await Lr(v,s.version,_,H),Ee){let A=await lt(H);await l(ee,`${JSON.stringify(A,null," ")}
1751
- `)}if(P.stop("Baseline template stored."),!Ee){let A=await pp(ee,H);A>0&&b.log.warn(`Rebuilt baseline differs from the original for ${A} file(s) (the CLI's shaping evolved since this project was scaffolded). Classification still follows the committed template-hashes.json; upstream diffs for those files may include unrelated noise.`)}}else if(Ee){P.start("Computing baseline template hashes...");let A=await lt(H);await l(ee,`${JSON.stringify(A,null," ")}
1752
- `),P.stop("Baseline hashes computed.")}await l(ze(i,on),`${JSON.stringify({currentVersion:s.version,targetVersion:m.latest,changelog:G,stagedAt:new Date().toISOString(),..._e.length>0?{newOptions:_e}:{}},null," ")}
1753
- `),b.log.info(`Update staged: ${L.cyan(s.version)} \u2192 ${L.cyan(m.latest)}`),b.log.info(`Ask your AI coding assistant to ${L.cyan("'update my GenerateSaaS project'")}.`),s.desktop===!0&&Jt(ze(i,"apps/tauri"))&&b.log.warn(`Desktop: the app moved to an Electron shell (${L.cyan("apps/desktop")}). Your project still has the old Tauri shell (${L.cyan("apps/tauri")}) - remove it after verifying the Electron app builds and runs. See ${L.cyan("/desktop/updates")}.`),s.desktop===!0&&Jt(ze(i,"apps/electron"))&&b.log.warn(`Desktop: the app now lives at ${L.cyan("apps/desktop")}. Your project still has the old ${L.cyan("apps/electron")} directory - move your local changes across, remove it, then run ${L.cyan("pnpm install")}. See ${L.cyan("/desktop/updates")}.`)}catch(m){P.stop("Failed."),b.cancel(`Update failed: ${N(m)}`),process.exit(1)}})}var ls="desktop-migration";function np(e,t){return t.push(e),t}function ip(e){let t=new Set([ls,...Object.keys(ds).map(n=>`retired:${n}`)]),r=new Map;for(let n of e){let i=n.indexOf("=");(i<=0||i===n.length-1)&&(b.cancel(`\`--answer ${n}\` is malformed. Use \`--answer <id>=<choice>\`.`),process.exit(1));let o=n.slice(0,i);t.has(o)||(b.cancel(`\`--answer ${n}\` names a question this update does not ask. Valid ids: ${[...t].join(", ")}.`),process.exit(1)),r.set(o,n.slice(i+1))}return r}async function ps(e,t){let r=t.get(e.id);if(r!==void 0){let n=e.choices.find(i=>i.id===r);return n||(b.cancel(`\`--answer ${e.id}=${r}\` is not a valid choice. Valid choices: ${e.choices.map(i=>i.id).join(", ")}.`),process.exit(1)),n}if(process.stdin.isTTY){let n=await b.select({message:e.message,options:e.choices.map(o=>({value:o.id,label:o.label,...o.hint?{hint:o.hint}:{}}))});b.isCancel(n)&&(b.cancel("Update cancelled. Nothing was changed or staged."),process.exit(1));let i=e.choices.find(o=>o.id===n);return i||(b.cancel("Update cancelled. Nothing was changed or staged."),process.exit(1)),i}b.cancel(`${e.message}
1754
+ Add the key to .generatesaas/manifest.json with a value your deployment target supports, then run ${C.cyan("generatesaas update")} again.`),process.exit(1));let Xe=JSON.stringify(xe)!==_e;if(s=xe,s.licenseToken)try{let I=await dn(w,{currentToken:s.licenseToken,newVersion:m.latest});s.licenseToken=I.token,I.licenseKeyHash&&(s.licenseKeyHash=I.licenseKeyHash),await l(o,`${JSON.stringify(s,null," ")}
1755
+ `),Xe=!1,b.log.success("License refreshed.")}catch(I){let c=Nt(I);c&&(b.cancel(c.message),process.exit(1)),b.log.warn("License refresh skipped.")}Xe&&await l(o,`${JSON.stringify(s,null," ")}
1756
+ `);let v=Bi(s,i),L=ze(i,on);P.start(`Staging v${m.latest} (shaped for your config)...`),await $r(w,m.latest,v,L),P.stop("Template staged.");let{text:F,title:ve}=await fp(w,m,s.version);F&&b.note(F,ve);let $=ze(i,xt),W=ze(i,Dt),ke=!Xt(W),z=!Xt($);if(ke){if(P.start("Building baseline template (one-time migration)..."),await $r(w,s.version,v,W),z){let I=await pt(W);await l($,`${JSON.stringify(I,null," ")}
1757
+ `)}if(P.stop("Baseline template stored."),!z){let I=await gp($,W);I>0&&b.log.warn(`Rebuilt baseline differs from the original for ${I} file(s) (the CLI's shaping evolved since this project was scaffolded). Classification still follows the committed template-hashes.json; upstream diffs for those files may include unrelated noise.`)}}else if(z){P.start("Computing baseline template hashes...");let I=await pt(W);await l($,`${JSON.stringify(I,null," ")}
1758
+ `),P.stop("Baseline hashes computed.")}await l(ze(i,an),`${JSON.stringify({currentVersion:s.version,targetVersion:m.latest,changelog:F,stagedAt:new Date().toISOString(),...Oe.length>0?{newOptions:Oe}:{}},null," ")}
1759
+ `),b.log.info(`Update staged: ${C.cyan(s.version)} \u2192 ${C.cyan(m.latest)}`),b.log.info(`Ask your AI coding assistant to ${C.cyan("'update my GenerateSaaS project'")}.`),s.desktop===!0&&Xt(ze(i,"apps/tauri"))&&b.log.warn(`Desktop: the app moved to an Electron shell (${C.cyan("apps/desktop")}). Your project still has the old Tauri shell (${C.cyan("apps/tauri")}) - remove it after verifying the Electron app builds and runs. See ${C.cyan("/desktop/updates")}.`),s.desktop===!0&&Xt(ze(i,"apps/electron"))&&b.log.warn(`Desktop: the app now lives at ${C.cyan("apps/desktop")}. Your project still has the old ${C.cyan("apps/electron")} directory - move your local changes across, remove it, then run ${C.cyan("pnpm install")}. See ${C.cyan("/desktop/updates")}.`)}catch(m){P.stop("Failed."),b.cancel(`Update failed: ${N(m)}`),process.exit(1)}})}var us="desktop-migration";function lp(e,t){return t.push(e),t}function pp(e){let t=new Set([us,...Object.keys(hs).map(n=>`retired:${n}`)]),r=new Map;for(let n of e){let i=n.indexOf("=");(i<=0||i===n.length-1)&&(b.cancel(`\`--answer ${n}\` is malformed. Use \`--answer <id>=<choice>\`.`),process.exit(1));let o=n.slice(0,i);t.has(o)||(b.cancel(`\`--answer ${n}\` names a question this update does not ask. Valid ids: ${[...t].join(", ")}.`),process.exit(1)),r.set(o,n.slice(i+1))}return r}async function ms(e,t){let r=t.get(e.id);if(r!==void 0){let n=e.choices.find(i=>i.id===r);return n||(b.cancel(`\`--answer ${e.id}=${r}\` is not a valid choice. Valid choices: ${e.choices.map(i=>i.id).join(", ")}.`),process.exit(1)),n}if(process.stdin.isTTY){let n=await b.select({message:e.message,options:e.choices.map(o=>({value:o.id,label:o.label,...o.hint?{hint:o.hint}:{}}))});b.isCancel(n)&&(b.cancel("Update cancelled. Nothing was changed or staged."),process.exit(1));let i=e.choices.find(o=>o.id===n);return i||(b.cancel("Update cancelled. Nothing was changed or staged."),process.exit(1)),i}b.cancel(`${e.message}
1754
1760
 
1755
1761
  This update is running without an interactive terminal, so it cannot ask you directly. Answer the question \`${e.id}\` and re-run, for example:
1756
1762
 
1757
- ${L.cyan(`generatesaas update --answer ${e.id}=${e.choices[0].id}`)}
1763
+ ${C.cyan(`generatesaas update --answer ${e.id}=${e.choices[0].id}`)}
1758
1764
 
1759
1765
  Choices:
1760
1766
  ${e.choices.map(n=>` - ${n.id}: ${n.label}${n.hint?` (${n.hint})`:""}`).join(`
1761
- `)}`),process.exit(1)}async function sp(e,t,r){if(t.kind==="none")return;let n=cp[t.kind];(await ps({id:ls,message:n.message,choices:n.choices},r)).apply(e)}var ds={billingScope:[{value:"stage",label:"Stage it - I will move each organization's balance to its owner myself",hint:"move every paying organization's credits and plan onto its owner before you take new checkouts - the columns holding them are going away, and a stored balance is not migrated for you"},{value:"stop",label:"Stop, and stage nothing",hint:"migrate those balances in your database first, then re-run update - this is buyer DATA, not a config line, so nothing the update stages can put it back"}],emailTracking:[{value:"stage",label:"Stage it - I will turn tracking back off myself",hint:"set `config.email.tracking.enabled` to false in packages/config/src/index.ts before your next send"},{value:"stop",label:"Stop, and stage nothing",hint:"edit packages/config/src/index.ts first, then re-run update - a file you have edited is walked as a 3-way merge instead of being replaced"}]};async function op(e,t){let r=[];for(let n of e){let i=n.severity==="ask"?ds[n.key]:void 0;if(!i){b.log.warn(n.message);continue}r.push({notice:n,answers:i})}for(let{notice:n,answers:i}of r)(await ps({id:`retired:${n.key}`,message:n.message,choices:i.map(s=>({id:s.value,label:s.label,hint:s.hint}))},t)).id==="stop"&&(b.cancel("Update cancelled. Nothing was changed or staged."),process.exit(1))}function ap(e){e.desktop=!1}var cp={"legacy-desktop-ai":{message:"Your desktop app runs the local AI stack through the retired desktop-AI option. Desktop AI now follows the AI option. Keep it?",choices:[{id:"keep-ai",label:"Turn AI on, keep the desktop AI stack",hint:"also makes your website's AI surface available - keep it hidden with config.ai.enabled: false",apply:e=>{e.ai=!0}},{id:"drop-ai",label:"Turn desktop AI off",hint:"your desktop app becomes a client shell: no AI, no Terminal",apply:e=>{e.ai=!1}}]},"desktop-gains-ai":{message:"Your desktop app has no AI today, but your project has the AI option on. With the desktop-AI option retired, AI on a desktop project now ships the app's local AI stack. Keep it?",choices:[{id:"keep-ai",label:"Keep AI - the desktop app gains the AI stack",hint:"adds the local AI stack and the Terminal to your desktop app",apply:()=>{}},{id:"drop-ai",label:"Drop AI",hint:"your website's AI surface hides",apply:e=>{e.ai=!1}},{id:"drop-desktop",label:"Drop the desktop app",hint:"your website keeps its AI surface exactly as it is today",apply:ap}]}};async function lp(e,t,r){let n=t.latest,i=t.versions.filter(d=>Te(d.version,r)>0&&Te(d.version,n)<=0).sort((d,h)=>Te(d.version,h.version)),o=async d=>{try{return await an(e,d)}catch{return null}};if(i.length<=1)return{text:await o(n),title:`Changelog v${n}`};let s=await Promise.all(i.map(d=>o(d.version)));return{text:i.map((d,h)=>{let g=d.date?` (${d.date.slice(0,10)})`:"",w=s[h]??"_No changelog available for this release._";return`# v${d.version}${g}
1767
+ `)}`),process.exit(1)}async function dp(e,t,r){if(t.kind==="none")return;let n=hp[t.kind];(await ms({id:us,message:n.message,choices:n.choices},r)).apply(e)}var hs={billingScope:[{value:"stage",label:"Stage it - I will move each organization's balance to its owner myself",hint:"move every paying organization's credits and plan onto its owner before you take new checkouts - the columns holding them are going away, and a stored balance is not migrated for you"},{value:"stop",label:"Stop, and stage nothing",hint:"migrate those balances in your database first, then re-run update - this is buyer DATA, not a config line, so nothing the update stages can put it back"}],emailTracking:[{value:"stage",label:"Stage it - I will turn tracking back off myself",hint:"set `config.email.tracking.enabled` to false in packages/config/src/index.ts before your next send"},{value:"stop",label:"Stop, and stage nothing",hint:"edit packages/config/src/index.ts first, then re-run update - a file you have edited is walked as a 3-way merge instead of being replaced"}]};async function up(e,t){let r=[];for(let n of e){let i=n.severity==="ask"?hs[n.key]:void 0;if(!i){b.log.warn(n.message);continue}r.push({notice:n,answers:i})}for(let{notice:n,answers:i}of r)(await ms({id:`retired:${n.key}`,message:n.message,choices:i.map(s=>({id:s.value,label:s.label,hint:s.hint}))},t)).id==="stop"&&(b.cancel("Update cancelled. Nothing was changed or staged."),process.exit(1))}function mp(e){e.desktop=!1}var hp={"legacy-desktop-ai":{message:"Your desktop app runs the local AI stack through the retired desktop-AI option. Desktop AI now follows the AI option. Keep it?",choices:[{id:"keep-ai",label:"Turn AI on, keep the desktop AI stack",hint:"also makes your website's AI surface available - keep it hidden with config.ai.enabled: false",apply:e=>{e.ai=!0}},{id:"drop-ai",label:"Turn desktop AI off",hint:"your desktop app becomes a client shell: no AI, no Terminal",apply:e=>{e.ai=!1}}]},"desktop-gains-ai":{message:"Your desktop app has no AI today, but your project has the AI option on. With the desktop-AI option retired, AI on a desktop project now ships the app's local AI stack. Keep it?",choices:[{id:"keep-ai",label:"Keep AI - the desktop app gains the AI stack",hint:"adds the local AI stack and the Terminal to your desktop app",apply:()=>{}},{id:"drop-ai",label:"Drop AI",hint:"your website's AI surface hides",apply:e=>{e.ai=!1}},{id:"drop-desktop",label:"Drop the desktop app",hint:"your website keeps its AI surface exactly as it is today",apply:mp}]}};async function fp(e,t,r){let n=t.latest,i=t.versions.filter(d=>Re(d.version,r)>0&&Re(d.version,n)<=0).sort((d,h)=>Re(d.version,h.version)),o=async d=>{try{return await cn(e,d)}catch{return null}};if(i.length<=1)return{text:await o(n),title:`Changelog v${n}`};let s=await Promise.all(i.map(d=>o(d.version)));return{text:i.map((d,h)=>{let g=d.date?` (${d.date.slice(0,10)})`:"",E=s[h]??"_No changelog available for this release._";return`# v${d.version}${g}
1762
1768
 
1763
- ${w}`}).join(`
1769
+ ${E}`}).join(`
1764
1770
 
1765
- `),title:`Changelog v${r} \u2192 v${n}`}}async function pp(e,t){let r=JSON.parse(await as(e,"utf-8")),n=await lt(t),i=0;for(let[o,s]of Object.entries(r))ot(o)||n[o]!==s&&i++;for(let o of Object.keys(n))o in r||i++;return i}import*as B from"@clack/prompts";import ve from"picocolors";import{readFile as dp}from"fs/promises";import{join as up,resolve as mp}from"path";function us(e){e.command("status").description("Show project status and check for updates").option("--cwd <path>","project directory (default: current directory)").action(async t=>{let r=mp(t.cwd??process.cwd()),n=up(r,he),i;try{i=JSON.parse(await dp(n,"utf-8"))}catch{B.cancel(".generatesaas/manifest.json not found. Run this from a GenerateSaaS project."),process.exit(1)}let o=[`Version: ${ve.cyan(i.version)}`,i.deploymentTarget?`Deploy target: ${ve.cyan(i.deploymentTarget)}`:null,i.databaseProvider?`Database: ${ve.cyan(i.databaseProvider)}`:null,i.cacheProvider?`Cache: ${ve.cyan(i.cacheProvider)}`:null].filter(Boolean).join(`
1766
- `);B.note(o,ve.bold("Project Status"));let s=B.spinner();s.start("Checking for updates...");try{let a=await st(),d=ge(a),g=(await Ie(d)).latest;i.version===g?(s.stop("Up to date."),B.log.success(`Already on the latest version (${ve.green(g)})`)):(s.stop("Update available."),B.log.warning(`Update available: ${ve.yellow(i.version)} \u2192 ${ve.green(g)}`),B.log.info(`Open this project in your AI coding agent and ask it to ${ve.cyan("update my GenerateSaaS project")} - it fetches and applies the update for you.`))}catch(a){s.stop("Check failed."),a instanceof $&&a.status===401?B.log.warning("Invalid API key. Run `generatesaas auth` to update it, or set GENERATESAAS_API_KEY."):B.log.warning(`Could not check for updates: ${N(a)}`)}})}import{Buffer as hp}from"buffer";import{readFile as fp}from"fs/promises";import*as x from"@clack/prompts";import O from"picocolors";function gp(){return process.env.GENERATESAAS_API_KEY??gt()}function yp(e){return{verdict:e.verdict,plan:e.license?.plan??e.domainInstalls.find(t=>t.ownerPlan)?.ownerPlan??null,mismatchDomain:e.install?.domain??null,ejectedAt:e.install?.ejectedAt??e.domainInstalls.find(t=>t.ejectedAt)?.ejectedAt??null}}function bp(e){return{verdict:e.verdict??"unknown",ejectedAt:e.ejectedAt??null}}function vp(e){switch(e.verdict){case"licensed":return x.log.success(`${O.green("LICENSED")} - resolves to an account with an active${e.plan?` ${e.plan}`:""} license.`),!0;case"ejected":return x.log.success(`${O.green("EJECTED")} - a licensed buyer opted this install out of telemetry${e.ejectedAt?` on ${e.ejectedAt.slice(0,10)}`:""}. The site is legitimate.`),!0;case"revoked":return x.log.error(`${O.red("REVOKED")} - the owning account no longer holds a plan (refund or chargeback). This deployment is no longer licensed.`),!1;case"token_domain_mismatch":return x.log.error(`${O.red("LEAKED TOKEN")} - this license belongs to a different deployment${e.mismatchDomain?` (${O.cyan(e.mismatchDomain)})`:""}, not this site. The token was copied from a licensed project.`),!1;case"no_license_history":return x.log.error(`${O.red("NO LICENSE HISTORY")} - no license has ever been associated with this site. If it runs GenerateSaaS, treat it as unlicensed.`),!1;default:return x.log.warn(`${O.yellow("UNKNOWN")} - could not cross-reference the records right now. Try again shortly.`),!1}}async function ms(e,t){let r=process.env.GENERATESAAS_API_URL??ft,n=gp();e.start("Cross-referencing license records...");try{let i=n?yp(await dn(r,n,{lkh:t.lkh,nid:t.nid,domain:t.domain})):bp(await cr(r,{token:t.token,domain:t.domain}));return e.stop(`${O.green("Checked")} - records cross-referenced`),vp(i)}catch(i){return e.stop(`${O.yellow("Skipped")} - ${N(i)}`),null}}function wp(e){let t=e.split(".");if(t.length!==3||!t[1])throw new Error("Invalid JWT format");let r=hp.from(t[1],"base64url").toString("utf-8");return JSON.parse(r)}function jr(e){return typeof e!="number"?"unknown":new Date(e*1e3).toISOString().split("T")[0]}function hs(e){x.note([`License ID: ${O.cyan(String(e.lid??"unknown"))}`,`Version: ${O.cyan(String(e.ver??"unknown"))}`,`Init version: ${String(e.iver??"unknown")}`,`Frontend: ${String(e.fe??"unknown")}`,`Created: ${jr(e.pat)}`,`Last updated: ${jr(e.uat)}`,`Expires: ${jr(e.exp)}`,`Install ID: ${String(e.nid??"unknown")}`].join(`
1767
- `),O.yellow("License Details"))}function kp(e){let r=(/^https?:\/\//i.test(e)?e:`https://${e}`).replace(/\/+$/,"");if(r.endsWith("/api"))return[`${r}/license`];try{if(new URL(r).pathname!=="/")return[`${r}/license`]}catch{return[`${r}/license`]}return[`${r}/api/license`,`${r}/license`]}async function fs(e){let t=x.spinner(),r=null,n="no candidates";for(let s of kp(e)){t.start(`Checking ${s}...`);try{let a=await fetch(s);if(!a.ok){n=`${s} returned ${a.status}`,t.stop(`${O.yellow("Not here")} - ${n}`);continue}let d=(await a.text()).trim();if(!d||d.split(".").length!==3){n=`${s} did not return a JWT`,t.stop(`${O.yellow("Not here")} - ${n}`);continue}r=d,t.stop(`${O.green("Found")} - license endpoint responded`);break}catch(a){n=`${s}: ${N(a)}`,t.stop(`${O.yellow("Unreachable")} - ${n}`)}}if(r===null){x.log.warn(`No license endpoint found (last: ${n}). The site may be ejected, not a GenerateSaaS app, or serving its API elsewhere.`);let s=gs(e);return s?await ms(t,{domain:s})??!1:!1}let i;try{i=wp(r)}catch{return x.log.error("Could not decode JWT payload."),!1}t.start("Verifying signature...");try{let s=process.env.GENERATESAAS_API_URL??ft,a=await cr(s,{token:r});if(a.valid)t.stop(`${O.green("Valid")} - signature verified`);else return t.stop(`${O.red("Invalid")} - ${a.reason}`),!1}catch{return t.stop(`${O.yellow("Skipped")} - could not reach verification service`),x.log.warn("Signature not verified. Displaying unverified claims:"),hs(i),!1}return hs(i),await ms(t,{token:r,lkh:typeof i.lkh=="string"?i.lkh:void 0,nid:typeof i.nid=="string"?i.nid:void 0,domain:gs(e)})??!0}function gs(e){try{return new URL(/^https?:\/\//i.test(e)?e:`https://${e}`).hostname}catch{return}}function ys(e){e.command("verify").description("Verify a GenerateSaaS license on a deployed site").argument("[url]","URL of the site to verify (e.g. https://example.com or https://example.com/api)").option("--file <path>","file with URLs to check, one per line").action(async(t,r)=>{if(!t&&!r.file&&(x.cancel("Provide a URL or --file <path>."),process.exit(1)),r.file){let i=(await fp(r.file,"utf-8")).split(`
1768
- `).map(s=>s.trim()).filter(s=>s&&!s.startsWith("#"));i.length===0&&(x.cancel("No URLs found in file."),process.exit(1));let o=0;for(let s of i)await fs(s)&&o++,x.log.info("");x.log.success(`${o}/${i.length} sites verified.`)}else await fs(t)||process.exit(1)})}import{existsSync as Ep,rmSync as Sp}from"fs";import*as Z from"@clack/prompts";function bs(e){e.command("auth").description("Set or update your GenerateSaaS API key").option("--clear","remove saved API key").action(async t=>{if(t.clear){Ep(fe)?(Sp(fe),Z.log.success("API key removed.")):Z.log.info("No API key configured.");return}let r=gt();r?Z.log.info(`Current API key: ****${r.slice(-4)}`):Z.log.info("No API key configured.");let n=await yt(),i=ge(n),o=Z.spinner();o.start("Verifying API key...");try{await Ie(i),o.stop("API key verified."),$e(n),Z.log.success("API key saved.")}catch(s){o.stop("Verification failed."),s instanceof $&&s.status===401?Z.cancel("Invalid API key."):Z.cancel(N(s)),process.exit(1)}})}import{existsSync as Xt,readFileSync as Ur,rmSync as Pp,writeFileSync as vs}from"fs";import{join as qe}from"path";import*as U from"@clack/prompts";var Ap=["packages/api/src/functions/maintenance/license-heartbeat.ts","packages/api/src/lib/cron-spread.ts","packages/api/src/lib/manifest.ts","packages/api/src/routes/internal/license.ts","packages/api/tests/functions/license-heartbeat.test.ts","packages/api/tests/lib/cron-spread.test.ts"],Ip=[{file:"packages/api/src/routes/inngest.ts",removals:[`import { licenseHeartbeatFunction } from "../functions/maintenance/license-heartbeat";
1771
+ `),title:`Changelog v${r} \u2192 v${n}`}}async function gp(e,t){let r=JSON.parse(await ps(e,"utf-8")),n=await pt(t),i=0;for(let[o,s]of Object.entries(r))ot(o)||n[o]!==s&&i++;for(let o of Object.keys(n))o in r||i++;return i}import*as Y from"@clack/prompts";import ye from"picocolors";import{readFile as yp}from"fs/promises";import{join as bp,resolve as wp}from"path";function fs(e){e.command("status").description("Show project status and check for updates").option("--cwd <path>","project directory (default: current directory)").action(async t=>{let r=wp(t.cwd??process.cwd()),n=bp(r,me),i;try{i=JSON.parse(await yp(n,"utf-8"))}catch{Y.cancel(".generatesaas/manifest.json not found. Run this from a GenerateSaaS project."),process.exit(1)}let o=[`Version: ${ye.cyan(i.version)}`,i.deploymentTarget?`Deploy target: ${ye.cyan(i.deploymentTarget)}`:null,i.databaseProvider?`Database: ${ye.cyan(i.databaseProvider)}`:null,i.cacheProvider?`Cache: ${ye.cyan(i.cacheProvider)}`:null].filter(Boolean).join(`
1772
+ `);Y.note(o,ye.bold("Project Status"));let s=Y.spinner();s.start("Checking for updates...");try{let a=await st(),d=fe(a),g=(await Ae(d)).latest;i.version===g?(s.stop("Up to date."),Y.log.success(`Already on the latest version (${ye.green(g)})`)):(s.stop("Update available."),Y.log.warning(`Update available: ${ye.yellow(i.version)} \u2192 ${ye.green(g)}`),Y.log.info(`Open this project in your AI coding agent and ask it to ${ye.cyan("update my GenerateSaaS project")} - it fetches and applies the update for you.`))}catch(a){s.stop("Check failed."),a instanceof j&&a.status===401?Y.log.warning("Invalid API key. Run `generatesaas auth` to update it, or set GENERATESAAS_API_KEY."):Y.log.warning(`Could not check for updates: ${N(a)}`)}})}import{Buffer as vp}from"buffer";import{readFile as kp}from"fs/promises";import*as D from"@clack/prompts";import x from"picocolors";function Ep(){return process.env.GENERATESAAS_API_KEY??yt()}function Sp(e){return{verdict:e.verdict,plan:e.license?.plan??e.domainInstalls.find(t=>t.ownerPlan)?.ownerPlan??null,mismatchDomain:e.install?.domain??null,ejectedAt:e.install?.ejectedAt??e.domainInstalls.find(t=>t.ejectedAt)?.ejectedAt??null}}function Pp(e){return{verdict:e.verdict??"unknown",ejectedAt:e.ejectedAt??null}}function Ap(e){switch(e.verdict){case"licensed":return D.log.success(`${x.green("LICENSED")} - resolves to an account with an active${e.plan?` ${e.plan}`:""} license.`),!0;case"ejected":return D.log.success(`${x.green("EJECTED")} - a licensed buyer opted this install out of telemetry${e.ejectedAt?` on ${e.ejectedAt.slice(0,10)}`:""}. The site is legitimate.`),!0;case"revoked":return D.log.error(`${x.red("REVOKED")} - the owning account no longer holds a plan (refund or chargeback). This deployment is no longer licensed.`),!1;case"token_domain_mismatch":return D.log.error(`${x.red("LEAKED TOKEN")} - this license belongs to a different deployment${e.mismatchDomain?` (${x.cyan(e.mismatchDomain)})`:""}, not this site. The token was copied from a licensed project.`),!1;case"no_license_history":return D.log.error(`${x.red("NO LICENSE HISTORY")} - no license has ever been associated with this site. If it runs GenerateSaaS, treat it as unlicensed.`),!1;default:return D.log.warn(`${x.yellow("UNKNOWN")} - could not cross-reference the records right now. Try again shortly.`),!1}}async function gs(e,t){let r=process.env.GENERATESAAS_API_URL??gt,n=Ep();e.start("Cross-referencing license records...");try{let i=n?Sp(await un(r,n,{lkh:t.lkh,nid:t.nid,domain:t.domain})):Pp(await lr(r,{token:t.token,domain:t.domain}));return e.stop(`${x.green("Checked")} - records cross-referenced`),Ap(i)}catch(i){return e.stop(`${x.yellow("Skipped")} - ${N(i)}`),null}}function Ip(e){let t=e.split(".");if(t.length!==3||!t[1])throw new Error("Invalid JWT format");let r=vp.from(t[1],"base64url").toString("utf-8");return JSON.parse(r)}function Mr(e){return typeof e!="number"?"unknown":new Date(e*1e3).toISOString().split("T")[0]}function ys(e){D.note([`License ID: ${x.cyan(String(e.lid??"unknown"))}`,`Version: ${x.cyan(String(e.ver??"unknown"))}`,`Init version: ${String(e.iver??"unknown")}`,`Frontend: ${String(e.fe??"unknown")}`,`Created: ${Mr(e.pat)}`,`Last updated: ${Mr(e.uat)}`,`Expires: ${Mr(e.exp)}`,`Install ID: ${String(e.nid??"unknown")}`].join(`
1773
+ `),x.yellow("License Details"))}function Tp(e){let r=(/^https?:\/\//i.test(e)?e:`https://${e}`).replace(/\/+$/,"");if(r.endsWith("/api"))return[`${r}/license`];try{if(new URL(r).pathname!=="/")return[`${r}/license`]}catch{return[`${r}/license`]}return[`${r}/api/license`,`${r}/license`]}async function bs(e){let t=D.spinner(),r=null,n="no candidates";for(let s of Tp(e)){t.start(`Checking ${s}...`);try{let a=await fetch(s);if(!a.ok){n=`${s} returned ${a.status}`,t.stop(`${x.yellow("Not here")} - ${n}`);continue}let d=(await a.text()).trim();if(!d||d.split(".").length!==3){n=`${s} did not return a JWT`,t.stop(`${x.yellow("Not here")} - ${n}`);continue}r=d,t.stop(`${x.green("Found")} - license endpoint responded`);break}catch(a){n=`${s}: ${N(a)}`,t.stop(`${x.yellow("Unreachable")} - ${n}`)}}if(r===null){D.log.warn(`No license endpoint found (last: ${n}). The site may be ejected, not a GenerateSaaS app, or serving its API elsewhere.`);let s=ws(e);return s?await gs(t,{domain:s})??!1:!1}let i;try{i=Ip(r)}catch{return D.log.error("Could not decode JWT payload."),!1}t.start("Verifying signature...");try{let s=process.env.GENERATESAAS_API_URL??gt,a=await lr(s,{token:r});if(a.valid)t.stop(`${x.green("Valid")} - signature verified`);else return t.stop(`${x.red("Invalid")} - ${a.reason}`),!1}catch{return t.stop(`${x.yellow("Skipped")} - could not reach verification service`),D.log.warn("Signature not verified. Displaying unverified claims:"),ys(i),!1}return ys(i),await gs(t,{token:r,lkh:typeof i.lkh=="string"?i.lkh:void 0,nid:typeof i.nid=="string"?i.nid:void 0,domain:ws(e)})??!0}function ws(e){try{return new URL(/^https?:\/\//i.test(e)?e:`https://${e}`).hostname}catch{return}}function vs(e){e.command("verify").description("Verify a GenerateSaaS license on a deployed site").argument("[url]","URL of the site to verify (e.g. https://example.com or https://example.com/api)").option("--file <path>","file with URLs to check, one per line").action(async(t,r)=>{if(!t&&!r.file&&(D.cancel("Provide a URL or --file <path>."),process.exit(1)),r.file){let i=(await kp(r.file,"utf-8")).split(`
1774
+ `).map(s=>s.trim()).filter(s=>s&&!s.startsWith("#"));i.length===0&&(D.cancel("No URLs found in file."),process.exit(1));let o=0;for(let s of i)await bs(s)&&o++,D.log.info("");D.log.success(`${o}/${i.length} sites verified.`)}else await bs(t)||process.exit(1)})}import{existsSync as Rp,rmSync as _p}from"fs";import*as te from"@clack/prompts";function ks(e){e.command("auth").description("Set or update your GenerateSaaS API key").option("--clear","remove saved API key").action(async t=>{if(t.clear){Rp(he)?(_p(he),te.log.success("API key removed.")):te.log.info("No API key configured.");return}let r=yt();r?te.log.info(`Current API key: ****${r.slice(-4)}`):te.log.info("No API key configured.");let n=await bt(),i=fe(n),o=te.spinner();o.start("Verifying API key...");try{await Ae(i),o.stop("API key verified."),Me(n),te.log.success("API key saved.")}catch(s){o.stop("Verification failed."),s instanceof j&&s.status===401?te.cancel("Invalid API key."):te.cancel(N(s)),process.exit(1)}})}import{existsSync as Zt,readFileSync as Fr,rmSync as Op,writeFileSync as Es}from"fs";import{join as qe}from"path";import*as U from"@clack/prompts";var xp=["packages/api/src/functions/maintenance/license-heartbeat.ts","packages/api/src/lib/cron-spread.ts","packages/api/src/lib/manifest.ts","packages/api/src/routes/internal/license.ts","packages/api/tests/functions/license-heartbeat.test.ts","packages/api/tests/lib/cron-spread.test.ts"],Dp=[{file:"packages/api/src/routes/inngest.ts",removals:[`import { licenseHeartbeatFunction } from "../functions/maintenance/license-heartbeat";
1769
1775
  `,` licenseHeartbeatFunction,
1770
1776
  `]},{file:"packages/api/src/routes/internal/index.ts",removals:[`import licenseRoutes from "./license";
1771
1777
  `,` .route("/license", licenseRoutes)
1772
1778
  `]},{file:"packages/api/src/routes/public/v1/health.ts",removals:[`import { manifest } from "../../../lib/manifest";
1773
- `],replacements:[{from:'c.json({ status: "success" as const, version: manifest?.version })',to:'c.json({ status: "success" as const })'}]}];function Tp(){return Ge.flatMap(e=>Dr.map(t=>qe(e,t)))}function Mr(e){return Xt(e)?(Pp(e,{recursive:!0}),!0):!1}function Rp(e,t,r=[]){if(!Xt(e))return!1;let n=Ur(e,"utf-8"),i=n;for(let o of t)i=i.replace(o,"");for(let{from:o,to:s}of r)i=i.replace(o,s);return i===n?!1:(vs(e,i,"utf-8"),!0)}function _p(e){let t=qe(e,".gitignore");if(!Xt(t))return!1;let r=Ur(t,"utf-8"),n=r.split(`
1779
+ `],replacements:[{from:'c.json({ status: "success" as const, version: manifest?.version })',to:'c.json({ status: "success" as const })'}]}];function Np(){return Ye.flatMap(e=>Nr.map(t=>qe(e,t)))}function Ur(e){return Zt(e)?(Op(e,{recursive:!0}),!0):!1}function Cp(e,t,r=[]){if(!Zt(e))return!1;let n=Fr(e,"utf-8"),i=n;for(let o of t)i=i.replace(o,"");for(let{from:o,to:s}of r)i=i.replace(o,s);return i===n?!1:(Es(e,i,"utf-8"),!0)}function Lp(e){let t=qe(e,".gitignore");if(!Zt(t))return!1;let r=Fr(t,"utf-8"),n=r.split(`
1774
1780
  `).filter(i=>!i.includes(".generatesaas")).join(`
1775
- `);return n===r?!1:(vs(t,n,"utf-8"),!0)}function ws(e){e.command("eject").description("Remove all GenerateSaaS ties - manifest, license, heartbeat, skills").action(async()=>{let t=process.cwd(),r=qe(t,he),n;try{n=JSON.parse(Ur(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 o=[],s=[];for(let a of Tp())Mr(qe(t,a))&&o.push(a);for(let a of Ap)Mr(qe(t,a))&&o.push(a);Mr(qe(t,Y))&&o.push(`${Y}/`);for(let a of Ip){let d=qe(t,a.file);Rp(d,a.removals,a.replacements)?s.push(a.file):Xt(d)&&U.log.warn(`Could not auto-modify ${a.file} - manually remove license/heartbeat references.`)}_p(t)&&s.push(".gitignore");for(let a of o)U.log.info(`Deleted ${a}`);for(let a of s)U.log.info(`Modified ${a}`);U.log.success("Ejected successfully. This project is now fully standalone.")})}var Je=new Op().name("generatesaas").description("CLI for scaffolding and managing GenerateSaaS projects").version("3.29.0").addHelpText("after",`
1781
+ `);return n===r?!1:(Es(t,n,"utf-8"),!0)}function Ss(e){e.command("eject").description("Remove all GenerateSaaS ties - manifest, license, heartbeat, skills").action(async()=>{let t=process.cwd(),r=qe(t,me),n;try{n=JSON.parse(Fr(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 o=[],s=[];for(let a of Np())Ur(qe(t,a))&&o.push(a);for(let a of xp)Ur(qe(t,a))&&o.push(a);Ur(qe(t,q))&&o.push(`${q}/`);for(let a of Dp){let d=qe(t,a.file);Cp(d,a.removals,a.replacements)?s.push(a.file):Zt(d)&&U.log.warn(`Could not auto-modify ${a.file} - manually remove license/heartbeat references.`)}Lp(t)&&s.push(".gitignore");for(let a of o)U.log.info(`Deleted ${a}`);for(let a of s)U.log.info(`Modified ${a}`);U.log.success("Ejected successfully. This project is now fully standalone.")})}var Je=new $p().name("generatesaas").description("CLI for scaffolding and managing GenerateSaaS projects").version("3.31.0").addHelpText("after",`
1776
1782
  Examples:
1777
1783
  $ generatesaas init Interactive setup
1778
1784
  $ generatesaas init -n my-app -y Quick setup with defaults
1779
1785
  $ generatesaas status Check for updates
1780
1786
  $ generatesaas auth Set or update API key
1781
- `);ts(Je);cs(Je);us(Je);ys(Je);bs(Je);ws(Je);Je.parseAsync().catch(e=>{ks.cancel("An unexpected error occurred."),console.error(e),process.exit(1)});
1787
+ `);is(Je);ds(Je);fs(Je);vs(Je);ks(Je);Ss(Je);Je.parseAsync().catch(e=>{Ps.cancel("An unexpected error occurred."),console.error(e),process.exit(1)});