generatesaas 3.37.0 → 3.39.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,28 +1,28 @@
1
1
  #!/usr/bin/env node
2
- import{Command as rd}from"commander";import*as Ns from"@clack/prompts";import{existsSync as fp,readdirSync as gp,rmSync as yp}from"fs";import{join as bp,resolve as wp}from"path";import{Option as Q}from"commander";import*as E from"@clack/prompts";import*as Rt from"@clack/prompts";import sr from"picocolors";function Xr(e){let t=e?` GenerateSaaS v${e} `:" GenerateSaaS ";Rt.intro(sr.bgYellow(sr.black(t)))}function Zr(){Rt.outro(sr.yellow("Happy building!"))}import*as f from"@clack/prompts";import y from"picocolors";var gt={fullstack:{label:"Fullstack",hint:"Frontend hosts the API - works on serverless or long-running"},separate:{label:"Separate",hint:"Standalone Hono backend - long-running runtimes only (Docker, Render, Fly.io, Railway, Coolify, Dokploy)"}},_t={stripe:{label:"Stripe"},polar:{label:"Polar"},none:{label:"None",hint:"disable payments"}},Ot={smtp:{label:"SMTP",hint:"Mailpit for local dev"},ses:{label:"Amazon SES"},resend:{label:"Resend"}},xt={sentry:{label:"Sentry",hint:"web, server and desktop - release health, tracing, alerting"},posthog:{label:"PostHog",hint:"web and server, plus LLM analytics - no Electron SDK, so a desktop build reports nothing"}},Qr={postgres:{label:"PostgreSQL",hint:"port 5432",port:5432},redis:{label:"Redis",hint:"port 6379",port:6379},inngest:{label:"Inngest",hint:"port 8288",port:8288},mailpit:{label:"Mailpit",hint:"port 1025",port:1025}};var Ne={USD:{symbol:"$",name:"US Dollar",place:"left",space:!1},EUR:{symbol:"\u20AC",name:"Euro",place:"right",space:!1},GBP:{symbol:"\xA3",name:"British Pound",place:"left",space:!1},CAD:{symbol:"CA$",name:"Canadian Dollar",place:"left",space:!1},AUD:{symbol:"A$",name:"Australian Dollar",place:"left",space:!1},BRL:{symbol:"R$",name:"Brazilian Real",place:"left",space:!1},JPY:{symbol:"\xA5",name:"Japanese Yen",place:"left",space:!1}};var 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}},Ce={postgres:{label:"PostgreSQL (self-hosted)",hint:"local Docker, drizzle-orm/node-postgres",managed:!1,envVars:[{key:"DATABASE_URL",defaultValue:"postgres://postgres:postgres@localhost:5432/saas"}]},neon:{label:"Neon",hint:"serverless Postgres",managed:!0,envVars:[{key:"DATABASE_URL",comment:"# TODO: Add your Neon connection string"}]},supabase:{label:"Supabase",hint:"managed Postgres",managed:!0,envVars:[{key:"DATABASE_URL",comment:"# TODO: Add your Supabase connection string"}]}},Le={redis:{label:"Redis (self-hosted)",hint:"local Docker, ioredis",managed:!1,envVars:[{key:"REDIS_URL",defaultValue:"redis://localhost:6379"}]},upstash:{label:"Upstash",hint:"serverless Redis",managed:!0,envVars:[{key:"UPSTASH_REDIS_REST_URL",comment:"# TODO: Add your Upstash REST URL"},{key:"UPSTASH_REDIS_REST_TOKEN",comment:"# TODO: Add your Upstash REST token"}]}},et=[{target:"vercel",provider:"redis",reason:"Vercel serverless cannot maintain persistent Redis connections. Consider Upstash."},{target:"vercel",provider:"postgres",reason:"Vercel serverless cannot pool connections to a self-hosted Postgres. Use Neon or Supabase - both are managed, connection-pooled Postgres."}],tt=[{architecture:"separate",target:"vercel",reason:"Standalone backends need a long-running runtime. Vercel's per-function TypeScript check conflicts with pnpm's isolated install. Use --architecture fullstack for serverless, or deploy the standalone backend to a long-running runtime (Render, Fly.io, Railway, Coolify, Dokploy, or your own VPS via Docker)."}],ae={serverless:{label:"Serverless",hint:"Vercel + Neon + Upstash",values:{deploymentTarget:"vercel",databaseProvider:"neon",cacheProvider:"upstash"}},selfhost:{label:"Self-host",hint:"Docker or Node + Postgres + Redis",values:{deploymentTarget:"node",databaseProvider:"postgres",cacheProvider:"redis"}}},$e=Object.keys(ae);function or(e){let t=[];for(let r of et)if(e.deploymentTarget===r.target&&(e.databaseProvider===r.provider||e.cacheProvider===r.provider)){let n=e.databaseProvider===r.provider?"databaseProvider":"cacheProvider";t.push(`\`${n}: "${r.provider}"\` with \`deploymentTarget: "${r.target}"\` - ${r.reason}`)}for(let r of tt)e.deploymentTarget===r.target&&e.architecture===r.architecture&&t.push(`\`architecture: "${r.architecture}"\` with \`deploymentTarget: "${r.target}"\` - ${r.reason}`);return t}var en=["Local file storage (sharp, geoip-lite)","SMTP email (use Resend or SES instead)","Content API git integration"];function rt(e){let t=[];return e.databaseProvider==="postgres"&&t.push("postgres"),e.cacheProvider==="redis"&&t.push("redis"),e.emailProvider==="smtp"&&t.push("mailpit"),t.push("inngest"),t}var nt=["fullstack","separate"],it=["stripe","polar","none"],st=["smtp","ses","resend"],tn=["claude-code","cursor","codex","gemini-cli","windsurf"],ce=["USD","EUR","GBP","CAD","AUD","BRL","JPY"],le=["node","vercel"],pe=["postgres","neon","supabase"],de=["redis","upstash"],G=["sentry","posthog"],je=["revenuecat","none"];function re(e){return e.paymentProvider!==void 0&&e.paymentProvider!=="none"}var ar=[{key:"architecture",label:"Architecture",hint:"Fullstack (frontend hosts the API) or a standalone Hono backend.",category:"Infrastructure",kind:"enum",default:"fullstack",choices:nt,adoptable:!1,impact:"structural",shapesTree:!0},{key:"deploymentTarget",label:"Deployment target",hint:"Node.js / Docker or Vercel serverless.",category:"Infrastructure",kind:"enum",default:"node",choices:le,adoptable:!1,impact:"config",shapesTree:!0},{key:"databaseProvider",label:"Database provider",hint:"Self-hosted PostgreSQL, Neon, or Supabase.",category:"Infrastructure",kind:"enum",default:"postgres",choices:pe,adoptable:!1,impact:"config",shapesTree:!0},{key:"cacheProvider",label:"Cache provider",hint:"Self-hosted Redis or Upstash.",category:"Infrastructure",kind:"enum",default:"redis",choices:de,adoptable:!1,impact:"config",shapesTree:!0},{key:"paymentProvider",label:"Payment provider",hint:"Stripe, Polar, or none.",category:"Features",kind:"enum",default:"none",choices:it,adoptable:!1,impact:"structural",shapesTree:!0},{key:"defaultCurrency",label:"Default currency",hint:"Billing and pricing currency.",category:"Features",kind:"enum",default:"USD",choices:ce,adoptable:!1,impact:"config",shapesTree:!1},{key:"emailProvider",label:"Email provider",hint:"SMTP, Amazon SES, or Resend.",category:"Features",kind:"enum",default:"smtp",choices:st,adoptable:!1,impact:"config",shapesTree:!1},{key:"observability",label:"Observability",hint:"Which services receive your app's errors, and on PostHog its LLM analytics. Pick any combination - anything you do not pick costs nothing, since its SDK and its adapter are never generated.",category:"Features",kind:"multiselect",default:[],choices:G,adoptable:!0,impact:"config",shapesTree:!0},{key:"multiTenancy",label:"Multi-tenancy (organizations)",hint:"Adds organizations - teams, members, and shared resources.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!1},{key:"projects",label:"Projects",hint:"Adds projects - a switcher that scopes a user's work inside their account or organization.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"config",shapesTree:!1},{key:"docs",label:"Docs app",hint:"Adds the self-hosted Fumadocs documentation site (apps/docs).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0},{key:"desktop",label:"Desktop app",hint:"Adds the cross-platform desktop app (apps/desktop, built with Electron).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0},{key:"mobile",label:"Mobile app",hint:"Adds the cross-platform mobile app (apps/mobile, built with Expo).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0},{key:"mobilePurchases",label:"Mobile store purchases",hint:"In-app purchases in the mobile app, through RevenueCat. Store purchases sit ON TOP of your web payment provider - a subscriber who buys in the app is the same account, billed by Apple or Google instead of by you. Off keeps the app on web billing, where the plan card says the subscription is managed on your website.",category:"Features",kind:"enum",default:()=>"none",choices:je,adoptable:!0,impact:"structural",shapesTree:!0,requires:e=>e.mobile===!0&&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; 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=>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 Ls(e,t){return e[t]!==void 0}function rn(e){return ar.filter(t=>t.adoptable&&!Ls(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 $s(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 js(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 nn(e){let t=[];for(let r of ar){let n=e[r.key];n!==void 0&&($s(r,n)||t.push(`\`${r.key}\` is ${JSON.stringify(n)}, but it must be ${js(r)}.`))}return t}function sn(e){let t={};for(let r of ar)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 cr(e,t){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||t}function Dt(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Nt(e){return/^[a-z][a-z0-9-]*$/.test(e)}function N(e){return e instanceof Error?e.message:String(e)}function yt(e){if(e.mobilePurchases!=="revenuecat")return e;if(e.mobile===!1)throw new Error("--mobile-purchases revenuecat requires the mobile app; remove --no-mobile.");if(e.paymentProvider==="none")throw new Error("--mobile-purchases revenuecat requires a payment provider (got --payment none): store purchases are additive to your web billing, never a replacement.");return e.mobile===void 0&&(e.mobile=!0),e}function bt(e){if(e.webAi!==!1)return e;if(e.ai===!1)throw new Error("--no-web-ai requires --ai (the desktop and mobile apps are where AI lives when the web surface is off).");if(e.desktop===!1&&e.mobile===!1)throw new Error("--no-web-ai requires --desktop or --mobile - with the web AI surface off, the desktop and mobile apps are the only places your AI features exist.");return e}function on(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 an(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 cn(e){let t=Ms(e,e.desktopAi);return delete e.desktopAi,t}function Ms(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 ln(e){let t={};if(e.name!==void 0){if(!Nt(e.name))throw new Error(`Invalid project name "${e.name}". Use lowercase letters, numbers, and hyphens only. Must start with a letter.`);t.projectName=e.name}if(e.appName!==void 0){if(!e.appName.trim())throw new Error("App name cannot be empty.");t.appName=e.appName}if(e.location!==void 0?t.projectDir=e.location==="."?process.cwd():e.location:t.projectName!==void 0&&(t.projectDir=`./${t.projectName}`),e.architecture!==void 0&&(t.architecture=e.architecture),e.payment!==void 0&&(t.paymentProvider=e.payment),e.email!==void 0&&(t.emailProvider=e.email),e.org!==void 0&&(t.multiTenancy=e.org),e.projects!==void 0&&(t.projects=e.projects),e.docs!==void 0&&(t.docs=e.docs),e.desktop!==void 0&&(t.desktop=e.desktop),e.mobile!==void 0&&(t.mobile=e.mobile),e.mobilePurchases!==void 0){if(!je.includes(e.mobilePurchases))throw new Error(`Invalid mobile purchases "${e.mobilePurchases}". Valid values: ${je.join(", ")}`);t.mobilePurchases=e.mobilePurchases}if(e.ai!==void 0&&(t.ai=e.ai),e.webAi!==void 0&&(t.webAi=e.webAi),yt(t),bt(t),e.revenueSharing!==void 0&&(t.revenueSharing=e.revenueSharing),e.credits!==void 0){if(e.credits===!0&&e.payment==="none")throw new Error("--credits requires a payment provider (got --payment none).");t.credits=e.credits}if(e.currency!==void 0){if(!ce.includes(e.currency))throw new Error(`Invalid currency "${e.currency}". Valid values: ${ce.join(", ")}`);t.defaultCurrency=e.currency}if(e.deploy!==void 0){if(!le.includes(e.deploy))throw new Error(`Invalid deployment target "${e.deploy}". Valid values: ${le.join(", ")}`);t.deploymentTarget=e.deploy}if(e.database!==void 0){if(!pe.includes(e.database))throw new Error(`Invalid database provider "${e.database}". Valid values: ${pe.join(", ")}`);t.databaseProvider=e.database}if(e.cache!==void 0){if(!de.includes(e.cache))throw new Error(`Invalid cache provider "${e.cache}". Valid values: ${de.join(", ")}`);t.cacheProvider=e.cache}if(e.observability!==void 0){let r=e.observability.split(",").map(i=>i.trim()).filter(Boolean),n=r.filter(i=>!G.includes(i));if(n.length>0)throw new Error(`Invalid observability provider ${JSON.stringify(n.join(", "))}. Valid values: ${G.join(", ")}`);t.observability=r}if(e.preset!==void 0){if(!$e.includes(e.preset))throw new Error(`Invalid preset "${e.preset}". Valid values: ${$e.join(", ")}`);let r=ae[e.preset].values;t.deploymentTarget??=r.deploymentTarget,t.databaseProvider??=r.databaseProvider,t.cacheProvider??=r.cacheProvider}if(e.demo===!0&&(t.demo=!0),e.baseUrl!==void 0){let r=e.baseUrl.trim();if(r==="")throw new Error("--base-url cannot be empty. Provide an absolute URL like https://example.com.");let n;try{n=new URL(r)}catch{throw new Error(`Invalid --base-url "${e.baseUrl}". Must be an absolute URL like https://example.com.`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw new Error(`Invalid --base-url "${e.baseUrl}". Must use http or https.`);t.baseUrl=`${n.protocol}//${n.host}`}return t}var ot={projectName:"my-saas",architecture:"fullstack",paymentProvider:"stripe",emailProvider:"smtp",multiTenancy:!1,projects:!1,docs:!1,desktop:!1,mobile:!1,mobilePurchases:"none",ai:!1,webAi:!0,revenueSharing:!1,credits:!0,defaultCurrency:"USD",deploymentTarget:"node",databaseProvider:"postgres",cacheProvider:"redis",observability:[]};function pn(e){let t=e.projectName??ot.projectName,r=e.projectDir??`./${t}`,n=e.appName??Dt(t),i=e.deploymentTarget??ot.deploymentTarget,o=te[i]?.edgeRuntime??!1,s=e.databaseProvider??(o?"neon":ot.databaseProvider),a=e.cacheProvider??(o?"upstash":ot.cacheProvider),p=e.emailProvider??(o?"resend":ot.emailProvider),h={...ot,...e,projectName:t,appName:n,projectDir:r,deploymentTarget:i,databaseProvider:s,cacheProvider:a,emailProvider:p};h.paymentProvider==="none"&&(h.credits=!1),(!h.mobile||h.paymentProvider==="none")&&(h.mobilePurchases="none"),yt(h);for(let g of et){if(h.deploymentTarget!==g.target)continue;let k=h.databaseProvider===g.provider?"database":"cache";if(h.databaseProvider===g.provider||h.cacheProvider===g.provider)throw new Error(`Incompatible: --deploy ${g.target} + --${k} ${g.provider}. ${g.reason}`)}for(let g of tt)if(h.architecture===g.architecture&&h.deploymentTarget===g.target)throw new Error(`Incompatible: --architecture ${g.architecture} + --deploy ${g.target}. ${g.reason}`);return bt(h),h}function I(e){f.isCancel(e)&&(f.cancel("Setup cancelled."),process.exit(0))}function lr(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 dn(e,t){let r=!1;e&&yt(e),e&&bt(e),f.log.info(y.bold("Project"));let n=e?.projectName??await(async()=>{r=!0;let c=await f.text({message:"Project name:",placeholder:"my-saas",validate:d=>{if(!d?.trim())return"Project name is required.";if(!Nt(d))return"Use lowercase letters, numbers, and hyphens only. Must start with a letter."}});return I(c),c})(),i=e?.appName??await(async()=>{r=!0;let c=await f.text({message:"App name:",initialValue:Dt(n),validate:d=>{if(!d?.trim())return"App name is required."}});return I(c),c})(),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:[...$e.map(d=>({value:d,label:ae[d].label,hint:ae[d].hint})),{value:"custom",label:"Customize",hint:"choose each piece yourself"}]});if(I(c),c!=="custom"){let d=ae[c].values;s.deploymentTarget=d.deploymentTarget,s.databaseProvider=d.databaseProvider,s.cacheProvider=d.cacheProvider,f.log.info(`${ae[c].label}: ${ae[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:le.map(d=>({value:d,label:te[d].label,hint:te[d].hint}))});I(c),a=c}let p=e?.architecture?tt.find(c=>c.architecture===e.architecture&&c.target===a):void 0;if(p)throw new Error(`Incompatible: --architecture ${p.architecture} + --deploy ${p.target}. ${p.reason}`);let h=new Set(tt.filter(c=>c.target===a).map(c=>c.architecture)),g=nt.filter(c=>!h.has(c)),k=e?.architecture??await(async()=>{if(g.length===1){let d=g[0];return f.log.info(`Auto-selected ${gt[d].label} architecture (only compatible option for ${te[a].label}).`),d}r=!0;let c=await f.select({message:"Architecture:",options:g.map(d=>({value:d,label:gt[d].label,hint:gt[d].hint}))});return I(c),c})(),w=e?.databaseProvider??s.databaseProvider??await(async()=>{r=!0;let c=pe.filter(R=>!et.some(Ee=>Ee.target===a&&Ee.provider===R));if(c.length===1){let R=c[0];return f.log.info(`Auto-selected ${Ce[R].label} (only compatible option for ${te[a].label}).`),R}let d=await f.select({message:"Database provider:",options:c.map(R=>({value:R,label:Ce[R].label,hint:Ce[R].hint}))});return I(d),d})(),P=e?.cacheProvider??s.cacheProvider??await(async()=>{r=!0;let c=de.filter(R=>!et.some(Ee=>Ee.target===a&&Ee.provider===R));if(c.length===1){let R=c[0];return f.log.info(`Auto-selected ${Le[R].label} (only compatible option for ${te[a].label}).`),R}let d=await f.select({message:"Cache provider:",options:c.map(R=>({value:R,label:Le[R].label,hint:Le[R].hint}))});return I(d),d})();if(te[a]?.edgeRuntime){let c=en.map(d=>` - ${d}`).join(`
3
- `);f.note(c,"Unavailable on edge runtime")}f.log.info(y.bold("Features"));let u=e?.paymentProvider??await(async()=>{r=!0;let c=await f.select({message:"Payment provider:",options:it.map(d=>({value:d,label:_t[d].label,hint:_t[d].hint}))});return I(c),c})(),O=e?.defaultCurrency??await(async()=>{if(u==="none")return"USD";r=!0;let c=await f.select({message:"Default currency:",options:ce.map(d=>({value:d,label:d,hint:Ne[d].name}))});return I(c),c})(),be=e?.emailProvider??await(async()=>{r=!0;let c=await f.select({message:"Email provider:",options:st.map(d=>({value:d,label:Ot[d].label,hint:Ot[d].hint}))});return I(c),c})(),B=e?.observability??await(async()=>{r=!0;let c=await f.multiselect({message:"Observability (space to select, enter to confirm):",required:!1,initialValues:[],options:G.map(d=>({value:d,label:xt[d].label,hint:xt[d].hint}))});return I(c),c})(),oe=e?.multiTenancy??await(async()=>{r=!0;let c=await f.confirm({message:"Enable multi-tenancy (organizations)?",initialValue:!1});return I(c),c})(),Oe=e?.projects??await(async()=>{r=!0;let c=await f.confirm({message:"Enable projects (a switcher that scopes a user's work)?",initialValue:!1});return I(c),c})(),xe=e?.docs??await(async()=>{r=!0;let c=await f.confirm({message:"Include docs app? (self-hosted Fumadocs documentation site)",initialValue:!1});return I(c),c})(),De=t?.desktopAllowed!==!1,we=e?.desktop??(De?await(async()=>{r=!0;let c=await f.confirm({message:"Include the desktop app? (apps/desktop - cross-platform, built with Electron, device-auth). With AI on, it also runs a local AI stack.",initialValue:!1});return I(c),c})():(f.log.info(y.dim("Desktop app: available on the Pro plan and up - skipped.")),!1)),Qe=t?.mobileAllowed!==!1,v=e?.mobile??(Qe?await(async()=>{r=!0;let c=await f.confirm({message:"Include the mobile app? (apps/mobile - iOS and Android, built with Expo, with push notifications and universal links)",initialValue:!1});return I(c),c})():(f.log.info(y.dim("Mobile app: available on the Pro plan and up - skipped.")),!1)),L=!v||u==="none"?"none":e?.mobilePurchases??await(async()=>{r=!0;let R=await f.select({message:"Mobile in-app purchases?",options:[{value:"revenuecat",label:"RevenueCat",hint:"store billing on top of your web provider - Apple and Google charge, your app grants"},{value:"none",label:"None",hint:"web billing only; the app shows the plan, never a paywall"}],initialValue:"none"});return I(R),R})();yt({mobile:v,mobilePurchases:L,paymentProvider:u});let F=e?.ai??await(async()=>{r=!0;let c=await f.confirm({message:"Add AI features? (chat, models, automations, integrations)",initialValue:!1});return I(c),c})(),ve=e?.webAi??((we||v)&&F?await(async()=>{r=!0;let c=await f.confirm({message:"Show the AI surfaces in the web app? (No: app-first - your desktop or mobile app is where your AI product lives, and the web keeps account, billing, and licensing only)",initialValue:!0});return I(c),c})():!0);bt({webAi:ve,ai:F,desktop:we,mobile:v});let $=e?.revenueSharing??await(async()=>{r=!0;let c=await f.confirm({message:"Enable revenue sharing? (opt-in MRR leaderboard with dofollow backlinks)",initialValue:!1});return I(c),c})(),W=u==="none"?!1:e?.credits??await(async()=>{r=!0;let c=await f.confirm({message:"Enable credits? (metered usage on top of subscription plans)",initialValue:!0});return I(c),c})(),ke=e?.demo,z=lr({databaseProvider:w,cacheProvider:P,paymentProvider:u,emailProvider:be,demo:ke}),T={};if(z.length>0&&r){f.log.info(y.bold("Credentials")+y.dim(" all optional - press Enter to skip, fill in .env later"));for(let c of z)if(r=!0,c.secret){let d=await f.password({message:c.message,mask:"*"});I(d),typeof d=="string"&&d.trim()&&(T[c.key]=d.trim())}else{let d=await f.text({message:c.message,placeholder:c.placeholder});I(d),typeof d=="string"&&d.trim()&&(T[c.key]=d.trim())}}if(r){let c=[` Name: ${y.cyan(n)}`,` App name: ${y.cyan(i)}`,` Location: ${y.cyan(o)}`,` Architecture: ${y.cyan(gt[k].label)}`].join(`
4
- `),d=[` Deploy target: ${y.cyan(te[a]?.label??"Node.js / Docker")}`,` Database: ${y.cyan(Ce[w].label)}`,` Cache: ${y.cyan(Le[P].label)}`].filter(Boolean).join(`
5
- `),R=[u!=="none"?` Payment: ${y.cyan(_t[u].label)} (${O})`:` Payment: ${y.dim("none")}`,` Credits: ${W?y.cyan("Yes"):y.dim("No")}`,` AI features: ${F?y.cyan("Yes"):y.dim("No")}`,...ve?[]:[` Web AI: ${y.dim("No")} (app-first)`],` Email: ${y.cyan(Ot[be].label)}`,` Observability: ${B.length===0?y.dim("none"):y.cyan(B.map(ir=>xt[ir].label).join(", "))}`,` Multi-tenancy: ${oe?y.cyan("Yes"):y.dim("No")}`,` Projects: ${Oe?y.cyan("Yes"):y.dim("No")}`,` Docs app: ${xe?y.cyan("Yes"):y.dim("No")}`,` Desktop app: ${we?y.cyan("Yes"):y.dim("No")}`,` Mobile app: ${v?y.cyan("Yes"):y.dim("No")}`,...L==="none"?[]:[` In-app purch.: ${y.cyan("RevenueCat")}`],` Rev. sharing: ${$?y.cyan("Yes"):y.dim("No")}`].join(`
6
- `),Ee=[y.bold("Project"),c,"",y.bold("Infrastructure"),d,"",y.bold("Features"),R];if(z.length>0){let ir=z.map(qr=>{let Cs=T[qr.key]?y.green("provided"):y.dim("skipped");return` ${qr.key}: ${Cs}`}).join(`
7
- `);Ee.push("",y.bold("Credentials"),ir)}f.note(Ee.join(`
8
- `),"Summary");let Jr=await f.confirm({message:"Proceed with these settings?"});(f.isCancel(Jr)||!Jr)&&(f.cancel("Setup cancelled."),process.exit(0))}return{projectName:n,appName:i,projectDir:o,architecture:k,deploymentTarget:a,databaseProvider:w,cacheProvider:P,paymentProvider:u,emailProvider:be,observability:B,multiTenancy:oe,projects:Oe,docs:xe,desktop:we,mobile:v,mobilePurchases:L,ai:F,webAi:ve,revenueSharing:$,credits:W,defaultCurrency:O,...Object.keys(T).length>0?{credentials:T}:{},...e?.baseUrl!==void 0?{baseUrl:e.baseUrl}:{},...ke!==void 0?{demo:ke}:{}}}import{createReadStream as En,existsSync as zs}from"fs";import{mkdir as Js}from"fs/promises";import{join as qs}from"path";import{Readable as Xs}from"stream";import{pipeline as wr}from"stream/promises";import{extract as Zs}from"tar";import{join as Me}from"path";import{homedir as Us}from"os";var pr="https://cli.generatesaas.com",wt=process.env.GENERATESAAS_API_URL??pr,J=".generatesaas",ue=Me(J,"manifest.json"),un="nextjs",dr="nuxt",ur="2.4.1",mn=Me(J,"hashes.json"),Ct=Me(J,"template-hashes.json"),Lt=Me(J,"template"),hn=Me(J,"staging"),fn=Me(J,"staging.json"),me=Me(Us(),".generatesaas");var M=class extends Error{constructor(r,n,i){super(n);this.status=r;this.body=i}status;body;name="ApiError"};function he(e){return{apiKey:e,baseUrl:wt}}async function Se(e,t,r){let n=`${e.baseUrl}${t}`,i=await fetch(n,{...r,headers:{...r?.headers,Authorization:`Bearer ${e.apiKey}`,"User-Agent":"generatesaas-cli/3.37.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 M(i.status,o,s)}return i}import{existsSync as Fs,mkdirSync as Vs,readFileSync as Bs,writeFileSync as Gs}from"fs";import{dirname as Ks}from"path";import*as Pe from"@clack/prompts";function vt(){if(!Fs(me))return null;try{let e=JSON.parse(Bs(me,"utf-8"));return e.apiKey?e.apiKey:(e.token&&!e.apiKey&&Pe.log.warning(`Found old GitHub token in ${me}. Run 'generatesaas init' to set up your API key.`),null)}catch{return null}}function Ue(e){let t=process.env.GENERATESAAS_API_URL;t&&t.replace(/\/+$/,"")!==pr||(Vs(Ks(me),{recursive:!0}),Gs(me,`${JSON.stringify({apiKey:e},null," ")}
9
- `,{mode:384}))}async function at(e){if(e?.apiKey)return e.apiKey;let t=process.env.GENERATESAAS_API_KEY;if(t)return t;let r=vt();if(r)return r;if(!e?.prompt)throw new Error("API key not found. Set GENERATESAAS_API_KEY or run 'generatesaas init' to configure.");return kt()}async function kt(){let e=await Pe.text({message:"Enter your GenerateSaaS API key:",placeholder:"gs_live_...",validate:t=>{if(!t?.trim())return"API key is required."}});return Pe.isCancel(e)&&(Pe.cancel("Setup cancelled."),process.exit(0)),e.trim()}import{readFile as Hs}from"fs/promises";async function Ae(e){let t=process.env.GENERATESAAS_VERSION_INDEX;return t?JSON.parse(await Hs(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 gn(e,t){if(process.env.GENERATESAAS_OFFLINE_LICENSE==="1")return null;try{return await(await Se(e,`/changelog/${encodeURIComponent(t)}`)).text()}catch(r){if(r instanceof M&&r.status===404)return null;throw r}}async function yn(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 $t(e){if(!(e instanceof M)||e.status!==403)return null;let t=e.body;return!t||t.code!=="update_window_expired"?null:{message:e.message,lastAllowedVersion:t.lastAllowedVersion??null}}var mr="nextjs";function bn(e){return{frontend:mr,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 hr(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 wn(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 fr(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 vn(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 gr=new Set([".git","node_modules",".pnpm-store",".env",".env.test",".turbo",".data","dist",".next",".next-e2e-web",".next-e2e-desktop",".wrangler",".devcontainer","playwright-report","test-results",".drive-out",".mastra"]),yr=new Set(["pnpm-lock.yaml","widget-documents.generated.ts"]);function ct(e){if(br(e))return!0;for(let t of e.split("/"))if(yr.has(t))return!0;return!1}var Ys=new Set(["data","references","scripts",".cursor",".agents",".codex",".generatesaas",".vscode",".mcp.json","vitest.config.ts","README.md","TODO.md","OVERVIEW.md"]),kn=["scripts/docs-lint.ts"],Ws=["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 br(e){let t=e.split("/");for(let r of t)if(gr.has(r))return!0;if(kn.includes(e)||kn.some(r=>r.startsWith(`${e}/`)))return!1;if(Ys.has(t[0]))return!0;for(let r of Ws)if(e===r||e.startsWith(`${r}/`))return!0;return!1}async function jt(e,t,r){await Js(r,{recursive:!0});let n=process.env.GENERATESAAS_TEMPLATE_TARBALL_DIR;if(n){let a=qs(n,`v${t}.tar.gz`);if(!zs(a))throw new Error(`GENERATESAAS_TEMPLATE_TARBALL_DIR is set but ${a} does not exist.`);await wr(En(a),vr(r));return}let i=process.env.GENERATESAAS_TEMPLATE_TARBALL;if(i){await wr(En(i),vr(r));return}let o=await Se(e,`/template/${encodeURIComponent(t)}`);if(!o.body)throw new Error("Empty response body");let s=Xs.fromWeb(o.body);await wr(s,vr(r))}function vr(e){return Zs({cwd:e,strip:1,filter:t=>{let r=t.replace(/^[^/]+\//,"");return r?!br(r):!0},sync:!1})}import{readdir as Mt,readFile as lt,rm as Pn,rmdir as Qs,writeFile as Et}from"fs/promises";import{join as K}from"path";async function An(e){let t;try{t=await Mt(e,{withFileTypes:!0})}catch{return!1}let r=!1;for(let n of t){let i=K(e,n.name);if(n.isDirectory()){await An(i)&&(r=!0);continue}if(n.name.startsWith("_")){r=!0;continue}await Pn(i,{force:!0})}return r||await Qs(e).catch(()=>{}),r}async function In(e){let t=K(e,"packages/content"),r=[];try{r=(await Mt(t,{withFileTypes:!0})).filter(s=>s.isDirectory()).map(s=>s.name)}catch{return}let n=new Set;for(let s of r){let a=K(t,s),p;try{p=(await Mt(a,{withFileTypes:!0})).filter(h=>h.isDirectory())}catch{continue}for(let h of p)n.add(h.name),await An(K(a,h.name))}let i=await no(e),o=new Set([...n].filter(s=>i===void 0||i.has(s)));await Promise.all([...o].map(s=>Pn(K(e,"apps/web/public/images",s),{recursive:!0,force:!0}))),await so(e,o)}var eo="packages/config/src/index.ts",to=/\bcontent:\s*\{[\s\S]*?\bsections:\s*\[([\s\S]*?)\]/,ro=/\bslug:\s*"([^"]+)"/g;async function no(e){let t;try{t=await lt(K(e,eo),"utf-8")}catch{return}let r=to.exec(t)?.[1];if(r===void 0)return;let n=[...r.matchAll(ro)].map(i=>i[1]).filter(i=>i!==void 0);return n.length>0?new Set(n):void 0}var io="packages/translate/.meta/mdx-translation-meta.json";async function so(e,t){if(t.size===0)return;let r=K(e,io),n;try{n=JSON.parse(await lt(r,"utf-8"))}catch{return}if(typeof n!="object"||n===null)return;let i=n;if(typeof i.locales!="object"||i.locales===null)return;let o={};for(let[s,a]of Object.entries(i.locales)){if(typeof a!="object"||a===null)continue;let p={};for(let[h,g]of Object.entries(a)){let k=h.split("/"),w=k.length>1?k[0]:void 0,P=k[k.length-1]?.startsWith("_")===!0;w!==void 0&&t.has(w)&&!P||(p[h]=g)}o[s]=p}await Et(r,`${JSON.stringify({...i,locales:o},null," ")}
11
- `)}var oo="packages/config/src/blog.ts";async function Tn(e){let t=K(e,oo),r=await lt(t,"utf-8"),n=Sn(Sn(r,"blogCategories",t),"blogAuthors",t);await Et(t,n)}function Sn(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 Rn(e){let t=K(e,"packages/i18n/translations"),r;try{r=await Mt(t)}catch{return}for(let n of r){let i=K(t,n,"web.json"),o;try{o=await lt(i,"utf-8")}catch{continue}let s=JSON.parse(o);!s.content?.categories||s.content.categories.blog===void 0||(s.content.categories.blog={},await Et(i,`${JSON.stringify(s,null," ")}
12
- `))}}var ao="packages/config/src/ai/tasks.ts",co="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.",lo="The array starts EMPTY, which hides the Tasks tab until you declare your first task.";async function _n(e){let t=K(e,ao),r=await lt(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(co,lo);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 Et(t,i)}async function On(e){let t=K(e,".claude","settings.json"),r;try{r=await lt(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(po)),await Et(t,`${JSON.stringify(n,null," ")}
13
- `)}function po(e){return!(e.startsWith("mcp__")||e.includes("nuxt"))}import{readFileSync as ko}from"fs";import{dirname as Eo,join as Dn}from"path";import{fileURLToPath as So}from"url";import{existsSync as uo}from"fs";import{join as xn}from"path";function Ut(e,t,r){let n=xn(e,...t);return uo(n)?n:xn(e,r)}import{mkdir as mo,writeFile as ho,readdir as fo,rm as go,rmdir as yo}from"fs/promises";import{dirname as Ft,join as bo,relative as wo,sep as vo}from"path";function Fe(e){return e.split(vo).join("/")}async function Vt(e){await mo(e,{recursive:!0})}async function l(e,t){await Vt(Ft(e)),await ho(e,t,"utf-8")}async function Ve(e,t){await go(e,{force:!0});let r=Ft(e);for(;r!==t&&r!==Ft(r);){try{await yo(r)}catch{return}r=Ft(r)}}async function q(e,t,r,n){let i=[],o=await fo(e,{withFileTypes:!0});for(let s of o){let a=bo(e,s.name),p=Fe(wo(t,a));r(p)||(s.isDirectory()?i.push(...await q(a,t,r,n)):s.isFile()&&(n===void 0||n(p))&&i.push(a))}return i}var Po={postgres:"Postgres",neon:"Neon (managed Postgres)",supabase:"Supabase (managed Postgres)"},Ao={resend:"Resend",ses:"Amazon SES",smtp:"SMTP"},Io={redis:"Redis",upstash:"Upstash Redis"},To={node:"Node.js / Docker",vercel:"Vercel"},kr="apps/web",Ro="Next.js 16",_o="`app/` routes, `components/`, `lib/`",Oo={stripe:"Stripe",polar:"Polar"};function xo(e){let t=e.architecture==="fullstack",r=t?"(fullstack - Hono API mounted inside the app)":"(separate - standalone Hono backend)",n=t?`Mounted inside \`${kr}\`. 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=Io[e.cacheProvider],o=To[e.deploymentTarget],s=e.paymentProvider==="none"?"":`
14
- - **Payments:** ${Oo[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/`":"",p=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 \`${kr}/i18n/request.ts\`.`;return No({archSuffix:r,apiLocation:n,databaseName:Po[e.databaseProvider],cacheName:i,paymentLine:s,emailName:Ao[e.emailProvider],deployName:o,appDocsRef:a,sharedScreensBothShells:p,i18nRule:h,webAppDir:kr,webAppName:Ro,webAppLayout:_o})}function Do(){return Ut(Eo(So(import.meta.url)),["generators","content"],"content")}function No(e){let t=ko(Dn(Do(),"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 Nn(e){await l(Dn(e.projectDir,"AGENTS.md"),xo(e))}import{join as Co}from"path";var Cn="apps/web",Er="Next.js 16",Lo={postgres:"Postgres (self-hosted)",neon:"Neon (managed Postgres)",supabase:"Supabase (managed Postgres)"};function $o(e){let t=e.appName.trim()||e.projectName,r=Lo[e.databaseProvider],n=e.architecture==="fullstack"?`${Er} app at \`${Cn}/\` 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.`:`${Er} app at \`${Cn}/\` and a separate Hono backend at \`apps/backend/\`.`,i=e.architecture==="fullstack"?`- App + API: http://localhost:3000
2
+ import{Command as id}from"commander";import*as Cs from"@clack/prompts";import{existsSync as yp,readdirSync as bp,rmSync as wp}from"fs";import{join as vp,resolve as kp}from"path";import{Option as ee}from"commander";import*as E from"@clack/prompts";import*as Rt from"@clack/prompts";import cr from"picocolors";function Zr(e){let t=e?` GenerateSaaS v${e} `:" GenerateSaaS ";Rt.intro(cr.bgYellow(cr.black(t)))}function Qr(){Rt.outro(cr.yellow("Happy building!"))}import*as f from"@clack/prompts";import y from"picocolors";var gt={fullstack:{label:"Fullstack",hint:"Frontend hosts the API - works on serverless or long-running"},separate:{label:"Separate",hint:"Standalone Hono backend - long-running runtimes only (Docker, Render, Fly.io, Railway, Coolify, Dokploy)"}},_t={stripe:{label:"Stripe"},polar:{label:"Polar"},none:{label:"None",hint:"disable payments"}},Ot={smtp:{label:"SMTP",hint:"Mailpit for local dev"},ses:{label:"Amazon SES"},resend:{label:"Resend"}},xt={sentry:{label:"Sentry",hint:"web, server and desktop - release health, tracing, alerting"},posthog:{label:"PostHog",hint:"web and server, plus LLM analytics - no Electron SDK, so a desktop build reports nothing"}},en={postgres:{label:"PostgreSQL",hint:"port 5432",port:5432},redis:{label:"Redis",hint:"port 6379",port:6379},inngest:{label:"Inngest",hint:"port 8288",port:8288},mailpit:{label:"Mailpit",hint:"port 1025",port:1025}};var Ne={USD:{symbol:"$",name:"US Dollar",place:"left",space:!1},EUR:{symbol:"\u20AC",name:"Euro",place:"right",space:!1},GBP:{symbol:"\xA3",name:"British Pound",place:"left",space:!1},CAD:{symbol:"CA$",name:"Canadian Dollar",place:"left",space:!1},AUD:{symbol:"A$",name:"Australian Dollar",place:"left",space:!1},BRL:{symbol:"R$",name:"Brazilian Real",place:"left",space:!1},JPY:{symbol:"\xA5",name:"Japanese Yen",place:"left",space:!1}};var re={node:{label:"Node.js / Docker",hint:"long-running runtime - Render, Fly.io, Railway, Coolify, Dokploy, VPS",edgeRuntime:!1},vercel:{label:"Vercel",hint:"serverless functions",edgeRuntime:!0}},Ce={postgres:{label:"PostgreSQL (self-hosted)",hint:"local Docker, drizzle-orm/node-postgres",managed:!1,envVars:[{key:"DATABASE_URL",defaultValue:"postgres://postgres:postgres@localhost:5432/saas"}]},neon:{label:"Neon",hint:"serverless Postgres",managed:!0,envVars:[{key:"DATABASE_URL",comment:"# TODO: Add your Neon connection string"}]},supabase:{label:"Supabase",hint:"managed Postgres",managed:!0,envVars:[{key:"DATABASE_URL",comment:"# TODO: Add your Supabase connection string"}]}},Le={redis:{label:"Redis (self-hosted)",hint:"local Docker, ioredis",managed:!1,envVars:[{key:"REDIS_URL",defaultValue:"redis://localhost:6379"}]},upstash:{label:"Upstash",hint:"serverless Redis",managed:!0,envVars:[{key:"UPSTASH_REDIS_REST_URL",comment:"# TODO: Add your Upstash REST URL"},{key:"UPSTASH_REDIS_REST_TOKEN",comment:"# TODO: Add your Upstash REST token"}]}},et=[{target:"vercel",provider:"redis",reason:"Vercel serverless cannot maintain persistent Redis connections. Consider Upstash."},{target:"vercel",provider:"postgres",reason:"Vercel serverless cannot pool connections to a self-hosted Postgres. Use Neon or Supabase - both are managed, connection-pooled Postgres."}],tt=[{architecture:"separate",target:"vercel",reason:"Standalone backends need a long-running runtime. Vercel's per-function TypeScript check conflicts with pnpm's isolated install. Use --architecture fullstack for serverless, or deploy the standalone backend to a long-running runtime (Render, Fly.io, Railway, Coolify, Dokploy, or your own VPS via Docker)."}],ae={serverless:{label:"Serverless",hint:"Vercel + Neon + Upstash",values:{deploymentTarget:"vercel",databaseProvider:"neon",cacheProvider:"upstash"}},selfhost:{label:"Self-host",hint:"Docker or Node + Postgres + Redis",values:{deploymentTarget:"node",databaseProvider:"postgres",cacheProvider:"redis"}}},$e=Object.keys(ae);function lr(e){let t=[];for(let r of et)if(e.deploymentTarget===r.target&&(e.databaseProvider===r.provider||e.cacheProvider===r.provider)){let n=e.databaseProvider===r.provider?"databaseProvider":"cacheProvider";t.push(`\`${n}: "${r.provider}"\` with \`deploymentTarget: "${r.target}"\` - ${r.reason}`)}for(let r of tt)e.deploymentTarget===r.target&&e.architecture===r.architecture&&t.push(`\`architecture: "${r.architecture}"\` with \`deploymentTarget: "${r.target}"\` - ${r.reason}`);return t}var tn=["Local file storage (sharp, geoip-lite)","SMTP email (use Resend or SES instead)","Content API git integration"];function rt(e){let t=[];return e.databaseProvider==="postgres"&&t.push("postgres"),e.cacheProvider==="redis"&&t.push("redis"),e.emailProvider==="smtp"&&t.push("mailpit"),t.push("inngest"),t}var nt=["fullstack","separate"],it=["stripe","polar","none"],st=["smtp","ses","resend"],rn=["claude-code","cursor","codex","gemini-cli","windsurf"],ce=["USD","EUR","GBP","CAD","AUD","BRL","JPY"],le=["node","vercel"],pe=["postgres","neon","supabase"],de=["redis","upstash"],G=["sentry","posthog"],je=["revenuecat","none"];function ne(e){return e.paymentProvider!==void 0&&e.paymentProvider!=="none"}var pr=[{key:"architecture",label:"Architecture",hint:"Fullstack (frontend hosts the API) or a standalone Hono backend.",category:"Infrastructure",kind:"enum",default:"fullstack",choices:nt,adoptable:!1,impact:"structural",shapesTree:!0},{key:"deploymentTarget",label:"Deployment target",hint:"Node.js / Docker or Vercel serverless.",category:"Infrastructure",kind:"enum",default:"node",choices:le,adoptable:!1,impact:"config",shapesTree:!0},{key:"databaseProvider",label:"Database provider",hint:"Self-hosted PostgreSQL, Neon, or Supabase.",category:"Infrastructure",kind:"enum",default:"postgres",choices:pe,adoptable:!1,impact:"config",shapesTree:!0},{key:"cacheProvider",label:"Cache provider",hint:"Self-hosted Redis or Upstash.",category:"Infrastructure",kind:"enum",default:"redis",choices:de,adoptable:!1,impact:"config",shapesTree:!0},{key:"paymentProvider",label:"Payment provider",hint:"Stripe, Polar, or none.",category:"Features",kind:"enum",default:"none",choices:it,adoptable:!1,impact:"structural",shapesTree:!0},{key:"defaultCurrency",label:"Default currency",hint:"Billing and pricing currency.",category:"Features",kind:"enum",default:"USD",choices:ce,adoptable:!1,impact:"config",shapesTree:!1},{key:"emailProvider",label:"Email provider",hint:"SMTP, Amazon SES, or Resend.",category:"Features",kind:"enum",default:"smtp",choices:st,adoptable:!1,impact:"config",shapesTree:!1},{key:"observability",label:"Observability",hint:"Which services receive your app's errors, and on PostHog its LLM analytics. Pick any combination - anything you do not pick costs nothing, since its SDK and its adapter are never generated.",category:"Features",kind:"multiselect",default:[],choices:G,adoptable:!0,impact:"config",shapesTree:!0},{key:"multiTenancy",label:"Multi-tenancy (organizations)",hint:"Adds organizations - teams, members, and shared resources.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!1},{key:"projects",label:"Projects",hint:"Adds projects - a switcher that scopes a user's work inside their account or organization.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"config",shapesTree:!1},{key:"docs",label:"Docs app",hint:"Adds the self-hosted Fumadocs documentation site (apps/docs).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0},{key:"desktop",label:"Desktop app",hint:"Adds the cross-platform desktop app (apps/desktop, built with Electron).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0},{key:"mobile",label:"Mobile app",hint:"Adds the cross-platform mobile app (apps/mobile, built with Expo).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0},{key:"mobilePurchases",label:"Mobile store purchases",hint:"In-app purchases in the mobile app, through RevenueCat. Store purchases sit ON TOP of your web payment provider - a subscriber who buys in the app is the same account, billed by Apple or Google instead of by you. Off keeps the app on web billing, where the plan card says the subscription is managed on your website.",category:"Features",kind:"enum",default:()=>"none",choices:je,adoptable:!0,impact:"structural",shapesTree:!0,requires:e=>e.mobile===!0&&ne(e),requiresLabel:"requires the mobile app and a web payment provider - store purchases are additive to the web lane, never a replacement"},{key:"ai",label:"AI features",hint:"Adds the AI surface (chat, models, automations, integrations). A desktop project ALWAYS ships the app's local AI stack: this option sets config.desktop.agents.enabled (the runtime gate on those screens). Off keeps config.ai.enabled false so the AI nav stays hidden - the AI packages still ship, because packages/translate depends on @repo/ai for the i18n pipeline every project uses; off drops only the MCP widgets (packages/mcp-widgets).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0},{key:"webAi",label:"AI in the web app",hint:"Whether the WEB app shows the AI surfaces - chat, automations, model and integration settings, and their nav entries. Off is the app-first shape: your desktop or mobile app is where your AI product lives and the website keeps account, billing and licensing only. The AI SERVICE is untouched either way (config.ai.enabled, the /api/ai routes and the desktop agents all stay exactly as your AI option set them), so both apps keep talking to the same backend. Only meaningful with AI features and at least one app - the desktop app or the mobile app.",category:"Features",kind:"boolean",default:!0,adoptable:!0,impact:"config",shapesTree:!1,requires:e=>e.ai===!0&&(e.desktop===!0||e.mobile===!0),requiresLabel:"requires AI features and an app to host them (the desktop app or the mobile app)"},{key:"credits",label:"Metered credits",hint:"Adds metered usage credits on top of subscription plans.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"config",shapesTree:!1,requires:e=>ne(e),requiresLabel:"requires a payment provider"},{key:"revenueSharing",label:"Revenue sharing",hint:"Opt-in MRR leaderboard with dofollow backlinks.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"config",shapesTree:!1}];function $s(e,t){return e[t]!==void 0}function nn(e){return pr.filter(t=>t.adoptable&&!$s(e,t.key)&&(t.requires?t.requires(e):!0)).map(t=>({key:t.key,label:t.label,hint:t.hint,kind:t.kind,default:typeof t.default=="function"?t.default(e):t.default,...t.choices?{choices:t.choices}:{},impact:t.impact,...t.requiresLabel?{requiresLabel:t.requiresLabel}:{}}))}function js(e,t){switch(e.kind){case"boolean":return typeof t=="boolean";case"enum":return typeof t=="string"&&(e.choices??[]).includes(t);case"multiselect":return Array.isArray(t)&&t.every(r=>typeof r=="string"&&(e.choices??[]).includes(r))}}function Ms(e){let t=(e.choices??[]).map(r=>JSON.stringify(r)).join(", ");switch(e.kind){case"boolean":return"true or false";case"enum":return`one of ${t}`;case"multiselect":return`an array of ${t}`}}function sn(e){let t=[];for(let r of pr){let n=e[r.key];n!==void 0&&(js(r,n)||t.push(`\`${r.key}\` is ${JSON.stringify(n)}, but it must be ${Ms(r)}.`))}return t}function on(e){let t={};for(let r of pr)if(typeof r.default=="function"){if(r.requires&&!r.requires(e))continue;t[r.key]=r.default(e)}else t[r.key]=Array.isArray(r.default)?[...r.default]:r.default;return{...t,...e}}function dr(e,t){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||t}function Dt(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Nt(e){return/^[a-z][a-z0-9-]*$/.test(e)}function N(e){return e instanceof Error?e.message:String(e)}function yt(e){if(e.mobilePurchases!=="revenuecat")return e;if(e.mobile===!1)throw new Error("--mobile-purchases revenuecat requires the mobile app; remove --no-mobile.");if(e.paymentProvider==="none")throw new Error("--mobile-purchases revenuecat requires a payment provider (got --payment none): store purchases are additive to your web billing, never a replacement.");return e.mobile===void 0&&(e.mobile=!0),e}function bt(e){if(e.webAi!==!1)return e;if(e.ai===!1)throw new Error("--no-web-ai requires --ai (the desktop and mobile apps are where AI lives when the web surface is off).");if(e.desktop===!1&&e.mobile===!1)throw new Error("--no-web-ai requires --desktop or --mobile - with the web AI surface off, the desktop and mobile apps are the only places your AI features exist.");return e}function an(e){if(e.webAi!==!1)return[];let t=[];return e.desktop!==!0&&e.mobile!==!0&&t.push("neither `desktop` nor `mobile` is true, so this project has no desktop or mobile app - and with the web AI surface off, those apps are the only places its AI features would exist."),t}function cn(e){if(e.mobilePurchases!=="revenuecat")return[];let t=[];return e.mobile!==!0&&t.push("`mobile` is not true, so this project has no app to sell in - the store lane's paywall, purchase and restore surfaces all live in `apps/mobile`."),ne(e)||t.push('`paymentProvider` is absent or `"none"`, and store purchases are additive to your web billing - there is nothing here for them to sit on top of.'),t}function ln(e){let t=Us(e,e.desktopAi);return delete e.desktopAi,t}function Us(e,t){return e.desktop!==!0?{kind:"none"}:t===!0&&e.ai!==!0?{kind:"legacy-desktop-ai"}:t===!1&&e.ai===!0?{kind:"desktop-gains-ai"}:{kind:"none"}}function pn(e){let t={};if(e.name!==void 0){if(!Nt(e.name))throw new Error(`Invalid project name "${e.name}". Use lowercase letters, numbers, and hyphens only. Must start with a letter.`);t.projectName=e.name}if(e.appName!==void 0){if(!e.appName.trim())throw new Error("App name cannot be empty.");t.appName=e.appName}if(e.location!==void 0?t.projectDir=e.location==="."?process.cwd():e.location:t.projectName!==void 0&&(t.projectDir=`./${t.projectName}`),e.architecture!==void 0&&(t.architecture=e.architecture),e.payment!==void 0&&(t.paymentProvider=e.payment),e.email!==void 0&&(t.emailProvider=e.email),e.org!==void 0&&(t.multiTenancy=e.org),e.projects!==void 0&&(t.projects=e.projects),e.docs!==void 0&&(t.docs=e.docs),e.desktop!==void 0&&(t.desktop=e.desktop),e.mobile!==void 0&&(t.mobile=e.mobile),e.mobilePurchases!==void 0){if(!je.includes(e.mobilePurchases))throw new Error(`Invalid mobile purchases "${e.mobilePurchases}". Valid values: ${je.join(", ")}`);t.mobilePurchases=e.mobilePurchases}if(e.ai!==void 0&&(t.ai=e.ai),e.webAi!==void 0&&(t.webAi=e.webAi),yt(t),bt(t),e.revenueSharing!==void 0&&(t.revenueSharing=e.revenueSharing),e.credits!==void 0){if(e.credits===!0&&e.payment==="none")throw new Error("--credits requires a payment provider (got --payment none).");t.credits=e.credits}if(e.currency!==void 0){if(!ce.includes(e.currency))throw new Error(`Invalid currency "${e.currency}". Valid values: ${ce.join(", ")}`);t.defaultCurrency=e.currency}if(e.deploy!==void 0){if(!le.includes(e.deploy))throw new Error(`Invalid deployment target "${e.deploy}". Valid values: ${le.join(", ")}`);t.deploymentTarget=e.deploy}if(e.database!==void 0){if(!pe.includes(e.database))throw new Error(`Invalid database provider "${e.database}". Valid values: ${pe.join(", ")}`);t.databaseProvider=e.database}if(e.cache!==void 0){if(!de.includes(e.cache))throw new Error(`Invalid cache provider "${e.cache}". Valid values: ${de.join(", ")}`);t.cacheProvider=e.cache}if(e.observability!==void 0){let r=e.observability.split(",").map(i=>i.trim()).filter(Boolean),n=r.filter(i=>!G.includes(i));if(n.length>0)throw new Error(`Invalid observability provider ${JSON.stringify(n.join(", "))}. Valid values: ${G.join(", ")}`);t.observability=r}if(e.preset!==void 0){if(!$e.includes(e.preset))throw new Error(`Invalid preset "${e.preset}". Valid values: ${$e.join(", ")}`);let r=ae[e.preset].values;t.deploymentTarget??=r.deploymentTarget,t.databaseProvider??=r.databaseProvider,t.cacheProvider??=r.cacheProvider}if(e.demo===!0&&(t.demo=!0),e.baseUrl!==void 0){let r=e.baseUrl.trim();if(r==="")throw new Error("--base-url cannot be empty. Provide an absolute URL like https://example.com.");let n;try{n=new URL(r)}catch{throw new Error(`Invalid --base-url "${e.baseUrl}". Must be an absolute URL like https://example.com.`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw new Error(`Invalid --base-url "${e.baseUrl}". Must use http or https.`);t.baseUrl=`${n.protocol}//${n.host}`}return t}var ot={projectName:"my-saas",architecture:"fullstack",paymentProvider:"stripe",emailProvider:"smtp",multiTenancy:!1,projects:!1,docs:!1,desktop:!1,mobile:!1,mobilePurchases:"none",ai:!1,webAi:!0,revenueSharing:!1,credits:!0,defaultCurrency:"USD",deploymentTarget:"node",databaseProvider:"postgres",cacheProvider:"redis",observability:[]};function dn(e){let t=e.projectName??ot.projectName,r=e.projectDir??`./${t}`,n=e.appName??Dt(t),i=e.deploymentTarget??ot.deploymentTarget,s=re[i]?.edgeRuntime??!1,o=e.databaseProvider??(s?"neon":ot.databaseProvider),a=e.cacheProvider??(s?"upstash":ot.cacheProvider),p=e.emailProvider??(s?"resend":ot.emailProvider),h={...ot,...e,projectName:t,appName:n,projectDir:r,deploymentTarget:i,databaseProvider:o,cacheProvider:a,emailProvider:p};h.paymentProvider==="none"&&(h.credits=!1),(!h.mobile||h.paymentProvider==="none")&&(h.mobilePurchases="none"),yt(h);for(let g of et){if(h.deploymentTarget!==g.target)continue;let k=h.databaseProvider===g.provider?"database":"cache";if(h.databaseProvider===g.provider||h.cacheProvider===g.provider)throw new Error(`Incompatible: --deploy ${g.target} + --${k} ${g.provider}. ${g.reason}`)}for(let g of tt)if(h.architecture===g.architecture&&h.deploymentTarget===g.target)throw new Error(`Incompatible: --architecture ${g.architecture} + --deploy ${g.target}. ${g.reason}`);return bt(h),h}function I(e){f.isCancel(e)&&(f.cancel("Setup cancelled."),process.exit(0))}function ur(e){let t=[];return e.databaseProvider==="neon"&&t.push({key:"DATABASE_URL",message:"Neon connection string (optional):",placeholder:"postgres://...",secret:!0}),e.databaseProvider==="supabase"&&t.push({key:"DATABASE_URL",message:"Supabase connection string (optional):",placeholder:"postgres://...",secret:!0}),e.cacheProvider==="upstash"&&(t.push({key:"UPSTASH_REDIS_REST_URL",message:"Upstash REST URL (optional):",placeholder:"https://...",secret:!1}),t.push({key:"UPSTASH_REDIS_REST_TOKEN",message:"Upstash REST token (optional):",secret:!0})),e.paymentProvider==="stripe"&&(t.push({key:"STRIPE_SECRET_KEY",message:"Stripe secret key (optional):",placeholder:"sk_test_...",secret:!0}),t.push({key:"STRIPE_WEBHOOK_SECRET",message:"Stripe webhook secret (optional):",placeholder:"whsec_...",secret:!0})),e.paymentProvider==="polar"&&(t.push({key:"POLAR_ACCESS_TOKEN",message:"Polar access token (optional):",secret:!0}),t.push({key:"POLAR_WEBHOOK_SECRET",message:"Polar webhook secret (optional):",secret:!0})),e.emailProvider==="resend"&&t.push({key:"RESEND_API_KEY",message:"Resend API key (optional):",placeholder:"re_...",secret:!0}),e.emailProvider==="ses"&&(t.push({key:"AMAZON_SES_REGION",message:"Amazon SES region (optional):",placeholder:"us-east-1",secret:!1}),t.push({key:"AMAZON_SES_KEY",message:"Amazon SES access key (optional):",secret:!0}),t.push({key:"AMAZON_SES_SECRET",message:"Amazon SES secret (optional):",secret:!0})),e.demo&&t.push({key:"TURNSTILE_SECRET_KEY",message:"Cloudflare Turnstile secret key (optional):",secret:!0}),t}async function un(e,t){let r=!1;e&&yt(e),e&&bt(e),f.log.info(y.bold("Project"));let n=e?.projectName??await(async()=>{r=!0;let c=await f.text({message:"Project name:",placeholder:"my-saas",validate:d=>{if(!d?.trim())return"Project name is required.";if(!Nt(d))return"Use lowercase letters, numbers, and hyphens only. Must start with a letter."}});return I(c),c})(),i=e?.appName??await(async()=>{r=!0;let c=await f.text({message:"App name:",initialValue:Dt(n),validate:d=>{if(!d?.trim())return"App name is required."}});return I(c),c})(),s=e?.projectDir??await(async()=>{r=!0;let c=await f.text({message:"Project location:",initialValue:`./${n}`});return I(c),c==="."?process.cwd():c})();f.log.info(y.bold("Infrastructure"));let o={};if(e?.deploymentTarget===void 0&&e?.databaseProvider===void 0&&e?.cacheProvider===void 0){r=!0;let c=await f.select({message:"Infrastructure:",options:[...$e.map(d=>({value:d,label:ae[d].label,hint:ae[d].hint})),{value:"custom",label:"Customize",hint:"choose each piece yourself"}]});if(I(c),c!=="custom"){let d=ae[c].values;o.deploymentTarget=d.deploymentTarget,o.databaseProvider=d.databaseProvider,o.cacheProvider=d.cacheProvider,f.log.info(`${ae[c].label}: ${ae[c].hint}.`)}}let a=e?.deploymentTarget??o.deploymentTarget??"node";if(e?.deploymentTarget===void 0&&o.deploymentTarget===void 0){r=!0;let c=await f.select({message:"Deployment target:",options:le.map(d=>({value:d,label:re[d].label,hint:re[d].hint}))});I(c),a=c}let p=e?.architecture?tt.find(c=>c.architecture===e.architecture&&c.target===a):void 0;if(p)throw new Error(`Incompatible: --architecture ${p.architecture} + --deploy ${p.target}. ${p.reason}`);let h=new Set(tt.filter(c=>c.target===a).map(c=>c.architecture)),g=nt.filter(c=>!h.has(c)),k=e?.architecture??await(async()=>{if(g.length===1){let d=g[0];return f.log.info(`Auto-selected ${gt[d].label} architecture (only compatible option for ${re[a].label}).`),d}r=!0;let c=await f.select({message:"Architecture:",options:g.map(d=>({value:d,label:gt[d].label,hint:gt[d].hint}))});return I(c),c})(),w=e?.databaseProvider??o.databaseProvider??await(async()=>{r=!0;let c=pe.filter(R=>!et.some(Ee=>Ee.target===a&&Ee.provider===R));if(c.length===1){let R=c[0];return f.log.info(`Auto-selected ${Ce[R].label} (only compatible option for ${re[a].label}).`),R}let d=await f.select({message:"Database provider:",options:c.map(R=>({value:R,label:Ce[R].label,hint:Ce[R].hint}))});return I(d),d})(),P=e?.cacheProvider??o.cacheProvider??await(async()=>{r=!0;let c=de.filter(R=>!et.some(Ee=>Ee.target===a&&Ee.provider===R));if(c.length===1){let R=c[0];return f.log.info(`Auto-selected ${Le[R].label} (only compatible option for ${re[a].label}).`),R}let d=await f.select({message:"Cache provider:",options:c.map(R=>({value:R,label:Le[R].label,hint:Le[R].hint}))});return I(d),d})();if(re[a]?.edgeRuntime){let c=tn.map(d=>` - ${d}`).join(`
3
+ `);f.note(c,"Unavailable on edge runtime")}f.log.info(y.bold("Features"));let u=e?.paymentProvider??await(async()=>{r=!0;let c=await f.select({message:"Payment provider:",options:it.map(d=>({value:d,label:_t[d].label,hint:_t[d].hint}))});return I(c),c})(),O=e?.defaultCurrency??await(async()=>{if(u==="none")return"USD";r=!0;let c=await f.select({message:"Default currency:",options:ce.map(d=>({value:d,label:d,hint:Ne[d].name}))});return I(c),c})(),be=e?.emailProvider??await(async()=>{r=!0;let c=await f.select({message:"Email provider:",options:st.map(d=>({value:d,label:Ot[d].label,hint:Ot[d].hint}))});return I(c),c})(),B=e?.observability??await(async()=>{r=!0;let c=await f.multiselect({message:"Observability (space to select, enter to confirm):",required:!1,initialValues:[],options:G.map(d=>({value:d,label:xt[d].label,hint:xt[d].hint}))});return I(c),c})(),oe=e?.multiTenancy??await(async()=>{r=!0;let c=await f.confirm({message:"Enable multi-tenancy (organizations)?",initialValue:!1});return I(c),c})(),Oe=e?.projects??await(async()=>{r=!0;let c=await f.confirm({message:"Enable projects (a switcher that scopes a user's work)?",initialValue:!1});return I(c),c})(),xe=e?.docs??await(async()=>{r=!0;let c=await f.confirm({message:"Include docs app? (self-hosted Fumadocs documentation site)",initialValue:!1});return I(c),c})(),De=t?.desktopAllowed!==!1,we=e?.desktop??(De?await(async()=>{r=!0;let c=await f.confirm({message:"Include the desktop app? (apps/desktop - cross-platform, built with Electron, device-auth). With AI on, it also runs a local AI stack.",initialValue:!1});return I(c),c})():(f.log.info(y.dim("Desktop app: available on the Pro plan and up - skipped.")),!1)),Qe=t?.mobileAllowed!==!1,v=e?.mobile??(Qe?await(async()=>{r=!0;let c=await f.confirm({message:"Include the mobile app? (apps/mobile - iOS and Android, built with Expo, with push notifications and universal links)",initialValue:!1});return I(c),c})():(f.log.info(y.dim("Mobile app: available on the Pro plan and up - skipped.")),!1)),L=!v||u==="none"?"none":e?.mobilePurchases??await(async()=>{r=!0;let R=await f.select({message:"Mobile in-app purchases?",options:[{value:"revenuecat",label:"RevenueCat",hint:"store billing on top of your web provider - Apple and Google charge, your app grants"},{value:"none",label:"None",hint:"web billing only; the app shows the plan, never a paywall"}],initialValue:"none"});return I(R),R})();yt({mobile:v,mobilePurchases:L,paymentProvider:u});let F=e?.ai??await(async()=>{r=!0;let c=await f.confirm({message:"Add AI features? (chat, models, automations, integrations)",initialValue:!1});return I(c),c})(),ve=e?.webAi??((we||v)&&F?await(async()=>{r=!0;let c=await f.confirm({message:"Show the AI surfaces in the web app? (No: app-first - your desktop or mobile app is where your AI product lives, and the web keeps account, billing, and licensing only)",initialValue:!0});return I(c),c})():!0);bt({webAi:ve,ai:F,desktop:we,mobile:v});let $=e?.revenueSharing??await(async()=>{r=!0;let c=await f.confirm({message:"Enable revenue sharing? (opt-in MRR leaderboard with dofollow backlinks)",initialValue:!1});return I(c),c})(),W=u==="none"?!1:e?.credits??await(async()=>{r=!0;let c=await f.confirm({message:"Enable credits? (metered usage on top of subscription plans)",initialValue:!0});return I(c),c})(),ke=e?.demo,z=ur({databaseProvider:w,cacheProvider:P,paymentProvider:u,emailProvider:be,demo:ke}),T={};if(z.length>0&&r){f.log.info(y.bold("Credentials")+y.dim(" all optional - press Enter to skip, fill in .env later"));for(let c of z)if(r=!0,c.secret){let d=await f.password({message:c.message,mask:"*"});I(d),typeof d=="string"&&d.trim()&&(T[c.key]=d.trim())}else{let d=await f.text({message:c.message,placeholder:c.placeholder});I(d),typeof d=="string"&&d.trim()&&(T[c.key]=d.trim())}}if(r){let c=[` Name: ${y.cyan(n)}`,` App name: ${y.cyan(i)}`,` Location: ${y.cyan(s)}`,` Architecture: ${y.cyan(gt[k].label)}`].join(`
4
+ `),d=[` Deploy target: ${y.cyan(re[a]?.label??"Node.js / Docker")}`,` Database: ${y.cyan(Ce[w].label)}`,` Cache: ${y.cyan(Le[P].label)}`].filter(Boolean).join(`
5
+ `),R=[u!=="none"?` Payment: ${y.cyan(_t[u].label)} (${O})`:` Payment: ${y.dim("none")}`,` Credits: ${W?y.cyan("Yes"):y.dim("No")}`,` AI features: ${F?y.cyan("Yes"):y.dim("No")}`,...ve?[]:[` Web AI: ${y.dim("No")} (app-first)`],` Email: ${y.cyan(Ot[be].label)}`,` Observability: ${B.length===0?y.dim("none"):y.cyan(B.map(ar=>xt[ar].label).join(", "))}`,` Multi-tenancy: ${oe?y.cyan("Yes"):y.dim("No")}`,` Projects: ${Oe?y.cyan("Yes"):y.dim("No")}`,` Docs app: ${xe?y.cyan("Yes"):y.dim("No")}`,` Desktop app: ${we?y.cyan("Yes"):y.dim("No")}`,` Mobile app: ${v?y.cyan("Yes"):y.dim("No")}`,...L==="none"?[]:[` In-app purch.: ${y.cyan("RevenueCat")}`],` Rev. sharing: ${$?y.cyan("Yes"):y.dim("No")}`].join(`
6
+ `),Ee=[y.bold("Project"),c,"",y.bold("Infrastructure"),d,"",y.bold("Features"),R];if(z.length>0){let ar=z.map(Xr=>{let Ls=T[Xr.key]?y.green("provided"):y.dim("skipped");return` ${Xr.key}: ${Ls}`}).join(`
7
+ `);Ee.push("",y.bold("Credentials"),ar)}f.note(Ee.join(`
8
+ `),"Summary");let qr=await f.confirm({message:"Proceed with these settings?"});(f.isCancel(qr)||!qr)&&(f.cancel("Setup cancelled."),process.exit(0))}return{projectName:n,appName:i,projectDir:s,architecture:k,deploymentTarget:a,databaseProvider:w,cacheProvider:P,paymentProvider:u,emailProvider:be,observability:B,multiTenancy:oe,projects:Oe,docs:xe,desktop:we,mobile:v,mobilePurchases:L,ai:F,webAi:ve,revenueSharing:$,credits:W,defaultCurrency:O,...Object.keys(T).length>0?{credentials:T}:{},...e?.baseUrl!==void 0?{baseUrl:e.baseUrl}:{},...ke!==void 0?{demo:ke}:{}}}import{createReadStream as Sn,existsSync as Js}from"fs";import{mkdir as qs}from"fs/promises";import{join as Xs}from"path";import{Readable as Zs}from"stream";import{pipeline as Er}from"stream/promises";import{extract as Qs}from"tar";import{join as Me}from"path";import{homedir as Fs}from"os";var mr="https://cli.generatesaas.com",wt=process.env.GENERATESAAS_API_URL??mr,J=".generatesaas",ue=Me(J,"manifest.json"),mn="nextjs",hr="nuxt",fr="2.4.1",hn=Me(J,"hashes.json"),Ct=Me(J,"template-hashes.json"),Lt=Me(J,"template"),fn=Me(J,"staging"),gn=Me(J,"staging.json"),me=Me(Fs(),".generatesaas");var M=class extends Error{constructor(r,n,i){super(n);this.status=r;this.body=i}status;body;name="ApiError"};function he(e){return{apiKey:e,baseUrl:wt}}async function Se(e,t,r){let n=`${e.baseUrl}${t}`,i=await fetch(n,{...r,headers:{...r?.headers,Authorization:`Bearer ${e.apiKey}`,"User-Agent":"generatesaas-cli/3.39.0"}});if(!i.ok){let s,o;try{o=await i.json(),s=o.error??`API ${i.status}: ${t}`}catch{s=`API ${i.status}: ${t}`}throw new M(i.status,s,o)}return i}import{existsSync as Vs,mkdirSync as Bs,readFileSync as Gs,writeFileSync as Ks}from"fs";import{dirname as Hs}from"path";import*as Pe from"@clack/prompts";function vt(){if(!Vs(me))return null;try{let e=JSON.parse(Gs(me,"utf-8"));return e.apiKey?e.apiKey:(e.token&&!e.apiKey&&Pe.log.warning(`Found old GitHub token in ${me}. Run 'generatesaas init' to set up your API key.`),null)}catch{return null}}function Ue(e){let t=process.env.GENERATESAAS_API_URL;t&&t.replace(/\/+$/,"")!==mr||(Bs(Hs(me),{recursive:!0}),Ks(me,`${JSON.stringify({apiKey:e},null," ")}
9
+ `,{mode:384}))}async function at(e){if(e?.apiKey)return e.apiKey;let t=process.env.GENERATESAAS_API_KEY;if(t)return t;let r=vt();if(r)return r;if(!e?.prompt)throw new Error("API key not found. Set GENERATESAAS_API_KEY or run 'generatesaas init' to configure.");return kt()}async function kt(){let e=await Pe.text({message:"Enter your GenerateSaaS API key:",placeholder:"gs_live_...",validate:t=>{if(!t?.trim())return"API key is required."}});return Pe.isCancel(e)&&(Pe.cancel("Setup cancelled."),process.exit(0)),e.trim()}import{readFile as Ys}from"fs/promises";async function Ae(e){let t=process.env.GENERATESAAS_VERSION_INDEX;return t?JSON.parse(await Ys(t,"utf-8")):process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{latest:"0.0.0-ci",versions:[{version:"0.0.0-ci",date:new Date().toISOString(),breaking:!1}],entitlements:null}:await(await Se(e,"/versions")).json()}async function yn(e,t){if(process.env.GENERATESAAS_OFFLINE_LICENSE==="1")return null;try{return await(await Se(e,`/changelog/${encodeURIComponent(t)}`)).text()}catch(r){if(r instanceof M&&r.status===404)return null;throw r}}async function bn(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{skills:{"generatesaas-update":{skillMd:`# Offline skill stub
10
+ `,scripts:{},references:{}}}}:await(await Se(e,`/skills/${encodeURIComponent(t)}`)).json()}function $t(e){if(!(e instanceof M)||e.status!==403)return null;let t=e.body;return!t||t.code!=="update_window_expired"?null:{message:e.message,lastAllowedVersion:t.lastAllowedVersion??null}}var gr="nextjs";function wn(e){return{frontend:gr,architecture:e.architecture,deployTarget:e.deploymentTarget,database:e.databaseProvider,cache:e.cacheProvider,payment:e.paymentProvider,email:e.emailProvider,multiTenancy:e.multiTenancy,blog:!0,docs:e.docs,desktop:e.desktop,mobile:e.mobile,runner:!1,credits:e.credits,revenueSharing:e.revenueSharing,currency:e.defaultCurrency}}async function yr(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{token:"offline-test-token",licenseId:"offline-test-license-id",installId:t.installId}:await(await Se(e,"/license/sign",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json()}async function vn(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{token:t.currentToken}:await(await Se(e,"/license/refresh",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json()}async function br(e,t){let r=await fetch(`${e}/license/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok)throw new Error(`Verification service returned ${r.status}`);return await r.json()}async function kn(e,t,r){let n=await fetch(`${e}/license/inspect`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(r)});if(!n.ok){let i=await n.json().catch(()=>null);throw new Error(i?.error??`Inspect endpoint returned ${n.status}`)}return await n.json()}var wr=new Set([".git","node_modules",".pnpm-store",".env",".env.test",".turbo",".data","dist",".next",".next-e2e-web",".next-e2e-desktop",".wrangler",".devcontainer","playwright-report","test-results",".drive-out",".mastra"]),vr=new Set(["pnpm-lock.yaml","widget-documents.generated.ts"]);function ct(e){if(kr(e))return!0;for(let t of e.split("/"))if(vr.has(t))return!0;return!1}var Ws=new Set(["data","references","scripts",".cursor",".agents",".codex",".generatesaas",".vscode",".mcp.json","vitest.config.ts","README.md","TODO.md","OVERVIEW.md"]),En=["scripts/docs-lint.ts"],zs=["docs/superpowers","packages/cli","packages/cli-api","packages/database/tests/no-migration-history.test.ts","infra/docker-compose.yml",".claude/commands",".claude/skills/web-port",".claude/skills/web-port-workspace",".claude/settings.local.json",".claude/worktrees"];function kr(e){let t=e.split("/");for(let r of t)if(wr.has(r))return!0;if(En.includes(e)||En.some(r=>r.startsWith(`${e}/`)))return!1;if(Ws.has(t[0]))return!0;for(let r of zs)if(e===r||e.startsWith(`${r}/`))return!0;return!1}async function jt(e,t,r){await qs(r,{recursive:!0});let n=process.env.GENERATESAAS_TEMPLATE_TARBALL_DIR;if(n){let a=Xs(n,`v${t}.tar.gz`);if(!Js(a))throw new Error(`GENERATESAAS_TEMPLATE_TARBALL_DIR is set but ${a} does not exist.`);await Er(Sn(a),Sr(r));return}let i=process.env.GENERATESAAS_TEMPLATE_TARBALL;if(i){await Er(Sn(i),Sr(r));return}let s=await Se(e,`/template/${encodeURIComponent(t)}`);if(!s.body)throw new Error("Empty response body");let o=Zs.fromWeb(s.body);await Er(o,Sr(r))}function Sr(e){return Qs({cwd:e,strip:1,filter:t=>{let r=t.replace(/^[^/]+\//,"");return r?!kr(r):!0},sync:!1})}import{readdir as Mt,readFile as lt,rm as An,rmdir as eo,writeFile as Et}from"fs/promises";import{join as K}from"path";async function In(e){let t;try{t=await Mt(e,{withFileTypes:!0})}catch{return!1}let r=!1;for(let n of t){let i=K(e,n.name);if(n.isDirectory()){await In(i)&&(r=!0);continue}if(n.name.startsWith("_")){r=!0;continue}await An(i,{force:!0})}return r||await eo(e).catch(()=>{}),r}async function Tn(e){let t=K(e,"packages/content"),r=[];try{r=(await Mt(t,{withFileTypes:!0})).filter(o=>o.isDirectory()).map(o=>o.name)}catch{return}let n=new Set;for(let o of r){let a=K(t,o),p;try{p=(await Mt(a,{withFileTypes:!0})).filter(h=>h.isDirectory())}catch{continue}for(let h of p)n.add(h.name),await In(K(a,h.name))}let i=await io(e),s=new Set([...n].filter(o=>i===void 0||i.has(o)));await Promise.all([...s].map(o=>An(K(e,"apps/web/public/images",o),{recursive:!0,force:!0}))),await oo(e,s)}var to="packages/config/src/index.ts",ro=/\bcontent:\s*\{[\s\S]*?\bsections:\s*\[([\s\S]*?)\]/,no=/\bslug:\s*"([^"]+)"/g;async function io(e){let t;try{t=await lt(K(e,to),"utf-8")}catch{return}let r=ro.exec(t)?.[1];if(r===void 0)return;let n=[...r.matchAll(no)].map(i=>i[1]).filter(i=>i!==void 0);return n.length>0?new Set(n):void 0}var so="packages/translate/.meta/mdx-translation-meta.json";async function oo(e,t){if(t.size===0)return;let r=K(e,so),n;try{n=JSON.parse(await lt(r,"utf-8"))}catch{return}if(typeof n!="object"||n===null)return;let i=n;if(typeof i.locales!="object"||i.locales===null)return;let s={};for(let[o,a]of Object.entries(i.locales)){if(typeof a!="object"||a===null)continue;let p={};for(let[h,g]of Object.entries(a)){let k=h.split("/"),w=k.length>1?k[0]:void 0,P=k[k.length-1]?.startsWith("_")===!0;w!==void 0&&t.has(w)&&!P||(p[h]=g)}s[o]=p}await Et(r,`${JSON.stringify({...i,locales:s},null," ")}
11
+ `)}var ao="packages/config/src/blog.ts";async function Rn(e){let t=K(e,ao),r=await lt(t,"utf-8"),n=Pn(Pn(r,"blogCategories",t),"blogAuthors",t);await Et(t,n)}function Pn(e,t,r){let n=new RegExp(`(export const ${t}\\b[^=]*=\\s*)\\[[\\s\\S]*?\\];`);if(!n.test(e))throw new Error(`emptyBlogConfig: could not find the \`export const ${t} = [...]\` declaration in ${r}. The boilerplate blog config may have been renamed or restructured; update the CLI strip in cleanup.ts.`);return e.replace(n,"$1[];")}async function _n(e){let t=K(e,"packages/i18n/translations"),r;try{r=await Mt(t)}catch{return}for(let n of r){let i=K(t,n,"web.json"),s;try{s=await lt(i,"utf-8")}catch{continue}let o=JSON.parse(s);!o.content?.categories||o.content.categories.blog===void 0||(o.content.categories.blog={},await Et(i,`${JSON.stringify(o,null," ")}
12
+ `))}}var co="packages/config/src/ai/tasks.ts",lo="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.",po="The array starts EMPTY, which hides the Tasks tab until you declare your first task.";async function On(e){let t=K(e,co),r=await lt(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(lo,po);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 Et(t,i)}async function xn(e){let t=K(e,".claude","settings.json"),r;try{r=await lt(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(uo)),await Et(t,`${JSON.stringify(n,null," ")}
13
+ `)}function uo(e){return!(e.startsWith("mcp__")||e.includes("nuxt"))}import{readFileSync as Eo}from"fs";import{dirname as So,join as Nn}from"path";import{fileURLToPath as Po}from"url";import{existsSync as mo}from"fs";import{join as Dn}from"path";function Ut(e,t,r){let n=Dn(e,...t);return mo(n)?n:Dn(e,r)}import{mkdir as ho,writeFile as fo,readdir as go,rm as yo,rmdir as bo}from"fs/promises";import{dirname as Ft,join as wo,relative as vo,sep as ko}from"path";function Fe(e){return e.split(ko).join("/")}async function Vt(e){await ho(e,{recursive:!0})}async function l(e,t){await Vt(Ft(e)),await fo(e,t,"utf-8")}async function Ve(e,t){await yo(e,{force:!0});let r=Ft(e);for(;r!==t&&r!==Ft(r);){try{await bo(r)}catch{return}r=Ft(r)}}async function q(e,t,r,n){let i=[],s=await go(e,{withFileTypes:!0});for(let o of s){let a=wo(e,o.name),p=Fe(vo(t,a));r(p)||(o.isDirectory()?i.push(...await q(a,t,r,n)):o.isFile()&&(n===void 0||n(p))&&i.push(a))}return i}var Ao={postgres:"Postgres",neon:"Neon (managed Postgres)",supabase:"Supabase (managed Postgres)"},Io={resend:"Resend",ses:"Amazon SES",smtp:"SMTP"},To={redis:"Redis",upstash:"Upstash Redis"},Ro={node:"Node.js / Docker",vercel:"Vercel"},Pr="apps/web",_o="Next.js 16",Oo="`app/` routes, `components/`, `lib/`",xo={stripe:"Stripe",polar:"Polar"};function Do(e){let t=e.architecture==="fullstack",r=t?"(fullstack - Hono API mounted inside the app)":"(separate - standalone Hono backend)",n=t?`Mounted inside \`${Pr}\`. 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=To[e.cacheProvider],s=Ro[e.deploymentTarget],o=e.paymentProvider==="none"?"":`
14
+ - **Payments:** ${xo[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/`":"",p=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 \`${Pr}/i18n/request.ts\`.`;return Co({archSuffix:r,apiLocation:n,databaseName:Ao[e.databaseProvider],cacheName:i,paymentLine:o,emailName:Io[e.emailProvider],deployName:s,appDocsRef:a,sharedScreensBothShells:p,i18nRule:h,webAppDir:Pr,webAppName:_o,webAppLayout:Oo})}function No(){return Ut(So(Po(import.meta.url)),["generators","content"],"content")}function Co(e){let t=Eo(Nn(No(),"AGENTS.template.md"),"utf-8"),r=new Map(Object.entries(e)),n=t.replace(/\{\{(\w+)\}\}/g,(s,o)=>{let a=r.get(o);if(a===void 0)throw new Error(`AGENTS.template.md uses unknown token {{${o}}}`);return a}),i=/\{\{[^}]*\}\}/.exec(n);if(i)throw new Error(`AGENTS.template.md carries an unrendered token: ${i[0]}`);return n}async function Cn(e){await l(Nn(e.projectDir,"AGENTS.md"),Do(e))}import{join as Lo}from"path";var Ln="apps/web",Ar="Next.js 16",$o={postgres:"Postgres (self-hosted)",neon:"Neon (managed Postgres)",supabase:"Supabase (managed Postgres)"};function jo(e){let t=e.appName.trim()||e.projectName,r=$o[e.databaseProvider],n=e.architecture==="fullstack"?`${Ar} app at \`${Ln}/\` 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.`:`${Ar} app at \`${Ln}/\` 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
- - 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)
18
- `:"",s=`pnpm infra # optional: starts local Docker services (Postgres / Redis / Inngest / Mailpit)
17
+ - Inngest dev server: http://127.0.0.1:8288`,s=e.ai?`pnpm mastra:studio # optional: inspect the AI assistant and its memory (localhost:4111)
18
+ `:"",o=`pnpm infra # optional: starts local Docker services (Postgres / Redis / Inngest / Mailpit)
19
19
  `,a=e.deploymentTarget==="vercel"?"### Deployment\n\nDeploy to Vercel: `vercel deploy` (or connect the repo in the Vercel dashboard). Required environment variables are listed in `.env`.":"### Deployment\n\nThis project ships with Dockerfiles for each app. Build images with `docker build` and deploy to your runtime of choice (Render / Fly.io / Railway / Coolify / Dokploy / your own VPS).\n\nThe `infra/` directory ships a Docker Compose file for the local-only services (Postgres / Redis / Inngest / Mailpit, filtered by your provider choices).";return`# ${t}
20
20
 
21
21
  ${n}
22
22
 
23
23
  ## Stack
24
24
 
25
- - **Frontend:** ${Er}
25
+ - **Frontend:** ${Ar}
26
26
  - **Backend:** Hono (TypeScript, RPC-typed)
27
27
  - **Auth:** Better Auth
28
28
  - **ORM / DB:** Drizzle + ${r}
@@ -36,9 +36,9 @@ pnpm install
36
36
  # A ready-to-run \`.env\` was generated for you - open it and fill in the
37
37
  # values marked \`# TODO\` (provider API keys). \`.env.example\` is the committed
38
38
  # reference. All apps load the single root \`.env\`.
39
- ${s}pnpm db:setup # first run: create the database schema (idempotent)
39
+ ${o}pnpm db:setup # first run: create the database schema (idempotent)
40
40
  pnpm dev
41
- ${o}\`\`\`
41
+ ${s}\`\`\`
42
42
 
43
43
  ${i}
44
44
 
@@ -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 Ln(e){await l(Co(e.projectDir,"README.md"),$o(e))}import{access as jo}from"fs/promises";import{join as St}from"path";async function Mo(e,t,r){let n=St(e,"apps/desktop/dev-app-update.yml");try{await jo(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 $n(e){await l(Lo(e.projectDir,"README.md"),jo(e))}import{access as Mo}from"fs/promises";import{join as St}from"path";async function Uo(e,t,r){let n=St(e,"apps/desktop/dev-app-update.yml");try{await Mo(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 Uo(e){let t=e.split(".");return t.length>=3?t.slice(1).join("."):e}function Fo(e,t){let r=cr(e,"app");return{appId:`${t.split(".").reverse().join(".")}.${r.replace(/-/g,"")}`,productName:e,protocol:r}}function Vo(e){let t=e.toLowerCase().replace(/[^a-z0-9_]/g,"");return/^[a-z]/.test(t)?t:`app${t}`}function Bo(e,t){let r=cr(e,"app");return{appName:e,slug:r,bundleId:[...t.split(".").reverse(),r.replace(/-/g,"")].map(Vo).join("."),scheme:/^[a-z]/.test(r)?r:`app-${r}`}}function Go(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 Fo(e){let t=e.split(".");return t.length>=3?t.slice(1).join("."):e}function Vo(e,t){let r=dr(e,"app");return{appId:`${t.split(".").reverse().join(".")}.${r.replace(/-/g,"")}`,productName:e,protocol:r}}function Bo(e){let t=e.toLowerCase().replace(/[^a-z0-9_]/g,"");return/^[a-z]/.test(t)?t:`app${t}`}function Go(e,t){let r=dr(e,"app");return{appName:e,slug:r,bundleId:[...t.split(".").reverse(),r.replace(/-/g,"")].map(Bo).join("."),scheme:/^[a-z]/.test(r)?r:`app-${r}`}}function Ko(e){let t=[" // PRESENCE IS THE SWITCH: reporting runs as soon as the credential below is non-empty. There"," // is no separate `enabled` flag to remember - pasting the key IS turning it on, and clearing it"," // is turning it off. These are PUBLISHABLE credentials: they only authorize SENDING events,"," // never reading them, which is why they live here rather than in env and why a packaged desktop"," // app can carry them. Server-side, SENTRY_DSN and POSTHOG_API_KEY override them."].join(`
81
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 $n(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=Uo(i),s=e.demo?"false":"true",a=e.multiTenancy?`{
87
+ },`}async function jn(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",s=Fo(i),o=e.demo?"false":"true",a=e.multiTenancy?`{
88
88
  multiTenant: true,
89
89
  organizationLimit: 5,
90
90
  defaultOrganizationName: "{name}'s workspace"
91
- }`:"{ multiTenant: false }",p=e.projects?"{ enabled: true, seedDefault: true }":"{ enabled: false, seedDefault: true }",h=Go(e.observability),g=e.demo?`{
91
+ }`:"{ multiTenant: false }",p=e.projects?"{ enabled: true, seedDefault: true }":"{ enabled: false, seedDefault: true }",h=Ko(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
- }`:"{}",k=e.architecture==="fullstack"?"false":"true",w=Fo(t,o),P=`https://cdn.${o}/desktop`,u=Bo(t,o),O=` // Store purchases (RevenueCat) for the mobile app - ADDITIVE to the web provider, never a
97
+ }`:"{}",k=e.architecture==="fullstack"?"false":"true",w=Vo(t,s),P=`https://cdn.${s}/desktop`,u=Go(t,s),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"},
@@ -127,7 +127,7 @@ export const config: AppConfig = {
127
127
  fullSiteName: "${t}",
128
128
  domain: "${i}",
129
129
  baseUrl: "${n}",
130
- indexable: ${s},
130
+ indexable: ${o},
131
131
  logo: {
132
132
  main: "/images/logo.svg",
133
133
  square: "/images/logo-square.svg"
@@ -158,16 +158,16 @@ export const config: AppConfig = {
158
158
  limitPerSecond: 3,
159
159
  senders: {
160
160
  transactional: {
161
- email: "noreply@${o}",
161
+ email: "noreply@${s}",
162
162
  senderName: "${t}"
163
163
  },
164
164
  marketing: {
165
- email: "hello@${o}",
165
+ email: "hello@${s}",
166
166
  senderName: "${t}",
167
167
  signatureName: "Alex"
168
168
  },
169
169
  support: {
170
- email: "support@${o}",
170
+ email: "support@${s}",
171
171
  senderName: "${t} Support"
172
172
  }
173
173
  },
@@ -646,9 +646,9 @@ export const SETTINGS_PRIVACY_PATH = "/settings/privacy";
646
646
  export const SETTINGS_APP_LOCK_PATH = "/settings/app-lock";
647
647
  /** app/(app)/settings/about.tsx - version, legal links and support. */
648
648
  export const SETTINGS_ABOUT_PATH = "/settings/about";
649
- `),e.desktop&&await Mo(e.projectDir,P,`${w.protocol}-updater`)}import{join as Ko}from"path";function Ho(e,t){let r=[e==="stripe"?' stripePriceId: "",':' polarProductId: "",'];return t&&r.push(' appleProductId: "",',' googleProductId: "",'," storeAmounts: {},"),r.join(`
650
- `)}function Sr(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(`,
651
- `)}async function jn(e){let t=Ko(e.projectDir,"packages/config/src/pricing.ts"),r=e.defaultCurrency;if(e.paymentProvider==="none"){let P=`import type { PricingConfig } from "@repo/config/types";
649
+ `),e.desktop&&await Uo(e.projectDir,P,`${w.protocol}-updater`)}import{join as Ho}from"path";function Yo(e,t){let r=[e==="stripe"?' stripePriceId: "",':' polarProductId: "",'];return t&&r.push(' appleProductId: "",',' googleProductId: "",'," storeAmounts: {},"),r.join(`
650
+ `)}function Ir(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(`,
651
+ `)}async function Mn(e){let t=Ho(e.projectDir,"packages/config/src/pricing.ts"),r=e.defaultCurrency;if(e.paymentProvider==="none"){let P=`import type { PricingConfig } from "@repo/config/types";
652
652
 
653
653
  export const pricingConfig: PricingConfig = {
654
654
  defaultPlan: "free",
@@ -677,16 +677,16 @@ export const pricingConfig: PricingConfig = {
677
677
  credits: { enabled: false },
678
678
  products: { enabled: false, items: [] }
679
679
  };
680
- `;await l(t,P);return}let n=e.paymentProvider,i=Ho(n,e.mobilePurchases==="revenuecat"),o=e.credits,s=!!e.ai,a=Sr({credits:5,rateLimit:100,withCredits:o,recurring:!1,...s&&{maxConcurrentRuns:2,automationMinutesPerMonth:60}}),p=Sr({credits:10,rateLimit:1e3,withCredits:o,...s&&{maxConcurrentRuns:5,automationMinutesPerMonth:600}}),h=Sr({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
680
+ `;await l(t,P);return}let n=e.paymentProvider,i=Yo(n,e.mobilePurchases==="revenuecat"),s=e.credits,o=!!e.ai,a=Ir({credits:5,rateLimit:100,withCredits:s,recurring:!1,...o&&{maxConcurrentRuns:2,automationMinutesPerMonth:60}}),p=Ir({credits:10,rateLimit:1e3,withCredits:s,...o&&{maxConcurrentRuns:5,automationMinutesPerMonth:600}}),h=Ir({credits:40,rateLimit:5e3,withCredits:s,...o&&{maxConcurrentRuns:10,automationMinutesPerMonth:3e3}}),g=r==="USD"?"":` // !! ${r} pricing WARNING: creditsPerUsd anchors credit cost to USD (AI providers bill in
681
681
  // !! USD), but your plan prices and credit purchases are denominated in ${r}. Verify that the
682
682
  // !! ${r} amounts above cover the USD cost per credit (~0.50 USD at creditsPerUsd 1 with the
683
683
  // !! 100% markup) - and raise prices or creditsPerUsd if they do not.
684
- `;o&&r!=="USD"&&console.warn(`
684
+ `;s&&r!=="USD"&&console.warn(`
685
685
  !! ${r} pricing warning: AI credit costs are anchored to USD (providers bill in USD), but your
686
686
  !! plan prices and credit purchases are denominated in ${r}. At the shipped economics 1 credit
687
687
  !! carries ~0.50 USD of AI cost - verify every ${r} price still covers it (see the comment on the
688
688
  !! credits block in packages/config/src/pricing.ts), or raise prices / creditsPerUsd.
689
- `);let k=o?` // creditsPerUsd scales USD cost -> credits (1 = 1 credit carries ~0.50 USD of cost after the
689
+ `);let k=s?` // creditsPerUsd scales USD cost -> credits (1 = 1 credit carries ~0.50 USD of cost after the
690
690
  // 100% markup); markupPercent is the DEFAULT margin for everything that debits credits (AI,
691
691
  // external APIs, your own features), and credits.markupByCategory overrides it per metered
692
692
  // service ("ai", "webSearch", "webExtract"). Two optional knobs shape each debit's size:
@@ -795,16 +795,16 @@ ${k},
795
795
  items: []
796
796
  }
797
797
  };
798
- `;await l(t,w)}var Yo={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)"}]},Wo={stripe:[{key:"STRIPE_SECRET_KEY",comment:"# TODO: Add your Stripe keys"},{key:"STRIPE_WEBHOOK_SECRET"},{key:"STRIPE_API_BASE",comment:"# Point the Stripe SDK at another host - a local mock, or a proxy of your own. Unset means api.stripe.com."},{key:"STRIPE_PORTAL_GENERATION",comment:"# A number your deploy sets higher on every release (build timestamp, pipeline run number), so a new release retires the Stripe portal configurations an older one created. Unset, none are retired."}],polar:[{key:"POLAR_ACCESS_TOKEN",comment:"# TODO: Add your Polar keys"},{key:"POLAR_WEBHOOK_SECRET"}]};function Bt(e,t){return t?e.map(r=>{let n=t[r.key];return n?{...r,defaultValue:n,comment:void 0}:r}):e}function Pt(e,t){for(let r of e)r.comment&&t.push(r.comment),r.defaultValue!==void 0?t.push(`${r.key}=${r.defaultValue}`):t.push(`#${r.key}=`)}function Pr(e){return Array.from(crypto.getRandomValues(new Uint8Array(e))).map(t=>t.toString(16).padStart(2,"0")).join("")}function Ar(e){return e.architecture==="fullstack"?{apiUrl:"http://localhost:3000/api",baseUrl:"http://localhost:3000"}:{apiUrl:"http://localhost:3010",baseUrl:"http://localhost:3000"}}var zo="https://your-app.example.com/api";function Gt(e,t,r,n){e.push(n==="example"?`${t}=`:`${t}=${r}`)}function Mn(e,t){let r=t==="example"?void 0:e.credentials,{apiUrl:n,baseUrl:i}=Ar(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"),Pt(Bt(Ce[e.databaseProvider].envVars,r),o),o.push("","# Cache"),Pt(Bt(Le[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`"),Gt(o,"BETTER_AUTH_SECRET",crypto.randomUUID(),t),o.push("","# Content API (random secret; required when contentApi feature is enabled in @repo/config)"),Gt(o,"CONTENT_API_KEY",Pr(32),t),o.push("","# Job Queue - Inngest","INNGEST_APP_ID=api"),Gt(o,"INNGEST_EVENT_KEY",Pr(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."),Gt(o,"INNGEST_SIGNING_KEY",Pr(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=Yo[e.emailProvider];if(s&&(o.push("","# Email"),Pt(Bt(s,r),o)),e.paymentProvider!=="none"){let p=Wo[e.paymentProvider];p&&(o.push("","# Payment"),Pt(Bt(p,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).
798
+ `;await l(t,w)}var Wo={smtp:[{key:"SMTP_HOST",defaultValue:"127.0.0.1"},{key:"SMTP_PORT",defaultValue:"1025"},{key:"SMTP_USER"},{key:"SMTP_PASSWORD"}],ses:[{key:"AMAZON_SES_REGION",comment:"# TODO: Configure Amazon SES credentials (e.g. us-east-1)"},{key:"AMAZON_SES_KEY"},{key:"AMAZON_SES_SECRET"},{key:"AMAZON_SES_CONFIGURATION_SET",comment:"# Delivery events: configuration set -> SNS topic -> /webhooks/email/ses (see docs: Email)"},{key:"AMAZON_SES_SNS_TOPIC_ARN"}],resend:[{key:"RESEND_API_KEY",comment:"# TODO: Add your Resend API key"},{key:"RESEND_WEBHOOK_SECRET",comment:"# Delivery events: Resend webhook -> /webhooks/email/resend (see docs: Email)"}]},zo={stripe:[{key:"STRIPE_SECRET_KEY",comment:"# TODO: Add your Stripe keys"},{key:"STRIPE_WEBHOOK_SECRET"},{key:"STRIPE_API_BASE",comment:"# Point the Stripe SDK at another host - a local mock, or a proxy of your own. Unset means api.stripe.com."},{key:"STRIPE_PORTAL_GENERATION",comment:"# A number your deploy sets higher on every release (build timestamp, pipeline run number), so a new release retires the Stripe portal configurations an older one created. Unset, none are retired."}],polar:[{key:"POLAR_ACCESS_TOKEN",comment:"# TODO: Add your Polar keys"},{key:"POLAR_WEBHOOK_SECRET"}]};function Bt(e,t){return t?e.map(r=>{let n=t[r.key];return n?{...r,defaultValue:n,comment:void 0}:r}):e}function Pt(e,t){for(let r of e)r.comment&&t.push(r.comment),r.defaultValue!==void 0?t.push(`${r.key}=${r.defaultValue}`):t.push(`#${r.key}=`)}function Tr(e){return Array.from(crypto.getRandomValues(new Uint8Array(e))).map(t=>t.toString(16).padStart(2,"0")).join("")}function Rr(e){return e.architecture==="fullstack"?{apiUrl:"http://localhost:3000/api",baseUrl:"http://localhost:3000"}:{apiUrl:"http://localhost:3010",baseUrl:"http://localhost:3000"}}var Jo="https://your-app.example.com/api";function Gt(e,t,r,n){e.push(n==="example"?`${t}=`:`${t}=${r}`)}function Un(e,t){let r=t==="example"?void 0:e.credentials,{apiUrl:n,baseUrl:i}=Rr(e),s=[];e.architecture==="separate"?s.push("# API Configuration","# Standalone backend's own URL (the frontend reaches it via the public var above).",`API_URL=${n}`,`BASE_URL=${i}`):s.push("# App","# (API_URL is derived from the frontend's *_PUBLIC_API_URL by the runtime env schema.)",`BASE_URL=${i}`),s.push("","# Client IP (production)","# The backend rate-limits by client IP and stamps it on audit entries. YOU ALMOST","# CERTAINLY DO NOT NEED THIS: it detects Vercel, Fly.io, Render, Railway, Netlify and","# Coolify from their own env vars, and treats a private connection peer (Docker, compose,","# Kubernetes, Dokploy, an nginx/Traefik/Caddy on the same host) as proof that something is","# forwarding to it. A forwarded header is trusted only in those cases, never on a server","# exposed directly - there, a caller could have sent it themselves."),e.architecture==="fullstack"?s.push("# This build runs the API in the frontend's route handler, which has no connection","# address, so on a host the backend does not recognise there is nothing to fall back on","# and every caller shares ONE rate-limit bucket: the 10/min sign-in limit applies to","# your whole app rather than per person, and audit entries record no address."):s.push("# This build reads the connection peer, so a server exposed directly identifies its","# callers correctly with nothing set here."),s.push("# SET IT when nothing above can see your topology - the common case is a CDN in front of a","# directly exposed server, where connections arrive from a public CDN address:","# Cloudflare -> TRUSTED_PROXY=cf-connecting-ip","# another proxy in front -> TRUSTED_PROXY=1 (the number of proxies)","# Whatever you set wins over detection; `false` turns detection off and trusts nothing.","# TRUSTED_PROXY=1"),s.push("","# Auth rate limits","# Raises every Better Auth rate limit by a whole number (1-50). Unset = 1 = the","# shipped limits. No value disables them: 0, empty or unparseable fails at boot.","# You almost certainly want the default. The reason to raise it is an automated suite,","# which drives ONE address and so shares one bucket - and the e2e config already sets","# its own value, so it needs nothing here.","# AUTH_RATE_LIMIT_MULTIPLIER=1"),s.push("","# Database"),Pt(Bt(Ce[e.databaseProvider].envVars,r),s),s.push("","# Cache"),Pt(Bt(Le[e.cacheProvider].envVars,r),s),e.cacheProvider==="redis"&&s.push("# Optional prefix on every Redis key the app writes. Set it when several deployments share","# one Redis instance, or to keep a load test out of the live keyspace.","# Set it once, before first boot. Changing it on a running deployment orphans in-flight","# auto-top-up claims and distributed locks (autotopup:pending:*, withMutex) - drain or use","# a maintenance window first.","#REDIS_KEY_PREFIX="),s.push("","# Authentication"),t==="example"&&s.push("# Generate a strong secret, e.g. `openssl rand -hex 32`"),Gt(s,"BETTER_AUTH_SECRET",crypto.randomUUID(),t),s.push("","# Content API (random secret; required when contentApi feature is enabled in @repo/config)"),Gt(s,"CONTENT_API_KEY",Tr(32),t),s.push("","# Job Queue - Inngest","INNGEST_APP_ID=api"),Gt(s,"INNGEST_EVENT_KEY",Tr(32),t),s.push("# REQUIRED in production: it is how the /inngest endpoint tells Inngest from anyone else who","# finds the URL. The app refuses to boot without it unless INNGEST_DEV is set (local dev server).","# Take the real value from the Inngest dashboard."),Gt(s,"INNGEST_SIGNING_KEY",Tr(32),t),s.push("# The local Inngest dev server (pnpm dev:inngest). In production on Inngest Cloud leave this UNSET:","# Cloud takes events and registration on two hosts, which no single URL can name. Set it only for a","# self-hosted Inngest, to its one host.","INNGEST_BASE_URL=http://127.0.0.1:8288"),e.architecture==="separate"&&(s.push("","# API Port (standalone backend)","API_PORT=3010"),s.push("","# CORS + cross-subdomain cookies (production only - leave unset for local dev)","# TRUSTED_ORIGINS=https://your-app.example.com","# AUTH_COOKIE_DOMAIN=.example.com"));let o=Wo[e.emailProvider];if(o&&(s.push("","# Email"),Pt(Bt(o,r),s)),e.paymentProvider!=="none"){let p=zo[e.paymentProvider];p&&(s.push("","# Payment"),Pt(Bt(p,r),s))}s.push("","# Storage - S3 Compatible (required for uploads: avatars, files)","# Works with AWS S3, Cloudflare R2, MinIO, and other S3-compatible services.","# Uploads fail until these are set - storage is enabled in @repo/config by default.","#STORAGE_REGION=us-east-1","#STORAGE_ENDPOINT=https://your-account.r2.cloudflarestorage.com","#STORAGE_ACCESS_KEY_ID=","#STORAGE_SECRET_ACCESS_KEY=","# Two buckets: one publicly readable (avatars, assets), one credentials-only (private","# uploads served through the app). The bucket boundary is the privacy guarantee.","#STORAGE_PUBLIC_BUCKET=","#STORAGE_PRIVATE_BUCKET=",'# Public base URL for the public bucket. Public file URLs are STORAGE_PUBLIC_URL + "/" + key.',"#STORAGE_PUBLIC_URL=https://cdn.example.com","","# Storage - Local Filesystem (optional overrides)","# Defaults work out of the box; override for Docker volume mounts.","#STORAGE_LOCAL_PATH=/data","#STORAGE_LOCAL_PUBLIC_URL=https://cdn.example.com/files"),s.push("","# Admin Notifications (optional)","# Real-time notifications when business events occur (signups, purchases, etc.).","# Each provider is auto-enabled when its env vars are set.","#DISCORD_WEBHOOK_URL=https://discord.com/api/webhooks/...","#SLACK_WEBHOOK_URL=https://hooks.slack.com/services/...","#TELEGRAM_BOT_TOKEN=123456789:ABCdefGHIjklMNOpqrsTUVwxyz","#TELEGRAM_CHAT_ID=-1001234567890","#TELEGRAM_TOPIC_ID=123"),s.push("","# Social sign-in (optional)","# Enable the matching provider in @repo/config, then set its pair here.","#GOOGLE_CLIENT_ID=","#GOOGLE_CLIENT_SECRET=","#GITHUB_CLIENT_ID=","#GITHUB_CLIENT_SECRET=","# Apple: APPLE_TEAM_ID + APPLE_KEY_ID + APPLE_PRIVATE_KEY are the signing key. Add APPLE_CLIENT_ID",'# (a Service ID) for the web button, and list "apple" in config.auth.socialProviders.',"#APPLE_CLIENT_ID=","#APPLE_TEAM_ID=","#APPLE_KEY_ID=","#APPLE_PRIVATE_KEY="),s.push("","# SMS - Twilio (optional)","#TWILIO_ACCOUNT_SID=ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx","#TWILIO_AUTH_TOKEN=","#TWILIO_PHONE_NUMBER=+1234567890"),s.push("","# Newsletter (optional)","#RESEND_AUDIENCE_ID=","#LISTMONK_URL=https://listmonk.yourdomain.com","#LISTMONK_API_USER=admin","#LISTMONK_API_TOKEN=","#LISTMONK_LIST_ID=1"),e.demo&&s.push("","# Support chat - Chatwoot identity validation (optional)","# The website inbox's HMAC token (Inbox -> Settings -> Configuration -> Identity validation).","# Server-only: the backend signs the signed-in user's id with it so the inbox can enforce","# identity validation. Never expose it to the browser.","#CHATWOOT_HMAC_TOKEN="),s.push("","# Translations - OpenRouter (optional)","# Set to auto-translate en/* into your other locales with `pnpm translate`.","# The pre-commit hook runs it on commit; without a key it skips and untranslated","# locales fall back to the default locale. Get a key: https://openrouter.ai/keys","#OPENROUTER_API_KEY=");let a=[];return e.observability.includes("sentry")&&a.push({key:"SENTRY_DSN",comment:"# Overrides config.observability.sentry.dsn for the server only."}),e.observability.includes("posthog")&&a.push({key:"POSTHOG_API_KEY",comment:`# Overrides config.observability.posthog.publicKey for the server only (host stays in config).
799
799
  # Set but EMPTY switches every server-side PostHog report off (the e2e harness does this). Leave it
800
- # unset in production: the committed key is used, and only the deployment reports.`}),a.length>0&&(o.push("","# Error and product reporting (optional)"),Pt(a,o)),o.push("","# Release (optional)","# The release this deployment runs (a version, tag or commit), set by your deploy pipeline.","# Product feedback records it beside each item. Unset records none.","#APP_VERSION="),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(`
801
- `)}var Un="NEXT_PUBLIC_API_URL";function Jo(e){let{apiUrl:t}=Ar(e),r=["# API Configuration",`${Un}=${t}`];return e.architecture==="separate"&&r.push("","# Production (uncomment and replace with your deployed hostnames):",`# ${Un}=${zo}`),r.push(""),r.join(`
802
- `)}function qo(e){let{apiUrl:t,baseUrl:r}=Ar(e),n=["# Expo reads env from THIS directory, never the monorepo root.","# Every EXPO_PUBLIC_* value is inlined into the app bundle - never put a secret here.","# Android emulator: replace localhost with 10.0.2.2; a physical device needs your machine's LAN IP","# EXPO_PUBLIC_API_URL is the value to fill first - without it the app throws at launch and names it.",`EXPO_PUBLIC_API_URL=${t}`,`EXPO_PUBLIC_WEB_URL=${r}`,"","# Native Google sign-in (optional)","#EXPO_PUBLIC_GOOGLE_WEB_CLIENT_ID=","#EXPO_PUBLIC_GOOGLE_IOS_CLIENT_ID="];e.mobilePurchases==="revenuecat"&&n.push("","# RevenueCat public SDK keys (optional until you create your products)","#EXPO_PUBLIC_REVENUECAT_IOS_KEY=","#EXPO_PUBLIC_REVENUECAT_ANDROID_KEY=");let i=[];return e.observability.includes("sentry")&&i.push("#EXPO_PUBLIC_SENTRY_DSN="),e.observability.includes("posthog")&&i.push("#EXPO_PUBLIC_POSTHOG_KEY="),i.length>0&&n.push("","# Observability (optional)",...i),n.push(""),n.join(`
803
- `)}async function Fn(e){let t=Jo(e);if(await l(`${e.projectDir}/.env`,`${t}
804
- ${Mn(e,"env")}`),await l(`${e.projectDir}/.env.example`,`${t}
805
- ${Mn(e,"example")}`),e.mobile){let r=qo(e);await l(`${e.projectDir}/apps/mobile/.env`,r),await l(`${e.projectDir}/apps/mobile/.env.example`,r)}}import{join as Xo}from"path";var Zo=`# Every port is published on 127.0.0.1 only: these development services run with fixed credentials
800
+ # unset in production: the committed key is used, and only the deployment reports.`}),a.length>0&&(s.push("","# Error and product reporting (optional)"),Pt(a,s)),s.push("","# Release (optional)","# The release this deployment runs (a version, tag or commit), set by your deploy pipeline.","# Product feedback records it beside each item. Unset records none.","#APP_VERSION="),s.push("","# AI base (optional)","# Enable config.ai in packages/config. Built-in AI resolves through OpenRouter only,","# so OPENROUTER_API_KEY above is the only MODEL provider key the backend reads.","# BYOK is per-user and never an env var: users paste their own key in the app and it","# is stored encrypted in the database.","# Override the OpenRouter API base - a gateway or a proxy of your own. It must carry the","# /api/v1 suffix. Unset uses the hosted API.","#OPENROUTER_BASE_URL=https://openrouter.ai/api/v1","","# AI web tools (optional)","# Give the assistant its own web access, on chat (on by default), the desktop app-tools","# lane, automations and the MCP server. A key's presence is the whole switch: set one","# and the model gets its tools, set none and chat is unchanged. config.ai.webSearch:","# false switches every lane off.","# ANY one key alone covers both capabilities. With several set, auto-detection takes the","# CHEAPEST first - TinyFish, then Firecrawl, then Parallel - per capability; naming","# config.ai.webTools.searchEngine or .extractEngine wins over that order, and a named","# engine whose key is missing ships no tool at all.","# WHAT A CALL COSTS THE USER: the vendor price x credits.creditsPerUsd x the","# webSearch/webExtract markup (shipped at 100, so twice cost). Override the vendor price","# with config.ai.webTools.searchCostUsd / .extractCostUsd.","# TinyFish (the auto-detect default) - both tools at a $0 list price, so a call debits","# nothing, writes no ledger row and is never refused for an empty balance. Rate-limited","# instead (30 searches and 150 pages a minute per API key by default, shared by every","# user), so set a price on a busy app. Note its terms include a license to train on","# submitted content.","# https://agent.tinyfish.ai/","#TINYFISH_API_KEY=","# Firecrawl (the recommended PAID engine) - `web_search` AND `web_extract` (reads one","# page) from one signup, and the only vendor here whose terms carry no license over what","# you submit.","# https://firecrawl.dev/","#FIRECRAWL_API_KEY=","# Parallel (optional) - both tools, cheaper than Firecrawl on each, at high quality;","# extract is slower on a page it has not already indexed. Note its customer terms","# include a license to train on submitted queries.","# https://platform.parallel.ai/","#PARALLEL_API_KEY="),e.desktop&&s.push("","# Desktop app (optional)","# Base URL the marketing download page reads the release feed from.","# Unset uses config.desktop.autoUpdate.url.","#DESKTOP_FEED_BASE_URL="),e.mobile&&(s.push("","# Mobile app","# The bundle identifier the native Sign in with Apple token is issued to - it joins","# APPLE_CLIENT_ID in the audience the backend accepts. With the three Apple signing values","# and no APPLE_CLIENT_ID, it alone turns on native-only Sign in with Apple: the iOS app shows","# Apple beside Google (it reads that at runtime) and the web shows no Apple button.","#APPLE_APP_BUNDLE_IDENTIFIER=","# Comma-separated Android signing certificate SHA-256 fingerprints. They feed","# .well-known/assetlinks.json (which verifies your universal links) and the passkey","# Android origins.","#MOBILE_ANDROID_SHA256_FINGERPRINTS=","# Optional. An Expo access token turns on enhanced security for push sends.","#EXPO_ACCESS_TOKEN="),e.mobilePurchases==="revenuecat"&&s.push("","# Mobile store purchases - RevenueCat (server)","# The first two verify incoming webhooks; the third is read by the sync route and the","# nightly reconcile pass.","#REVENUECAT_WEBHOOK_SECRET=","#REVENUECAT_AUTH_HEADER=","#REVENUECAT_API_KEY=")),s.push("","# Build output (optional)","# Next's distDir for apps/web. Unset uses .next; the e2e harness sets its own so a test","# build never overwrites a dev server's.","#NEXT_DIST_DIR="),s.push(""),s.join(`
801
+ `)}var Fn="NEXT_PUBLIC_API_URL";function qo(e){let{apiUrl:t}=Rr(e),r=["# API Configuration",`${Fn}=${t}`];return e.architecture==="separate"&&r.push("","# Production (uncomment and replace with your deployed hostnames):",`# ${Fn}=${Jo}`),r.push(""),r.join(`
802
+ `)}function Xo(e){let{apiUrl:t,baseUrl:r}=Rr(e),n=["# Expo reads env from THIS directory, never the monorepo root.","# Every EXPO_PUBLIC_* value is inlined into the app bundle - never put a secret here.","# Android emulator: replace localhost with 10.0.2.2; a physical device needs your machine's LAN IP","# EXPO_PUBLIC_API_URL is the value to fill first - without it the app throws at launch and names it.",`EXPO_PUBLIC_API_URL=${t}`,`EXPO_PUBLIC_WEB_URL=${r}`,"","# Native Google sign-in (optional)","#EXPO_PUBLIC_GOOGLE_WEB_CLIENT_ID=","#EXPO_PUBLIC_GOOGLE_IOS_CLIENT_ID="];e.mobilePurchases==="revenuecat"&&n.push("","# RevenueCat public SDK keys (optional until you create your products)","#EXPO_PUBLIC_REVENUECAT_IOS_KEY=","#EXPO_PUBLIC_REVENUECAT_ANDROID_KEY=");let i=[];return e.observability.includes("sentry")&&i.push("#EXPO_PUBLIC_SENTRY_DSN="),e.observability.includes("posthog")&&i.push("#EXPO_PUBLIC_POSTHOG_KEY="),i.length>0&&n.push("","# Observability (optional)",...i),n.push(""),n.join(`
803
+ `)}async function Vn(e){let t=qo(e);if(await l(`${e.projectDir}/.env`,`${t}
804
+ ${Un(e,"env")}`),await l(`${e.projectDir}/.env.example`,`${t}
805
+ ${Un(e,"example")}`),e.mobile){let r=Xo(e);await l(`${e.projectDir}/apps/mobile/.env`,r),await l(`${e.projectDir}/apps/mobile/.env.example`,r)}}import{join as Zo}from"path";var Qo=`# Every port is published on 127.0.0.1 only: these development services run with fixed credentials
806
806
  # or none, so nothing else on your network should reach them.
807
- `;async function Vn(e){let t=rt(e),r=[],n=[];if(t.includes("postgres")&&(r.push(` postgres:
807
+ `;async function Bn(e){let t=rt(e),r=[],n=[];if(t.includes("postgres")&&(r.push(` postgres:
808
808
  image: postgres:18-alpine
809
809
  restart: unless-stopped
810
810
  ports:
@@ -839,7 +839,7 @@ ${Mn(e,"example")}`),e.mobile){let r=qo(e);await l(`${e.projectDir}/apps/mobile/
839
839
  - "127.0.0.1:\${MAILPIT_UI_PORT:-8025}:8025"
840
840
  environment:
841
841
  MP_SMTP_AUTH_ACCEPT_ANY: 1
842
- 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:
842
+ MP_SMTP_AUTH_ALLOW_INSECURE: 1`),t.includes("inngest")){let o=e.architecture==="separate"?"http://host.docker.internal:3010/inngest":"http://host.docker.internal:3000/api/inngest";r.push(` inngest:
843
843
  image: inngest/inngest:v1.46.0
844
844
  restart: unless-stopped
845
845
  ports:
@@ -859,34 +859,34 @@ ${Mn(e,"example")}`),e.mobile){let r=qo(e);await l(`${e.projectDir}/apps/mobile/
859
859
  # Linux, which is what \`extra_hosts\` supplies.
860
860
  command: >-
861
861
  inngest dev
862
- -u ${s}
862
+ -u ${o}
863
863
  extra_hosts:
864
- - "host.docker.internal:host-gateway"`)}let o=`name: ${`${e.projectName}-infra`}
864
+ - "host.docker.internal:host-gateway"`)}let s=`name: ${`${e.projectName}-infra`}
865
865
 
866
- ${Zo}services:
866
+ ${Qo}services:
867
867
  ${r.join(`
868
868
 
869
869
  `)}
870
- `;n.length>0&&(o+=`
870
+ `;n.length>0&&(s+=`
871
871
  volumes:
872
872
  ${n.join(`
873
873
  `)}
874
- `),await l(Xo(e.projectDir,"infra/docker-compose.yml"),o)}import{join as Qo}from"path";var At="Next.js";function ea(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:At,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 ta(e){let t=[];return e.architecture==="separate"?t.push({name:`Dev (${At} + Backend + Inngest)`,configurations:["Backend",At,"Inngest"]}):t.push({name:`Dev (${At} + Inngest)`,configurations:[At,"Inngest"]}),t}async function Bn(e){let t={version:"0.2.0",configurations:ea(e),compounds:ta(e)};await l(Qo(e.projectDir,".vscode/launch.json"),`${JSON.stringify(t,null," ")}
875
- `)}import{readFile as Kn}from"fs/promises";import{join as Hn}from"path";var Ir='import { drizzle } from "drizzle-orm/node-postgres";',Tr=`export const db = drizzle(parsed.data.DATABASE_URL, { schema });
876
- export const pool = db.$client;`,ra={postgres:{importLine:Ir,instantiation:Tr},neon:{importLine:`import { Pool } from "@neondatabase/serverless";
874
+ `),await l(Zo(e.projectDir,"infra/docker-compose.yml"),s)}import{join as ea}from"path";var At="Next.js";function ta(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:At,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 ra(e){let t=[];return e.architecture==="separate"?t.push({name:`Dev (${At} + Backend + Inngest)`,configurations:["Backend",At,"Inngest"]}):t.push({name:`Dev (${At} + Inngest)`,configurations:[At,"Inngest"]}),t}async function Gn(e){let t={version:"0.2.0",configurations:ta(e),compounds:ra(e)};await l(ea(e.projectDir,".vscode/launch.json"),`${JSON.stringify(t,null," ")}
875
+ `)}import{readFile as Hn}from"fs/promises";import{join as Yn}from"path";var _r='import { drizzle } from "drizzle-orm/node-postgres";',Or=`export const db = drizzle(parsed.data.DATABASE_URL, { schema });
876
+ export const pool = db.$client;`,na={postgres:{importLine:_r,instantiation:Or},neon:{importLine:`import { Pool } from "@neondatabase/serverless";
877
877
  import { drizzle } from "drizzle-orm/neon-serverless";`,instantiation:`const pool = new Pool({ connectionString: parsed.data.DATABASE_URL });
878
878
  export const db = drizzle(pool, { schema });`},supabase:{importLine:`import { drizzle } from "drizzle-orm/postgres-js";
879
879
  import postgres from "postgres";`,instantiation:`const client = postgres(parsed.data.DATABASE_URL);
880
- export const db = drizzle(client, { schema });`}};async function Yn(e){let t=Hn(e.projectDir,"packages/database/src/index.ts"),r=await Kn(t,"utf-8");if(!r.includes(Ir)||!r.includes(Tr))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=ra[e.databaseProvider],i=r.replace(Ir,n.importLine).replace(Tr,n.instantiation);await l(t,i),await ia(e)}var Gn='import { Client } from "pg";',Rr=` const client = new Client({ connectionString });
880
+ export const db = drizzle(client, { schema });`}};async function Wn(e){let t=Yn(e.projectDir,"packages/database/src/index.ts"),r=await Hn(t,"utf-8");if(!r.includes(_r)||!r.includes(Or))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=na[e.databaseProvider],i=r.replace(_r,n.importLine).replace(Or,n.instantiation);await l(t,i),await sa(e)}var Kn='import { Client } from "pg";',xr=` const client = new Client({ connectionString });
881
881
  await client.connect();
882
882
  return {
883
883
  query: async (text) => ({ rows: (await client.query<LiveColumnRow>(text)).rows }),
884
884
  end: () => client.end()
885
- };`,na={postgres:null,neon:{importLine:'import { Client } from "@neondatabase/serverless";',open:Rr},supabase:{importLine:'import postgres from "postgres";',open:` const sql = postgres(connectionString, { prepare: false });
885
+ };`,ia={postgres:null,neon:{importLine:'import { Client } from "@neondatabase/serverless";',open:xr},supabase:{importLine:'import postgres from "postgres";',open:` const sql = postgres(connectionString, { prepare: false });
886
886
  return {
887
887
  query: async (text) => ({ rows: await sql.unsafe(text) }),
888
888
  end: () => sql.end()
889
- };`}};async function ia(e){let t=na[e.databaseProvider];if(!t)return;let r=Hn(e.projectDir,"packages/database/src/db-verify.ts"),n=await Kn(r,"utf-8");if(!n.includes(Gn)||!n.includes(Rr))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(Gn,t.importLine).replace(Rr,t.open))}import{join as Wn}from"path";async function zn(e){e.cacheProvider==="upstash"&&(await sa(e),await oa(e))}async function sa(e){await l(Wn(e.projectDir,"packages/runtime/src/redis.ts"),`import { Redis } from "@upstash/redis";
889
+ };`}};async function sa(e){let t=ia[e.databaseProvider];if(!t)return;let r=Yn(e.projectDir,"packages/database/src/db-verify.ts"),n=await Hn(r,"utf-8");if(!n.includes(Kn)||!n.includes(xr))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(Kn,t.importLine).replace(xr,t.open))}import{join as zn}from"path";async function Jn(e){e.cacheProvider==="upstash"&&(await oa(e),await aa(e))}async function oa(e){await l(zn(e.projectDir,"packages/runtime/src/redis.ts"),`import { Redis } from "@upstash/redis";
890
890
  import type { Store } from "hono-rate-limiter";
891
891
  import { env } from "./env";
892
892
 
@@ -1098,7 +1098,7 @@ export function subscribeRedisChannel(
1098
1098
 
1099
1099
  /** No persistent connection to close with Upstash REST. */
1100
1100
  export async function closeRedis(): Promise<void> {}
1101
- `)}async function oa(e){await l(Wn(e.projectDir,"packages/runtime/src/mutex.ts"),`import { Lock } from "@upstash/lock";
1101
+ `)}async function aa(e){await l(zn(e.projectDir,"packages/runtime/src/mutex.ts"),`import { Lock } from "@upstash/lock";
1102
1102
  import { redis } from "./redis";
1103
1103
 
1104
1104
  export class MutexTimeoutError extends Error {
@@ -1176,18 +1176,18 @@ export async function withMutex<T>(
1176
1176
  });
1177
1177
  }
1178
1178
  }
1179
- `)}import{readFile as aa}from"fs/promises";import{join as ca}from"path";var Jn=" REDIS_URL: z.string(),",la=` UPSTASH_REDIS_REST_URL: z.string(),
1180
- UPSTASH_REDIS_REST_TOKEN: z.string(),`;async function qn(e){let t=ca(e.projectDir,"packages/runtime/src/env.ts"),r=await aa(t,"utf-8");if(!r.includes(Jn))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(Jn,la):r;await l(t,n)}import{existsSync as Aa}from"fs";import{readFile as ni}from"fs/promises";import{join as j}from"path";import{readFile as xr,rm as fa}from"fs/promises";import{join as He}from"path";import{AsyncLocalStorage as pa}from"async_hooks";import{existsSync as Xn}from"fs";import{readFile as _r,rm as da}from"fs/promises";import{join as ua}from"path";var Or=new pa;async function Zn(e){let t=[];return await Or.run(t,e),t}async function Be(e,t){let r=Or.getStore();if(!r)return t();try{await t()}catch(n){r.push(`${e}: ${n instanceof Error?n.message:String(n)}`)}}function pt(e,t,r){let n=Or.getStore();if(!n)throw new Error(r);n.push(`${e}: ${t}`)}async function S(e,t,r){let n=ua(e,t);if(!Xn(n)){pt(r,t,`${r}: expected ${t} to exist, but it was missing (boilerplate drift).`);return}await da(n,{recursive:!0})}async function Kt(e,t,r){return Xn(e)?_r(e,"utf-8"):(pt(r,t,`${r}: expected ${e} to carry the ${t} seam, but the file is missing (boilerplate drift).`),null)}function ma(e){return new RegExp(`^[ \\t]*(?:\\/\\/|\\{\\/\\*|\\*) gsaas:${e}-start(?: \\*\\/\\})?[ \\t]*\\r?\\n[\\s\\S]*?^[ \\t]*(?:\\/\\/|\\{\\/\\*|\\*) gsaas:${e}-end(?: \\*\\/\\})?[ \\t]*\\r?\\n`,"gm")}function Ge(e,t,r,n){let i=ma(r);if(e.match(i)===null)return pt(n,`${r} markers in ${t}`,`${n}: expected gsaas ${r} markers in ${t}, but found none (boilerplate drift).`),e;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,`
1179
+ `)}import{readFile as ca}from"fs/promises";import{join as la}from"path";var qn=" REDIS_URL: z.string(),",pa=` UPSTASH_REDIS_REST_URL: z.string(),
1180
+ UPSTASH_REDIS_REST_TOKEN: z.string(),`;async function Xn(e){let t=la(e.projectDir,"packages/runtime/src/env.ts"),r=await ca(t,"utf-8");if(!r.includes(qn))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(qn,pa):r;await l(t,n)}import{existsSync as Ia}from"fs";import{readFile as ii}from"fs/promises";import{join as j}from"path";import{readFile as Cr,rm as ga}from"fs/promises";import{join as He}from"path";import{AsyncLocalStorage as da}from"async_hooks";import{existsSync as Zn}from"fs";import{readFile as Dr,rm as ua}from"fs/promises";import{join as ma}from"path";var Nr=new da;async function Qn(e){let t=[];return await Nr.run(t,e),t}async function Be(e,t){let r=Nr.getStore();if(!r)return t();try{await t()}catch(n){r.push(`${e}: ${n instanceof Error?n.message:String(n)}`)}}function pt(e,t,r){let n=Nr.getStore();if(!n)throw new Error(r);n.push(`${e}: ${t}`)}async function S(e,t,r){let n=ma(e,t);if(!Zn(n)){pt(r,t,`${r}: expected ${t} to exist, but it was missing (boilerplate drift).`);return}await ua(n,{recursive:!0})}async function Kt(e,t,r){return Zn(e)?Dr(e,"utf-8"):(pt(r,t,`${r}: expected ${e} to carry the ${t} seam, but the file is missing (boilerplate drift).`),null)}function ha(e){return new RegExp(`^[ \\t]*(?:\\/\\/|\\{\\/\\*|\\*) gsaas:${e}-start(?: \\*\\/\\})?[ \\t]*\\r?\\n[\\s\\S]*?^[ \\t]*(?:\\/\\/|\\{\\/\\*|\\*) gsaas:${e}-end(?: \\*\\/\\})?[ \\t]*\\r?\\n`,"gm")}function Ge(e,t,r,n){let i=ha(r);if(e.match(i)===null)return pt(n,`${r} markers in ${t}`,`${n}: expected gsaas ${r} markers in ${t}, but found none (boilerplate drift).`),e;let s=e.replace(i,"");if(s.includes(`gsaas:${r}-start`)||s.includes(`gsaas:${r}-end`))throw new Error(`${n}: an unbalanced gsaas ${r} marker is left in ${t} (boilerplate drift).`);return s.replace(/\n{3,}/g,`
1181
1181
 
1182
- `).replace(/,(\r?\n[ \t]*[\]})])/g,"$1")}async function A(e,t,r,n,i){let o=await Kt(e,n,i);if(o===null)return;let s=o.indexOf(t);if(s===-1){pt(i,n,`${i}: expected to find the ${n} seam, but it was missing (boilerplate drift).`);return}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 Ke(e,t,r,n){let i=/\n([\t ]+)"/.exec(await _r(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)}
1183
- `)}function ha(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]!==`
1182
+ `).replace(/,(\r?\n[ \t]*[\]})])/g,"$1")}async function A(e,t,r,n,i){let s=await Kt(e,n,i);if(s===null)return;let o=s.indexOf(t);if(o===-1){pt(i,n,`${i}: expected to find the ${n} seam, but it was missing (boilerplate drift).`);return}if(s.includes(t,o+t.length))throw new Error(`${i}: the ${n} seam appears more than once (boilerplate drift).`);await l(e,s.slice(0,o)+r+s.slice(o+t.length))}async function Ke(e,t,r,n){let i=/\n([\t ]+)"/.exec(await Dr(e,"utf-8"))?.[1];if(i!==r){let s=o=>o===" "?"tab":`${o.length}-space`;throw new Error(`${n}: expected ${e} to be ${s(r)}-indented, but it is ${i===void 0?"not indented":s(i)}-indented (boilerplate drift). Re-serializing it with the wrong indent would reformat the whole file.`)}await l(e,`${JSON.stringify(t,null,r)}
1183
+ `)}function fa(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]!==`
1184
1184
  `;)r++;continue}if(n==="/"&&i==="*"){for(r+=2;r<e.length&&!(e[r]==="*"&&e[r+1]==="/");)e[r]===`
1185
1185
  `&&(t+=`
1186
- `),r++;r+=2;continue}if(n==='"'||n==="'"||n==="`"){let o=n;for(r++;r<e.length&&e[r]!==o;)e[r]==="\\"?r++:e[r]===`
1186
+ `),r++;r+=2;continue}if(n==='"'||n==="'"||n==="`"){let s=n;for(r++;r<e.length&&e[r]!==s;)e[r]==="\\"?r++:e[r]===`
1187
1187
  `&&(t+=`
1188
- `),r++;r++;continue}t+=n,r++}return t}async function Qn(e){let t=`import { config } from "@repo/config";
1189
- `,r=await _r(e,"utf-8");if(!r.includes(t))return;let n=r.replace(t,""),i=ha(n);/\bconfig\b/.test(i)||await l(e,n)}var Ye="stripMobileObservability",ei=["apps/mobile/lib/observability.ts","apps/mobile/types/env.d.ts","apps/mobile/tests/settings-privacy-screen.test.tsx"],ti="apps/mobile/tests/observability.test.ts",ga="mobile-obs-any",ya=["apps/mobile/tests/settings-privacy-screen.test.tsx"],Ht={sentry:["@sentry/react-native","@sentry/cli"],posthog:[]},ba=`,
1190
- ...sentryExpoPlugin()`,wa=["apps/mobile/app.config.ts"],va="|@sentry/react-native",ka=" * DUAL-PROVIDER, the way `packages/observability` is. This repo carries the Sentry and the PostHog\n * halves at once so dev and the test suite exercise both. A generated project carries only the\n * providers its `observability` manifest option names: the CLI removes the other one's marked region\n * from this file and, for Sentry, its SDK from `apps/mobile/package.json` and its Expo config plugin\n * from `app.config.ts`. PostHog's SDK stays whatever this choice says, because product analytics\n * (`lib/product-analytics.ts`) runs on it too. Otherwise this is the same \"an unselected provider\n * costs nothing\" contract the server, the browser and the desktop app already keep.\n *\n * THE RULE THAT KEEPS THAT WORKING: a surviving region may never reference a stripped one. Every\n * cross-provider `{@link}` and every paragraph about one provider's credentials sits INSIDE that\n * provider's own region, and what is left between them is provider-neutral - the {@link PROVIDERS}\n * list and the two exported entry points that walk it, which is what a project generated with\n * `observability: []` keeps and starts nothing with.",Ea='import { readPrivacySettings, type PrivacySettings } from "@/lib/privacy";',Sa='import type { PrivacySettings } from "@/lib/privacy";';function Pa(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
1188
+ `),r++;r++;continue}t+=n,r++}return t}async function ei(e){let t=`import { config } from "@repo/config";
1189
+ `,r=await Dr(e,"utf-8");if(!r.includes(t))return;let n=r.replace(t,""),i=fa(n);/\bconfig\b/.test(i)||await l(e,n)}var Ye="stripMobileObservability",ti=["apps/mobile/lib/observability.ts","apps/mobile/types/env.d.ts","apps/mobile/tests/settings-privacy-screen.test.tsx"],ri="apps/mobile/tests/observability.test.ts",ya="mobile-obs-any",ba=["apps/mobile/tests/settings-privacy-screen.test.tsx"],Ht={sentry:["@sentry/react-native","@sentry/cli"],posthog:[]},wa=`,
1190
+ ...sentryExpoPlugin()`,va=["apps/mobile/app.config.ts"],ka="|@sentry/react-native",Ea=" * DUAL-PROVIDER, the way `packages/observability` is. This repo carries the Sentry and the PostHog\n * halves at once so dev and the test suite exercise both. A generated project carries only the\n * providers its `observability` manifest option names: the CLI removes the other one's marked region\n * from this file and, for Sentry, its SDK from `apps/mobile/package.json` and its Expo config plugin\n * from `app.config.ts`. PostHog's SDK stays whatever this choice says, because product analytics\n * (`lib/product-analytics.ts`) runs on it too. Otherwise this is the same \"an unselected provider\n * costs nothing\" contract the server, the browser and the desktop app already keep.\n *\n * THE RULE THAT KEEPS THAT WORKING: a surviving region may never reference a stripped one. Every\n * cross-provider `{@link}` and every paragraph about one provider's credentials sits INSIDE that\n * provider's own region, and what is left between them is provider-neutral - the {@link PROVIDERS}\n * list and the two exported entry points that walk it, which is what a project generated with\n * `observability: []` keeps and starts nothing with.",Sa='import { readPrivacySettings, type PrivacySettings } from "@/lib/privacy";',Pa='import type { PrivacySettings } from "@/lib/privacy";';function Aa(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
1191
1191
  * and no reporting SDK: {@link PROVIDERS} is empty, and both functions below are no-ops that load
1192
1192
  * nothing and send nothing.`:` * This app reports to ${t}. No other provider's start or Expo config plugin was generated,
1193
1193
  * so there is nothing here for Metro to fold away.`}
@@ -1195,8 +1195,8 @@ export async function withMutex<T>(
1195
1195
  * To change providers, edit \`observability\` in .generatesaas/manifest.json and run
1196
1196
  * \`generatesaas update\`: re-shaping brings that provider's half of this file, its SDK and its env
1197
1197
  * key back. Pasting the other provider's credential into \`config.observability\` on its own cannot -
1198
- * the start it would need is not here.`}async function ri(e){if(!e.mobile)return;let t=e.projectDir,r=["sentry","posthog"].filter(o=>!e.observability.includes(o));e.observability.length===0&&await fa(He(t,ti),{force:!0});let n=e.observability.length===0?ei:[...ei,ti];for(let o of r)for(let s of n){let a=He(t,s);await l(a,Ge(await xr(a,"utf-8"),s,`mobile-obs-${o}`,Ye))}if(e.observability.length===0)for(let o of ya){let s=He(t,o);await l(s,Ge(await xr(s,"utf-8"),o,ga,Ye))}if(r.includes("sentry")){for(let o of wa){let s=He(t,o);await l(s,Ge(await xr(s,"utf-8"),o,"mobile-obs-sentry",Ye))}await A(He(t,"apps/mobile/app.config.ts"),ba,"","app.config.ts Sentry Expo plugin",Ye),await A(He(t,"apps/mobile/jest.config.js"),va,"","jest.config.js Sentry transform allowance",Ye)}let i=He(t,"apps/mobile/lib/observability.ts");await A(i,ka,Pa(e.observability),"lib/observability.ts dual-provider note",Ye),e.observability.length===0&&(await A(i,Ea,Sa,"lib/observability.ts privacy import",Ye),await Qn(i))}var dt={"@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 ni(e,"utf-8");return JSON.parse(t)}async function ie(e,t){let r=/\n([\t ]+)"/.exec(await ni(e,"utf-8"))?.[1]??" ";await l(e,`${JSON.stringify(t,null,r)}
1199
- `)}function X(e,t){for(let r of t)delete e.dependencies?.[r],delete e.devDependencies?.[r]}function Ia(e){e.dependencies&&Object.keys(e.dependencies).length===0&&delete e.dependencies,e.devDependencies&&Object.keys(e.devDependencies).length===0&&delete e.devDependencies}function We(e,t,r,n=!1){let i=n?"devDependencies":"dependencies";e[i]||(e[i]={}),e[i][t]=r}async function ii(e){await Ra(e),await _a(e),await Oa(e),await Ca(e),await La(e),await Ga(e),await Ta(e)}async function Ta(e){if(!e.mobile){let t=j(e.projectDir,"packages/auth/package.json"),r=await ne(t);X(r,["@better-auth/expo"]),await ie(t,r);let n=j(e.projectDir,"tooling/styles/package.json"),i=await ne(n);X(i,["tsx"]),Ia(i),await ie(n,i)}if(e.mobile&&e.mobilePurchases!=="revenuecat"){let t=j(e.projectDir,"apps/mobile/package.json"),r=await ne(t);X(r,["react-native-purchases","react-native-purchases-ui"]),await ie(t,r)}}async function Ra(e){let t=j(e.projectDir,"packages/api/package.json"),r=await ne(t);X(r,["sharp","@types/sharp"]),e.cacheProvider==="upstash"&&(X(r,["ioredis"]),We(r,"@upstash/redis",dt["@upstash/redis"],!0),We(r,"@upstash/lock",dt["@upstash/lock"],!0)),await ie(t,r)}async function _a(e){let t=j(e.projectDir,"apps/web/package.json"),r=await ne(t);X(r,["@upstash/ratelimit","@upstash/redis"]),await ie(t,r)}async function Oa(e){let t=j(e.projectDir,"packages/runtime/package.json"),r=await ne(t);e.cacheProvider==="upstash"&&(X(r,["ioredis","rate-limit-redis","redis-semaphore"]),We(r,"@upstash/redis",dt["@upstash/redis"]),We(r,"@upstash/lock",dt["@upstash/lock"])),await ie(t,r)}var Dr={sentry:["@sentry/node","@sentry/browser","@sentry/electron"],posthog:["posthog-node","posthog-js"]},xa=["@sentry/electron"],Da=[...Dr.sentry,...Dr.posthog],Na=[...Ht.sentry,...Ht.posthog];async function Ca(e){let t=j(e.projectDir,"packages/observability/package.json"),r=await ne(t),n=new Set(e.observability.flatMap(a=>Dr[a]));if(!e.desktop)for(let a of xa)n.delete(a);if(X(r,Da.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=>Ht[a]));X(o,Na.filter(a=>!s.has(a))),await ie(i,o)}async function La(e){let t=j(e.projectDir,"packages/database/package.json"),r=await ne(t);e.databaseProvider==="neon"?(X(r,["pg","@types/pg"]),We(r,"@neondatabase/serverless",dt["@neondatabase/serverless"])):e.databaseProvider==="supabase"&&(X(r,["pg","@types/pg"]),We(r,"postgres",dt.postgres)),await ie(t,r)}var $a=["app/.well-known/oauth-authorization-server/[[...path]]/route.ts","app/.well-known/oauth-protected-resource/[[...path]]/route.ts"],ja="app/.well-known/api-catalog/route.ts",Ma=`import { agentsConfig } from "@repo/config";
1198
+ * the start it would need is not here.`}async function ni(e){if(!e.mobile)return;let t=e.projectDir,r=["sentry","posthog"].filter(s=>!e.observability.includes(s));e.observability.length===0&&await ga(He(t,ri),{force:!0});let n=e.observability.length===0?ti:[...ti,ri];for(let s of r)for(let o of n){let a=He(t,o);await l(a,Ge(await Cr(a,"utf-8"),o,`mobile-obs-${s}`,Ye))}if(e.observability.length===0)for(let s of ba){let o=He(t,s);await l(o,Ge(await Cr(o,"utf-8"),s,ya,Ye))}if(r.includes("sentry")){for(let s of va){let o=He(t,s);await l(o,Ge(await Cr(o,"utf-8"),s,"mobile-obs-sentry",Ye))}await A(He(t,"apps/mobile/app.config.ts"),wa,"","app.config.ts Sentry Expo plugin",Ye),await A(He(t,"apps/mobile/jest.config.js"),ka,"","jest.config.js Sentry transform allowance",Ye)}let i=He(t,"apps/mobile/lib/observability.ts");await A(i,Ea,Aa(e.observability),"lib/observability.ts dual-provider note",Ye),e.observability.length===0&&(await A(i,Sa,Pa,"lib/observability.ts privacy import",Ye),await ei(i))}var dt={"@upstash/redis":"^1.37.0","@upstash/lock":"^0.2.1","@neondatabase/serverless":"^1.0.1",postgres:"^3.4.7"};async function ie(e){let t=await ii(e,"utf-8");return JSON.parse(t)}async function se(e,t){let r=/\n([\t ]+)"/.exec(await ii(e,"utf-8"))?.[1]??" ";await l(e,`${JSON.stringify(t,null,r)}
1199
+ `)}function X(e,t){for(let r of t)delete e.dependencies?.[r],delete e.devDependencies?.[r]}function Ta(e){e.dependencies&&Object.keys(e.dependencies).length===0&&delete e.dependencies,e.devDependencies&&Object.keys(e.devDependencies).length===0&&delete e.devDependencies}function We(e,t,r,n=!1){let i=n?"devDependencies":"dependencies";e[i]||(e[i]={}),e[i][t]=r}async function si(e){await _a(e),await Oa(e),await xa(e),await La(e),await $a(e),await Ka(e),await Ra(e)}async function Ra(e){if(!e.mobile){let t=j(e.projectDir,"packages/auth/package.json"),r=await ie(t);X(r,["@better-auth/expo"]),await se(t,r);let n=j(e.projectDir,"tooling/styles/package.json"),i=await ie(n);X(i,["tsx"]),Ta(i),await se(n,i)}if(e.mobile&&e.mobilePurchases!=="revenuecat"){let t=j(e.projectDir,"apps/mobile/package.json"),r=await ie(t);X(r,["react-native-purchases","react-native-purchases-ui"]),await se(t,r)}}async function _a(e){let t=j(e.projectDir,"packages/api/package.json"),r=await ie(t);X(r,["sharp","@types/sharp"]),e.cacheProvider==="upstash"&&(X(r,["ioredis"]),We(r,"@upstash/redis",dt["@upstash/redis"],!0),We(r,"@upstash/lock",dt["@upstash/lock"],!0)),await se(t,r)}async function Oa(e){let t=j(e.projectDir,"apps/web/package.json"),r=await ie(t);X(r,["@upstash/ratelimit","@upstash/redis"]),await se(t,r)}async function xa(e){let t=j(e.projectDir,"packages/runtime/package.json"),r=await ie(t);e.cacheProvider==="upstash"&&(X(r,["ioredis","rate-limit-redis","redis-semaphore"]),We(r,"@upstash/redis",dt["@upstash/redis"]),We(r,"@upstash/lock",dt["@upstash/lock"])),await se(t,r)}var Lr={sentry:["@sentry/node","@sentry/browser","@sentry/electron"],posthog:["posthog-node","posthog-js"]},Da=["@sentry/electron"],Na=[...Lr.sentry,...Lr.posthog],Ca=[...Ht.sentry,...Ht.posthog];async function La(e){let t=j(e.projectDir,"packages/observability/package.json"),r=await ie(t),n=new Set(e.observability.flatMap(a=>Lr[a]));if(!e.desktop)for(let a of Da)n.delete(a);if(X(r,Na.filter(a=>!n.has(a))),await se(t,r),!e.mobile)return;let i=j(e.projectDir,"apps/mobile/package.json"),s=await ie(i),o=new Set(e.observability.flatMap(a=>Ht[a]));X(s,Ca.filter(a=>!o.has(a))),await se(i,s)}async function $a(e){let t=j(e.projectDir,"packages/database/package.json"),r=await ie(t);e.databaseProvider==="neon"?(X(r,["pg","@types/pg"]),We(r,"@neondatabase/serverless",dt["@neondatabase/serverless"])):e.databaseProvider==="supabase"&&(X(r,["pg","@types/pg"]),We(r,"postgres",dt.postgres)),await se(t,r)}var ja=["app/.well-known/oauth-authorization-server/[[...path]]/route.ts","app/.well-known/oauth-protected-resource/[[...path]]/route.ts","app/.well-known/ai-catalog.json/route.ts"],Ma="app/.well-known/api-catalog/route.ts",Ua=`import { agentsConfig } from "@repo/config";
1200
1200
 
1201
1201
  /**
1202
1202
  * RFC 9727 API catalog. A client resolves \`/.well-known/*\` against the SITE ROOT; in this
@@ -1212,8 +1212,8 @@ export function GET(): Response {
1212
1212
  308
1213
1213
  );
1214
1214
  }
1215
- `;async function Ua(e){let t=j(e,ja);if(!Aa(t))throw new Error(`generateDependencies: ${t} is missing; the boilerplate drifted.`);await l(t,Ma)}async function Fa(e){let t=await ne(e),r=t.dependencies?.["@repo/api"];r&&(delete t.dependencies?.["@repo/api"],We(t,"@repo/api",r,!0),await ie(e,t))}var Va=["instrumentation.ts","tests/instrumentation.test.ts"],Ba="tests/api-trailing-slash.test.ts";async function Ga(e){if(e.architecture!=="separate")return;let t=j(e.projectDir,"apps/web");await Ve(j(t,"app/api/[[...rest]]/route.ts"),t),await Ve(j(t,Ba),t);for(let r of $a)await Ve(j(t,r),t);for(let r of Va)await Ve(j(t,r),t);await Ua(t),await Fa(j(t,"package.json"))}import{readFile as Ka}from"fs/promises";import{join as Ha}from"path";var Ya=["base.json","node.json","next.json"],si="GenerateSaaS ";async function oi(e){if(!e.demo)for(let t of Ya){let r=Ha(e.projectDir,"tooling/typescript",t),n;try{n=await Ka(r,"utf-8")}catch{continue}let i=JSON.parse(n);typeof i.display!="string"||!i.display.startsWith(si)||(i.display=i.display.slice(si.length),await l(r,`${JSON.stringify(i,null," ")}
1216
- `))}}import{readFile as li,rm as Wa}from"fs/promises";import{join as It}from"path";async function pi(e){e.cacheProvider==="upstash"&&(await Promise.all([ai(It(e.projectDir,"packages/runtime/tests/setup.ts")),ai(It(e.projectDir,"packages/mail/tests/setup.ts")),Ja(e.projectDir),Wa(It(e.projectDir,"packages/runtime/tests/redis.test.ts"),{force:!0})]),await za(e.projectDir))}async function za(e){await l(It(e,"packages/runtime/tests/redis.test.ts"),`import { beforeEach, describe, expect, it, vi } from "vitest";
1215
+ `;async function Fa(e){let t=j(e,Ma);if(!Ia(t))throw new Error(`generateDependencies: ${t} is missing; the boilerplate drifted.`);await l(t,Ua)}async function Va(e){let t=await ie(e),r=t.dependencies?.["@repo/api"];r&&(delete t.dependencies?.["@repo/api"],We(t,"@repo/api",r,!0),await se(e,t))}var Ba=["instrumentation.ts","tests/instrumentation.test.ts"],Ga="tests/api-trailing-slash.test.ts";async function Ka(e){if(e.architecture!=="separate")return;let t=j(e.projectDir,"apps/web");await Ve(j(t,"app/api/[[...rest]]/route.ts"),t),await Ve(j(t,Ga),t);for(let r of ja)await Ve(j(t,r),t);for(let r of Ba)await Ve(j(t,r),t);await Fa(t),await Va(j(t,"package.json"))}import{readFile as Ha}from"fs/promises";import{join as Ya}from"path";var Wa=["base.json","node.json","next.json"],oi="GenerateSaaS ";async function ai(e){if(!e.demo)for(let t of Wa){let r=Ya(e.projectDir,"tooling/typescript",t),n;try{n=await Ha(r,"utf-8")}catch{continue}let i=JSON.parse(n);typeof i.display!="string"||!i.display.startsWith(oi)||(i.display=i.display.slice(oi.length),await l(r,`${JSON.stringify(i,null," ")}
1216
+ `))}}import{readFile as pi,rm as za}from"fs/promises";import{join as It}from"path";async function di(e){e.cacheProvider==="upstash"&&(await Promise.all([ci(It(e.projectDir,"packages/runtime/tests/setup.ts")),ci(It(e.projectDir,"packages/mail/tests/setup.ts")),qa(e.projectDir),za(It(e.projectDir,"packages/runtime/tests/redis.test.ts"),{force:!0})]),await Ja(e.projectDir))}async function Ja(e){await l(It(e,"packages/runtime/tests/redis.test.ts"),`import { beforeEach, describe, expect, it, vi } from "vitest";
1217
1217
 
1218
1218
  /**
1219
1219
  * Regression guards for the Upstash-backed cache layer in src/redis.ts.
@@ -1346,9 +1346,9 @@ describe("pub/sub", () => {
1346
1346
  expect(() => stop()).not.toThrow();
1347
1347
  });
1348
1348
  });
1349
- `)}async function ai(e){let t;try{t=await li(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",
1349
+ `)}async function ci(e){let t;try{t=await pi(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",
1350
1350
  UPSTASH_REDIS_REST_TOKEN: "test-token",
1351
- `);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 fe="ioredisCounters",ci="COUNT_UNDER_LIMIT_SCRIPT";async function Ja(e){let t=It(e,"packages/api/tests/setup.ts"),r;try{r=await li(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",
1351
+ `);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 fe="ioredisCounters",li="COUNT_UNDER_LIMIT_SCRIPT";async function qa(e){let t=It(e,"packages/api/tests/setup.ts"),r;try{r=await pi(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",
1352
1352
  UPSTASH_REDIS_REST_TOKEN: "test-token",
1353
1353
  `),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",
1354
1354
  UPSTASH_REDIS_REST_TOKEN: "test-token",
@@ -1373,7 +1373,7 @@ describe("pub/sub", () => {
1373
1373
  pttl = vi.fn().mockResolvedValue(-1);
1374
1374
  scan = vi.fn().mockResolvedValue(["0", []]);
1375
1375
  eval = vi.fn(async (script: string, keys: string[], args: (string | number)[]) => {
1376
- if (script !== ${ci}) return null;
1376
+ if (script !== ${li}) return null;
1377
1377
  const key = String(keys[0]);
1378
1378
  const limit = Number(args[0]);
1379
1379
  const next = (${fe}.get(key) ?? 0) + 1;
@@ -1393,33 +1393,33 @@ vi.mock("@upstash/lock", () => {
1393
1393
  return { Lock };
1394
1394
  });
1395
1395
 
1396
- `;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 ${fe} = new Map`,`${ci},`,`${fe}.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 qa}from"fs/promises";var Xa=/^[ \t]*(?:\/\/|\{\/\*|\*) gsaas:[a-z0-9-]+-(?:start|end)(?: \*\/\})?[ \t]*\r?\n/gm,Za=new Set([".ts",".tsx",".mjs",".js",".jsx",".md",".mdx"]),di=32;function Qa(e){let t=e.lastIndexOf(".");return t>=0&&Za.has(e.slice(t))}async function ec(e){let t=await qa(e,"utf-8");if(!t.includes("gsaas:"))return;let r=t.replace(Xa,"");r!==t&&await l(e,r)}async function ui(e){let t=await q(e.projectDir,e.projectDir,r=>r==="node_modules"||r.startsWith("node_modules/")||r===".git"||r.startsWith(".git/"),Qa);for(let r=0;r<t.length;r+=di)await Promise.all(t.slice(r,r+di).map(ec))}import{existsSync as tc}from"fs";import{readdir as ut,readFile as ge,rm as Ie}from"fs/promises";import{join as m}from"path";var rc=new Set(["ci.yml","desktop-release.yml","mobile-release.yml"]),nc=["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"],ic=["packages/auth/src/config.ts","packages/api/src/routes/internal/index.ts","packages/api/src/index.ts"],sc=["packages/api/src/routes/internal/index.ts","packages/api/src/routes/inngest.ts","packages/notifications/src/index.ts","packages/config/src/cache.ts"],oc=["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"],ac=["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"],cc=["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"],lc=["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"],pc=[{dir:"apps/mobile/components/billing",prefixes:["paywall","credit-packs","store-"]},{dir:"apps/mobile/tests",prefixes:["purchases-"]}],dc=["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"],uc=[","," {",' 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(`
1397
- `),mc=[["## 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(`
1396
+ `;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 s of['vi.mock("ioredis"','vi.mock("rate-limit-redis"',"REDIS_URL:"])if(n.includes(s))throw new Error(`pruneCacheTests: ${t} still contains ${s} after the Upstash swap (boilerplate drift).`);for(let s of[`const ${fe} = new Map`,`${li},`,`${fe}.clear()`])if(!n.includes(s))throw new Error(`pruneCacheTests: ${t} no longer contains ${s}, which the Upstash mock relies on (boilerplate drift).`);await l(t,n)}import{readFile as Xa}from"fs/promises";var Za=/^[ \t]*(?:\/\/|\{\/\*|\*) gsaas:[a-z0-9-]+-(?:start|end)(?: \*\/\})?[ \t]*\r?\n/gm,Qa=new Set([".ts",".tsx",".mjs",".js",".jsx",".md",".mdx"]),ui=32;function ec(e){let t=e.lastIndexOf(".");return t>=0&&Qa.has(e.slice(t))}async function tc(e){let t=await Xa(e,"utf-8");if(!t.includes("gsaas:"))return;let r=t.replace(Za,"");r!==t&&await l(e,r)}async function mi(e){let t=await q(e.projectDir,e.projectDir,r=>r==="node_modules"||r.startsWith("node_modules/")||r===".git"||r.startsWith(".git/"),ec);for(let r=0;r<t.length;r+=ui)await Promise.all(t.slice(r,r+ui).map(tc))}import{existsSync as rc}from"fs";import{readdir as ut,readFile as ge,rm as Ie}from"fs/promises";import{join as m}from"path";var nc=new Set(["ci.yml","desktop-release.yml","mobile-release.yml"]),ic=["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"],sc=["packages/auth/src/config.ts","packages/api/src/routes/internal/index.ts","packages/api/src/index.ts"],oc=["packages/api/src/routes/internal/index.ts","packages/api/src/routes/inngest.ts","packages/notifications/src/index.ts","packages/config/src/cache.ts"],ac=["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"],cc=["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"],lc=["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"],pc=["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"],dc=[{dir:"apps/mobile/components/billing",prefixes:["paywall","credit-packs","store-"]},{dir:"apps/mobile/tests",prefixes:["purchases-"]}],uc=["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"],mc=[","," {",' 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(`
1397
+ `),hc=[["## 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(`
1398
1398
  `),["#### 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(`
1399
1399
  `),["#### 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(`
1400
- `)],hc=["apps/web/app/[locale]/(marketing)/download","apps/web/tests/routes/download-page.test.tsx"],fc=["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 mi(e){let t=m(e.projectDir,".github/workflows"),r=await ut(t).catch(()=>[]);for(let n of r)rc.has(n)||await Ie(m(t,n),{recursive:!0,force:!0})}async function gc(e,t){let r=m(e,"package.json"),n=JSON.parse(await ge(r,"utf-8"));if(!n.scripts)return;let i=!1;for(let s of t)s in n.scripts&&(delete n.scripts[s],i=!0);if(!i)return;let o=/\n([\t ]+)"/.exec(await ge(r,"utf-8"))?.[1]??" ";await l(r,`${JSON.stringify(n,null,o)}
1401
- `)}async function hi(e){await gc(e.projectDir,[...fc])}async function fi(e){let t=m(e.projectDir,"package.json"),r=await ge(t,"utf-8"),n=JSON.parse(r);!n.scripts||!("dev"in n.scripts)||(n.scripts.dev=e.architecture==="separate"?"turbo run dev --continue":"turbo run dev --continue --filter=!backend",await l(t,`${JSON.stringify(n,null," ")}
1402
- `))}async function gi(e){let t=m(e.projectDir,"package.json"),r=JSON.parse(await ge(t,"utf-8")),n=r.scripts?.test;if(n!=="turbo run test --concurrency=2 && vitest run")throw new Error(`rewriteRootTestScript: expected the root test script to be "turbo run test --concurrency=2 && vitest run", got ${JSON.stringify(n)} (boilerplate drift).`);r.scripts.test="turbo run test --concurrency=2",await l(t,`${JSON.stringify(r,null," ")}
1403
- `)}async function yi(e){e.docs||await S(e.projectDir,"apps/docs","stripDocsApp")}async function bi(e){let t=m(e.projectDir,"docs/(platform)/meta.json"),r=JSON.parse(await ge(t,"utf-8"));if(r.title!=="GenerateSaaS")throw new Error(`stripUnusedDocsSilo: expected the feature-page group to be titled "GenerateSaaS", found ${JSON.stringify(r.title)} (boilerplate drift).`);r.title=e.appName,await Ke(t,r," ","stripUnusedDocsSilo"),e.desktop||await Ie(m(e.projectDir,"docs/desktop"),{recursive:!0,force:!0}),e.mobile||await Ie(m(e.projectDir,"docs/mobile"),{recursive:!0,force:!0}),await yc(e),await Ec(e)}async function V(e,t,r,n){let i=await Kt(e,t,n);i!==null&&await l(e,Ge(i,t,r,n))}async function yc(e){let t=e.projectDir,r="stripUnusedDocsSilo",n=m(t,"docs/(platform)/configuration.mdx"),i=e.desktop;e.desktop||(await A(n,"| Desktop app + device sign-in - see [desktop app](/desktop) |","| Desktop app + device sign-in |","configuration.mdx desktop config-table link",r),await V(n,"configuration.mdx desktop TRUSTED_ORIGINS callout","desktop-origins-docs",r),await A(m(t,"docs/cli/init.mdx"),"the [desktop app](/desktop), AI features","the desktop app, AI features","cli init.mdx desktop app link",r),await V(m(t,"docs/(platform)/payments/organizations.mdx"),"payments organizations.mdx desktop tenancy callout","desktop-tenancy-docs",r),await V(m(t,"docs/(platform)/projects.mdx"),"projects.mdx desktop scoping callout","desktop-projects-docs",r),await V(m(t,"docs/(platform)/client-architecture.mdx"),"client-architecture.mdx desktop card","desktop-architecture-docs",r),await V(m(t,"docs/(platform)/screens.mdx"),"screens.mdx desktop halves","screens-desktop-docs",r),await V(m(t,"docs/(platform)/testing/e2e.mdx"),"testing/e2e.mdx desktop e2e callout","desktop-testing-docs",r),await A(m(t,"docs/(platform)/index.mdx"),` <Card href="/desktop" title="Desktop app" description="Cross-platform desktop app with device sign-in and AI agents." />
1404
- `,"","index.mdx desktop app card",r),await V(m(t,"docs/(platform)/ai.mdx"),"ai.mdx automation lanes row + section","desktop-lanes-docs",r),await A(m(t,"docs/(platform)/ai.mdx"),"| Creating or changing an automation on the user's computer (desktop) | `create_local_automation`, an `update_local_automation` beyond a rename or a pause, `delete_local_automation` ([how](/desktop/ai#what-runs-and-where)) | No |\n","","ai.mdx device-automation approval row",r)),i||(await V(n,"configuration.mdx desktop-AI paragraph","desktop-ai-docs",r),await A(m(t,"docs/(platform)/navigation.mdx"),"gates the desktop app's Chat and Automations, see [desktop AI](/desktop/ai) |","gates the desktop app's Chat and Automations |","navigation.mdx sidebar-flag agents-row link",r))}async function wi(e){if(e.desktop)return;await S(e.projectDir,"apps/desktop","stripDesktopApp");let t=m(e.projectDir,"packages/i18n/translations");for(let i of await ut(t,{withFileTypes:!0}))i.isDirectory()&&await Ie(m(t,i.name,"desktop.json"),{force:!0});await S(e.projectDir,".github/workflows/desktop-release.yml","stripDesktopApp");for(let i of hc)await S(e.projectDir,i,"stripDesktopApp");await S(e.projectDir,"packages/utils/src/desktop-download.ts","stripDesktopApp"),await S(e.projectDir,"packages/utils/tests/desktop-download.test.ts","stripDesktopApp");let r=m(e.projectDir,"packages/utils/package.json"),n=JSON.parse(await ge(r,"utf-8"));if(!n.exports?.["./desktop-download"])throw new Error("stripDesktopApp: expected packages/utils/package.json to carry the ./desktop-download export");delete n.exports["./desktop-download"],await Ke(r,n," ","stripDesktopApp")}function bc(e){return e.desktop}async function vi(e){bc(e)||await S(e.projectDir,"packages/agent-core","stripDesktopAiRuntimePackages")}var wc=["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"],Nr="gsaas:mcp-apps-start";async function vc(e){let t=[];for(let r of await ut(m(e,"packages"),{withFileTypes:!0}))if(r.isDirectory())for(let n of["src","tests"]){let i=m(e,"packages",r.name,n);if(!tc(i))continue;let o=await q(i,i,s=>s.split("/").includes("node_modules"),s=>/\.(?:ts|tsx)$/.test(s));for(let s of o)(await ge(s,"utf-8")).includes(Nr)&&t.push(s)}return t.sort()}async function ki(e){if(e.ai)return;let t="stripMcpApps",r=e.projectDir;for(let o of wc)await S(r,o,"stripMcpApps");let n=await vc(r);n.length===0&&pt(t,`${Nr} regions`,`${t}: expected ${Nr} regions under packages/<name>/src or tests, but found none (boilerplate drift).`);for(let o of n)await Tt(o,o,"mcp-apps",t);let i=m(r,"packages/i18n/translations");await S(r,"packages/i18n/translations/en/mcp-widgets.json","stripMcpApps");for(let o of await ut(i,{withFileTypes:!0}))o.isDirectory()&&await Ie(m(i,o.name,"mcp-widgets.json"),{force:!0});await A(m(r,"docs/(platform)/meta.json"),` "mcp-widgets",
1405
- `,"","platform meta.json mcp-widgets entry",t),await V(m(r,"docs/(platform)/external-agent-mcp.mdx"),"external-agent-mcp.mdx widgets paragraph","mcp-apps-docs",t),await V(m(r,"docs/(platform)/ai.mdx"),"ai.mdx widgets under tool rows section","mcp-apps-docs",t)}async function kc(e,t,r,n){let i=await ut(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 Ie(m(e,a),{recursive:!0})}}async function Tt(e,t,r,n){let i=await Kt(e,t,n);i!==null&&await l(e,Ge(i,t,r,n))}async function Ec(e){let t=e.projectDir,r="stripUnusedDocsSilo",n=e.mobile&&e.mobilePurchases==="revenuecat";e.mobile||(await A(m(t,"docs/(platform)/index.mdx"),` <Card href="/mobile" title="Mobile app" description="Cross-platform iOS and Android app with push, universal links, and store billing." />
1400
+ `)],fc=["apps/web/app/[locale]/(marketing)/download","apps/web/tests/routes/download-page.test.tsx"],gc=["cli","cli:clean","demo:bench","playground:regen","playground:test","playground:test:repo","playground:test:audit","playground:test:units","playground:test:e2e","playground:test:build","playground:test:mobile","check-types:scripts","ai:parity"];async function hi(e){let t=m(e.projectDir,".github/workflows"),r=await ut(t).catch(()=>[]);for(let n of r)nc.has(n)||await Ie(m(t,n),{recursive:!0,force:!0})}async function yc(e,t){let r=m(e,"package.json"),n=JSON.parse(await ge(r,"utf-8"));if(!n.scripts)return;let i=!1;for(let o of t)o in n.scripts&&(delete n.scripts[o],i=!0);if(!i)return;let s=/\n([\t ]+)"/.exec(await ge(r,"utf-8"))?.[1]??" ";await l(r,`${JSON.stringify(n,null,s)}
1401
+ `)}async function fi(e){await yc(e.projectDir,[...gc])}async function gi(e){let t=m(e.projectDir,"package.json"),r=await ge(t,"utf-8"),n=JSON.parse(r);!n.scripts||!("dev"in n.scripts)||(n.scripts.dev=e.architecture==="separate"?"turbo run dev --continue":"turbo run dev --continue --filter=!backend",await l(t,`${JSON.stringify(n,null," ")}
1402
+ `))}async function yi(e){let t=m(e.projectDir,"package.json"),r=JSON.parse(await ge(t,"utf-8")),n=r.scripts?.test;if(n!=="turbo run test --concurrency=2 && vitest run")throw new Error(`rewriteRootTestScript: expected the root test script to be "turbo run test --concurrency=2 && vitest run", got ${JSON.stringify(n)} (boilerplate drift).`);r.scripts.test="turbo run test --concurrency=2",await l(t,`${JSON.stringify(r,null," ")}
1403
+ `)}async function bi(e){e.docs||await S(e.projectDir,"apps/docs","stripDocsApp")}async function wi(e){let t=m(e.projectDir,"docs/(platform)/meta.json"),r=JSON.parse(await ge(t,"utf-8"));if(r.title!=="GenerateSaaS")throw new Error(`stripUnusedDocsSilo: expected the feature-page group to be titled "GenerateSaaS", found ${JSON.stringify(r.title)} (boilerplate drift).`);r.title=e.appName,await Ke(t,r," ","stripUnusedDocsSilo"),e.desktop||await Ie(m(e.projectDir,"docs/desktop"),{recursive:!0,force:!0}),e.mobile||await Ie(m(e.projectDir,"docs/mobile"),{recursive:!0,force:!0}),await bc(e),await Sc(e)}async function V(e,t,r,n){let i=await Kt(e,t,n);i!==null&&await l(e,Ge(i,t,r,n))}async function bc(e){let t=e.projectDir,r="stripUnusedDocsSilo",n=m(t,"docs/(platform)/configuration.mdx"),i=e.desktop;e.desktop||(await A(n,"| Desktop app + device sign-in - see [desktop app](/desktop) |","| Desktop app + device sign-in |","configuration.mdx desktop config-table link",r),await V(n,"configuration.mdx desktop TRUSTED_ORIGINS callout","desktop-origins-docs",r),await A(m(t,"docs/cli/init.mdx"),"the [desktop app](/desktop), AI features","the desktop app, AI features","cli init.mdx desktop app link",r),await V(m(t,"docs/(platform)/payments/organizations.mdx"),"payments organizations.mdx desktop tenancy callout","desktop-tenancy-docs",r),await V(m(t,"docs/(platform)/projects.mdx"),"projects.mdx desktop scoping callout","desktop-projects-docs",r),await V(m(t,"docs/(platform)/client-architecture.mdx"),"client-architecture.mdx desktop card","desktop-architecture-docs",r),await V(m(t,"docs/(platform)/screens.mdx"),"screens.mdx desktop halves","screens-desktop-docs",r),await V(m(t,"docs/(platform)/testing/e2e.mdx"),"testing/e2e.mdx desktop e2e callout","desktop-testing-docs",r),await A(m(t,"docs/(platform)/index.mdx"),` <Card href="/desktop" title="Desktop app" description="Cross-platform desktop app with device sign-in and AI agents." />
1404
+ `,"","index.mdx desktop app card",r),await V(m(t,"docs/(platform)/ai.mdx"),"ai.mdx automation lanes row + section","desktop-lanes-docs",r),await A(m(t,"docs/(platform)/ai.mdx"),"| Creating or changing an automation on the user's computer (desktop) | `create_local_automation`, an `update_local_automation` beyond a rename or a pause, `delete_local_automation` ([how](/desktop/ai#what-runs-and-where)) | No |\n","","ai.mdx device-automation approval row",r)),i||(await V(n,"configuration.mdx desktop-AI paragraph","desktop-ai-docs",r),await A(m(t,"docs/(platform)/navigation.mdx"),"gates the desktop app's Chat and Automations, see [desktop AI](/desktop/ai) |","gates the desktop app's Chat and Automations |","navigation.mdx sidebar-flag agents-row link",r))}async function vi(e){if(e.desktop)return;await S(e.projectDir,"apps/desktop","stripDesktopApp");let t=m(e.projectDir,"packages/i18n/translations");for(let i of await ut(t,{withFileTypes:!0}))i.isDirectory()&&await Ie(m(t,i.name,"desktop.json"),{force:!0});await S(e.projectDir,".github/workflows/desktop-release.yml","stripDesktopApp");for(let i of fc)await S(e.projectDir,i,"stripDesktopApp");await S(e.projectDir,"packages/utils/src/desktop-download.ts","stripDesktopApp"),await S(e.projectDir,"packages/utils/tests/desktop-download.test.ts","stripDesktopApp");let r=m(e.projectDir,"packages/utils/package.json"),n=JSON.parse(await ge(r,"utf-8"));if(!n.exports?.["./desktop-download"])throw new Error("stripDesktopApp: expected packages/utils/package.json to carry the ./desktop-download export");delete n.exports["./desktop-download"],await Ke(r,n," ","stripDesktopApp")}function wc(e){return e.desktop}async function ki(e){wc(e)||await S(e.projectDir,"packages/agent-core","stripDesktopAiRuntimePackages")}var vc=["packages/mcp-widgets","packages/api/src/ai/mcp-apps","packages/api/src/routes/internal/ai/widgets-router.ts","packages/api/tests/routes/mcp-apps.test.ts","packages/api/tests/ai/organization-widgets.test.ts","packages/api/tests/routes/widgets-router.test.ts","packages/app-core/src/mcp-app","packages/app-core/src/test-support/mcp-fake-host.ts","packages/app-core/tests/mcp-app","packages/ui/src/components/mcp-widgets","packages/ui/src/lib/mcp-widgets","packages/ui/src/components/ai/tool-widget.tsx","packages/ui/src/components/ai/tool-widget.test.tsx","packages/ui/src/components/ai/tool-widget-split.test.tsx","docs/(platform)/mcp-widgets.mdx"],$r="gsaas:mcp-apps-start";async function kc(e){let t=[];for(let r of await ut(m(e,"packages"),{withFileTypes:!0}))if(r.isDirectory())for(let n of["src","tests"]){let i=m(e,"packages",r.name,n);if(!rc(i))continue;let s=await q(i,i,o=>o.split("/").includes("node_modules"),o=>/\.(?:ts|tsx)$/.test(o));for(let o of s)(await ge(o,"utf-8")).includes($r)&&t.push(o)}return t.sort()}async function Ei(e){if(e.ai)return;let t="stripMcpApps",r=e.projectDir;for(let s of vc)await S(r,s,"stripMcpApps");let n=await kc(r);n.length===0&&pt(t,`${$r} regions`,`${t}: expected ${$r} regions under packages/<name>/src or tests, but found none (boilerplate drift).`);for(let s of n)await Tt(s,s,"mcp-apps",t);let i=m(r,"packages/i18n/translations");await S(r,"packages/i18n/translations/en/mcp-widgets.json","stripMcpApps");for(let s of await ut(i,{withFileTypes:!0}))s.isDirectory()&&await Ie(m(i,s.name,"mcp-widgets.json"),{force:!0});await A(m(r,"docs/(platform)/meta.json"),` "mcp-widgets",
1405
+ `,"","platform meta.json mcp-widgets entry",t),await V(m(r,"docs/(platform)/external-agent-mcp.mdx"),"external-agent-mcp.mdx widgets paragraph","mcp-apps-docs",t),await V(m(r,"docs/(platform)/ai.mdx"),"ai.mdx widgets under tool rows section","mcp-apps-docs",t)}async function Ec(e,t,r,n){let i=await ut(e);for(let s of t){let o=i.filter(a=>a.startsWith(s));if(o.length===0)throw new Error(`${n}: expected ${r} to hold at least one ${s}* entry`);for(let a of o)await Ie(m(e,a),{recursive:!0})}}async function Tt(e,t,r,n){let i=await Kt(e,t,n);i!==null&&await l(e,Ge(i,t,r,n))}async function Sc(e){let t=e.projectDir,r="stripUnusedDocsSilo",n=e.mobile&&e.mobilePurchases==="revenuecat";e.mobile||(await A(m(t,"docs/(platform)/index.mdx"),` <Card href="/mobile" title="Mobile app" description="Cross-platform iOS and Android app with push, universal links, and store billing." />
1406
1406
  `,"","index.mdx mobile app card",r),await A(m(t,"docs/(platform)/configuration.mdx")," - see [mobile app](/mobile)","","configuration.mdx mobile config-table link",r),await A(m(t,"docs/(platform)/client-architecture.mdx"),` <Card href="/mobile" title="Mobile app">The Expo app - the third surface this client core serves.</Card>
1407
1407
  `,"","client-architecture.mdx mobile app card",r),await A(m(t,"docs/cli/init.mdx"),"The [mobile app](/mobile) (`apps/mobile`, built with Expo)","The mobile app (`apps/mobile`, built with Expo)","cli init.mdx mobile app link",r),await A(m(t,"docs/(platform)/notifications.mdx"),"- **On a phone too.** With the [mobile app](/mobile) shipped and `config.mobile.push.enabled` on, the same notification is delivered to the user's registered devices as a push - see [mobile notifications](/mobile/notifications).\n\n","","notifications.mdx mobile push bullet",r),await A(m(t,"docs/(platform)/authentication/social-oauth.mdx")," - the native flow adds `APPLE_APP_BUNDLE_IDENTIFIER`; without `APPLE_CLIENT_ID` it runs native-only (no web button), see [mobile auth](/mobile/auth) |"," |","social-oauth.mdx Apple native-flow tail",r),await A(m(t,"docs/(platform)/authentication/two-factor-and-passkeys.mdx"),"- **On the [mobile app](/mobile/auth)**, passkeys use the platform's own biometrics and are claimed by the same `.well-known` association files. The app's biometric **App lock** is a separate device gate, never a second factor.\n\n","","two-factor-and-passkeys.mdx mobile passkeys bullet",r),await A(m(t,"docs/(platform)/project-structure.mdx"),"the web, desktop and mobile apps","the web and desktop apps","project-structure.mdx surface list",r),await V(m(t,"docs/(platform)/testing/e2e.mdx"),"testing e2e.mdx mobile Maestro section","mobile-testing-docs",r),await V(m(t,"docs/(platform)/environment-variables/index.mdx"),"environment-variables mobile section","mobile-env-docs",r)),n||(await A(m(t,"docs/(platform)/payments/meta.json"),', "mobile-billing"',"","payments meta.json mobile-billing entry",r),await A(m(t,"docs/(platform)/payments/index.mdx"),` <Card href="/payments/mobile-billing" title="Mobile store billing" description="In-app purchases through RevenueCat, additive to your web provider." />
1408
1408
  `,"","payments index.mdx mobile store billing card",r),await S(t,"docs/(platform)/payments/mobile-billing.mdx",r)),e.mobile&&!n&&(await A(m(t,"docs/mobile/meta.json"),', "billing"',"","mobile meta.json billing entry",r),await A(m(t,"docs/mobile/index.mdx"),` <Card href="/mobile/billing" title="Billing" description="Store purchases through RevenueCat, and the web-billing shape." />
1409
- `,"","mobile index.mdx billing card",r),await V(m(t,"docs/mobile/index.mdx"),"mobile index.mdx store-purchases block","mobile-purchases-docs",r),await Ie(m(t,"docs/mobile/billing"),{recursive:!0,force:!0}))}async function Ei(e){if(e.mobile)return;await S(e.projectDir,"apps/mobile","stripMobileApp");let t=m(e.projectDir,"packages/i18n/translations");for(let i of await ut(t,{withFileTypes:!0}))i.isDirectory()&&await Ie(m(t,i.name,"mobile.json"),{force:!0});await S(e.projectDir,"packages/i18n/tests/mobile-notification-labels.test.ts","stripMobileApp"),await S(e.projectDir,"packages/i18n/tests/mobile-brand-literals.test.ts","stripMobileApp"),await S(e.projectDir,"packages/i18n/tests/mobile-shared-merge.test.ts","stripMobileApp"),await S(e.projectDir,"packages/auth/tests/expo-plugin.test.ts","stripMobileApp"),await S(e.projectDir,"packages/auth/tests/expo-authorization-allowlist.test.ts","stripMobileApp"),await S(e.projectDir,"packages/auth/src/expo-authorization-allowlist.ts","stripMobileApp"),await S(e.projectDir,".github/workflows/mobile-release.yml","stripMobileApp"),await S(e.projectDir,"tooling/styles/scripts/build-mobile-css.ts","stripMobileApp");let r=m(e.projectDir,"tooling/styles/package.json"),n=JSON.parse(await ge(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 Ke(r,n," ","stripMobileApp");for(let i of nc)await Ve(m(e.projectDir,i),m(e.projectDir,"apps/web"));await S(e.projectDir,"packages/api/src/routes/internal/well-known.ts","stripMobileApp"),await S(e.projectDir,"packages/api/tests/routes/well-known-mobile.test.ts","stripMobileApp"),await S(e.projectDir,"packages/api/src/routes/internal/mobile-auth.ts","stripMobileApp"),await S(e.projectDir,"packages/api/tests/routes/mobile-auth.test.ts","stripMobileApp"),await S(e.projectDir,"apps/web/public/images/stores","stripMobileApp");for(let i of ic)await Tt(m(e.projectDir,i),i,"mobile-auth","stripMobileApp");for(let i of sc)await Tt(m(e.projectDir,i),i,"mobile-push","stripMobileApp");for(let i of oc)await S(e.projectDir,i,"stripMobileApp")}async function Si(e){if(e.mobile&&e.mobilePurchases==="revenuecat")return;for(let n of ac)await S(e.projectDir,n,"stripMobilePurchases");let t=m(e.projectDir,"packages/payments/package.json"),r=JSON.parse(await ge(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 Ke(t,r," ","stripMobilePurchases");for(let n of cc)await Tt(m(e.projectDir,n),n,"mobile-purchases","stripMobilePurchases");if(e.mobile){for(let n of lc)await S(e.projectDir,n,"stripMobilePurchases");for(let{dir:n,prefixes:i}of pc)await kc(m(e.projectDir,n),i,n,"stripMobilePurchases");for(let n of dc)await Tt(m(e.projectDir,n),n,"mobile-purchases","stripMobilePurchases");for(let n of mc)await A(m(e.projectDir,"apps/mobile/e2e/README.md"),n,"","e2e README purchases row block","stripMobilePurchases");await A(m(e.projectDir,"apps/mobile/e2e/tags.ts"),uc,`
1410
- `,"e2e tags.ts purchases inventory entries","stripMobilePurchases")}}import{readFile as Tc}from"fs/promises";import{join as Rc}from"path";var Sc="[self-hosted, contabo]",Pc="[self-hosted, macmini]",Ac=`matrix.os == 'macos-latest' && fromJSON('["self-hosted", "macmini"]') || `,Ic=`\${{ matrix.os == 'ubuntu-latest' && fromJSON('["self-hosted", "contabo"]') || matrix.os }}`;function Yt(e,t){let r=e.replaceAll(Ac,"").replaceAll(Ic,"${{ matrix.os }}").replaceAll(Sc,"ubuntu-latest").replaceAll(Pc,"macos-latest");if(r.includes("contabo")||r.includes("macmini"))throw new Error(`Cannot move ${t} onto GitHub-hosted runners: it names one of the boilerplate's self-hosted runners in a form the generator does not know. The boilerplate workflow may have drifted.`);return r}var Pi=`on:
1409
+ `,"","mobile index.mdx billing card",r),await V(m(t,"docs/mobile/index.mdx"),"mobile index.mdx store-purchases block","mobile-purchases-docs",r),await Ie(m(t,"docs/mobile/billing"),{recursive:!0,force:!0}))}async function Si(e){if(e.mobile)return;await S(e.projectDir,"apps/mobile","stripMobileApp");let t=m(e.projectDir,"packages/i18n/translations");for(let i of await ut(t,{withFileTypes:!0}))i.isDirectory()&&await Ie(m(t,i.name,"mobile.json"),{force:!0});await S(e.projectDir,"packages/i18n/tests/mobile-notification-labels.test.ts","stripMobileApp"),await S(e.projectDir,"packages/i18n/tests/mobile-brand-literals.test.ts","stripMobileApp"),await S(e.projectDir,"packages/i18n/tests/mobile-shared-merge.test.ts","stripMobileApp"),await S(e.projectDir,"packages/auth/tests/expo-plugin.test.ts","stripMobileApp"),await S(e.projectDir,"packages/auth/tests/expo-authorization-allowlist.test.ts","stripMobileApp"),await S(e.projectDir,"packages/auth/src/expo-authorization-allowlist.ts","stripMobileApp"),await S(e.projectDir,".github/workflows/mobile-release.yml","stripMobileApp"),await S(e.projectDir,"tooling/styles/scripts/build-mobile-css.ts","stripMobileApp");let r=m(e.projectDir,"tooling/styles/package.json"),n=JSON.parse(await ge(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 Ke(r,n," ","stripMobileApp");for(let i of ic)await Ve(m(e.projectDir,i),m(e.projectDir,"apps/web"));await S(e.projectDir,"packages/api/src/routes/internal/well-known.ts","stripMobileApp"),await S(e.projectDir,"packages/api/tests/routes/well-known-mobile.test.ts","stripMobileApp"),await S(e.projectDir,"packages/api/src/routes/internal/mobile-auth.ts","stripMobileApp"),await S(e.projectDir,"packages/api/tests/routes/mobile-auth.test.ts","stripMobileApp"),await S(e.projectDir,"apps/web/public/images/stores","stripMobileApp");for(let i of sc)await Tt(m(e.projectDir,i),i,"mobile-auth","stripMobileApp");for(let i of oc)await Tt(m(e.projectDir,i),i,"mobile-push","stripMobileApp");for(let i of ac)await S(e.projectDir,i,"stripMobileApp")}async function Pi(e){if(e.mobile&&e.mobilePurchases==="revenuecat")return;for(let n of cc)await S(e.projectDir,n,"stripMobilePurchases");let t=m(e.projectDir,"packages/payments/package.json"),r=JSON.parse(await ge(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 Ke(t,r," ","stripMobilePurchases");for(let n of lc)await Tt(m(e.projectDir,n),n,"mobile-purchases","stripMobilePurchases");if(e.mobile){for(let n of pc)await S(e.projectDir,n,"stripMobilePurchases");for(let{dir:n,prefixes:i}of dc)await Ec(m(e.projectDir,n),i,n,"stripMobilePurchases");for(let n of uc)await Tt(m(e.projectDir,n),n,"mobile-purchases","stripMobilePurchases");for(let n of hc)await A(m(e.projectDir,"apps/mobile/e2e/README.md"),n,"","e2e README purchases row block","stripMobilePurchases");await A(m(e.projectDir,"apps/mobile/e2e/tags.ts"),mc,`
1410
+ `,"e2e tags.ts purchases inventory entries","stripMobilePurchases")}}import{readFile as Rc}from"fs/promises";import{join as _c}from"path";var Pc="[self-hosted, contabo]",Ac="[self-hosted, macmini]",Ic=`matrix.os == 'macos-latest' && fromJSON('["self-hosted", "macmini"]') || `,Tc=`\${{ matrix.os == 'ubuntu-latest' && fromJSON('["self-hosted", "contabo"]') || matrix.os }}`;function Yt(e,t){let r=e.replaceAll(Ic,"").replaceAll(Tc,"${{ matrix.os }}").replaceAll(Pc,"ubuntu-latest").replaceAll(Ac,"macos-latest");if(r.includes("contabo")||r.includes("macmini"))throw new Error(`Cannot move ${t} onto GitHub-hosted runners: it names one of the boilerplate's self-hosted runners in a form the generator does not know. The boilerplate workflow may have drifted.`);return r}var Ai=`on:
1411
1411
  workflow_run:
1412
1412
  workflows: ["Tag Release"]
1413
1413
  branches: [main]
1414
1414
  types: [completed]
1415
- workflow_dispatch:`,_c=`on:
1416
- workflow_dispatch:`;async function Ai(e){if(!e.desktop)return;let t=Rc(e.projectDir,".github/workflows/desktop-release.yml"),r=await Tc(t,"utf8");if(!r.includes(Pi))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,Yt(r.replace(Pi,_c),t))}import{readFile as Oc}from"fs/promises";import{join as xc}from"path";var Ii=`on:
1415
+ workflow_dispatch:`,Oc=`on:
1416
+ workflow_dispatch:`;async function Ii(e){if(!e.desktop)return;let t=_c(e.projectDir,".github/workflows/desktop-release.yml"),r=await Rc(t,"utf8");if(!r.includes(Ai))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,Yt(r.replace(Ai,Oc),t))}import{readFile as xc}from"fs/promises";import{join as Dc}from"path";var Ti=`on:
1417
1417
  workflow_run:
1418
1418
  workflows: ["Tag Release"]
1419
1419
  branches: [main]
1420
1420
  types: [completed]
1421
- workflow_dispatch:`,Dc=`on:
1422
- workflow_dispatch:`;async function Ti(e){if(!e.mobile)return;let t=xc(e.projectDir,".github/workflows/mobile-release.yml"),r=await Oc(t,"utf8");if(!r.includes(Ii))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,Yt(r.replace(Ii,Dc),t))}import{join as Nc}from"path";async function Oi(e){let t=Cc(e);await l(Nc(e.projectDir,".github/workflows/ci.yml"),t)}function Ri(e){return e.databaseProvider!=="neon"&&e.cacheProvider!=="upstash"}function _i(e,t,r){return` - uses: actions/upload-artifact@v4
1421
+ workflow_dispatch:`,Nc=`on:
1422
+ workflow_dispatch:`;async function Ri(e){if(!e.mobile)return;let t=Dc(e.projectDir,".github/workflows/mobile-release.yml"),r=await xc(t,"utf8");if(!r.includes(Ti))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,Yt(r.replace(Ti,Nc),t))}import{join as Cc}from"path";async function xi(e){let t=Lc(e);await l(Cc(e.projectDir,".github/workflows/ci.yml"),t)}function _i(e){return e.databaseProvider!=="neon"&&e.cacheProvider!=="upstash"}function Oi(e,t,r){return` - uses: actions/upload-artifact@v4
1423
1423
  if: \${{ ${r} }}
1424
1424
  with:
1425
1425
  name: playwright-report-${e}
@@ -1428,7 +1428,7 @@ vi.mock("@upstash/lock", () => {
1428
1428
  ${t}/test-results
1429
1429
  if-no-files-found: ignore
1430
1430
  retention-days: 7
1431
- `}function Cc(e){let t=e.cacheProvider==="upstash",r=t?"":` redis:
1431
+ `}function Lc(e){let t=e.cacheProvider==="upstash",r=t?"":` redis:
1432
1432
  image: redis:8-alpine
1433
1433
  ports:
1434
1434
  - 6379:6379
@@ -1438,7 +1438,7 @@ vi.mock("@upstash/lock", () => {
1438
1438
  --health-timeout 5s
1439
1439
  --health-retries 5
1440
1440
  `,n=r===""?"":` services:
1441
- ${r}`,s=` postgres:
1441
+ ${r}`,o=` postgres:
1442
1442
  image: postgres:18-alpine
1443
1443
  env:
1444
1444
  POSTGRES_USER: postgres
@@ -1472,7 +1472,7 @@ ${r} mailpit:
1472
1472
  # suite's port is derived per checkout - a baked URL would name a port nothing serves.
1473
1473
  - name: Start Inngest
1474
1474
  run: docker run -d --name inngest --network host inngest/inngest:v1.46.0 inngest dev
1475
- `,p=Ri(e)?`
1475
+ `,p=_i(e)?`
1476
1476
  # The end-to-end suite, on a manual "Run workflow" dispatch only - it builds the app in production
1477
1477
  # mode and drives it with Playwright, too slow to pay for on every PR. It needs no keys and no
1478
1478
  # internet: the harness preflights the services below, builds and starts the app itself, provisions
@@ -1484,7 +1484,7 @@ ${r} mailpit:
1484
1484
  runs-on: ubuntu-latest
1485
1485
  timeout-minutes: 30
1486
1486
  services:
1487
- ${s} steps:
1487
+ ${o} steps:
1488
1488
  - uses: actions/checkout@v6
1489
1489
  - uses: ./.github/actions/setup
1490
1490
 
@@ -1507,7 +1507,7 @@ ${a}
1507
1507
  env:
1508
1508
  NODE_OPTIONS: --max-old-space-size=6144
1509
1509
 
1510
- ${_i("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&&Ri(e)?`
1510
+ ${Oi("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&&_i(e)?`
1511
1511
  # The DESKTOP end-to-end suite, on a manual "Run workflow" dispatch only: it builds the Electron
1512
1512
  # bundles AND a Next production build, which is too slow to pay for on every push. It has its own
1513
1513
  # port and its own build directory, so it can never collide with the web job above.
@@ -1517,7 +1517,7 @@ ${_i("web","apps/web","!cancelled()")}`:"\n # No end-to-end job: this project's
1517
1517
  runs-on: ubuntu-latest
1518
1518
  timeout-minutes: 45
1519
1519
  services:
1520
- ${s} steps:
1520
+ ${o} steps:
1521
1521
  - uses: actions/checkout@v6
1522
1522
  - uses: ./.github/actions/setup
1523
1523
 
@@ -1541,7 +1541,7 @@ ${a}
1541
1541
  env:
1542
1542
  NODE_OPTIONS: --max-old-space-size=6144
1543
1543
 
1544
- ${_i("desktop","apps/desktop","failure()")}`:"",k=e.databaseProvider==="neon"?`
1544
+ ${Oi("desktop","apps/desktop","failure()")}`:"",k=e.databaseProvider==="neon"?`
1545
1545
  # Required for neon: the api suite's embedded Postgres is TCP-only and the neon
1546
1546
  # websocket driver cannot reach it. Add this repository secret (any Postgres this
1547
1547
  # suite may CREATE DATABASE on - a Neon branch works).
@@ -1602,22 +1602,22 @@ ${n} env:
1602
1602
  - run: pnpm check-types
1603
1603
 
1604
1604
  - run: pnpm test
1605
- ${p}${g}`}import{readFile as xi}from"fs/promises";import{existsSync as Lc}from"fs";import{join as Cr}from"path";var Di="@repo/database";function $c(e){return e?"pnpm -F @repo/database reset && pnpm -F @repo/database run deploy -- --push":"pnpm -F @repo/database run deploy"}function jc(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 Mc(e,t,r){let n=await xi(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(Di)||(i.scripts={...i.scripts,[t]:`${r} && ${o}`},await l(e,`${JSON.stringify(i,null," ")}
1606
- `))}async function Uc(e,t){let r=Lc(e)?JSON.parse(await xi(e,"utf-8")):{$schema:"https://openapi.vercel.sh/vercel.json"},n=r.buildCommand?.trim()||"pnpm build";n.includes(Di)||(r.buildCommand=`${t} && ${n}`,await l(e,`${JSON.stringify(r,null," ")}
1607
- `))}async function Ni(e){let t=$c(e.demo===!0),r=jc(e.architecture),n=Cr(e.projectDir,"apps",r);switch(e.deploymentTarget){case"node":await Mc(Cr(n,"package.json"),"start",t);return;case"vercel":await Uc(Cr(n,"vercel.json"),t);return;default:{let i=e.deploymentTarget;throw new Error(`generateDeployScripts: unhandled deployment target "${String(i)}"`)}}}import{readFile as Fc}from"fs/promises";import{existsSync as Vc}from"fs";import{join as Wt}from"path";var Ci=["stripe","polar"],Bc=[...Ci,"none"];async function Li(e){let t=Wt(e.projectDir,"packages/payments/src"),r=e.paymentProvider,i=`// Active payment provider. To switch, change the path below to
1608
- // ${Bc.filter(o=>o!==r).map(o=>`"./${o}/index"`).join(" or ")} (other folders are kept in place).
1605
+ ${p}${g}`}import{readFile as Di}from"fs/promises";import{existsSync as $c}from"fs";import{join as jr}from"path";var Ni="@repo/database";function jc(e){return e?"pnpm -F @repo/database reset && pnpm -F @repo/database run deploy -- --push":"pnpm -F @repo/database run deploy"}function Mc(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 Di(e,"utf-8"),i=JSON.parse(n),s=i.scripts?.[t];if(!s)throw new Error(`Cannot prepend to missing script "${t}" in ${e}`);s.includes(Ni)||(i.scripts={...i.scripts,[t]:`${r} && ${s}`},await l(e,`${JSON.stringify(i,null," ")}
1606
+ `))}async function Fc(e,t){let r=$c(e)?JSON.parse(await Di(e,"utf-8")):{$schema:"https://openapi.vercel.sh/vercel.json"},n=r.buildCommand?.trim()||"pnpm build";n.includes(Ni)||(r.buildCommand=`${t} && ${n}`,await l(e,`${JSON.stringify(r,null," ")}
1607
+ `))}async function Ci(e){let t=jc(e.demo===!0),r=Mc(e.architecture),n=jr(e.projectDir,"apps",r);switch(e.deploymentTarget){case"node":await Uc(jr(n,"package.json"),"start",t);return;case"vercel":await Fc(jr(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 Bc}from"fs";import{join as Wt}from"path";var Li=["stripe","polar"],Gc=[...Li,"none"];async function $i(e){let t=Wt(e.projectDir,"packages/payments/src"),r=e.paymentProvider,i=`// Active payment provider. To switch, change the path below to
1608
+ // ${Gc.filter(s=>s!==r).map(s=>`"./${s}/index"`).join(" or ")} (other folders are kept in place).
1609
1609
  export { ops } from "./${r}/index";
1610
- `;await l(Wt(t,"providers/index.ts"),i),await l(Wt(t,"index.ts"),await Gc(t,r))}async function Gc(e,t){let r=Wt(e,"index.ts");if(!Vc(r))throw new Error(`generatePaymentBarrel: expected ${r} to exist - did packages/payments move?`);let n=await Fc(r,"utf-8"),i=Ci.filter(s=>s!==t);return n.split(`
1611
- `).filter(s=>!i.some(a=>s.includes(`./providers/${a}/`))).join(`
1612
- `)}import{access as Kc,readFile as qt,rm as zt}from"fs/promises";import{join as Z}from"path";var Fi=["sentry","posthog"],Lr={sentry:"src/providers/sentry",posthog:"src/providers/posthog"},Jt={sentry:["tests/sentry-load-guard.test.ts","tests/sentry-browser-scrub.test.ts","tests/sentry-server-scrub.test.ts"],posthog:["tests/posthog-load-guard.test.ts","tests/llm-analytics.test.ts"]},Hc=["tests/resolution.test.ts","tests/export-isolation.test.ts"],Yc=["src/providers/sentry/desktop-main.ts","src/providers/sentry/desktop-renderer.ts","src/resolve-desktop-main.ts","src/resolve-desktop-renderer.ts"],Wc=["./desktop-main","./desktop-renderer"],zc=[`vi.mock("@sentry/electron/main", sdk.factories["@sentry/electron/main"]);
1610
+ `;await l(Wt(t,"providers/index.ts"),i),await l(Wt(t,"index.ts"),await Kc(t,r))}async function Kc(e,t){let r=Wt(e,"index.ts");if(!Bc(r))throw new Error(`generatePaymentBarrel: expected ${r} to exist - did packages/payments move?`);let n=await Vc(r,"utf-8"),i=Li.filter(o=>o!==t);return n.split(`
1611
+ `).filter(o=>!i.some(a=>o.includes(`./providers/${a}/`))).join(`
1612
+ `)}import{access as Hc,readFile as qt,rm as zt}from"fs/promises";import{join as Z}from"path";var Vi=["sentry","posthog"],Mr={sentry:"src/providers/sentry",posthog:"src/providers/posthog"},Jt={sentry:["tests/sentry-load-guard.test.ts","tests/sentry-browser-scrub.test.ts","tests/sentry-server-scrub.test.ts"],posthog:["tests/posthog-load-guard.test.ts","tests/llm-analytics.test.ts"]},Yc=["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"],zc=["./desktop-main","./desktop-renderer"],Jc=[`vi.mock("@sentry/electron/main", sdk.factories["@sentry/electron/main"]);
1613
1613
  `,`vi.mock("@sentry/electron/renderer", sdk.factories["@sentry/electron/renderer"]);
1614
- `],Jc=[' describeGate("desktop main", "electronMain", async () => {',' describeGate("desktop renderer", "electronRenderer", async () => {',' describe("the desktop main init options", () => {',' describe("the desktop renderer init", () => {'],$i=`
1614
+ `],qc=[' describeGate("desktop main", "electronMain", async () => {',' describeGate("desktop renderer", "electronRenderer", async () => {',' describe("the desktop main init options", () => {',' describe("the desktop renderer init", () => {'],ji=`
1615
1615
  });
1616
- `,qc=" ";async function Vi(e){let t=Z(e.projectDir,"packages/observability");await ji(t,"packages/observability");let r=e.observability,n=r.filter(s=>!G.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: ${G.join(", ")}. Shaping stops here so the project is not left half-stripped.`);for(let s of r)await ji(Z(t,Lr[s]),`packages/observability/${Lr[s]}`);let i=e.desktop?[...Ui,...Bl]:Ui,o=new Map;for(let s of i)o.set(s.file,await qt(Z(t,s.file),"utf-8"));for(let s of ol(r,e.desktop))await al(t,s);for(let s of Fi)if(!r.includes(s)){await zt(Z(t,Lr[s]),{recursive:!0,force:!0});for(let a of Jt[s])await zt(Z(t,a),{force:!0})}for(let s of Hc)await zt(Z(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(Z(t,s.file),el(a,s,r))}}async function ji(e,t){try{await Kc(e)}catch{throw new Error(`generateObservabilityProvider: expected ${t} to exist - did the observability package move?`)}}async function Xc(e,t){for(let i of Yc)await zt(Z(e,i),{force:!0});t.includes("sentry")&&await Zc(e);let r=Z(e,"package.json"),n=JSON.parse(await qt(r,"utf-8"));for(let i of Wc){if(!n.exports?.[i])throw new Error(`generateObservabilityProvider: expected packages/observability/package.json to carry the ${i} export`);delete n.exports[i]}await Ke(r,n," ","generateObservabilityProvider")}async function Zc(e){let t=Z(e,Jt.sentry[0]),r=await qt(t,"utf-8");r=$r(r,zc.map(n=>({find:n,replace:""})),Jt.sentry[0]);for(let n of Jc)r=Qc(r,n,Jt.sentry[0]);await l(t,r)}function Qc(e,t,r){let n=e.indexOf(t),i=n===-1?-1:e.indexOf($i,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(`
1617
- `).find(a=>a.trim().length>0&&!a.startsWith(`${qc} `));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+$i.length;return e[s]===`
1618
- `&&(s+=1),e.slice(0,n)+e.slice(s)}function el(e,t,r){let n=Fi.filter(s=>!r.includes(s)),i=e,o=[];for(let s of n){let a=tl(i,s);i=a.source,o.push(...a.bindings)}t.dualMode!==!1&&(i=$r(i,[{find:nl,replace:il(r)}],t.file)),i=$r(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 $r(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(`
1619
- `)[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(`
1620
- `)[0]}`);n=i.all===!0?n.replaceAll(i.find,i.replace):n.replace(i.find,i.replace)}return n}function tl(e,t){let r=new RegExp(String.raw`^import[^;]*?from "\./providers/${t}/[^"]*";\n`,"gm"),n=[];return{source:e.replace(r,o=>(n.push(...rl(o)),"")),bindings:n}}function rl(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 nl=" * 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 il(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
1616
+ `,Xc=" ";async function Bi(e){let t=Z(e.projectDir,"packages/observability");await Mi(t,"packages/observability");let r=e.observability,n=r.filter(o=>!G.includes(o));if(n.length>0)throw new Error(`observability names ${JSON.stringify(n)}, which is not a reporting provider. Every entry must be one of: ${G.join(", ")}. Shaping stops here so the project is not left half-stripped.`);for(let o of r)await Mi(Z(t,Mr[o]),`packages/observability/${Mr[o]}`);let i=e.desktop?[...Fi,...Gl]:Fi,s=new Map;for(let o of i)s.set(o.file,await qt(Z(t,o.file),"utf-8"));for(let o of al(r,e.desktop))await cl(t,o);for(let o of Vi)if(!r.includes(o)){await zt(Z(t,Mr[o]),{recursive:!0,force:!0});for(let a of Jt[o])await zt(Z(t,a),{force:!0})}for(let o of Yc)await zt(Z(t,o),{force:!0});e.desktop||await Zc(t,r);for(let o of i){let a=s.get(o.file);a!==void 0&&await l(Z(t,o.file),tl(a,o,r))}}async function Mi(e,t){try{await Hc(e)}catch{throw new Error(`generateObservabilityProvider: expected ${t} to exist - did the observability package move?`)}}async function Zc(e,t){for(let i of Wc)await zt(Z(e,i),{force:!0});t.includes("sentry")&&await Qc(e);let r=Z(e,"package.json"),n=JSON.parse(await qt(r,"utf-8"));for(let i of zc){if(!n.exports?.[i])throw new Error(`generateObservabilityProvider: expected packages/observability/package.json to carry the ${i} export`);delete n.exports[i]}await Ke(r,n," ","generateObservabilityProvider")}async function Qc(e){let t=Z(e,Jt.sentry[0]),r=await qt(t,"utf-8");r=Ur(r,Jc.map(n=>({find:n,replace:""})),Jt.sentry[0]);for(let n of qc)r=el(r,n,Jt.sentry[0]);await l(t,r)}function el(e,t,r){let n=e.indexOf(t),i=n===-1?-1:e.indexOf(ji,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 s=e.slice(n+t.length,i).split(`
1617
+ `).find(a=>a.trim().length>0&&!a.startsWith(`${Xc} `));if(s!==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: ${s.trim()}`);let o=i+ji.length;return e[o]===`
1618
+ `&&(o+=1),e.slice(0,n)+e.slice(o)}function tl(e,t,r){let n=Vi.filter(o=>!r.includes(o)),i=e,s=[];for(let o of n){let a=rl(i,o);i=a.source,s.push(...a.bindings)}t.dualMode!==!1&&(i=Ur(i,[{find:il,replace:sl(r)}],t.file)),i=Ur(i,t.edits(r),t.file);for(let o of n)if(i.includes(`./providers/${o}`))throw new Error(`generateObservabilityProvider: ${t.file} still reaches providers/${o} after the strip - the boilerplate grew an import shape the drop does not know.`);for(let o of s)if(new RegExp(String.raw`\b${o}\b`).test(i))throw new Error(`generateObservabilityProvider: ${t.file} still names ${o}, whose import the strip removed - the boilerplate grew a use the pinned rewrites do not cover.`);return i}function Ur(e,t,r){let n=e;for(let i of t){let s=n.indexOf(i.find);if(s===-1)throw new Error(`generateObservabilityProvider: ${r} no longer contains the text this strip rewrites - re-point the anchor. Missing: ${i.find.split(`
1619
+ `)[0]}`);if(i.all!==!0&&n.includes(i.find,s+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(`
1620
+ `)[0]}`);n=i.all===!0?n.replaceAll(i.find,i.replace):n.replace(i.find,i.replace)}return n}function rl(e,t){let r=new RegExp(String.raw`^import[^;]*?from "\./providers/${t}/[^"]*";\n`,"gm"),n=[];return{source:e.replace(r,s=>(n.push(...nl(s)),"")),bindings:n}}function nl(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(o=>o.trim().replace(/^type\s+/,"")).map(o=>o.split(/\s+as\s+/).at(-1)??"").filter(o=>o.length>0));let i=t.replace(/\{[\s\S]*?\}/,"").replace(/,/g," ").trim(),s=/^\*\s+as\s+([A-Za-z_$][\w$]*)$/.exec(i);return s?.[1]?r.push(s[1]):/^[A-Z_$][\w$]*$/i.test(i)&&r.push(i),r}var il=" * 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 sl(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
1621
1621
  * 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
1622
1622
  * there is nothing here for a bundler to fold away and nothing for pnpm to install.`}
1623
1623
  *
@@ -1625,28 +1625,28 @@ export { ops } from "./${r}/index";
1625
1625
  * run \`generatesaas update\`: re-shaping brings that provider's adapter and its dependency back. The
1626
1626
  * update stages nothing while you are already on the latest version, so the switch lands with the
1627
1627
  * next release. Pasting the other provider's credential into \`config.observability\` on its own
1628
- * cannot: the adapter it would need is not here.`}var Mi={source:"src/providers/sentry/browser.ts",name:"SentryBrowserInitOptions",fields:["environment: string;"]},sl={source:"src/providers/sentry/desktop-main.ts",name:"SentryDesktopMainInitOptions",fields:["environment: string;","appIsReady: boolean;"]};function ol(e,t){return e.includes("sentry")?[]:t?[Mi,sl]:[Mi]}async function al(e,t){let r=await qt(Z(e,t.source),"utf-8"),n=`export interface ${t.name} {
1629
- `,i=r.indexOf(n),o=r.indexOf(`
1628
+ * cannot: the adapter it would need is not here.`}var Ui={source:"src/providers/sentry/browser.ts",name:"SentryBrowserInitOptions",fields:["environment: string;"]},ol={source:"src/providers/sentry/desktop-main.ts",name:"SentryDesktopMainInitOptions",fields:["environment: string;","appIsReady: boolean;"]};function al(e,t){return e.includes("sentry")?[]:t?[Ui,ol]:[Ui]}async function cl(e,t){let r=await qt(Z(e,t.source),"utf-8"),n=`export interface ${t.name} {
1629
+ `,i=r.indexOf(n),s=r.indexOf(`
1630
1630
  }
1631
- `,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(`
1632
- `).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 cl=" into every browser bundle. `tests/export-isolation.test.ts` walks the real module graph to keep\n * that from ever landing quietly.",ll=` if (resolveSentryDsn(observability, process.env.SENTRY_DSN)) ops.push(sentryServerOps);
1633
- `,pl=` if (resolveServerPosthogCredentials(observability, process.env)) {
1631
+ `,i);if(i===-1||s===-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 o=r.slice(i+n.length,s).split(`
1632
+ `).map(a=>a.trim()).filter(a=>/^[A-Z_$][\w$]*\??: .+;$/i.test(a));if(o.join(" ")!==t.fields.join(" "))throw new Error(`generateObservabilityProvider: ${t.name} now declares [${o.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 ll=" into every browser bundle. `tests/export-isolation.test.ts` walks the real module graph to keep\n * that from ever landing quietly.",pl=` if (resolveSentryDsn(observability, process.env.SENTRY_DSN)) ops.push(sentryServerOps);
1633
+ `,dl=` if (resolveServerPosthogCredentials(observability, process.env)) {
1634
1634
  ops.push(posthogServerOps);
1635
1635
  }
1636
- `,dl=` if (resolveSentryDsn(config.observability, process.env.SENTRY_DSN)) {
1636
+ `,ul=` if (resolveSentryDsn(config.observability, process.env.SENTRY_DSN)) {
1637
1637
  await initSentryServer();
1638
1638
  }
1639
- `,ul=` if (observability?.sentry?.dsn) ops.push(sentryBrowserOps);
1640
- `,ml=` if (observability?.posthog?.publicKey) ops.push(posthogBrowserOps);
1641
- `,hl=` if (config.observability?.sentry?.dsn) await initSentryBrowser(options);
1642
- `,fl=` if (observability?.posthog?.publicKey && !observability?.sentry?.dsn) {
1639
+ `,ml=` if (observability?.sentry?.dsn) ops.push(sentryBrowserOps);
1640
+ `,hl=` if (observability?.posthog?.publicKey) ops.push(posthogBrowserOps);
1641
+ `,fl=` if (config.observability?.sentry?.dsn) await initSentryBrowser(options);
1642
+ `,gl=` if (observability?.posthog?.publicKey && !observability?.sentry?.dsn) {
1643
1643
  announceMissingDesktopSdk("posthog");
1644
1644
  }
1645
- `,gl=` // PostHog ships no desktop SDK, so a project configured ONLY for PostHog reports nothing here -
1645
+ `,yl=` // PostHog ships no desktop SDK, so a project configured ONLY for PostHog reports nothing here -
1646
1646
  // announced rather than silent, because a desktop build that quietly drops every error looks
1647
1647
  // identical to one with reporting off.
1648
- `,yl=`import { createProviderGapAnnouncer } from "./announce";
1649
- `,bl=`/**
1648
+ `,bl=`import { createProviderGapAnnouncer } from "./announce";
1649
+ `,wl=`/**
1650
1650
  * Say once that the selected provider cannot report from the desktop main process.
1651
1651
  *
1652
1652
  * A WARNING and never an error: PostHog ships no Electron SDK, and a buyer running PostHog on the
@@ -1664,7 +1664,7 @@ const announceMissingDesktopSdk = createProviderGapAnnouncer({
1664
1664
  remedy: "Select sentry to report errors from the desktop app."
1665
1665
  });
1666
1666
 
1667
- `,wl=`/**
1667
+ `,vl=`/**
1668
1668
  * Say once that the selected provider cannot report from the desktop renderer.
1669
1669
  *
1670
1670
  * A WARNING and never an error: PostHog ships no Electron SDK, and a buyer running PostHog on the
@@ -1678,33 +1678,33 @@ const announceMissingDesktopSdk = createProviderGapAnnouncer({
1678
1678
  remedy: "Select sentry to report errors from the desktop app."
1679
1679
  });
1680
1680
 
1681
- `,vl=` const observability = config.observability;
1682
- `,kl=`import { config } from "@repo/config";
1683
- `,El=` // No error-reporting adapter was generated for this project, so there is nothing to arm.
1684
- `,Sl="export type BrowserReportingOptions = SentryBrowserInitOptions;",Pl=`export interface BrowserReportingOptions {
1681
+ `,kl=` const observability = config.observability;
1682
+ `,El=`import { config } from "@repo/config";
1683
+ `,Sl=` // No error-reporting adapter was generated for this project, so there is nothing to arm.
1684
+ `,Pl="export type BrowserReportingOptions = SentryBrowserInitOptions;",Al=`export interface BrowserReportingOptions {
1685
1685
  /** The deployment environment reports are tagged with. */
1686
1686
  environment: string;
1687
- }`,Al=` return observability?.sentry?.dsn ? [sentryDesktopMainOps] : [];
1688
- `,Il=` if (observability?.sentry?.dsn) await initSentryDesktopMain(options);
1689
- `,Tl="export type DesktopMainReportingOptions = SentryDesktopMainInitOptions;",Rl=`export interface DesktopMainReportingOptions {
1687
+ }`,Il=` return observability?.sentry?.dsn ? [sentryDesktopMainOps] : [];
1688
+ `,Tl=` if (observability?.sentry?.dsn) await initSentryDesktopMain(options);
1689
+ `,Rl="export type DesktopMainReportingOptions = SentryDesktopMainInitOptions;",_l=`export interface DesktopMainReportingOptions {
1690
1690
  /** The deployment environment reports are tagged with. */
1691
1691
  environment: string;
1692
1692
  /** Whether Electron's \`app\` has emitted \`ready\` yet. */
1693
1693
  appIsReady: boolean;
1694
- }`,_l=` return observability?.sentry?.dsn ? [sentryDesktopRendererOps] : [];
1695
- `,Ol=` if (observability?.sentry?.dsn) await initSentryDesktopRenderer();
1696
- `;function Bi(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 xl(e){let t=[{find:cl,replace:" into every browser bundle."},...Bi(e,{sentry:ll,posthog:pl})];return e.includes("sentry")||t.push({find:dl,replace:""}),t}function Dl(e){let t=[...Bi(e,{sentry:ul,posthog:ml})];return e.includes("sentry")||t.push({find:hl,replace:""},Nl),t}var Nl={find:Sl,replace:Pl};function Cl(e){let t=[...Gi(e,bl)];return e.includes("sentry")||t.push({find:Al,replace:` return [];
1697
- `},{find:Il,replace:Hi(e)},{find:Tl,replace:Rl}),t.push(...Ki(e)),t}function Ll(e){let t=[...Gi(e,wl)];return e.includes("sentry")||t.push({find:_l,replace:` return [];
1698
- `},{find:Ol,replace:Hi(e)}),t.push(...Ki(e)),t}function Gi(e,t){return e.includes("posthog")?[]:[{find:gl,replace:""},{find:fl,replace:"",all:!0},{find:t,replace:""},{find:yl,replace:""}]}function Ki(e){return e.length>0?[]:[{find:vl,replace:"",all:!0},{find:kl,replace:""}]}function Hi(e){return e.length>0?"":El}var $l=` if (!posthogConfigured()) return;
1694
+ }`,Ol=` return observability?.sentry?.dsn ? [sentryDesktopRendererOps] : [];
1695
+ `,xl=` if (observability?.sentry?.dsn) await initSentryDesktopRenderer();
1696
+ `;function Gi(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:ll,replace:" into every browser bundle."},...Gi(e,{sentry:pl,posthog:dl})];return e.includes("sentry")||t.push({find:ul,replace:""}),t}function Nl(e){let t=[...Gi(e,{sentry:ml,posthog:hl})];return e.includes("sentry")||t.push({find:fl,replace:""},Cl),t}var Cl={find:Pl,replace:Al};function Ll(e){let t=[...Ki(e,wl)];return e.includes("sentry")||t.push({find:Il,replace:` return [];
1697
+ `},{find:Tl,replace:Yi(e)},{find:Rl,replace:_l}),t.push(...Hi(e)),t}function $l(e){let t=[...Ki(e,vl)];return e.includes("sentry")||t.push({find:Ol,replace:` return [];
1698
+ `},{find:xl,replace:Yi(e)}),t.push(...Hi(e)),t}function Ki(e,t){return e.includes("posthog")?[]:[{find:yl,replace:""},{find:gl,replace:"",all:!0},{find:t,replace:""},{find:bl,replace:""}]}function Hi(e){return e.length>0?[]:[{find:kl,replace:"",all:!0},{find:El,replace:""}]}function Yi(e){return e.length>0?"":Sl}var jl=` if (!posthogConfigured()) return;
1699
1699
  try {
1700
1700
  const { captureAiGeneration: capture } = await import("./providers/posthog/llm");
1701
1701
  await capture(event);
1702
1702
  } catch (reportingError) {
1703
1703
  logReportingFailure("[observability] failed to report an AI generation", reportingError);
1704
1704
  }
1705
- `,jl=` // No PostHog adapter was generated for this project, so there is nothing to report to.
1706
- `,Ml=` // No PostHog adapter was generated for this project, so there is nothing queued to drain.
1707
- `,Ul=`/**
1705
+ `,Ml=` // No PostHog adapter was generated for this project, so there is nothing to report to.
1706
+ `,Ul=` // No PostHog adapter was generated for this project, so there is nothing queued to drain.
1707
+ `,Fl=`/**
1708
1708
  * Whether PostHog is configured on this server AND this process is the deployment, without touching
1709
1709
  * the PostHog folder. The second half is the same \`serverReportingAllowed\` the adapter's own gate
1710
1710
  * asks, so a test run or a local build never even loads the SDK to find out it must stay silent.
@@ -1716,59 +1716,59 @@ function posthogConfigured(): boolean {
1716
1716
  return Boolean(process.env.POSTHOG_API_KEY || config.observability?.posthog?.publicKey);
1717
1717
  }
1718
1718
 
1719
- `,Fl=` if (!posthogConfigured()) return;
1719
+ `,Vl=` if (!posthogConfigured()) return;
1720
1720
  try {
1721
1721
  const { flushAiGenerations: flush } = await import("./providers/posthog/llm");
1722
1722
  await flush();
1723
1723
  } catch (reportingError) {
1724
1724
  logReportingFailure("[observability] failed to flush queued AI generations", reportingError);
1725
1725
  }
1726
- `;function Vl(e){return e.includes("posthog")?[]:[{find:$l,replace:jl},{find:Fl,replace:Ml},{find:Ul,replace:""},{find:`import { logReportingFailure } from "./logger";
1726
+ `;function Bl(e){return e.includes("posthog")?[]:[{find:jl,replace:Ml},{find:Vl,replace:Ul},{find:Fl,replace:""},{find:`import { logReportingFailure } from "./logger";
1727
1727
  `,replace:""},{find:`import { config } from "@repo/config";
1728
1728
  `,replace:""},{find:`import { serverReportingAllowed } from "@repo/utils/reporting";
1729
- `,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 Ui=[{file:"src/resolve-server.ts",edits:xl},{file:"src/resolve-browser.ts",edits:Dl},{file:"src/llm-analytics.ts",edits:Vl,dualMode:!1}],Bl=[{file:"src/resolve-desktop-main.ts",edits:Cl},{file:"src/resolve-desktop-renderer.ts",edits:Ll}];import{readdir as Gl,readFile as Kl}from"fs/promises";import{join as Yi}from"path";async function Wi(e){if(e.demo)return;let t=e.appName.trim()||e.projectName,r=JSON.stringify(t).slice(1,-1),n=Yi(e.projectDir,"packages/i18n/translations"),i;try{i=await Gl(n)}catch{return}for(let o of i){let s=Yi(n,o,"web.json"),a;try{a=await Kl(s,"utf-8")}catch{continue}let p=a.replaceAll("GenerateSaaS",()=>r);p!==a&&await l(s,p)}}async function Xt(e){let t=e.projectDir,r=n=>Be(n.name,()=>n(e));e.demo||(await Be("removeSampleContent",()=>In(t)),await Be("emptyBlogConfig",()=>Tn(t)),await Be("pruneBlogCategoryTranslations",()=>Rn(t)),await Be("removeDemoAiTasks",()=>_n(t))),await Be("sanitizeClaudeSettings",()=>On(t)),await r(Nn),await r(Ln),await r($n),e.demo||await r(jn),await r(Fn),await r(Vn),await r(Bn),await r(Yn),await r(zn),await r(qn),await r(ii),await r(oi),await r(pi),await r(mi),await r(Oi),await r(hi),await r(fi),await r(gi),await r(yi),await r(bi),await r(wi),await r(vi),await r(ki),await r(Ai),await r(Ei),await r(Si),await r(Ti),await r(Ni),await r(Li),await r(Vi),await r(ri),await r(Wi),await r(ui)}import{basename as Ji,join as qi,relative as Yl}from"path";import{createHash as zi}from"crypto";import{readFile as Hl}from"fs/promises";async function Zt(e){let t=await Hl(e);return zi("sha256").update(t).digest("hex")}function jr(e){return zi("sha256").update(e).digest("hex")}var Wl=new Set(["data",J]);function zl(e){let t=e.split("/");for(let r of t)if(gr.has(r)||yr.has(r)||Wl.has(r)||r.startsWith(".env")&&!r.includes("example"))return!0;return!1}function Xi(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 Jl(e,t){return{version:e.version,initialVersion:e.version,appName:e.appName,projectName:e.projectName,frontend:un,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 Zi(e,t){let n=(await q(e.projectDir,e.projectDir,zl)).sort(),i=await Promise.all(n.map(async a=>[Fe(Yl(e.projectDir,a)),await Zt(a)])),o=Object.fromEntries(i),s=Jl(e,t);await l(qi(e.projectDir,ue),`${JSON.stringify(s,null," ")}
1730
- `),await l(qi(e.projectDir,mn),`${JSON.stringify(o,null," ")}
1731
- `)}import{relative as ql}from"path";async function mt(e){let r=(await q(e,e,ct)).sort(),n=await Promise.all(r.map(async i=>[Fe(ql(e,i)),await Zt(i)]));return Object.fromEntries(n)}import{copyFile as Xl,mkdir as Zl,rm as Ql}from"fs/promises";import{dirname as ep,join as Qi,relative as tp}from"path";import{existsSync as rp}from"fs";async function Mr(e,t){rp(t)&&await Ql(t,{recursive:!0,force:!0});let n=(await q(e,e,ct)).map(i=>({file:i,dest:Qi(t,Fe(tp(e,i)))}));await Promise.all([...new Set(n.map(({dest:i})=>ep(i)))].map(i=>Zl(i,{recursive:!0}))),await Promise.all(n.map(({file:i,dest:o})=>Xl(i,o)))}async function es(e,t){await Mr(e,Qi(t,Lt))}import{readdir as np,readFile as rs}from"fs/promises";import{existsSync as ip}from"fs";import{dirname as sp,join as se,resolve as Ur,sep as Fr}from"path";import{fileURLToPath as op}from"url";var ap={"claude-code":".claude/skills",cursor:".cursor/skills",codex:".agents/skills","gemini-cli":".gemini/skills",windsurf:".windsurf/skills"},ze=Object.values(ap),Vr=["generatesaas-update","generatesaas-translate","generatesaas-og-image","generatesaas-landing-animations"],cp=sp(op(import.meta.url));function lp(){return Ut(cp,["skill","content"],"content")}async function Br(e,t){for(let r of ze){let n=se(e,r);for(let[i,o]of Object.entries(t)){let s=Ur(n,i);if(!s.startsWith(n+Fr))continue;let a=se(s,"scripts"),p=se(s,"references");await Vt(a),await Vt(p),await l(se(s,"SKILL.md"),o.skillMd.replaceAll("__SKILL_ROOT__",r));for(let[g,k]of Object.entries(o.scripts)){let w=Ur(a,g);w.startsWith(a+Fr)&&await l(w,k)}let h=Object.entries(o.references);h.length===0&&await l(se(p,".gitkeep"),"");for(let[g,k]of h){let w=Ur(p,g);w.startsWith(p+Fr)&&await l(w,k)}}}}async function ts(e){if(!ip(e))return{};let t={};for(let r of await np(e))r!==".gitkeep"&&(t[r]=await rs(se(e,r),"utf-8"));return t}async function ns(e){let t=lp(),r={};for(let n of Vr){let i=se(t,n);r[n]={skillMd:await rs(se(i,"SKILL.md"),"utf-8"),scripts:await ts(se(i,"scripts")),references:await ts(se(i,"references"))}}await Br(e,r)}import{execFile as pp,execFileSync as dp}from"child_process";import{access as Gr,readFile as up}from"fs/promises";import{join as Qt}from"path";import*as _ from"@clack/prompts";function Re(e){try{let t=process.platform==="win32"?"where":"which";return dp(t,[e],{stdio:"ignore"}),!0}catch{return!1}}function Te(e,t,r,n=3e5){return new Promise((i,o)=>{pp(e,t,{cwd:r,timeout:n,maxBuffer:50*1024*1024},(s,a,p)=>{if(s){let h=String(a||"").trim(),k=[String(p||"").trim(),h].filter(Boolean).join(`
1732
- `);o(new Error(k?`${s.message}
1733
- ${k}`:s.message))}else i()})})}async function is(e){if(!Re("pnpm"))return _.log.warn("pnpm not found. Skipping lockfile regeneration."),!1;try{return await Te("pnpm",["install","--lockfile-only","--no-frozen-lockfile"],e),!0}catch(t){let r=t instanceof Error?t.message:String(t);return _.log.warn(`Lockfile regeneration failed: ${r}`),_.log.warn("Deploys using --frozen-lockfile may fail."),!1}}async function ss(e){if(!Re("pnpm"))return _.log.warn("pnpm not found. Skipping dependency installation."),_.log.info("Install pnpm: https://pnpm.io/installation"),!1;let t=_.spinner();t.start("Installing dependencies (this may take a minute)...");try{return await Te("pnpm",["install"],e),t.stop("Dependencies installed."),!0}catch(r){t.stop("Dependency installation failed.");let n=r instanceof Error?r.message:String(r);return _.log.warn(`pnpm install failed: ${n}`),_.log.warn("You can run it manually later."),!1}}async function os(e){if(!Re("pnpm"))return!1;let t=_.spinner();t.start("Generating baseline database migration...");try{return await Te("pnpm",["-F","@repo/database","generate"],e),t.stop("Baseline migration generated."),!0}catch(r){t.stop("Baseline migration generation failed.");let n=r instanceof Error?r.message:String(r);return _.log.warn(`Could not generate baseline migration: ${n}`),_.log.warn("Run 'pnpm -F @repo/database generate' before your first deploy."),!1}}async function as(e){if(!Re("pnpm"))return!1;try{await Gr(Qt(e,"packages/mcp-widgets"))}catch{return!1}let t=_.spinner();t.start("Building the MCP widgets...");try{return await Te("pnpm",["-F","@repo/mcp-widgets","widgets:build"],e),t.stop("MCP widgets built."),!0}catch(r){t.stop("MCP widget build failed.");let n=r instanceof Error?r.message:String(r);return _.log.warn(`Could not build the MCP widgets: ${n}`),_.log.warn("Run 'pnpm -F @repo/mcp-widgets widgets:build' and commit the result."),!1}}async function cs(e){try{return await Gr(Qt(e,".git")),_.log.info("Git repository already exists, skipping init."),!0}catch{}if(!Re("git"))return _.log.warn("git not found. Skipping repository initialization."),!1;let t=_.spinner();t.start("Initializing git repository...");try{return await Te("git",["init"],e),await Te("git",["add","-A"],e),await Te("git",["commit","--no-verify","-m","Initial commit from GenerateSaaS"],e),t.stop("Git repository initialized."),!0}catch{return t.stop("Git initialization failed."),_.log.warn("You can run git init manually later."),!1}}async function ls(e){if(!Re("pnpm"))return!1;try{await Gr(Qt(e,".git"))}catch{return!1}try{let t=JSON.parse(await up(Qt(e,"package.json"),"utf-8")),r=!!t.devDependencies?.["simple-git-hooks"],n=!!t["simple-git-hooks"];if(!r||!n)return!1}catch{return!1}try{return await Te("pnpm",["exec","simple-git-hooks"],e),!0}catch{return _.log.warn("Could not install git hooks. Run 'pnpm exec simple-git-hooks' manually."),!1}}import*as Je from"@clack/prompts";import H from"picocolors";function ps(e,t){let r=rt(e);t.dockerAvailable||Je.log.warn("Docker not found. Install Docker to run local services: https://docs.docker.com/get-docker/"),t.baselineMigrationMissing&&Je.log.warn("No database migration was generated (the install did not complete). Run `pnpm install` then `pnpm --filter @repo/database generate` and commit the result BEFORE deploying - otherwise your first deploy pushes the schema untracked.");let n=[];n.push(`cd ${e.projectDir}`),t.pnpmInstalled||n.push("pnpm install"),t.mcpWidgetsUnbuilt&&n.push(`pnpm -F @repo/mcp-widgets widgets:build ${H.dim("# then commit the rebuilt widget document")}`),n.push(`pnpm infra ${H.dim(`# ${r.map(a=>Qr[a].label).join(", ")}`)}`),n.push(`pnpm dev ${H.dim("# http://localhost:3000")}`),t.skippedCredentials.length>0&&(n.push(""),n.push(H.dim("Fill in remaining TODO values in .env"))),Je.note(n.join(`
1729
+ `,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 Fi=[{file:"src/resolve-server.ts",edits:Dl},{file:"src/resolve-browser.ts",edits:Nl},{file:"src/llm-analytics.ts",edits:Bl,dualMode:!1}],Gl=[{file:"src/resolve-desktop-main.ts",edits:Ll},{file:"src/resolve-desktop-renderer.ts",edits:$l}];import{readdir as Kl,readFile as Hl}from"fs/promises";import{join as Wi}from"path";async function zi(e){if(e.demo)return;let t=e.appName.trim()||e.projectName,r=JSON.stringify(t).slice(1,-1),n=Wi(e.projectDir,"packages/i18n/translations"),i;try{i=await Kl(n)}catch{return}for(let s of i){let o=Wi(n,s,"web.json"),a;try{a=await Hl(o,"utf-8")}catch{continue}let p=a.replaceAll("GenerateSaaS",()=>r);p!==a&&await l(o,p)}}async function Xt(e){let t=e.projectDir,r=n=>Be(n.name,()=>n(e));e.demo||(await Be("removeSampleContent",()=>Tn(t)),await Be("emptyBlogConfig",()=>Rn(t)),await Be("pruneBlogCategoryTranslations",()=>_n(t)),await Be("removeDemoAiTasks",()=>On(t))),await Be("sanitizeClaudeSettings",()=>xn(t)),await r(Cn),await r($n),await r(jn),e.demo||await r(Mn),await r(Vn),await r(Bn),await r(Gn),await r(Wn),await r(Jn),await r(Xn),await r(si),await r(ai),await r(di),await r(hi),await r(xi),await r(fi),await r(gi),await r(yi),await r(bi),await r(wi),await r(vi),await r(ki),await r(Ei),await r(Ii),await r(Si),await r(Pi),await r(Ri),await r(Ci),await r($i),await r(Bi),await r(ni),await r(zi),await r(mi)}import{basename as qi,join as Xi,relative as Wl}from"path";import{createHash as Ji}from"crypto";import{readFile as Yl}from"fs/promises";async function Zt(e){let t=await Yl(e);return Ji("sha256").update(t).digest("hex")}function Fr(e){return Ji("sha256").update(e).digest("hex")}var zl=new Set(["data",J]);function Jl(e){let t=e.split("/");for(let r of t)if(wr.has(r)||vr.has(r)||zl.has(r)||r.startsWith(".env")&&!r.includes("example"))return!0;return!1}function Zi(e,t){return{projectName:e.projectName??qi(t),appName:e.appName??e.projectName??qi(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 ql(e,t){return{version:e.version,initialVersion:e.version,appName:e.appName,projectName:e.projectName,frontend:mn,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 Qi(e,t){let n=(await q(e.projectDir,e.projectDir,Jl)).sort(),i=await Promise.all(n.map(async a=>[Fe(Wl(e.projectDir,a)),await Zt(a)])),s=Object.fromEntries(i),o=ql(e,t);await l(Xi(e.projectDir,ue),`${JSON.stringify(o,null," ")}
1730
+ `),await l(Xi(e.projectDir,hn),`${JSON.stringify(s,null," ")}
1731
+ `)}import{relative as Xl}from"path";async function mt(e){let r=(await q(e,e,ct)).sort(),n=await Promise.all(r.map(async i=>[Fe(Xl(e,i)),await Zt(i)]));return Object.fromEntries(n)}import{copyFile as Zl,mkdir as Ql,rm as ep}from"fs/promises";import{dirname as tp,join as es,relative as rp}from"path";import{existsSync as np}from"fs";async function Vr(e,t){np(t)&&await ep(t,{recursive:!0,force:!0});let n=(await q(e,e,ct)).map(i=>({file:i,dest:es(t,Fe(rp(e,i)))}));await Promise.all([...new Set(n.map(({dest:i})=>tp(i)))].map(i=>Ql(i,{recursive:!0}))),await Promise.all(n.map(({file:i,dest:s})=>Zl(i,s)))}async function ts(e,t){await Vr(e,es(t,Lt))}import{readdir as ip,readFile as ns,rm as sp}from"fs/promises";import{existsSync as op}from"fs";import{dirname as ap,join as Q,resolve as Qt,sep as er}from"path";import{fileURLToPath as cp}from"url";var lp={"claude-code":".claude/skills",cursor:".agents/skills",codex:".agents/skills","gemini-cli":".agents/skills",windsurf:".agents/skills"},ze=[...new Set(Object.values(lp))],Br=[".cursor/skills",".gemini/skills",".windsurf/skills"],tr=["generatesaas-update","generatesaas-translate","generatesaas-og-image","generatesaas-landing-animations"],pp=ap(cp(import.meta.url));function dp(){return Ut(pp,["skill","content"],"content")}async function Gr(e,t){for(let r of Br){let n=Q(e,r);for(let i of new Set([...tr,...Object.keys(t)])){let s=Qt(n,i);s.startsWith(n+er)&&await sp(s,{recursive:!0,force:!0})}}for(let r of ze){let n=Q(e,r);for(let[i,s]of Object.entries(t)){let o=Qt(n,i);if(!o.startsWith(n+er))continue;let a=Q(o,"scripts"),p=Q(o,"references");await Vt(a),await Vt(p),await l(Q(o,"SKILL.md"),s.skillMd.replaceAll("__SKILL_ROOT__",r));for(let[g,k]of Object.entries(s.scripts)){let w=Qt(a,g);w.startsWith(a+er)&&await l(w,k)}let h=Object.entries(s.references);h.length===0&&await l(Q(p,".gitkeep"),"");for(let[g,k]of h){let w=Qt(p,g);w.startsWith(p+er)&&await l(w,k)}}}}async function rs(e){if(!op(e))return{};let t={};for(let r of await ip(e))r!==".gitkeep"&&(t[r]=await ns(Q(e,r),"utf-8"));return t}async function is(e){let t=dp(),r={};for(let n of tr){let i=Q(t,n);r[n]={skillMd:await ns(Q(i,"SKILL.md"),"utf-8"),scripts:await rs(Q(i,"scripts")),references:await rs(Q(i,"references"))}}await Gr(e,r)}import{execFile as up,execFileSync as mp}from"child_process";import{access as Kr,readFile as hp}from"fs/promises";import{join as rr}from"path";import*as _ from"@clack/prompts";function Re(e){try{let t=process.platform==="win32"?"where":"which";return mp(t,[e],{stdio:"ignore"}),!0}catch{return!1}}function Te(e,t,r,n=3e5){return new Promise((i,s)=>{up(e,t,{cwd:r,timeout:n,maxBuffer:50*1024*1024},(o,a,p)=>{if(o){let h=String(a||"").trim(),k=[String(p||"").trim(),h].filter(Boolean).join(`
1732
+ `);s(new Error(k?`${o.message}
1733
+ ${k}`:o.message))}else i()})})}async function ss(e){if(!Re("pnpm"))return _.log.warn("pnpm not found. Skipping lockfile regeneration."),!1;try{return await Te("pnpm",["install","--lockfile-only","--no-frozen-lockfile"],e),!0}catch(t){let r=t instanceof Error?t.message:String(t);return _.log.warn(`Lockfile regeneration failed: ${r}`),_.log.warn("Deploys using --frozen-lockfile may fail."),!1}}async function os(e){if(!Re("pnpm"))return _.log.warn("pnpm not found. Skipping dependency installation."),_.log.info("Install pnpm: https://pnpm.io/installation"),!1;let t=_.spinner();t.start("Installing dependencies (this may take a minute)...");try{return await Te("pnpm",["install"],e),t.stop("Dependencies installed."),!0}catch(r){t.stop("Dependency installation failed.");let n=r instanceof Error?r.message:String(r);return _.log.warn(`pnpm install failed: ${n}`),_.log.warn("You can run it manually later."),!1}}async function as(e){if(!Re("pnpm"))return!1;let t=_.spinner();t.start("Generating baseline database migration...");try{return await Te("pnpm",["-F","@repo/database","generate"],e),t.stop("Baseline migration generated."),!0}catch(r){t.stop("Baseline migration generation failed.");let n=r instanceof Error?r.message:String(r);return _.log.warn(`Could not generate baseline migration: ${n}`),_.log.warn("Run 'pnpm -F @repo/database generate' before your first deploy."),!1}}async function cs(e){if(!Re("pnpm"))return!1;try{await Kr(rr(e,"packages/mcp-widgets"))}catch{return!1}let t=_.spinner();t.start("Building the MCP widgets...");try{return await Te("pnpm",["-F","@repo/mcp-widgets","widgets:build"],e),t.stop("MCP widgets built."),!0}catch(r){t.stop("MCP widget build failed.");let n=r instanceof Error?r.message:String(r);return _.log.warn(`Could not build the MCP widgets: ${n}`),_.log.warn("Run 'pnpm -F @repo/mcp-widgets widgets:build' and commit the result."),!1}}async function ls(e){try{return await Kr(rr(e,".git")),_.log.info("Git repository already exists, skipping init."),!0}catch{}if(!Re("git"))return _.log.warn("git not found. Skipping repository initialization."),!1;let t=_.spinner();t.start("Initializing git repository...");try{return await Te("git",["init"],e),await Te("git",["add","-A"],e),await Te("git",["commit","--no-verify","-m","Initial commit from GenerateSaaS"],e),t.stop("Git repository initialized."),!0}catch{return t.stop("Git initialization failed."),_.log.warn("You can run git init manually later."),!1}}async function ps(e){if(!Re("pnpm"))return!1;try{await Kr(rr(e,".git"))}catch{return!1}try{let t=JSON.parse(await hp(rr(e,"package.json"),"utf-8")),r=!!t.devDependencies?.["simple-git-hooks"],n=!!t["simple-git-hooks"];if(!r||!n)return!1}catch{return!1}try{return await Te("pnpm",["exec","simple-git-hooks"],e),!0}catch{return _.log.warn("Could not install git hooks. Run 'pnpm exec simple-git-hooks' manually."),!1}}import*as Je from"@clack/prompts";import H from"picocolors";function ds(e,t){let r=rt(e);t.dockerAvailable||Je.log.warn("Docker not found. Install Docker to run local services: https://docs.docker.com/get-docker/"),t.baselineMigrationMissing&&Je.log.warn("No database migration was generated (the install did not complete). Run `pnpm install` then `pnpm --filter @repo/database generate` and commit the result BEFORE deploying - otherwise your first deploy pushes the schema untracked.");let n=[];n.push(`cd ${e.projectDir}`),t.pnpmInstalled||n.push("pnpm install"),t.mcpWidgetsUnbuilt&&n.push(`pnpm -F @repo/mcp-widgets widgets:build ${H.dim("# then commit the rebuilt widget document")}`),n.push(`pnpm infra ${H.dim(`# ${r.map(a=>en[a].label).join(", ")}`)}`),n.push(`pnpm dev ${H.dim("# http://localhost:3000")}`),t.skippedCredentials.length>0&&(n.push(""),n.push(H.dim("Fill in remaining TODO values in .env"))),Je.note(n.join(`
1734
1734
  `),H.yellow("Start Development"));let i=[];i.push(`App ${H.cyan("http://localhost:3000")}`),e.architecture==="separate"&&i.push(`API ${H.cyan("http://localhost:3010")}`),r.includes("mailpit")&&i.push(`Mailpit ${H.cyan("http://localhost:8025")}`),r.includes("inngest")&&i.push(`Inngest ${H.cyan("http://localhost:8288")}`),Je.note(i.join(`
1735
- `),H.yellow("Dev Tools"));let o=[],s=mp(e);s.length>0&&o.push(`Set in production: ${H.dim(s.join(", "))}`),o.push("pnpm db:setup # Apply the database schema"),o.push(hp(e)),Je.note(o.join(`
1736
- `),H.yellow("Deployment"))}function mp(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 hp(e){switch(e.deploymentTarget){case"node":return"Deploy with Docker or your preferred Node.js host";case"vercel":return"vercel deploy # Deploy to Vercel"}}function ht(e){let r=(e.startsWith("v")?e.slice(1):e).match(/^(\d+)\.(\d+)\.(\d+)$/);return r?[Number(r[1]),Number(r[2]),Number(r[3])]:null}function _e(e,t){let r=ht(e),n=ht(t);if(!r||!n)return 0;for(let i=0;i<3;i++)if(r[i]!==n[i])return r[i]-n[i];return 0}function er(e,t){return e.versions.find(r=>r.version===t)?.cli}function ds(e){return process.env.GENERATESAAS_TEMPLATE_TARBALL||process.env.GENERATESAAS_TEMPLATE_TARBALL_DIR||process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?!0:ht(e)===null}function tr(e,t,r="3.37.0"){if(ds(r))return{ok:!0};let n=er(e,e.latest);return!n||ht(n)===null?{ok:!0}:_e(r,n)>=0?{ok:!0}:{ok:!1,message:`Your installed generatesaas CLI (v${r}) is too old for template v${e.latest}, which needs CLI v${n} or newer. Run npx generatesaas@latest ${t} so npm fetches the current CLI. If the release happened minutes ago, npm may still be propagating it - retry shortly.`}}function us(e,t,r="3.37.0"){if(ds(r))return{ok:!0};let n=er(e,t);return!n||ht(n)===null?{ok:!0}:_e(r,n)===0?{ok:!0}:{ok:!1,message:`Template v${t} must be scaffolded by CLI v${n} exactly (the CLI whose generators produced that release). Run npx generatesaas@${n} init.`}}import vp from"picocolors";var kp="a10a6fb9d7cadde32e37dad52059d17b5d2b916b08c76d8fbcc99982e9a3d87f";async function Ep(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 ms(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 Q("--architecture <type>","fullstack or separate").choices([...nt])).addOption(new Q("--payment <provider>","payment provider").choices([...it])).addOption(new Q("--email <provider>","email provider").choices([...st])).option("--org","enable multi-tenancy (organizations)").option("--no-org","disable multi-tenancy").option("--projects","enable projects (a switcher that scopes a user's work)").option("--no-projects","disable projects").option("--docs","include the docs app (apps/docs, Fumadocs)").option("--no-docs","exclude the docs app").option("--desktop","include the desktop app (apps/desktop, built with Electron)").option("--no-desktop","exclude the desktop app").option("--mobile","include the mobile app (apps/mobile, built with Expo)").option("--no-mobile","exclude the mobile app").addOption(new Q("--mobile-purchases <lane>","in-app purchases in the mobile app: revenuecat adds the store billing lane on top of your web payment provider, none keeps web billing only").choices([...je])).option("--ai","include the AI features (chat, models, automations, integrations)").option("--no-ai","exclude the AI features").option("--web-ai","show the AI features in the web app (the default)").option("--no-web-ai","desktop-first: keep the AI features out of the web app, which is reduced to account, login and billing - the desktop or mobile app is the AI product. Requires --desktop or --mobile, plus --ai").option("--revenue-sharing","enable revenue sharing").option("--no-revenue-sharing","disable revenue sharing").option("--credits","enable credits system").option("--no-credits","disable credits system (subscription-only)").addOption(new Q("--currency <code>","default currency for billing").choices([...ce])).addOption(new Q("--preset <preset>","infrastructure preset: serverless (Vercel + Neon + Upstash) or selfhost (Docker or Node + Postgres + Redis); --deploy/--database/--cache override it piecewise").choices([...$e])).addOption(new Q("--deploy <target>","deployment target").choices([...le])).addOption(new Q("--database <provider>","database provider").choices([...pe])).addOption(new Q("--cache <provider>","cache provider").choices([...de])).option("--observability <providers>",`comma-separated observability providers (${G.join(", ")}); anything unselected ships no SDK`).option("--api-key <key>","API key (skips interactive prompt)").option("--base-url <url>","public base URL (e.g. https://example.com) - bakes into canonical/og/sitemap").option("-y, --yes","accept defaults for unspecified options (non-interactive)").addOption(new Q("--demo","first-party demo build: keep sample content, mark site non-indexable - requires CI API key").hideHelp()).addOption(new Q("--no-db-migration","skip generating the baseline DB migration (internal: demos/CI/playground)").hideHelp()).action(async(t,r)=>{await Sp(t?{...r,apiKey:t}:r)})}async function Sp(e){let t=performance.now();Xr("3.37.0");let r;try{r=ln(e)}catch(v){E.cancel(N(v)),process.exit(1)}let n=E.spinner(),i;try{i=await at({apiKey:e.apiKey,prompt:!e.yes})}catch(v){E.cancel(N(v)),process.exit(1)}e.demo&&jr(i)!==kp&&(E.cancel("--demo is restricted to first-party demo deployments."),process.exit(1));let o=he(i),s,a=async()=>{s=await Ae(o);let v=tr(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 p,h,g=!0,k=!0;try{({latestVersion:p,selectedVersion:h,desktopAllowed:g,mobileAllowed:k}=await a()),n.stop("Access verified."),Ue(i)}catch(v){if(n.stop("Access verification failed."),v instanceof M&&v.status===401){e.yes&&(E.cancel("Invalid API key. Cannot prompt in non-interactive mode."),process.exit(1)),E.log.warning("Invalid API key."),i=await kt(),o=he(i),n.start("Verifying access...");try{({latestVersion:p,selectedVersion:h,desktopAllowed:g,mobileAllowed:k}=await a()),n.stop("Access verified."),Ue(i)}catch(L){n.stop("Access verification failed."),E.cancel(L instanceof M&&L.status===401?"Invalid API key.":N(L)),process.exit(1)}}else E.cancel(N(v)),process.exit(1)}E.log.success(`Latest version: ${p}`),r.desktop===!0&&!g&&(E.cancel("The desktop app is available on the Pro plan and up. Upgrade your plan at generatesaas.com."),process.exit(1)),r.mobile===!0&&!k&&(E.cancel("The mobile app is available on the Pro plan and up. Upgrade your plan at generatesaas.com."),process.exit(1));let w;e.yes?w=pn({...r,...g?{}:{desktop:!1},...k?{}:{mobile:!1}}):w=await dn(r,{desktopAllowed:g,mobileAllowed:k});let P;n.start("Activating license...");try{let v=e.demo&&w.baseUrl?await Ep(w.baseUrl):crypto.randomUUID(),L=()=>({frontend:mr,version:h,installId:v,projectName:w.projectName,options:bn(w)}),F;try{F=await hr(o,L())}catch(ve){let $=$t(ve);if(!$?.lastAllowedVersion||!s)throw ve;n.stop("License activation failed.");let W=us(s,$.lastAllowedVersion);if(W.ok||(E.cancel(`${$.message} ${W.message}`),process.exit(1)),e.yes){let z=er(s,$.lastAllowedVersion);E.cancel(`${$.message} Re-run ${z?`npx generatesaas@${z} init`:"init"} without --yes to continue with v${$.lastAllowedVersion} (the last version your license covers).`),process.exit(1)}let ke=await E.confirm({message:`Your update window has ended. Continue with v${$.lastAllowedVersion} (the last version your license covers)?`});(E.isCancel(ke)||!ke)&&(E.cancel("Setup cancelled."),process.exit(0)),h=$.lastAllowedVersion,n.start(`Activating license for v${h}...`),F=await hr(o,L())}P={token:F.token,keyHash:jr(i),installId:F.installId??v},n.stop("License activated.")}catch(v){n.stop("License activation failed."),E.cancel(N(v)),process.exit(1)}let u=wp(w.projectDir);if(fp(u)&&gp(u).length>0)if(e.yes)E.log.info(`Directory ${u} is not empty. Merging (keeping existing files, overwriting conflicts).`);else{let L=await E.select({message:`Directory ${u} is not empty.`,options:[{value:"merge",label:"Merge",hint:"keep existing files, overwrite conflicts"},{value:"overwrite",label:"Overwrite",hint:"delete everything and start fresh"},{value:"cancel",label:"Cancel"}]});(E.isCancel(L)||L==="cancel")&&(E.cancel("Setup cancelled."),process.exit(0)),L==="overwrite"&&yp(u,{recursive:!0,force:!0})}let O={...w,projectDir:u,version:h,...e.demo?{docs:!1}:{}};n.start("Downloading template...");try{await jt(o,h,u),n.stop("Template downloaded.")}catch(v){n.stop("Download failed."),E.cancel(N(v)),process.exit(1)}n.start("Generating project files...");try{if(await Xt(O),!e.demo){let v=await mt(u);await l(bp(u,Ct),`${JSON.stringify(v,null," ")}
1737
- `),await es(u,u)}await ns(u),await Zi(O,P),n.stop("Project files generated.")}catch(v){n.stop("Generation failed."),E.cancel(N(v)),process.exit(1)}!await is(u)&&O.demo===!0&&(E.cancel("Lockfile regeneration failed on a demo build - refusing to ship a stale lockfile."),process.exit(1));let B=await ss(u),oe=O.demo!==!0&&e.dbMigration!==!1,Oe=!1;oe&&B&&(await os(u),Oe=!0);let xe=B?await as(u):!1;await cs(u),B&&await ls(u);let De=Re("docker"),Qe=lr(O).map(v=>v.key).filter(v=>!O.credentials?.[v]);ps(O,{pnpmInstalled:B,dockerAvailable:De,skippedCredentials:Qe,baselineMigrationMissing:oe&&!Oe,mcpWidgetsUnbuilt:O.ai&&!xe}),Zr(),E.log.info(vp.dim(`Done in ${((performance.now()-t)/1e3).toFixed(1)}s`))}import{existsSync as rr}from"fs";import{readFile as ws}from"fs/promises";import{join as qe,resolve as Rp}from"path";import*as b from"@clack/prompts";import C from"picocolors";import{mkdtemp as Pp,rm as Ap}from"fs/promises";import{tmpdir as Ip}from"os";import{join as Tp}from"path";async function Kr(e,t,r,n,{olderRelease:i=!1}={}){let o=await Pp(Tp(Ip(),"generatesaas-stage-"));try{await jt(e,t,o);let s=()=>Xt({...r,projectDir:o}),a=[];return i?a=await Zn(s):await s(),await Mr(o,n),a}finally{await Ap(o,{recursive:!0,force:!0})}}function hs(e){return e?"ON":"OFF"}var ft="packages/config/src/index.ts";function fs(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 gs(e){return[...rt({databaseProvider:e.databaseProvider??"postgres",cacheProvider:e.cacheProvider??"redis",emailProvider:e.emailProvider??"smtp"})].sort()}var Hr=[{key:"errorTracking",severity:"warn",normalize:e=>{e.errorTracking===void 0||e.observability!==void 0||(e.observability=e.errorTracking==="none"?[]:[e.errorTracking])},preserved:()=>!0,describe:()=>"Retired option `errorTracking`: it is now `observability`, an array, because a project may run more than one provider at once. Your recorded choice was migrated across automatically."},{key:"companion",severity:"warn",normalize:e=>{e.companion===void 0||e.runner!==void 0||(e.runner=e.companion)},preserved:()=>!0,describe:()=>"Retired option `companion`: it was renamed to `runner`, and that lane has since been removed. Your recorded choice was migrated across automatically so the removal is reported under one name."},{key:"runner",severity:"warn",preserved:e=>e.runner!==!0,describe:()=>"Retired option `runner`: your project recorded the runner ON, and the paired-device lane is GONE - not moved to config, removed. This update deletes the pairing endpoint, the dispatch transport, the relay, the `/runner/*` routes and the Runners page from your project, so machines your users had paired are no longer reachable from it. Chat and automations keep running on your app's own AI backend (`config.ai`); nothing else about them changes."},{key:"companionSource",severity:"warn",preserved:()=>!1,describe:e=>`Retired option \`companionSource\`: your project recorded a \`${String(e.companionSource)}\` daemon source. The paired-device lane that daemon served has been removed from your project, so there is no daemon left to source.`},{key:"companionName",severity:"warn",preserved:()=>!1,describe:e=>`Retired option \`companionName\`: your project recorded a branded daemon called ${e.companionName}. The paired-device lane is gone, so your project no longer ships an install flow to brand. An existing install on a user's machine keeps running; it has nothing left to pair with here.`},{key:"companionRepoUrl",severity:"warn",preserved:()=>!1,describe:e=>`Retired option \`companionRepoUrl\`: your project pointed its install flow at ${e.companionRepoUrl}. The paired-device lane is gone, so there is no install flow left to point anywhere.`},{key:"companionLocalPath",severity:"warn",preserved:e=>(e.companionLocalPath??"").trim()==="",describe:e=>`Retired option \`companionLocalPath\`: your project recorded a local daemon checkout at ${e.companionLocalPath}. The option is gone, and so is the paired-device lane behind it - nothing in your project is built from a local daemon checkout any more.`},{key:"desktopAutoRelease",severity:"warn",applies:e=>e.desktop===!0,preserved:e=>e.desktopAutoRelease!==!0,describe:()=>"Retired option `desktopAutoRelease`: your project recorded automatic desktop releases, but the release trigger is no longer an option - cutting a release publishes signed installers from your repository and spends your Actions minutes, so it is always deliberate now. The staged `.github/workflows/desktop-release.yml` runs on `workflow_dispatch` only (the Actions tab). Add a `workflow_run` block to it if you want the CI-chained trigger back."},{key:"billingScope",severity:"ask",applies:e=>e.multiTenancy===!0,preserved:e=>e.billingScope!=="organization",describe:()=>"Retired option `billingScope`: your project recorded organization-scoped billing, and organization billing is GONE - not moved to config, removed. Money now lives only on a USER: an organization has no balance, no plan and no payment-provider customer of its own, and a workspace is funded by that organization's OWNER, whose personal balance every credit spent in it is drawn from. Payments already in flight are safe - a webhook arriving with old organization metadata is credited to that organization's owner rather than dropped - but a STORED balance is not: the `credits` and `plan` columns an organization holds them in are going away, and this update does NOT migrate them for you. MOVE every paying organization's credits and plan onto its owner BEFORE you take new checkouts, or that balance goes with the columns. How should this update proceed?"},{key:"socialProviders",severity:"warn",preserved:e=>(e.socialProviders??[]).length===0,describe:e=>`Retired option \`socialProviders\`: your project recorded ${(e.socialProviders??[]).join(", ")}, but it is now a plain config value that starts empty. Add those IDs back to \`config.auth.socialProviders\` in ${ft} or their sign-in buttons stop rendering.`},{key:"mcpServer",severity:"warn",preserved:e=>e.mcpServer!==!0,describe:()=>`Retired option \`mcpServer\`: your project recorded the outward MCP server ON, but its code now ships to every project behind a config gate generated OFF. Set \`config.mcpServer.enabled\` to \`true\` in ${ft} to keep your /mcp endpoint and its settings tab.`},{key:"emailTracking",severity:"ask",preserved:e=>e.emailTracking!==!1,describe:()=>`Retired option \`emailTracking\`: your project recorded email open/click tracking OFF, but it is now a plain config value generated ON. Applying this update as-is starts tracking opens and clicks for every user you mail. Put it back by setting \`config.email.tracking.enabled\` to \`false\` in ${ft}. How should this update proceed?`},{key:"aiBuiltin",severity:"warn",normalize:e=>{e.aiBuiltin===void 0&&e.aiByok!==void 0&&(e.aiBuiltin=e.aiByok===!1)},applies:e=>e.ai===!0,preserved:e=>e.aiBuiltin===re(e),describe:e=>`Retired option \`aiBuiltin\`: your project recorded built-in AI models ${hs(e.aiBuiltin)}, but it is now a plain config value generated ${hs(re(e))} for a project ${re(e)?"with":"without"} a payment provider. Set \`config.ai.builtin\` to \`${String(e.aiBuiltin===!0)}\` in ${ft} to keep your choice.`},{key:"aiByok",severity:"warn",applies:e=>e.ai===!0,preserved:e=>e.aiByok!==!1,describe:()=>`Retired option \`aiByok\`: your project recorded bring-your-own-key AI OFF, but it is now a plain config value generated ON. Set \`config.ai.byok\` to \`false\` in ${ft} to keep it off.`},{key:"dockerServices",severity:"warn",preserved:e=>fs(e).join(",")===gs(e).join(","),describe:e=>`Retired option \`dockerServices\`: your project recorded ${fs(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 ${gs(e).join(", ")}. Add any extra service back by hand; the file is yours to edit.`},{key:"aiTools",severity:"warn",preserved:e=>(e.aiTools??[]).length===tn.length,describe:e=>`Retired option \`aiTools\`: your project recorded ${(e.aiTools??[]).join(", ")||"no AI tools"}, but the \`generatesaas-update\` skill bundle now ships to every AI-tool root (${ze.join(", ")}) so it is there whichever assistant you switch to. Delete the roots you do not use - they are plain text files with no runtime path.`},{key:"blog",severity:"warn",preserved:e=>e.blog!==!1,describe:()=>`Retired option \`blog\`: your project recorded the blog OFF, but content is no longer an option. This update adds the \`/blog\`, \`/alternatives\` and \`/compare\` route code to your project; every one of them 404s until you add a file under \`packages/content/{locale}/{section}/\`, and none of them appears in your navbar, footer, sitemap or llms.txt while it is empty. Delete an entry from \`config.content.sections\` in ${ft} to drop a section for good.`}],eg=Hr.map(e=>e.key);function ys(e){for(let t of Hr)t.normalize?.(e)}function bs(e){let t=[];for(let r of Hr){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 vs(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",_p,[]).action(async(t,r)=>{r.args.length>0&&b.log.warn("`auto` is now the default and the argument is ignored.");let n=Op(t.answer),i=Rp(t.cwd??process.cwd()),o=qe(i,ue),s;try{s=JSON.parse(await ws(o,"utf-8"))}catch{b.cancel(".generatesaas/manifest.json not found. Run this from a GenerateSaaS project."),process.exit(1)}s.frontend===dr&&(b.cancel(`This project was generated on the Nuxt frontend (\`.generatesaas/manifest.json\` records \`frontend: "${dr}"\`).
1735
+ `),H.yellow("Dev Tools"));let s=[],o=fp(e);o.length>0&&s.push(`Set in production: ${H.dim(o.join(", "))}`),s.push("pnpm db:setup # Apply the database schema"),s.push(gp(e)),Je.note(s.join(`
1736
+ `),H.yellow("Deployment"))}function fp(e){let t=["DATABASE_URL","BETTER_AUTH_SECRET","INNGEST_APP_ID","INNGEST_EVENT_KEY","INNGEST_SIGNING_KEY"];return e.cacheProvider==="upstash"?t.push("UPSTASH_REDIS_REST_URL","UPSTASH_REDIS_REST_TOKEN"):t.push("REDIS_URL"),e.paymentProvider==="stripe"?t.push("STRIPE_SECRET_KEY","STRIPE_WEBHOOK_SECRET"):e.paymentProvider==="polar"&&t.push("POLAR_ACCESS_TOKEN","POLAR_WEBHOOK_SECRET"),e.emailProvider==="ses"?t.push("AMAZON_SES_REGION","AMAZON_SES_KEY","AMAZON_SES_SECRET"):e.emailProvider==="resend"?t.push("RESEND_API_KEY"):t.push("SMTP_HOST","SMTP_PORT"),t}function gp(e){switch(e.deploymentTarget){case"node":return"Deploy with Docker or your preferred Node.js host";case"vercel":return"vercel deploy # Deploy to Vercel"}}function ht(e){let r=(e.startsWith("v")?e.slice(1):e).match(/^(\d+)\.(\d+)\.(\d+)$/);return r?[Number(r[1]),Number(r[2]),Number(r[3])]:null}function _e(e,t){let r=ht(e),n=ht(t);if(!r||!n)return 0;for(let i=0;i<3;i++)if(r[i]!==n[i])return r[i]-n[i];return 0}function nr(e,t){return e.versions.find(r=>r.version===t)?.cli}function us(e){return process.env.GENERATESAAS_TEMPLATE_TARBALL||process.env.GENERATESAAS_TEMPLATE_TARBALL_DIR||process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?!0:ht(e)===null}function ir(e,t,r="3.39.0"){if(us(r))return{ok:!0};let n=nr(e,e.latest);return!n||ht(n)===null?{ok:!0}:_e(r,n)>=0?{ok:!0}:{ok:!1,message:`Your installed generatesaas CLI (v${r}) is too old for template v${e.latest}, which needs CLI v${n} or newer. Run npx generatesaas@latest ${t} so npm fetches the current CLI. If the release happened minutes ago, npm may still be propagating it - retry shortly.`}}function ms(e,t,r="3.39.0"){if(us(r))return{ok:!0};let n=nr(e,t);return!n||ht(n)===null?{ok:!0}:_e(r,n)===0?{ok:!0}:{ok:!1,message:`Template v${t} must be scaffolded by CLI v${n} exactly (the CLI whose generators produced that release). Run npx generatesaas@${n} init.`}}import Ep from"picocolors";var Sp="a10a6fb9d7cadde32e37dad52059d17b5d2b916b08c76d8fbcc99982e9a3d87f";async function Pp(e){let t=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`generatesaas-demo:${e}`)),r=[...new Uint8Array(t).subarray(0,16)].map(n=>n.toString(16).padStart(2,"0")).join("");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20,32)}`}function hs(e){e.command("init").description("Scaffold a new GenerateSaaS project").argument("[apiKey]","license key (same as --api-key)").option("-n, --name <name>","project name (lowercase, hyphens, starts with letter)").option("--app-name <name>","display name for the app").option("-l, --location <path>","project directory (default: ./{name})").addOption(new ee("--architecture <type>","fullstack or separate").choices([...nt])).addOption(new ee("--payment <provider>","payment provider").choices([...it])).addOption(new ee("--email <provider>","email provider").choices([...st])).option("--org","enable multi-tenancy (organizations)").option("--no-org","disable multi-tenancy").option("--projects","enable projects (a switcher that scopes a user's work)").option("--no-projects","disable projects").option("--docs","include the docs app (apps/docs, Fumadocs)").option("--no-docs","exclude the docs app").option("--desktop","include the desktop app (apps/desktop, built with Electron)").option("--no-desktop","exclude the desktop app").option("--mobile","include the mobile app (apps/mobile, built with Expo)").option("--no-mobile","exclude the mobile app").addOption(new ee("--mobile-purchases <lane>","in-app purchases in the mobile app: revenuecat adds the store billing lane on top of your web payment provider, none keeps web billing only").choices([...je])).option("--ai","include the AI features (chat, models, automations, integrations)").option("--no-ai","exclude the AI features").option("--web-ai","show the AI features in the web app (the default)").option("--no-web-ai","desktop-first: keep the AI features out of the web app, which is reduced to account, login and billing - the desktop or mobile app is the AI product. Requires --desktop or --mobile, plus --ai").option("--revenue-sharing","enable revenue sharing").option("--no-revenue-sharing","disable revenue sharing").option("--credits","enable credits system").option("--no-credits","disable credits system (subscription-only)").addOption(new ee("--currency <code>","default currency for billing").choices([...ce])).addOption(new ee("--preset <preset>","infrastructure preset: serverless (Vercel + Neon + Upstash) or selfhost (Docker or Node + Postgres + Redis); --deploy/--database/--cache override it piecewise").choices([...$e])).addOption(new ee("--deploy <target>","deployment target").choices([...le])).addOption(new ee("--database <provider>","database provider").choices([...pe])).addOption(new ee("--cache <provider>","cache provider").choices([...de])).option("--observability <providers>",`comma-separated observability providers (${G.join(", ")}); anything unselected ships no SDK`).option("--api-key <key>","API key (skips interactive prompt)").option("--base-url <url>","public base URL (e.g. https://example.com) - bakes into canonical/og/sitemap").option("-y, --yes","accept defaults for unspecified options (non-interactive)").addOption(new ee("--demo","first-party demo build: keep sample content, mark site non-indexable - requires CI API key").hideHelp()).addOption(new ee("--no-db-migration","skip generating the baseline DB migration (internal: demos/CI/playground)").hideHelp()).action(async(t,r)=>{await Ap(t?{...r,apiKey:t}:r)})}async function Ap(e){let t=performance.now();Zr("3.39.0");let r;try{r=pn(e)}catch(v){E.cancel(N(v)),process.exit(1)}let n=E.spinner(),i;try{i=await at({apiKey:e.apiKey,prompt:!e.yes})}catch(v){E.cancel(N(v)),process.exit(1)}e.demo&&Fr(i)!==Sp&&(E.cancel("--demo is restricted to first-party demo deployments."),process.exit(1));let s=he(i),o,a=async()=>{o=await Ae(s);let v=ir(o,"init");if(!v.ok)throw new Error(v.message);return{latestVersion:o.latest,selectedVersion:o.latest,desktopAllowed:o.entitlements?.desktopAllowed??!0,mobileAllowed:o.entitlements?.mobileAllowed??!0}};n.start("Verifying access...");let p,h,g=!0,k=!0;try{({latestVersion:p,selectedVersion:h,desktopAllowed:g,mobileAllowed:k}=await a()),n.stop("Access verified."),Ue(i)}catch(v){if(n.stop("Access verification failed."),v instanceof M&&v.status===401){e.yes&&(E.cancel("Invalid API key. Cannot prompt in non-interactive mode."),process.exit(1)),E.log.warning("Invalid API key."),i=await kt(),s=he(i),n.start("Verifying access...");try{({latestVersion:p,selectedVersion:h,desktopAllowed:g,mobileAllowed:k}=await a()),n.stop("Access verified."),Ue(i)}catch(L){n.stop("Access verification failed."),E.cancel(L instanceof M&&L.status===401?"Invalid API key.":N(L)),process.exit(1)}}else E.cancel(N(v)),process.exit(1)}E.log.success(`Latest version: ${p}`),r.desktop===!0&&!g&&(E.cancel("The desktop app is available on the Pro plan and up. Upgrade your plan at generatesaas.com."),process.exit(1)),r.mobile===!0&&!k&&(E.cancel("The mobile app is available on the Pro plan and up. Upgrade your plan at generatesaas.com."),process.exit(1));let w;e.yes?w=dn({...r,...g?{}:{desktop:!1},...k?{}:{mobile:!1}}):w=await un(r,{desktopAllowed:g,mobileAllowed:k});let P;n.start("Activating license...");try{let v=e.demo&&w.baseUrl?await Pp(w.baseUrl):crypto.randomUUID(),L=()=>({frontend:gr,version:h,installId:v,projectName:w.projectName,options:wn(w)}),F;try{F=await yr(s,L())}catch(ve){let $=$t(ve);if(!$?.lastAllowedVersion||!o)throw ve;n.stop("License activation failed.");let W=ms(o,$.lastAllowedVersion);if(W.ok||(E.cancel(`${$.message} ${W.message}`),process.exit(1)),e.yes){let z=nr(o,$.lastAllowedVersion);E.cancel(`${$.message} Re-run ${z?`npx generatesaas@${z} init`:"init"} without --yes to continue with v${$.lastAllowedVersion} (the last version your license covers).`),process.exit(1)}let ke=await E.confirm({message:`Your update window has ended. Continue with v${$.lastAllowedVersion} (the last version your license covers)?`});(E.isCancel(ke)||!ke)&&(E.cancel("Setup cancelled."),process.exit(0)),h=$.lastAllowedVersion,n.start(`Activating license for v${h}...`),F=await yr(s,L())}P={token:F.token,keyHash:Fr(i),installId:F.installId??v},n.stop("License activated.")}catch(v){n.stop("License activation failed."),E.cancel(N(v)),process.exit(1)}let u=kp(w.projectDir);if(yp(u)&&bp(u).length>0)if(e.yes)E.log.info(`Directory ${u} is not empty. Merging (keeping existing files, overwriting conflicts).`);else{let L=await E.select({message:`Directory ${u} is not empty.`,options:[{value:"merge",label:"Merge",hint:"keep existing files, overwrite conflicts"},{value:"overwrite",label:"Overwrite",hint:"delete everything and start fresh"},{value:"cancel",label:"Cancel"}]});(E.isCancel(L)||L==="cancel")&&(E.cancel("Setup cancelled."),process.exit(0)),L==="overwrite"&&wp(u,{recursive:!0,force:!0})}let O={...w,projectDir:u,version:h,...e.demo?{docs:!1}:{}};n.start("Downloading template...");try{await jt(s,h,u),n.stop("Template downloaded.")}catch(v){n.stop("Download failed."),E.cancel(N(v)),process.exit(1)}n.start("Generating project files...");try{if(await Xt(O),!e.demo){let v=await mt(u);await l(vp(u,Ct),`${JSON.stringify(v,null," ")}
1737
+ `),await ts(u,u)}await is(u),await Qi(O,P),n.stop("Project files generated.")}catch(v){n.stop("Generation failed."),E.cancel(N(v)),process.exit(1)}!await ss(u)&&O.demo===!0&&(E.cancel("Lockfile regeneration failed on a demo build - refusing to ship a stale lockfile."),process.exit(1));let B=await os(u),oe=O.demo!==!0&&e.dbMigration!==!1,Oe=!1;oe&&B&&(await as(u),Oe=!0);let xe=B?await cs(u):!1;await ls(u),B&&await ps(u);let De=Re("docker"),Qe=ur(O).map(v=>v.key).filter(v=>!O.credentials?.[v]);ds(O,{pnpmInstalled:B,dockerAvailable:De,skippedCredentials:Qe,baselineMigrationMissing:oe&&!Oe,mcpWidgetsUnbuilt:O.ai&&!xe}),Qr(),E.log.info(Ep.dim(`Done in ${((performance.now()-t)/1e3).toFixed(1)}s`))}import{existsSync as sr}from"fs";import{readFile as vs}from"fs/promises";import{join as qe,resolve as Op}from"path";import*as b from"@clack/prompts";import C from"picocolors";import{mkdtemp as Ip,rm as Tp}from"fs/promises";import{tmpdir as Rp}from"os";import{join as _p}from"path";async function Hr(e,t,r,n,{olderRelease:i=!1}={}){let s=await Ip(_p(Rp(),"generatesaas-stage-"));try{await jt(e,t,s);let o=()=>Xt({...r,projectDir:s}),a=[];return i?a=await Qn(o):await o(),await Vr(s,n),a}finally{await Tp(s,{recursive:!0,force:!0})}}function fs(e){return e?"ON":"OFF"}var ft="packages/config/src/index.ts";function gs(e){let t=e.databaseProvider!==void 0&&e.databaseProvider!=="postgres",r=e.cacheProvider!==void 0&&e.cacheProvider!=="redis";return[...e.dockerServices??[]].filter(n=>!(n==="postgres"&&t)&&!(n==="redis"&&r)).sort()}function ys(e){return[...rt({databaseProvider:e.databaseProvider??"postgres",cacheProvider:e.cacheProvider??"redis",emailProvider:e.emailProvider??"smtp"})].sort()}var Yr=[{key:"errorTracking",severity:"warn",normalize:e=>{e.errorTracking===void 0||e.observability!==void 0||(e.observability=e.errorTracking==="none"?[]:[e.errorTracking])},preserved:()=>!0,describe:()=>"Retired option `errorTracking`: it is now `observability`, an array, because a project may run more than one provider at once. Your recorded choice was migrated across automatically."},{key:"companion",severity:"warn",normalize:e=>{e.companion===void 0||e.runner!==void 0||(e.runner=e.companion)},preserved:()=>!0,describe:()=>"Retired option `companion`: it was renamed to `runner`, and that lane has since been removed. Your recorded choice was migrated across automatically so the removal is reported under one name."},{key:"runner",severity:"warn",preserved:e=>e.runner!==!0,describe:()=>"Retired option `runner`: your project recorded the runner ON, and the paired-device lane is GONE - not moved to config, removed. This update deletes the pairing endpoint, the dispatch transport, the relay, the `/runner/*` routes and the Runners page from your project, so machines your users had paired are no longer reachable from it. Chat and automations keep running on your app's own AI backend (`config.ai`); nothing else about them changes."},{key:"companionSource",severity:"warn",preserved:()=>!1,describe:e=>`Retired option \`companionSource\`: your project recorded a \`${String(e.companionSource)}\` daemon source. The paired-device lane that daemon served has been removed from your project, so there is no daemon left to source.`},{key:"companionName",severity:"warn",preserved:()=>!1,describe:e=>`Retired option \`companionName\`: your project recorded a branded daemon called ${e.companionName}. The paired-device lane is gone, so your project no longer ships an install flow to brand. An existing install on a user's machine keeps running; it has nothing left to pair with here.`},{key:"companionRepoUrl",severity:"warn",preserved:()=>!1,describe:e=>`Retired option \`companionRepoUrl\`: your project pointed its install flow at ${e.companionRepoUrl}. The paired-device lane is gone, so there is no install flow left to point anywhere.`},{key:"companionLocalPath",severity:"warn",preserved:e=>(e.companionLocalPath??"").trim()==="",describe:e=>`Retired option \`companionLocalPath\`: your project recorded a local daemon checkout at ${e.companionLocalPath}. The option is gone, and so is the paired-device lane behind it - nothing in your project is built from a local daemon checkout any more.`},{key:"desktopAutoRelease",severity:"warn",applies:e=>e.desktop===!0,preserved:e=>e.desktopAutoRelease!==!0,describe:()=>"Retired option `desktopAutoRelease`: your project recorded automatic desktop releases, but the release trigger is no longer an option - cutting a release publishes signed installers from your repository and spends your Actions minutes, so it is always deliberate now. The staged `.github/workflows/desktop-release.yml` runs on `workflow_dispatch` only (the Actions tab). Add a `workflow_run` block to it if you want the CI-chained trigger back."},{key:"billingScope",severity:"ask",applies:e=>e.multiTenancy===!0,preserved:e=>e.billingScope!=="organization",describe:()=>"Retired option `billingScope`: your project recorded organization-scoped billing, and organization billing is GONE - not moved to config, removed. Money now lives only on a USER: an organization has no balance, no plan and no payment-provider customer of its own, and a workspace is funded by that organization's OWNER, whose personal balance every credit spent in it is drawn from. Payments already in flight are safe - a webhook arriving with old organization metadata is credited to that organization's owner rather than dropped - but a STORED balance is not: the `credits` and `plan` columns an organization holds them in are going away, and this update does NOT migrate them for you. MOVE every paying organization's credits and plan onto its owner BEFORE you take new checkouts, or that balance goes with the columns. How should this update proceed?"},{key:"socialProviders",severity:"warn",preserved:e=>(e.socialProviders??[]).length===0,describe:e=>`Retired option \`socialProviders\`: your project recorded ${(e.socialProviders??[]).join(", ")}, but it is now a plain config value that starts empty. Add those IDs back to \`config.auth.socialProviders\` in ${ft} or their sign-in buttons stop rendering.`},{key:"mcpServer",severity:"warn",preserved:e=>e.mcpServer!==!0,describe:()=>`Retired option \`mcpServer\`: your project recorded the outward MCP server ON, but its code now ships to every project behind a config gate generated OFF. Set \`config.mcpServer.enabled\` to \`true\` in ${ft} to keep your /mcp endpoint and its settings tab.`},{key:"emailTracking",severity:"ask",preserved:e=>e.emailTracking!==!1,describe:()=>`Retired option \`emailTracking\`: your project recorded email open/click tracking OFF, but it is now a plain config value generated ON. Applying this update as-is starts tracking opens and clicks for every user you mail. Put it back by setting \`config.email.tracking.enabled\` to \`false\` in ${ft}. How should this update proceed?`},{key:"aiBuiltin",severity:"warn",normalize:e=>{e.aiBuiltin===void 0&&e.aiByok!==void 0&&(e.aiBuiltin=e.aiByok===!1)},applies:e=>e.ai===!0,preserved:e=>e.aiBuiltin===ne(e),describe:e=>`Retired option \`aiBuiltin\`: your project recorded built-in AI models ${fs(e.aiBuiltin)}, but it is now a plain config value generated ${fs(ne(e))} for a project ${ne(e)?"with":"without"} a payment provider. Set \`config.ai.builtin\` to \`${String(e.aiBuiltin===!0)}\` in ${ft} to keep your choice.`},{key:"aiByok",severity:"warn",applies:e=>e.ai===!0,preserved:e=>e.aiByok!==!1,describe:()=>`Retired option \`aiByok\`: your project recorded bring-your-own-key AI OFF, but it is now a plain config value generated ON. Set \`config.ai.byok\` to \`false\` in ${ft} to keep it off.`},{key:"dockerServices",severity:"warn",preserved:e=>gs(e).join(",")===ys(e).join(","),describe:e=>`Retired option \`dockerServices\`: your project recorded ${gs(e).join(", ")||"no services"}, but the local Docker services are now DERIVED from your stack - postgres when you self-host Postgres, redis when you self-host Redis, mailpit on SMTP, inngest always - so an inconsistent selection is no longer possible. Your regenerated \`infra/docker-compose.yml\` will contain ${ys(e).join(", ")}. Add any extra service back by hand; the file is yours to edit.`},{key:"aiTools",severity:"warn",preserved:e=>(e.aiTools??[]).length===rn.length,describe:e=>`Retired option \`aiTools\`: your project recorded ${(e.aiTools??[]).join(", ")||"no AI tools"}, but the \`generatesaas-update\` skill bundle now ships to every AI-tool root (${ze.join(", ")}) so it is there whichever assistant you switch to. Delete the roots you do not use - they are plain text files with no runtime path.`},{key:"blog",severity:"warn",preserved:e=>e.blog!==!1,describe:()=>`Retired option \`blog\`: your project recorded the blog OFF, but content is no longer an option. This update adds the \`/blog\`, \`/alternatives\` and \`/compare\` route code to your project; every one of them 404s until you add a file under \`packages/content/{locale}/{section}/\`, and none of them appears in your navbar, footer, sitemap or llms.txt while it is empty. Delete an entry from \`config.content.sections\` in ${ft} to drop a section for good.`}],rg=Yr.map(e=>e.key);function bs(e){for(let t of Yr)t.normalize?.(e)}function ws(e){let t=[];for(let r of Yr){if(r.normalize?.(e),e[r.key]===void 0)continue;(!r.applies||r.applies(e))&&!r.preserved(e)&&t.push({key:r.key,message:r.describe(e),severity:r.severity}),delete e[r.key]}return t}function ks(e){e.command("update").description("Update AI skill files and stage template updates").allowExcessArguments(!0).option("--cwd <path>","project directory (default: current directory)").option("--answer <id=choice>","answer a question that would otherwise prompt (repeatable), e.g. --answer desktop-migration=keep-ai",xp,[]).action(async(t,r)=>{r.args.length>0&&b.log.warn("`auto` is now the default and the argument is ignored.");let n=Dp(t.answer),i=Op(t.cwd??process.cwd()),s=qe(i,ue),o;try{o=JSON.parse(await vs(s,"utf-8"))}catch{b.cancel(".generatesaas/manifest.json not found. Run this from a GenerateSaaS project."),process.exit(1)}o.frontend===hr&&(b.cancel(`This project was generated on the Nuxt frontend (\`.generatesaas/manifest.json\` records \`frontend: "${hr}"\`).
1738
1738
 
1739
- v${ur} is the last release that ships a Nuxt frontend, and this CLI cannot update or migrate a Nuxt project to Next.js.
1739
+ v${fr} is the last release that ships a Nuxt frontend, and this CLI cannot update or migrate a Nuxt project to Next.js.
1740
1740
 
1741
- Your project keeps working exactly as it is - stay on v${ur}, or start a fresh project on Next.js with ${C.cyan("generatesaas init")} when you are ready to move.`),process.exit(1));let a=nn(s);a.length>0&&(b.cancel(`.generatesaas/manifest.json carries a value this CLI cannot shape a project from:
1741
+ Your project keeps working exactly as it is - stay on v${fr}, or start a fresh project on Next.js with ${C.cyan("generatesaas init")} when you are ready to move.`),process.exit(1));let a=sn(o);a.length>0&&(b.cancel(`.generatesaas/manifest.json carries a value this CLI cannot shape a project from:
1742
1742
 
1743
1743
  ${a.map(u=>` - ${u}`).join(`
1744
1744
  `)}
1745
1745
 
1746
- Correct it there, then run ${C.cyan("generatesaas update")} again.`),process.exit(1)),ys(s);let p=or(s);p.length>0&&(b.cancel(`.generatesaas/manifest.json records a combination this project cannot run:
1746
+ Correct it there, then run ${C.cyan("generatesaas update")} again.`),process.exit(1)),bs(o);let p=lr(o);p.length>0&&(b.cancel(`.generatesaas/manifest.json records a combination this project cannot run:
1747
1747
 
1748
1748
  ${p.map(u=>` - ${u}`).join(`
1749
1749
  `)}
1750
1750
 
1751
- Correct it there, then run ${C.cyan("generatesaas update")} again.`),process.exit(1));let h=on(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:
1751
+ Correct it there, then run ${C.cyan("generatesaas update")} again.`),process.exit(1));let h=an(o);h.length>0&&(b.cancel(`.generatesaas/manifest.json turns the web AI surface off (\`webAi: false\`) in a project that cannot run without it:
1752
1752
 
1753
1753
  ${h.map(u=>` - ${u}`).join(`
1754
1754
  `)}
1755
1755
 
1756
- Correct it there, then run ${C.cyan("generatesaas update")} again.`),process.exit(1));let g=an(s);g.length>0&&(b.cancel(`.generatesaas/manifest.json turns on mobile store purchases (\`mobilePurchases: "revenuecat"\`) in a project that cannot run them:
1756
+ Correct it there, then run ${C.cyan("generatesaas update")} again.`),process.exit(1));let g=cn(o);g.length>0&&(b.cancel(`.generatesaas/manifest.json turns on mobile store purchases (\`mobilePurchases: "revenuecat"\`) in a project that cannot run them:
1757
1757
 
1758
1758
  ${g.map(u=>` - ${u}`).join(`
1759
1759
  `)}
1760
1760
 
1761
- Correct it there, then run ${C.cyan("generatesaas update")} again.`),process.exit(1));let k;try{k=await at()}catch(u){b.cancel(N(u)),process.exit(1)}let w=he(k),P=b.spinner();try{P.start("Verifying access...");let u;try{u=await Ae(w)}catch(T){throw T instanceof M&&T.status===401?new Error("Your saved API key was rejected. Run `generatesaas auth` to update it, or set GENERATESAAS_API_KEY."):T}let O=tr(u,"update");if(!O.ok)throw new Error(O.message);P.stop("Access verified."),Ue(k),P.start("Fetching latest skill files...");let be=await yn(w,u.latest);await Br(i,be.skills);let B=ze;if(P.stop("Skills updated."),b.log.success(`Skill files installed to ${C.cyan(B.length.toString())} locations.`),s.version===u.latest){b.log.info(`Already on the latest version (${s.version}).`);return}_e(s.version,u.latest)>0&&(b.cancel(`This project is on ${s.version}, which is newer than the latest release (${u.latest}). Updating would stage the older template over it. Check that your API key points at the right account, or correct \`version\` in ${ue}.`),process.exit(1));let oe=u.entitlements;oe&&(s.desktop&&!oe.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&&oe.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 Oe=JSON.stringify(s);await xp(s,cn(s),n),await Dp(bs(s),n);let xe=rn(s),De=sn(s),we=or(De);we.length>0&&(b.cancel(`.generatesaas/manifest.json is missing a provider key, and its default would create a combination this project cannot run:
1761
+ Correct it there, then run ${C.cyan("generatesaas update")} again.`),process.exit(1));let k;try{k=await at()}catch(u){b.cancel(N(u)),process.exit(1)}let w=he(k),P=b.spinner();try{P.start("Verifying access...");let u;try{u=await Ae(w)}catch(T){throw T instanceof M&&T.status===401?new Error("Your saved API key was rejected. Run `generatesaas auth` to update it, or set GENERATESAAS_API_KEY."):T}let O=ir(u,"update");if(!O.ok)throw new Error(O.message);P.stop("Access verified."),Ue(k),P.start("Fetching latest skill files...");let be=await bn(w,u.latest);await Gr(i,be.skills);let B=ze;if(P.stop("Skills updated."),b.log.success(`Skill files installed to ${C.cyan(B.length.toString())} locations.`),o.version===u.latest){b.log.info(`Already on the latest version (${o.version}).`);return}_e(o.version,u.latest)>0&&(b.cancel(`This project is on ${o.version}, which is newer than the latest release (${u.latest}). Updating would stage the older template over it. Check that your API key points at the right account, or correct \`version\` in ${ue}.`),process.exit(1));let oe=u.entitlements;oe&&(o.desktop&&!oe.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)),o.mobile&&oe.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 Oe=JSON.stringify(o);await Np(o,ln(o),n),await Cp(ws(o),n);let xe=nn(o),De=on(o),we=lr(De);we.length>0&&(b.cancel(`.generatesaas/manifest.json is missing a provider key, and its default would create a combination this project cannot run:
1762
1762
 
1763
1763
  ${we.map(T=>` - ${T}`).join(`
1764
1764
  `)}
1765
1765
 
1766
- 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 Qe=JSON.stringify(De)!==Oe;if(s=De,s.licenseToken)try{let T=await wn(w,{currentToken:s.licenseToken,newVersion:u.latest});s.licenseToken=T.token,T.licenseKeyHash&&(s.licenseKeyHash=T.licenseKeyHash),await l(o,`${JSON.stringify(s,null," ")}
1767
- `),Qe=!1,b.log.success("License refreshed.")}catch(T){let c=$t(T);c&&(b.cancel(c.message),process.exit(1)),b.log.warn("License refresh skipped.")}Qe&&await l(o,`${JSON.stringify(s,null," ")}
1768
- `);let v=Xi(s,i),L=qe(i,hn);P.start(`Staging v${u.latest} (shaped for your config)...`),await Kr(w,u.latest,v,L),P.stop("Template staged.");let{text:F,title:ve}=await Lp(w,u,s.version);F&&b.note(F,ve);let $=qe(i,Ct),W=qe(i,Lt),ke=!rr(W),z=!rr($);if(ke){P.start("Building baseline template (one-time migration)...");let T=await Kr(w,s.version,v,W,{olderRelease:!0});if(z){let c=await mt(W);await l($,`${JSON.stringify(c,null," ")}
1769
- `)}if(P.stop("Baseline template stored."),T.length>0&&b.log.info(`v${s.version} predates ${T.length} strip seam(s) of this CLI, so the rebuilt baseline keeps those parts as v${s.version} shipped them.`),!z){let c=await $p($,W);c>0&&b.log.warn(`Rebuilt baseline differs from the original for ${c} 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 T=await mt(W);await l($,`${JSON.stringify(T,null," ")}
1770
- `),P.stop("Baseline hashes computed.")}await l(qe(i,fn),`${JSON.stringify({currentVersion:s.version,targetVersion:u.latest,changelog:F,stagedAt:new Date().toISOString(),...xe.length>0?{newOptions:xe}:{}},null," ")}
1771
- `),b.log.info(`Update staged: ${C.cyan(s.version)} \u2192 ${C.cyan(u.latest)}`),b.log.info(`Ask your AI coding assistant to ${C.cyan("'update my GenerateSaaS project'")}.`),s.desktop===!0&&rr(qe(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&&rr(qe(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(u){P.stop("Failed."),b.cancel(`Update failed: ${N(u)}`),process.exit(1)}})}var ks="desktop-migration";function _p(e,t){return t.push(e),t}function Op(e){let t=new Set([ks,...Object.keys(Ss).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 Es(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}
1766
+ 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 Qe=JSON.stringify(De)!==Oe;if(o=De,o.licenseToken)try{let T=await vn(w,{currentToken:o.licenseToken,newVersion:u.latest});o.licenseToken=T.token,T.licenseKeyHash&&(o.licenseKeyHash=T.licenseKeyHash),await l(s,`${JSON.stringify(o,null," ")}
1767
+ `),Qe=!1,b.log.success("License refreshed.")}catch(T){let c=$t(T);c&&(b.cancel(c.message),process.exit(1)),b.log.warn("License refresh skipped.")}Qe&&await l(s,`${JSON.stringify(o,null," ")}
1768
+ `);let v=Zi(o,i),L=qe(i,fn);P.start(`Staging v${u.latest} (shaped for your config)...`),await Hr(w,u.latest,v,L),P.stop("Template staged.");let{text:F,title:ve}=await jp(w,u,o.version);F&&b.note(F,ve);let $=qe(i,Ct),W=qe(i,Lt),ke=!sr(W),z=!sr($);if(ke){P.start("Building baseline template (one-time migration)...");let T=await Hr(w,o.version,v,W,{olderRelease:!0});if(z){let c=await mt(W);await l($,`${JSON.stringify(c,null," ")}
1769
+ `)}if(P.stop("Baseline template stored."),T.length>0&&b.log.info(`v${o.version} predates ${T.length} strip seam(s) of this CLI, so the rebuilt baseline keeps those parts as v${o.version} shipped them.`),!z){let c=await Mp($,W);c>0&&b.log.warn(`Rebuilt baseline differs from the original for ${c} 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 T=await mt(W);await l($,`${JSON.stringify(T,null," ")}
1770
+ `),P.stop("Baseline hashes computed.")}await l(qe(i,gn),`${JSON.stringify({currentVersion:o.version,targetVersion:u.latest,changelog:F,stagedAt:new Date().toISOString(),...xe.length>0?{newOptions:xe}:{}},null," ")}
1771
+ `),b.log.info(`Update staged: ${C.cyan(o.version)} \u2192 ${C.cyan(u.latest)}`),b.log.info(`Ask your AI coding assistant to ${C.cyan("'update my GenerateSaaS project'")}.`),o.desktop===!0&&sr(qe(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")}.`),o.desktop===!0&&sr(qe(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(u){P.stop("Failed."),b.cancel(`Update failed: ${N(u)}`),process.exit(1)}})}var Es="desktop-migration";function xp(e,t){return t.push(e),t}function Dp(e){let t=new Set([Es,...Object.keys(Ps).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 s=n.slice(0,i);t.has(s)||(b.cancel(`\`--answer ${n}\` names a question this update does not ask. Valid ids: ${[...t].join(", ")}.`),process.exit(1)),r.set(s,n.slice(i+1))}return r}async function Ss(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(s=>({value:s.id,label:s.label,...s.hint?{hint:s.hint}:{}}))});b.isCancel(n)&&(b.cancel("Update cancelled. Nothing was changed or staged."),process.exit(1));let i=e.choices.find(s=>s.id===n);return i||(b.cancel("Update cancelled. Nothing was changed or staged."),process.exit(1)),i}b.cancel(`${e.message}
1772
1772
 
1773
1773
  This update is running without an interactive terminal, so it cannot ask you directly. Answer the question \`${e.id}\` and re-run, for example:
1774
1774
 
@@ -1776,24 +1776,24 @@ This update is running without an interactive terminal, so it cannot ask you dir
1776
1776
 
1777
1777
  Choices:
1778
1778
  ${e.choices.map(n=>` - ${n.id}: ${n.label}${n.hint?` (${n.hint})`:""}`).join(`
1779
- `)}`),process.exit(1)}async function xp(e,t,r){if(t.kind==="none")return;let n=Cp[t.kind];(await Es({id:ks,message:n.message,choices:n.choices},r)).apply(e)}var Ss={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 Dp(e,t){let r=[];for(let n of e){let i=n.severity==="ask"?Ss[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 Es({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 Np(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:Np}]}};async function Lp(e,t,r){let n=t.latest,i=t.versions.filter(p=>_e(p.version,r)>0&&_e(p.version,n)<=0).sort((p,h)=>_e(p.version,h.version)),o=async p=>{try{return await gn(e,p)}catch{return null}};if(i.length<=1)return{text:await o(n),title:`Changelog v${n}`};let s=await Promise.all(i.map(p=>o(p.version)));return{text:i.map((p,h)=>{let g=p.date?` (${p.date.slice(0,10)})`:"",k=s[h]??"_No changelog available for this release._";return`# v${p.version}${g}
1779
+ `)}`),process.exit(1)}async function Np(e,t,r){if(t.kind==="none")return;let n=$p[t.kind];(await Ss({id:Es,message:n.message,choices:n.choices},r)).apply(e)}var Ps={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 Cp(e,t){let r=[];for(let n of e){let i=n.severity==="ask"?Ps[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 Ss({id:`retired:${n.key}`,message:n.message,choices:i.map(o=>({id:o.value,label:o.label,hint:o.hint}))},t)).id==="stop"&&(b.cancel("Update cancelled. Nothing was changed or staged."),process.exit(1))}function Lp(e){e.desktop=!1}var $p={"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:Lp}]}};async function jp(e,t,r){let n=t.latest,i=t.versions.filter(p=>_e(p.version,r)>0&&_e(p.version,n)<=0).sort((p,h)=>_e(p.version,h.version)),s=async p=>{try{return await yn(e,p)}catch{return null}};if(i.length<=1)return{text:await s(n),title:`Changelog v${n}`};let o=await Promise.all(i.map(p=>s(p.version)));return{text:i.map((p,h)=>{let g=p.date?` (${p.date.slice(0,10)})`:"",k=o[h]??"_No changelog available for this release._";return`# v${p.version}${g}
1780
1780
 
1781
1781
  ${k}`}).join(`
1782
1782
 
1783
- `),title:`Changelog v${r} \u2192 v${n}`}}async function $p(e,t){let r=JSON.parse(await ws(e,"utf-8")),n=await mt(t),i=0;for(let[o,s]of Object.entries(r))ct(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 jp}from"fs/promises";import{join as Mp,resolve as Up}from"path";function Ps(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=Up(t.cwd??process.cwd()),n=Mp(r,ue),i;try{i=JSON.parse(await jp(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(`
1784
- `);Y.note(o,ye.bold("Project Status"));let s=Y.spinner();s.start("Checking for updates...");try{let a=await at(),p=he(a),g=(await Ae(p)).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 M&&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 Fp}from"buffer";import{readFile as Vp}from"fs/promises";import*as D from"@clack/prompts";import x from"picocolors";function Bp(){return process.env.GENERATESAAS_API_KEY??vt()}function Gp(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 Kp(e){return{verdict:e.verdict??"unknown",ejectedAt:e.ejectedAt??null}}function Hp(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 As(e,t){let r=process.env.GENERATESAAS_API_URL??wt,n=Bp();e.start("Cross-referencing license records...");try{let i=n?Gp(await vn(r,n,{lkh:t.lkh,nid:t.nid,domain:t.domain})):Kp(await fr(r,{token:t.token,domain:t.domain}));return e.stop(`${x.green("Checked")} - records cross-referenced`),Hp(i)}catch(i){return e.stop(`${x.yellow("Skipped")} - ${N(i)}`),null}}function Yp(e){let t=e.split(".");if(t.length!==3||!t[1])throw new Error("Invalid JWT format");let r=Fp.from(t[1],"base64url").toString("utf-8");return JSON.parse(r)}function Yr(e){return typeof e!="number"?"unknown":new Date(e*1e3).toISOString().split("T")[0]}function Is(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: ${Yr(e.pat)}`,`Last updated: ${Yr(e.uat)}`,`Expires: ${Yr(e.exp)}`,`Install ID: ${String(e.nid??"unknown")}`].join(`
1785
- `),x.yellow("License Details"))}function Wp(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 Ts(e){let t=D.spinner(),r=null,n="no candidates";for(let s of Wp(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 p=(await a.text()).trim();if(!p||p.split(".").length!==3){n=`${s} did not return a JWT`,t.stop(`${x.yellow("Not here")} - ${n}`);continue}r=p,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=Rs(e);return s?await As(t,{domain:s})??!1:!1}let i;try{i=Yp(r)}catch{return D.log.error("Could not decode JWT payload."),!1}t.start("Verifying signature...");try{let s=process.env.GENERATESAAS_API_URL??wt,a=await fr(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:"),Is(i),!1}return Is(i),await As(t,{token:r,lkh:typeof i.lkh=="string"?i.lkh:void 0,nid:typeof i.nid=="string"?i.nid:void 0,domain:Rs(e)})??!0}function Rs(e){try{return new URL(/^https?:\/\//i.test(e)?e:`https://${e}`).hostname}catch{return}}function _s(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 Vp(r.file,"utf-8")).split(`
1786
- `).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 Ts(s)&&o++,D.log.info("");D.log.success(`${o}/${i.length} sites verified.`)}else await Ts(t)||process.exit(1)})}import{existsSync as zp,rmSync as Jp}from"fs";import*as ee from"@clack/prompts";function Os(e){e.command("auth").description("Set or update your GenerateSaaS API key").option("--clear","remove saved API key").action(async t=>{if(t.clear){zp(me)?(Jp(me),ee.log.success("API key removed.")):ee.log.info("No API key configured.");return}let r=vt();r?ee.log.info(`Current API key: ****${r.slice(-4)}`):ee.log.info("No API key configured.");let n=await kt(),i=he(n),o=ee.spinner();o.start("Verifying API key...");try{await Ae(i),o.stop("API key verified."),Ue(n),ee.log.success("API key saved.")}catch(s){o.stop("Verification failed."),s instanceof M&&s.status===401?ee.cancel("Invalid API key."):ee.cancel(N(s)),process.exit(1)}})}import{existsSync as nr,readFileSync as zr,rmSync as qp,writeFileSync as xs}from"fs";import{join as Xe}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"],Zp=[{file:"packages/api/src/routes/inngest.ts",removals:[`import { licenseHeartbeatFunction } from "../functions/maintenance/license-heartbeat";
1783
+ `),title:`Changelog v${r} \u2192 v${n}`}}async function Mp(e,t){let r=JSON.parse(await vs(e,"utf-8")),n=await mt(t),i=0;for(let[s,o]of Object.entries(r))ct(s)||n[s]!==o&&i++;for(let s of Object.keys(n))s in r||i++;return i}import*as Y from"@clack/prompts";import ye from"picocolors";import{readFile as Up}from"fs/promises";import{join as Fp,resolve as Vp}from"path";function As(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=Vp(t.cwd??process.cwd()),n=Fp(r,ue),i;try{i=JSON.parse(await Up(n,"utf-8"))}catch{Y.cancel(".generatesaas/manifest.json not found. Run this from a GenerateSaaS project."),process.exit(1)}let s=[`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(`
1784
+ `);Y.note(s,ye.bold("Project Status"));let o=Y.spinner();o.start("Checking for updates...");try{let a=await at(),p=he(a),g=(await Ae(p)).latest;i.version===g?(o.stop("Up to date."),Y.log.success(`Already on the latest version (${ye.green(g)})`)):(o.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){o.stop("Check failed."),a instanceof M&&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 Bp}from"buffer";import{readFile as Gp}from"fs/promises";import*as D from"@clack/prompts";import x from"picocolors";function Kp(){return process.env.GENERATESAAS_API_KEY??vt()}function Hp(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 Yp(e){return{verdict:e.verdict??"unknown",ejectedAt:e.ejectedAt??null}}function Wp(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 Is(e,t){let r=process.env.GENERATESAAS_API_URL??wt,n=Kp();e.start("Cross-referencing license records...");try{let i=n?Hp(await kn(r,n,{lkh:t.lkh,nid:t.nid,domain:t.domain})):Yp(await br(r,{token:t.token,domain:t.domain}));return e.stop(`${x.green("Checked")} - records cross-referenced`),Wp(i)}catch(i){return e.stop(`${x.yellow("Skipped")} - ${N(i)}`),null}}function zp(e){let t=e.split(".");if(t.length!==3||!t[1])throw new Error("Invalid JWT format");let r=Bp.from(t[1],"base64url").toString("utf-8");return JSON.parse(r)}function Wr(e){return typeof e!="number"?"unknown":new Date(e*1e3).toISOString().split("T")[0]}function Ts(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: ${Wr(e.pat)}`,`Last updated: ${Wr(e.uat)}`,`Expires: ${Wr(e.exp)}`,`Install ID: ${String(e.nid??"unknown")}`].join(`
1785
+ `),x.yellow("License Details"))}function Jp(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 Rs(e){let t=D.spinner(),r=null,n="no candidates";for(let o of Jp(e)){t.start(`Checking ${o}...`);try{let a=await fetch(o);if(!a.ok){n=`${o} returned ${a.status}`,t.stop(`${x.yellow("Not here")} - ${n}`);continue}let p=(await a.text()).trim();if(!p||p.split(".").length!==3){n=`${o} did not return a JWT`,t.stop(`${x.yellow("Not here")} - ${n}`);continue}r=p,t.stop(`${x.green("Found")} - license endpoint responded`);break}catch(a){n=`${o}: ${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 o=_s(e);return o?await Is(t,{domain:o})??!1:!1}let i;try{i=zp(r)}catch{return D.log.error("Could not decode JWT payload."),!1}t.start("Verifying signature...");try{let o=process.env.GENERATESAAS_API_URL??wt,a=await br(o,{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:"),Ts(i),!1}return Ts(i),await Is(t,{token:r,lkh:typeof i.lkh=="string"?i.lkh:void 0,nid:typeof i.nid=="string"?i.nid:void 0,domain:_s(e)})??!0}function _s(e){try{return new URL(/^https?:\/\//i.test(e)?e:`https://${e}`).hostname}catch{return}}function Os(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 Gp(r.file,"utf-8")).split(`
1786
+ `).map(o=>o.trim()).filter(o=>o&&!o.startsWith("#"));i.length===0&&(D.cancel("No URLs found in file."),process.exit(1));let s=0;for(let o of i)await Rs(o)&&s++,D.log.info("");D.log.success(`${s}/${i.length} sites verified.`)}else await Rs(t)||process.exit(1)})}import{existsSync as qp,rmSync as Xp}from"fs";import*as te from"@clack/prompts";function xs(e){e.command("auth").description("Set or update your GenerateSaaS API key").option("--clear","remove saved API key").action(async t=>{if(t.clear){qp(me)?(Xp(me),te.log.success("API key removed.")):te.log.info("No API key configured.");return}let r=vt();r?te.log.info(`Current API key: ****${r.slice(-4)}`):te.log.info("No API key configured.");let n=await kt(),i=he(n),s=te.spinner();s.start("Verifying API key...");try{await Ae(i),s.stop("API key verified."),Ue(n),te.log.success("API key saved.")}catch(o){s.stop("Verification failed."),o instanceof M&&o.status===401?te.cancel("Invalid API key."):te.cancel(N(o)),process.exit(1)}})}import{existsSync as or,readFileSync as Jr,rmSync as Zp,writeFileSync as Ds}from"fs";import{join as Xe}from"path";import*as U from"@clack/prompts";var Qp=["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"],ed=[{file:"packages/api/src/routes/inngest.ts",removals:[`import { licenseHeartbeatFunction } from "../functions/maintenance/license-heartbeat";
1787
1787
  `,` licenseHeartbeatFunction,
1788
1788
  `]},{file:"packages/api/src/routes/internal/index.ts",removals:[`import licenseRoutes from "./license";
1789
1789
  `,` .route("/license", licenseRoutes)
1790
1790
  `]},{file:"packages/api/src/routes/public/v1/health.ts",removals:[`import { manifest } from "../../../lib/manifest";
1791
- `],replacements:[{from:'c.json({ status: "success" as const, version: manifest?.version })',to:'c.json({ status: "success" as const })'}]}];function Qp(){return ze.flatMap(e=>Vr.map(t=>Xe(e,t)))}function Wr(e){return nr(e)?(qp(e,{recursive:!0}),!0):!1}function ed(e,t,r=[]){if(!nr(e))return!1;let n=zr(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:(xs(e,i,"utf-8"),!0)}function td(e){let t=Xe(e,".gitignore");if(!nr(t))return!1;let r=zr(t,"utf-8"),n=r.split(`
1791
+ `],replacements:[{from:'c.json({ status: "success" as const, version: manifest?.version })',to:'c.json({ status: "success" as const })'}]}];function td(){return[...ze,...Br].flatMap(e=>tr.map(t=>Xe(e,t)))}function zr(e){return or(e)?(Zp(e,{recursive:!0}),!0):!1}function rd(e,t,r=[]){if(!or(e))return!1;let n=Jr(e,"utf-8"),i=n;for(let s of t)i=i.replace(s,"");for(let{from:s,to:o}of r)i=i.replace(s,o);return i===n?!1:(Ds(e,i,"utf-8"),!0)}function nd(e){let t=Xe(e,".gitignore");if(!or(t))return!1;let r=Jr(t,"utf-8"),n=r.split(`
1792
1792
  `).filter(i=>!i.includes(".generatesaas")).join(`
1793
- `);return n===r?!1:(xs(t,n,"utf-8"),!0)}function Ds(e){e.command("eject").description("Remove all GenerateSaaS ties - manifest, license, heartbeat, skills").action(async()=>{let t=process.cwd(),r=Xe(t,ue),n;try{n=JSON.parse(zr(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 Qp())Wr(Xe(t,a))&&o.push(a);for(let a of Xp)Wr(Xe(t,a))&&o.push(a);Wr(Xe(t,J))&&o.push(`${J}/`);for(let a of Zp){let p=Xe(t,a.file);ed(p,a.removals,a.replacements)?s.push(a.file):nr(p)&&U.log.warn(`Could not auto-modify ${a.file} - manually remove license/heartbeat references.`)}td(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 Ze=new rd().name("generatesaas").description("CLI for scaffolding and managing GenerateSaaS projects").version("3.37.0").addHelpText("after",`
1793
+ `);return n===r?!1:(Ds(t,n,"utf-8"),!0)}function Ns(e){e.command("eject").description("Remove all GenerateSaaS ties - manifest, license, heartbeat, skills").action(async()=>{let t=process.cwd(),r=Xe(t,ue),n;try{n=JSON.parse(Jr(r,"utf-8"))}catch{U.cancel("No GenerateSaaS project found in this directory."),process.exit(1)}let i=await U.text({message:'Type "eject" to confirm (this cannot be undone):',validate:a=>{if(a!=="eject")return'Type "eject" to confirm, or press Ctrl+C to cancel.'}});if(U.isCancel(i)&&(U.cancel("Eject cancelled."),process.exit(0)),n.licenseToken)try{await fetch("https://generatesaas.com/api/v1/heartbeat",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n.licenseToken}`},body:JSON.stringify({event:"eject",version:n.version,frontend:n.frontend}),signal:AbortSignal.timeout(5e3)}),U.log.info("Recorded the opt-out with generatesaas.com (final event - nothing is sent after this).")}catch{U.log.warn("Could not reach generatesaas.com to record the opt-out. Ejecting anyway.")}let s=[],o=[];for(let a of td())zr(Xe(t,a))&&s.push(a);for(let a of Qp)zr(Xe(t,a))&&s.push(a);zr(Xe(t,J))&&s.push(`${J}/`);for(let a of ed){let p=Xe(t,a.file);rd(p,a.removals,a.replacements)?o.push(a.file):or(p)&&U.log.warn(`Could not auto-modify ${a.file} - manually remove license/heartbeat references.`)}nd(t)&&o.push(".gitignore");for(let a of s)U.log.info(`Deleted ${a}`);for(let a of o)U.log.info(`Modified ${a}`);U.log.success("Ejected successfully. This project is now fully standalone.")})}var Ze=new id().name("generatesaas").description("CLI for scaffolding and managing GenerateSaaS projects").version("3.39.0").addHelpText("after",`
1794
1794
  Examples:
1795
1795
  $ generatesaas init Interactive setup
1796
1796
  $ generatesaas init -n my-app -y Quick setup with defaults
1797
1797
  $ generatesaas status Check for updates
1798
1798
  $ generatesaas auth Set or update API key
1799
- `);ms(Ze);vs(Ze);Ps(Ze);_s(Ze);Os(Ze);Ds(Ze);Ze.parseAsync().catch(e=>{Ns.cancel("An unexpected error occurred."),console.error(e),process.exit(1)});
1799
+ `);hs(Ze);ks(Ze);As(Ze);Os(Ze);xs(Ze);Ns(Ze);Ze.parseAsync().catch(e=>{Cs.cancel("An unexpected error occurred."),console.error(e),process.exit(1)});