generatesaas 3.10.0 → 3.11.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,18 +1,18 @@
1
1
  #!/usr/bin/env node
2
- import{Command as qp}from"commander";import*as Us from"@clack/prompts";import{existsSync as cp,readdirSync as lp,rmSync as pp}from"fs";import{join as dp,resolve as up}from"path";import{Option as ne}from"commander";import*as k from"@clack/prompts";import*as Nt from"@clack/prompts";import ur from"picocolors";function rn(e){let t=e?` GenerateSaaS v${e} `:" GenerateSaaS ";Nt.intro(ur.bgYellow(ur.black(t)))}function nn(){Nt.outro(ur.yellow("Happy building!"))}import*as h from"@clack/prompts";import g 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)"}},Ct={stripe:{label:"Stripe"},polar:{label:"Polar"},none:{label:"None",hint:"disable payments"}},Lt={smtp:{label:"SMTP",hint:"Mailpit for local dev"},ses:{label:"Amazon SES"},resend:{label:"Resend"}},$t={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"}},sn={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 Le={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 Z={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}},$e={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"}]}},je={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"}]}},Xe=[{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."}],Ze=[{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)."}],Fs=[{feature:"runner",target:"vercel",reason:"Serverless (Vercel) cannot hold a connection open, and the runner holds one open per paired device. Deploy to a long-running runtime instead (Node.js / Docker on Render, Fly.io, Railway, Coolify, Dokploy, or your own VPS)."}];function me(e){return Fs.find(t=>e[t.feature]===!0&&e.deploymentTarget===t.target)}var he={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"}}},Ue=Object.keys(he);function mr(e){let t=[];for(let r of Xe)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 Ze)e.deploymentTarget===r.target&&e.architecture===r.architecture&&t.push(`\`architecture: "${r.architecture}"\` with \`deploymentTarget: "${r.target}"\` - ${r.reason}`);return t}var on=["Local file storage (sharp, geoip-lite)","SMTP email (use Resend or SES instead)","Content API git integration"];function Qe(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 et=["fullstack","separate"],tt=["stripe","polar","none"],rt=["smtp","ses","resend"];var an=["claude-code","cursor","codex","gemini-cli","windsurf"],fe=["USD","EUR","GBP","CAD","AUD","BRL","JPY"],ge=["node","vercel"],ye=["postgres","neon","supabase"],be=["redis","upstash"],K=["sentry","posthog"],Me=["revenuecat","none"];function oe(e){return e.paymentProvider!==void 0&&e.paymentProvider!=="none"}var hr=[{key:"architecture",label:"Architecture",hint:"Fullstack (frontend hosts the API) or a standalone Hono backend.",category:"Infrastructure",kind:"enum",default:"fullstack",choices:et,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:ge,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:ye,adoptable:!1,impact:"config",shapesTree:!0},{key:"cacheProvider",label:"Cache provider",hint:"Self-hosted Redis or Upstash.",category:"Infrastructure",kind:"enum",default:"redis",choices:be,adoptable:!1,impact:"config",shapesTree:!0},{key:"paymentProvider",label:"Payment provider",hint:"Stripe, Polar, or none.",category:"Features",kind:"enum",default:"none",choices:tt,adoptable:!1,impact:"structural",shapesTree:!0},{key:"defaultCurrency",label:"Default currency",hint:"Billing and pricing currency.",category:"Features",kind:"enum",default:"USD",choices:fe,adoptable:!1,impact:"config",shapesTree:!1},{key:"emailProvider",label:"Email provider",hint:"SMTP, Amazon SES, or Resend.",category:"Features",kind:"enum",default:"smtp",choices:rt,adoptable:!1,impact:"config",shapesTree:!1},{key:"observability",label:"Observability",hint:"Which services receive your app's errors, and on PostHog its LLM analytics. Pick any combination - anything you do not pick costs nothing, since its SDK and its adapter are never generated.",category:"Features",kind:"multiselect",default:[],choices:K,adoptable:!0,impact:"config",shapesTree:!0},{key:"multiTenancy",label:"Multi-tenancy (organizations)",hint:"Adds organizations - teams, members, and shared resources.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!1},{key:"projects",label:"Projects",hint:"Adds projects - a switcher that scopes a user's work inside their account or organization.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"config",shapesTree:!1},{key:"docs",label:"Docs app",hint:"Adds the self-hosted Fumadocs documentation site (apps/docs).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0},{key:"desktop",label:"Desktop app",hint:"Adds the cross-platform desktop app (apps/desktop, built with Electron).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0},{key:"mobile",label:"Mobile app",hint:"Adds the cross-platform mobile app (apps/mobile, built with Expo).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0},{key:"mobilePurchases",label:"Mobile store purchases",hint:"In-app purchases in the mobile app, through RevenueCat. Store purchases sit ON TOP of your web payment provider - a subscriber who buys in the app is the same account, billed by Apple or Google instead of by you. Off keeps the app on web billing, where the plan card says the subscription is managed on your website.",category:"Features",kind:"enum",default:()=>"none",choices:Me,adoptable:!0,impact:"structural",shapesTree:!0,requires:e=>e.mobile===!0&&oe(e),requiresLabel:"requires the mobile app and a web payment provider - store purchases are additive to the web lane, never a replacement"},{key:"ai",label:"AI features",hint:"Adds the AI surface (chat, models, automations, integrations) and unlocks the runner option. A desktop project ALWAYS ships the app's local AI stack: this option sets config.desktop.agents.enabled (the runtime gate on those screens). Off keeps config.ai.enabled false so the AI nav stays hidden - the AI packages still ship, because packages/translate depends on @repo/ai for the i18n pipeline every project uses.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0},{key:"webAi",label:"AI in the web app",hint:"Whether the WEB app shows the AI surfaces - chat, automations, model and integration settings, and their nav entries. Off is the app-first shape: your desktop or mobile app is where your AI product lives and the website keeps account, billing and licensing only. The AI SERVICE is untouched either way (config.ai.enabled, the /api/ai routes and the desktop agents all stay exactly as your AI option set them), so both apps keep talking to the same backend. Only meaningful with AI features and at least one app - the desktop app or the mobile app - and never with the runner: its pairing and device screens are part of the web AI surface.",category:"Features",kind:"boolean",default:!0,adoptable:!0,impact:"config",shapesTree:!1,requires:e=>e.ai===!0&&(e.desktop===!0||e.mobile===!0)&&e.runner!==!0,requiresLabel:"requires AI features and an app to host them (the desktop app or the mobile app), and is unavailable with the runner (its pairing and device screens live in the web AI surface)"},{key:"runner",label:"Runner daemon",hint:"Lets your users connect a machine that runs their own AI subscriptions (and any device-side work you add) on their hardware. They install AgentRunner, the daemon we publish and keep updated - your project ships the pairing, dispatch and Runners surface, never the daemon. Needs an always-on backend: the transport holds one connection open per paired device, which serverless (Vercel) cannot do.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0,requires:e=>e.ai===!0&&e.webAi!==!1&&me({...e,runner:!0})===void 0,requiresLabel:"requires AI features, the web AI surface, and an always-on deployment target (not Vercel)"},{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=>oe(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 Vs(e,t){return e[t]!==void 0}function cn(e){return hr.filter(t=>t.adoptable&&!Vs(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 Bs(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 Gs(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 ln(e){let t=[];for(let r of hr){let n=e[r.key];n!==void 0&&(Bs(r,n)||t.push(`\`${r.key}\` is ${JSON.stringify(n)}, but it must be ${Gs(r)}.`))}return t}function pn(e){let t={};for(let r of hr)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 fr(e,t){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||t}function jt(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Ut(e){return/^[a-z][a-z0-9-]*$/.test(e)}function j(e){return e instanceof Error?e.message:String(e)}var dn=["runner"];function gr(e){if(!dn.some(r=>e[r]===!0))return e;if(e.ai===!1)throw new Error("--runner requires AI features; remove --no-ai.");return e.ai===void 0&&(e.ai=!0),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.");if(e.runner===!0)throw new Error("--runner needs the web AI surface; drop --runner or keep web AI.");return e}function un(e){return dn.some(r=>e[r]===!0)&&(e.ai=!0),e}function mn(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."),e.runner===!0&&t.push("`runner` is true, and the runner's pairing, install and Runners screens are part of the web AI surface."),t}function hn(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`."),oe(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 fn(e){let t=Ks(e,e.desktopAi);return delete e.desktopAi,t}function Ks(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 gn(e){let t={};if(e.name!==void 0){if(!Ut(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(!Me.includes(e.mobilePurchases))throw new Error(`Invalid mobile purchases "${e.mobilePurchases}". Valid values: ${Me.join(", ")}`);t.mobilePurchases=e.mobilePurchases}if(e.ai!==void 0&&(t.ai=e.ai),e.webAi!==void 0&&(t.webAi=e.webAi),e.runner!==void 0&&(t.runner=e.runner),gr(t),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(!fe.includes(e.currency))throw new Error(`Invalid currency "${e.currency}". Valid values: ${fe.join(", ")}`);t.defaultCurrency=e.currency}if(e.deploy!==void 0){if(!ge.includes(e.deploy))throw new Error(`Invalid deployment target "${e.deploy}". Valid values: ${ge.join(", ")}`);t.deploymentTarget=e.deploy}if(e.database!==void 0){if(!ye.includes(e.database))throw new Error(`Invalid database provider "${e.database}". Valid values: ${ye.join(", ")}`);t.databaseProvider=e.database}if(e.cache!==void 0){if(!be.includes(e.cache))throw new Error(`Invalid cache provider "${e.cache}". Valid values: ${be.join(", ")}`);t.cacheProvider=e.cache}if(e.observability!==void 0){let r=e.observability.split(",").map(i=>i.trim()).filter(Boolean),n=r.filter(i=>!K.includes(i));if(n.length>0)throw new Error(`Invalid observability provider ${JSON.stringify(n.join(", "))}. Valid values: ${K.join(", ")}`);t.observability=r}if(e.preset!==void 0){if(!Ue.includes(e.preset))throw new Error(`Invalid preset "${e.preset}". Valid values: ${Ue.join(", ")}`);let r=he[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 nt={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,runner:!1,revenueSharing:!1,credits:!0,defaultCurrency:"USD",deploymentTarget:"node",databaseProvider:"postgres",cacheProvider:"redis",observability:[]};function yn(e){let t=e.projectName??nt.projectName,r=e.projectDir??`./${t}`,n=e.appName??jt(t),i=e.deploymentTarget??nt.deploymentTarget,o=Z[i]?.edgeRuntime??!1,s=e.databaseProvider??(o?"neon":nt.databaseProvider),a=e.cacheProvider??(o?"upstash":nt.cacheProvider),d=e.emailProvider??(o?"resend":nt.emailProvider),m={...nt,...e,projectName:t,appName:n,projectDir:r,deploymentTarget:i,databaseProvider:s,cacheProvider:a,emailProvider:d};m.paymentProvider==="none"&&(m.credits=!1),(!m.mobile||m.paymentProvider==="none")&&(m.mobilePurchases="none"),yt(m);for(let b of Xe){if(m.deploymentTarget!==b.target)continue;let P=m.databaseProvider===b.provider?"database":"cache";if(m.databaseProvider===b.provider||m.cacheProvider===b.provider)throw new Error(`Incompatible: --deploy ${b.target} + --${P} ${b.provider}. ${b.reason}`)}for(let b of Ze)if(m.architecture===b.architecture&&m.deploymentTarget===b.target)throw new Error(`Incompatible: --architecture ${b.architecture} + --deploy ${b.target}. ${b.reason}`);let w=me(m);if(w)throw new Error(`Incompatible: --${w.feature} + --deploy ${w.target}. ${w.reason}`);return bt(m),m}function R(e){h.isCancel(e)&&(h.cancel("Setup cancelled."),process.exit(0))}function yr(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 bn(e,t){let r=!1;e&&gr(e),e&&yt(e),e&&bt(e),h.log.info(g.bold("Project"));let n=e?.projectName??await(async()=>{r=!0;let l=await h.text({message:"Project name:",placeholder:"my-saas",validate:u=>{if(!u?.trim())return"Project name is required.";if(!Ut(u))return"Use lowercase letters, numbers, and hyphens only. Must start with a letter."}});return R(l),l})(),i=e?.appName??await(async()=>{r=!0;let l=await h.text({message:"App name:",initialValue:jt(n),validate:u=>{if(!u?.trim())return"App name is required."}});return R(l),l})(),o=e?.projectDir??await(async()=>{r=!0;let l=await h.text({message:"Project location:",initialValue:`./${n}`});return R(l),l==="."?process.cwd():l})();h.log.info(g.bold("Infrastructure"));let s={};if(e?.deploymentTarget===void 0&&e?.databaseProvider===void 0&&e?.cacheProvider===void 0){r=!0;let l=await h.select({message:"Infrastructure:",options:[...Ue.map(u=>({value:u,label:he[u].label,hint:he[u].hint})),{value:"custom",label:"Customize",hint:"choose each piece yourself"}]});if(R(l),l!=="custom"){let u=he[l].values;s.deploymentTarget=u.deploymentTarget,s.databaseProvider=u.databaseProvider,s.cacheProvider=u.cacheProvider,h.log.info(`${he[l].label}: ${he[l].hint}.`)}}let a=e?.deploymentTarget??s.deploymentTarget??"node";if(e?.deploymentTarget===void 0&&s.deploymentTarget===void 0){r=!0;let l=await h.select({message:"Deployment target:",options:ge.map(u=>({value:u,label:Z[u].label,hint:Z[u].hint}))});R(l),a=l}let d=e?.architecture?Ze.find(l=>l.architecture===e.architecture&&l.target===a):void 0;if(d)throw new Error(`Incompatible: --architecture ${d.architecture} + --deploy ${d.target}. ${d.reason}`);let m=me({...e,deploymentTarget:a});if(m)throw new Error(`Incompatible: --${m.feature} + --deploy ${m.target}. ${m.reason}`);let w=me({runner:!0,deploymentTarget:a})!==void 0,b=new Set(Ze.filter(l=>l.target===a).map(l=>l.architecture)),P=et.filter(l=>!b.has(l)),I=e?.architecture??await(async()=>{if(P.length===1){let u=P[0];return h.log.info(`Auto-selected ${gt[u].label} architecture (only compatible option for ${Z[a].label}).`),u}r=!0;let l=await h.select({message:"Architecture:",options:P.map(u=>({value:u,label:gt[u].label,hint:gt[u].hint}))});return R(l),l})(),_=e?.databaseProvider??s.databaseProvider??await(async()=>{r=!0;let l=ye.filter(x=>!Xe.some(Ae=>Ae.target===a&&Ae.provider===x));if(l.length===1){let x=l[0];return h.log.info(`Auto-selected ${$e[x].label} (only compatible option for ${Z[a].label}).`),x}let u=await h.select({message:"Database provider:",options:l.map(x=>({value:x,label:$e[x].label,hint:$e[x].hint}))});return R(u),u})(),f=e?.cacheProvider??s.cacheProvider??await(async()=>{r=!0;let l=be.filter(x=>!Xe.some(Ae=>Ae.target===a&&Ae.provider===x));if(l.length===1){let x=l[0];return h.log.info(`Auto-selected ${je[x].label} (only compatible option for ${Z[a].label}).`),x}let u=await h.select({message:"Cache provider:",options:l.map(x=>({value:x,label:je[x].label,hint:je[x].hint}))});return R(u),u})();if(Z[a]?.edgeRuntime){let l=on.map(u=>` - ${u}`).join(`
3
- `);h.note(l,"Unavailable on edge runtime")}h.log.info(g.bold("Features"));let O=e?.paymentProvider??await(async()=>{r=!0;let l=await h.select({message:"Payment provider:",options:tt.map(u=>({value:u,label:Ct[u].label,hint:Ct[u].hint}))});return R(l),l})(),Oe=e?.defaultCurrency??await(async()=>{if(O==="none")return"USD";r=!0;let l=await h.select({message:"Default currency:",options:fe.map(u=>({value:u,label:u,hint:Le[u].name}))});return R(l),l})(),q=e?.emailProvider??await(async()=>{r=!0;let l=await h.select({message:"Email provider:",options:rt.map(u=>({value:u,label:Lt[u].label,hint:Lt[u].hint}))});return R(l),l})(),J=e?.observability??await(async()=>{r=!0;let l=await h.multiselect({message:"Observability (space to select, enter to confirm):",required:!1,initialValues:[],options:K.map(u=>({value:u,label:$t[u].label,hint:$t[u].hint}))});return R(l),l})(),xe=e?.multiTenancy??await(async()=>{r=!0;let l=await h.confirm({message:"Enable multi-tenancy (organizations)?",initialValue:!1});return R(l),l})(),De=e?.projects??await(async()=>{r=!0;let l=await h.confirm({message:"Enable projects (a switcher that scopes a user's work)?",initialValue:!1});return R(l),l})(),Ne=e?.docs??await(async()=>{r=!0;let l=await h.confirm({message:"Include docs app? (self-hosted Fumadocs documentation site)",initialValue:!1});return R(l),l})(),Je=t?.desktopAllowed!==!1,v=e?.desktop??(Je?await(async()=>{r=!0;let l=await h.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 R(l),l})():(h.log.info(g.dim("Desktop app: available on the Pro plan and up - skipped.")),!1)),M=t?.mobileAllowed!==!1,G=e?.mobile??(M?await(async()=>{r=!0;let l=await h.confirm({message:"Include the mobile app? (apps/mobile - iOS and Android, built with Expo, with push notifications and universal links)",initialValue:!1});return R(l),l})():(h.log.info(g.dim("Mobile app: available on the Pro plan and up - skipped.")),!1)),se=!G||O==="none"?"none":e?.mobilePurchases??await(async()=>{r=!0;let x=await h.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 R(x),x})();yt({mobile:G,mobilePurchases:se,paymentProvider:O});let N=e?.ai??await(async()=>{r=!0;let l=await h.confirm({message:"Add AI features? (chat, models, automations, integrations - and unlocks the runner)",initialValue:!1});return R(l),l})(),de=t?.runnerAllowed!==!1,X=e?.webAi===!1,ue=!N||w||X?!1:e?.runner??(de?await(async()=>{r=!0;let l=await h.confirm({message:"Add the runner daemon for your WEB users? A small program they install on their own machine or VPS to run their Claude Code / Codex subscription for this app 24/7 - the AI runs on their hardware, not yours. Off means no install UI and no pairing endpoint on your site; you can adopt it later.",initialValue:!1});return R(l),l})():(h.log.info(g.dim("Runner: available on the Pro plan and up - skipped.")),!1));N&&w?h.log.info(g.dim(`Runner: ${Z[a].label} cannot hold a connection open - skipped.`)):N&&X&&h.log.info(g.dim("Runner: its pairing and device screens live in the web AI surface, which is off - skipped."));let Ce=e?.webAi??((v||G)&&N&&!ue?await(async()=>{r=!0;let l=await h.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 R(l),l})():!0);bt({webAi:Ce,ai:N,desktop:v,mobile:G,runner:ue});let D=e?.revenueSharing??await(async()=>{r=!0;let l=await h.confirm({message:"Enable revenue sharing? (opt-in MRR leaderboard with dofollow backlinks)",initialValue:!1});return R(l),l})(),ht=O==="none"?!1:e?.credits??await(async()=>{r=!0;let l=await h.confirm({message:"Enable credits? (metered usage on top of subscription plans)",initialValue:!0});return R(l),l})(),pr=e?.demo,Dt=yr({databaseProvider:_,cacheProvider:f,paymentProvider:O,emailProvider:q,demo:pr}),ft={};if(Dt.length>0&&r){h.log.info(g.bold("Credentials")+g.dim(" all optional - press Enter to skip, fill in .env later"));for(let l of Dt)if(r=!0,l.secret){let u=await h.password({message:l.message,mask:"*"});R(u),typeof u=="string"&&u.trim()&&(ft[l.key]=u.trim())}else{let u=await h.text({message:l.message,placeholder:l.placeholder});R(u),typeof u=="string"&&u.trim()&&(ft[l.key]=u.trim())}}if(r){let l=[` Name: ${g.cyan(n)}`,` App name: ${g.cyan(i)}`,` Location: ${g.cyan(o)}`,` Architecture: ${g.cyan(gt[I].label)}`].join(`
4
- `),u=[` Deploy target: ${g.cyan(Z[a]?.label??"Node.js / Docker")}`,` Database: ${g.cyan($e[_].label)}`,` Cache: ${g.cyan(je[f].label)}`].filter(Boolean).join(`
2
+ import{Command as Xp}from"commander";import*as Us from"@clack/prompts";import{existsSync as pp,readdirSync as dp,rmSync as up}from"fs";import{join as mp,resolve as hp}from"path";import{Option as ne}from"commander";import*as S from"@clack/prompts";import*as Nt from"@clack/prompts";import ur from"picocolors";function sn(e){let t=e?` GenerateSaaS v${e} `:" GenerateSaaS ";Nt.intro(ur.bgYellow(ur.black(t)))}function on(){Nt.outro(ur.yellow("Happy building!"))}import*as h from"@clack/prompts";import g 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)"}},Ct={stripe:{label:"Stripe"},polar:{label:"Polar"},none:{label:"None",hint:"disable payments"}},Lt={smtp:{label:"SMTP",hint:"Mailpit for local dev"},ses:{label:"Amazon SES"},resend:{label:"Resend"}},$t={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"}},an={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 Le={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 Z={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}},$e={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"}]}},je={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"}]}},Qe=[{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."}],et=[{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)."}],Fs=[{feature:"runner",target:"vercel",reason:"Serverless (Vercel) cannot hold a connection open, and the runner holds one open per paired device. Deploy to a long-running runtime instead (Node.js / Docker on Render, Fly.io, Railway, Coolify, Dokploy, or your own VPS)."}];function me(e){return Fs.find(t=>e[t.feature]===!0&&e.deploymentTarget===t.target)}var he={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"}}},Ue=Object.keys(he);function mr(e){let t=[];for(let r of Qe)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 et)e.deploymentTarget===r.target&&e.architecture===r.architecture&&t.push(`\`architecture: "${r.architecture}"\` with \`deploymentTarget: "${r.target}"\` - ${r.reason}`);return t}var cn=["Local file storage (sharp, geoip-lite)","SMTP email (use Resend or SES instead)","Content API git integration"];function tt(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 rt=["fullstack","separate"],nt=["stripe","polar","none"],it=["smtp","ses","resend"];var ln=["claude-code","cursor","codex","gemini-cli","windsurf"],fe=["USD","EUR","GBP","CAD","AUD","BRL","JPY"],ge=["node","vercel"],ye=["postgres","neon","supabase"],be=["redis","upstash"],Y=["sentry","posthog"],Me=["revenuecat","none"];function oe(e){return e.paymentProvider!==void 0&&e.paymentProvider!=="none"}var hr=[{key:"architecture",label:"Architecture",hint:"Fullstack (frontend hosts the API) or a standalone Hono backend.",category:"Infrastructure",kind:"enum",default:"fullstack",choices:rt,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:ge,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:ye,adoptable:!1,impact:"config",shapesTree:!0},{key:"cacheProvider",label:"Cache provider",hint:"Self-hosted Redis or Upstash.",category:"Infrastructure",kind:"enum",default:"redis",choices:be,adoptable:!1,impact:"config",shapesTree:!0},{key:"paymentProvider",label:"Payment provider",hint:"Stripe, Polar, or none.",category:"Features",kind:"enum",default:"none",choices:nt,adoptable:!1,impact:"structural",shapesTree:!0},{key:"defaultCurrency",label:"Default currency",hint:"Billing and pricing currency.",category:"Features",kind:"enum",default:"USD",choices:fe,adoptable:!1,impact:"config",shapesTree:!1},{key:"emailProvider",label:"Email provider",hint:"SMTP, Amazon SES, or Resend.",category:"Features",kind:"enum",default:"smtp",choices:it,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:Y,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:Me,adoptable:!0,impact:"structural",shapesTree:!0,requires:e=>e.mobile===!0&&oe(e),requiresLabel:"requires the mobile app and a web payment provider - store purchases are additive to the web lane, never a replacement"},{key:"ai",label:"AI features",hint:"Adds the AI surface (chat, models, automations, integrations) and unlocks the runner option. A desktop project ALWAYS ships the app's local AI stack: this option sets config.desktop.agents.enabled (the runtime gate on those screens). Off keeps config.ai.enabled false so the AI nav stays hidden - the AI packages still ship, because packages/translate depends on @repo/ai for the i18n pipeline every project uses.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0},{key:"webAi",label:"AI in the web app",hint:"Whether the WEB app shows the AI surfaces - chat, automations, model and integration settings, and their nav entries. Off is the app-first shape: your desktop or mobile app is where your AI product lives and the website keeps account, billing and licensing only. The AI SERVICE is untouched either way (config.ai.enabled, the /api/ai routes and the desktop agents all stay exactly as your AI option set them), so both apps keep talking to the same backend. Only meaningful with AI features and at least one app - the desktop app or the mobile app - and never with the runner: its pairing and device screens are part of the web AI surface.",category:"Features",kind:"boolean",default:!0,adoptable:!0,impact:"config",shapesTree:!1,requires:e=>e.ai===!0&&(e.desktop===!0||e.mobile===!0)&&e.runner!==!0,requiresLabel:"requires AI features and an app to host them (the desktop app or the mobile app), and is unavailable with the runner (its pairing and device screens live in the web AI surface)"},{key:"runner",label:"Runner daemon",hint:"Lets your users connect a machine that runs their own AI subscriptions (and any device-side work you add) on their hardware. They install AgentRunner, the daemon we publish and keep updated - your project ships the pairing, dispatch and Runners surface, never the daemon. Needs an always-on backend: the transport holds one connection open per paired device, which serverless (Vercel) cannot do.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0,requires:e=>e.ai===!0&&e.webAi!==!1&&me({...e,runner:!0})===void 0,requiresLabel:"requires AI features, the web AI surface, and an always-on deployment target (not Vercel)"},{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=>oe(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 Vs(e,t){return e[t]!==void 0}function pn(e){return hr.filter(t=>t.adoptable&&!Vs(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 Bs(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 Gs(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 dn(e){let t=[];for(let r of hr){let n=e[r.key];n!==void 0&&(Bs(r,n)||t.push(`\`${r.key}\` is ${JSON.stringify(n)}, but it must be ${Gs(r)}.`))}return t}function un(e){let t={};for(let r of hr)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 fr(e,t){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||t}function jt(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Ut(e){return/^[a-z][a-z0-9-]*$/.test(e)}function j(e){return e instanceof Error?e.message:String(e)}var mn=["runner"];function gr(e){if(!mn.some(r=>e[r]===!0))return e;if(e.ai===!1)throw new Error("--runner requires AI features; remove --no-ai.");return e.ai===void 0&&(e.ai=!0),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.");if(e.runner===!0)throw new Error("--runner needs the web AI surface; drop --runner or keep web AI.");return e}function hn(e){return mn.some(r=>e[r]===!0)&&(e.ai=!0),e}function fn(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."),e.runner===!0&&t.push("`runner` is true, and the runner's pairing, install and Runners screens are part of the web AI surface."),t}function gn(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`."),oe(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 yn(e){let t=Ks(e,e.desktopAi);return delete e.desktopAi,t}function Ks(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 bn(e){let t={};if(e.name!==void 0){if(!Ut(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(!Me.includes(e.mobilePurchases))throw new Error(`Invalid mobile purchases "${e.mobilePurchases}". Valid values: ${Me.join(", ")}`);t.mobilePurchases=e.mobilePurchases}if(e.ai!==void 0&&(t.ai=e.ai),e.webAi!==void 0&&(t.webAi=e.webAi),e.runner!==void 0&&(t.runner=e.runner),gr(t),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(!fe.includes(e.currency))throw new Error(`Invalid currency "${e.currency}". Valid values: ${fe.join(", ")}`);t.defaultCurrency=e.currency}if(e.deploy!==void 0){if(!ge.includes(e.deploy))throw new Error(`Invalid deployment target "${e.deploy}". Valid values: ${ge.join(", ")}`);t.deploymentTarget=e.deploy}if(e.database!==void 0){if(!ye.includes(e.database))throw new Error(`Invalid database provider "${e.database}". Valid values: ${ye.join(", ")}`);t.databaseProvider=e.database}if(e.cache!==void 0){if(!be.includes(e.cache))throw new Error(`Invalid cache provider "${e.cache}". Valid values: ${be.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=>!Y.includes(i));if(n.length>0)throw new Error(`Invalid observability provider ${JSON.stringify(n.join(", "))}. Valid values: ${Y.join(", ")}`);t.observability=r}if(e.preset!==void 0){if(!Ue.includes(e.preset))throw new Error(`Invalid preset "${e.preset}". Valid values: ${Ue.join(", ")}`);let r=he[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 st={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,runner:!1,revenueSharing:!1,credits:!0,defaultCurrency:"USD",deploymentTarget:"node",databaseProvider:"postgres",cacheProvider:"redis",observability:[]};function wn(e){let t=e.projectName??st.projectName,r=e.projectDir??`./${t}`,n=e.appName??jt(t),i=e.deploymentTarget??st.deploymentTarget,o=Z[i]?.edgeRuntime??!1,s=e.databaseProvider??(o?"neon":st.databaseProvider),a=e.cacheProvider??(o?"upstash":st.cacheProvider),d=e.emailProvider??(o?"resend":st.emailProvider),u={...st,...e,projectName:t,appName:n,projectDir:r,deploymentTarget:i,databaseProvider:s,cacheProvider:a,emailProvider:d};u.paymentProvider==="none"&&(u.credits=!1),(!u.mobile||u.paymentProvider==="none")&&(u.mobilePurchases="none"),yt(u);for(let y of Qe){if(u.deploymentTarget!==y.target)continue;let P=u.databaseProvider===y.provider?"database":"cache";if(u.databaseProvider===y.provider||u.cacheProvider===y.provider)throw new Error(`Incompatible: --deploy ${y.target} + --${P} ${y.provider}. ${y.reason}`)}for(let y of et)if(u.architecture===y.architecture&&u.deploymentTarget===y.target)throw new Error(`Incompatible: --architecture ${y.architecture} + --deploy ${y.target}. ${y.reason}`);let w=me(u);if(w)throw new Error(`Incompatible: --${w.feature} + --deploy ${w.target}. ${w.reason}`);return bt(u),u}function R(e){h.isCancel(e)&&(h.cancel("Setup cancelled."),process.exit(0))}function yr(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 vn(e,t){let r=!1;e&&gr(e),e&&yt(e),e&&bt(e),h.log.info(g.bold("Project"));let n=e?.projectName??await(async()=>{r=!0;let l=await h.text({message:"Project name:",placeholder:"my-saas",validate:m=>{if(!m?.trim())return"Project name is required.";if(!Ut(m))return"Use lowercase letters, numbers, and hyphens only. Must start with a letter."}});return R(l),l})(),i=e?.appName??await(async()=>{r=!0;let l=await h.text({message:"App name:",initialValue:jt(n),validate:m=>{if(!m?.trim())return"App name is required."}});return R(l),l})(),o=e?.projectDir??await(async()=>{r=!0;let l=await h.text({message:"Project location:",initialValue:`./${n}`});return R(l),l==="."?process.cwd():l})();h.log.info(g.bold("Infrastructure"));let s={};if(e?.deploymentTarget===void 0&&e?.databaseProvider===void 0&&e?.cacheProvider===void 0){r=!0;let l=await h.select({message:"Infrastructure:",options:[...Ue.map(m=>({value:m,label:he[m].label,hint:he[m].hint})),{value:"custom",label:"Customize",hint:"choose each piece yourself"}]});if(R(l),l!=="custom"){let m=he[l].values;s.deploymentTarget=m.deploymentTarget,s.databaseProvider=m.databaseProvider,s.cacheProvider=m.cacheProvider,h.log.info(`${he[l].label}: ${he[l].hint}.`)}}let a=e?.deploymentTarget??s.deploymentTarget??"node";if(e?.deploymentTarget===void 0&&s.deploymentTarget===void 0){r=!0;let l=await h.select({message:"Deployment target:",options:ge.map(m=>({value:m,label:Z[m].label,hint:Z[m].hint}))});R(l),a=l}let d=e?.architecture?et.find(l=>l.architecture===e.architecture&&l.target===a):void 0;if(d)throw new Error(`Incompatible: --architecture ${d.architecture} + --deploy ${d.target}. ${d.reason}`);let u=me({...e,deploymentTarget:a});if(u)throw new Error(`Incompatible: --${u.feature} + --deploy ${u.target}. ${u.reason}`);let w=me({runner:!0,deploymentTarget:a})!==void 0,y=new Set(et.filter(l=>l.target===a).map(l=>l.architecture)),P=rt.filter(l=>!y.has(l)),I=e?.architecture??await(async()=>{if(P.length===1){let m=P[0];return h.log.info(`Auto-selected ${gt[m].label} architecture (only compatible option for ${Z[a].label}).`),m}r=!0;let l=await h.select({message:"Architecture:",options:P.map(m=>({value:m,label:gt[m].label,hint:gt[m].hint}))});return R(l),l})(),_=e?.databaseProvider??s.databaseProvider??await(async()=>{r=!0;let l=ye.filter(x=>!Qe.some(Ae=>Ae.target===a&&Ae.provider===x));if(l.length===1){let x=l[0];return h.log.info(`Auto-selected ${$e[x].label} (only compatible option for ${Z[a].label}).`),x}let m=await h.select({message:"Database provider:",options:l.map(x=>({value:x,label:$e[x].label,hint:$e[x].hint}))});return R(m),m})(),f=e?.cacheProvider??s.cacheProvider??await(async()=>{r=!0;let l=be.filter(x=>!Qe.some(Ae=>Ae.target===a&&Ae.provider===x));if(l.length===1){let x=l[0];return h.log.info(`Auto-selected ${je[x].label} (only compatible option for ${Z[a].label}).`),x}let m=await h.select({message:"Cache provider:",options:l.map(x=>({value:x,label:je[x].label,hint:je[x].hint}))});return R(m),m})();if(Z[a]?.edgeRuntime){let l=cn.map(m=>` - ${m}`).join(`
3
+ `);h.note(l,"Unavailable on edge runtime")}h.log.info(g.bold("Features"));let O=e?.paymentProvider??await(async()=>{r=!0;let l=await h.select({message:"Payment provider:",options:nt.map(m=>({value:m,label:Ct[m].label,hint:Ct[m].hint}))});return R(l),l})(),Oe=e?.defaultCurrency??await(async()=>{if(O==="none")return"USD";r=!0;let l=await h.select({message:"Default currency:",options:fe.map(m=>({value:m,label:m,hint:Le[m].name}))});return R(l),l})(),q=e?.emailProvider??await(async()=>{r=!0;let l=await h.select({message:"Email provider:",options:it.map(m=>({value:m,label:Lt[m].label,hint:Lt[m].hint}))});return R(l),l})(),J=e?.observability??await(async()=>{r=!0;let l=await h.multiselect({message:"Observability (space to select, enter to confirm):",required:!1,initialValues:[],options:Y.map(m=>({value:m,label:$t[m].label,hint:$t[m].hint}))});return R(l),l})(),xe=e?.multiTenancy??await(async()=>{r=!0;let l=await h.confirm({message:"Enable multi-tenancy (organizations)?",initialValue:!1});return R(l),l})(),De=e?.projects??await(async()=>{r=!0;let l=await h.confirm({message:"Enable projects (a switcher that scopes a user's work)?",initialValue:!1});return R(l),l})(),Ne=e?.docs??await(async()=>{r=!0;let l=await h.confirm({message:"Include docs app? (self-hosted Fumadocs documentation site)",initialValue:!1});return R(l),l})(),Ze=t?.desktopAllowed!==!1,v=e?.desktop??(Ze?await(async()=>{r=!0;let l=await h.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 R(l),l})():(h.log.info(g.dim("Desktop app: available on the Pro plan and up - skipped.")),!1)),M=t?.mobileAllowed!==!1,G=e?.mobile??(M?await(async()=>{r=!0;let l=await h.confirm({message:"Include the mobile app? (apps/mobile - iOS and Android, built with Expo, with push notifications and universal links)",initialValue:!1});return R(l),l})():(h.log.info(g.dim("Mobile app: available on the Pro plan and up - skipped.")),!1)),se=!G||O==="none"?"none":e?.mobilePurchases??await(async()=>{r=!0;let x=await h.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 R(x),x})();yt({mobile:G,mobilePurchases:se,paymentProvider:O});let N=e?.ai??await(async()=>{r=!0;let l=await h.confirm({message:"Add AI features? (chat, models, automations, integrations - and unlocks the runner)",initialValue:!1});return R(l),l})(),de=t?.runnerAllowed!==!1,X=e?.webAi===!1,ue=!N||w||X?!1:e?.runner??(de?await(async()=>{r=!0;let l=await h.confirm({message:"Add the runner daemon for your WEB users? A small program they install on their own machine or VPS to run their Claude Code / Codex subscription for this app 24/7 - the AI runs on their hardware, not yours. Off means no install UI and no pairing endpoint on your site; you can adopt it later.",initialValue:!1});return R(l),l})():(h.log.info(g.dim("Runner: available on the Pro plan and up - skipped.")),!1));N&&w?h.log.info(g.dim(`Runner: ${Z[a].label} cannot hold a connection open - skipped.`)):N&&X&&h.log.info(g.dim("Runner: its pairing and device screens live in the web AI surface, which is off - skipped."));let Ce=e?.webAi??((v||G)&&N&&!ue?await(async()=>{r=!0;let l=await h.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 R(l),l})():!0);bt({webAi:Ce,ai:N,desktop:v,mobile:G,runner:ue});let D=e?.revenueSharing??await(async()=>{r=!0;let l=await h.confirm({message:"Enable revenue sharing? (opt-in MRR leaderboard with dofollow backlinks)",initialValue:!1});return R(l),l})(),ht=O==="none"?!1:e?.credits??await(async()=>{r=!0;let l=await h.confirm({message:"Enable credits? (metered usage on top of subscription plans)",initialValue:!0});return R(l),l})(),pr=e?.demo,Dt=yr({databaseProvider:_,cacheProvider:f,paymentProvider:O,emailProvider:q,demo:pr}),ft={};if(Dt.length>0&&r){h.log.info(g.bold("Credentials")+g.dim(" all optional - press Enter to skip, fill in .env later"));for(let l of Dt)if(r=!0,l.secret){let m=await h.password({message:l.message,mask:"*"});R(m),typeof m=="string"&&m.trim()&&(ft[l.key]=m.trim())}else{let m=await h.text({message:l.message,placeholder:l.placeholder});R(m),typeof m=="string"&&m.trim()&&(ft[l.key]=m.trim())}}if(r){let l=[` Name: ${g.cyan(n)}`,` App name: ${g.cyan(i)}`,` Location: ${g.cyan(o)}`,` Architecture: ${g.cyan(gt[I].label)}`].join(`
4
+ `),m=[` Deploy target: ${g.cyan(Z[a]?.label??"Node.js / Docker")}`,` Database: ${g.cyan($e[_].label)}`,` Cache: ${g.cyan(je[f].label)}`].filter(Boolean).join(`
5
5
  `),x=[O!=="none"?` Payment: ${g.cyan(Ct[O].label)} (${Oe})`:` Payment: ${g.dim("none")}`,` Credits: ${ht?g.cyan("Yes"):g.dim("No")}`,` AI features: ${N?g.cyan("Yes"):g.dim("No")}`,...N?[` Runner: ${ue?g.cyan("Yes"):g.dim("No")}`]:[],...Ce?[]:[` Web AI: ${g.dim("No")} (app-first)`],` Email: ${g.cyan(Lt[q].label)}`,` Observability: ${J.length===0?g.dim("none"):g.cyan(J.map(dr=>$t[dr].label).join(", "))}`,` Multi-tenancy: ${xe?g.cyan("Yes"):g.dim("No")}`,` Projects: ${De?g.cyan("Yes"):g.dim("No")}`,` Docs app: ${Ne?g.cyan("Yes"):g.dim("No")}`,` Desktop app: ${v?g.cyan("Yes"):g.dim("No")}`,` Mobile app: ${G?g.cyan("Yes"):g.dim("No")}`,...se==="none"?[]:[` In-app purch.: ${g.cyan("RevenueCat")}`],` Rev. sharing: ${D?g.cyan("Yes"):g.dim("No")}`].join(`
6
- `),Ae=[g.bold("Project"),l,"",g.bold("Infrastructure"),u,"",g.bold("Features"),x];if(Dt.length>0){let dr=Dt.map(tn=>{let Ms=ft[tn.key]?g.green("provided"):g.dim("skipped");return` ${tn.key}: ${Ms}`}).join(`
6
+ `),Ae=[g.bold("Project"),l,"",g.bold("Infrastructure"),m,"",g.bold("Features"),x];if(Dt.length>0){let dr=Dt.map(nn=>{let Ms=ft[nn.key]?g.green("provided"):g.dim("skipped");return` ${nn.key}: ${Ms}`}).join(`
7
7
  `);Ae.push("",g.bold("Credentials"),dr)}h.note(Ae.join(`
8
- `),"Summary");let en=await h.confirm({message:"Proceed with these settings?"});(h.isCancel(en)||!en)&&(h.cancel("Setup cancelled."),process.exit(0))}return{projectName:n,appName:i,projectDir:o,architecture:I,deploymentTarget:a,databaseProvider:_,cacheProvider:f,paymentProvider:O,emailProvider:q,observability:J,multiTenancy:xe,projects:De,docs:Ne,desktop:v,mobile:G,mobilePurchases:se,ai:N,webAi:Ce,runner:ue,revenueSharing:D,credits:ht,defaultCurrency:Oe,...Object.keys(ft).length>0?{credentials:ft}:{},...e?.baseUrl!==void 0?{baseUrl:e.baseUrl}:{},...pr!==void 0?{demo:pr}:{}}}import{createReadStream as _n,existsSync as eo}from"fs";import{mkdir as to}from"fs/promises";import{join as ro}from"path";import{Readable as no}from"stream";import{pipeline as Ir}from"stream/promises";import{extract as io}from"tar";import{join as Fe}from"path";import{homedir as Hs}from"os";var wt=process.env.GENERATESAAS_API_URL??"https://cli.generatesaas.com",Q=".generatesaas",we=Fe(Q,"manifest.json"),wn="nextjs",br="nuxt",wr="2.4.1",vn=Fe(Q,"hashes.json"),Mt=Fe(Q,"template-hashes.json"),Ft=Fe(Q,"template"),kn=Fe(Q,"staging"),En=Fe(Q,"staging.json"),ve=Fe(Hs(),".generatesaas");var F=class extends Error{constructor(r,n,i){super(n);this.status=r;this.body=i}status;body;name="ApiError"};function ke(e){return{apiKey:e,baseUrl:wt}}async function Ie(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.10.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 F(i.status,o,s)}return i}import{existsSync as Ys,mkdirSync as Ws,readFileSync as zs,writeFileSync as qs}from"fs";import{dirname as Js}from"path";import*as Re from"@clack/prompts";function vt(){if(!Ys(ve))return null;try{let e=JSON.parse(zs(ve,"utf-8"));return e.apiKey?e.apiKey:(e.token&&!e.apiKey&&Re.log.warning(`Found old GitHub token in ${ve}. Run 'generatesaas init' to set up your API key.`),null)}catch{return null}}function Ve(e){Ws(Js(ve),{recursive:!0}),qs(ve,`${JSON.stringify({apiKey:e},null," ")}
9
- `,{mode:384})}async function it(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 Re.text({message:"Enter your GenerateSaaS API key:",placeholder:"gs_live_...",validate:t=>{if(!t?.trim())return"API key is required."}});return Re.isCancel(e)&&(Re.cancel("Setup cancelled."),process.exit(0)),e.trim()}import{readFile as Xs}from"fs/promises";async function Te(e){let t=process.env.GENERATESAAS_VERSION_INDEX;return t?JSON.parse(await Xs(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 Ie(e,"/versions")).json()}async function Sn(e,t){if(process.env.GENERATESAAS_OFFLINE_LICENSE==="1")return null;try{return await(await Ie(e,`/changelog/${encodeURIComponent(t)}`)).text()}catch(r){if(r instanceof F&&r.status===404)return null;throw r}}async function Pn(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{skills:{"generatesaas-update":{skillMd:`# Offline skill stub
10
- `,scripts:{},references:{}}}}:await(await Ie(e,`/skills/${encodeURIComponent(t)}`)).json()}function Vt(e){if(!(e instanceof F)||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 vr="nextjs";function An(e){return{frontend:vr,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:e.runner,credits:e.credits,revenueSharing:e.revenueSharing,currency:e.defaultCurrency}}async function kr(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{token:"offline-test-token",licenseId:"offline-test-license-id",installId:t.installId}:await(await Ie(e,"/license/sign",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json()}async function In(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{token:t.currentToken}:await(await Ie(e,"/license/refresh",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json()}async function Er(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 Rn(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 Sr=new Set([".git","node_modules",".pnpm-store",".env",".env.test",".turbo",".data","dist",".next",".next-e2e-web",".next-e2e-desktop",".svelte-kit",".wrangler",".devcontainer","playwright-report","test-results",".drive-out",".mastra"]),Pr=new Set(["pnpm-lock.yaml"]);function st(e){if(Ar(e))return!0;for(let t of e.split("/"))if(Pr.has(t))return!0;return!1}var Zs=new Set(["data","mksaas","references","scripts",".cursor",".agents",".codex",".generatesaas",".vscode",".mcp.json","vitest.config.ts","README.md","TODO.md","OVERVIEW.md","HANDOFF.md"]),Tn=["scripts/docs-lint.ts"],Qs=["docs/superpowers","packages/cli","packages/cli-api","packages/config/tests/runner-brand-lockstep.test.ts","packages/database/tests/no-migration-history.test.ts","apps/runner","docs/agentrunner","infra/docker-compose.yml",".claude/commands",".claude/skills/web-port",".claude/skills/web-port-workspace",".claude/settings.local.json",".claude/worktrees"];function Ar(e){let t=e.split("/");for(let r of t)if(Sr.has(r))return!0;if(Tn.includes(e)||Tn.some(r=>r.startsWith(`${e}/`)))return!1;if(Zs.has(t[0]))return!0;for(let r of Qs)if(e===r||e.startsWith(`${r}/`))return!0;return!1}async function Bt(e,t,r){await to(r,{recursive:!0});let n=process.env.GENERATESAAS_TEMPLATE_TARBALL_DIR;if(n){let a=ro(n,`v${t}.tar.gz`);if(!eo(a))throw new Error(`GENERATESAAS_TEMPLATE_TARBALL_DIR is set but ${a} does not exist.`);await Ir(_n(a),Rr(r));return}let i=process.env.GENERATESAAS_TEMPLATE_TARBALL;if(i){await Ir(_n(i),Rr(r));return}let o=await Ie(e,`/template/${encodeURIComponent(t)}`);if(!o.body)throw new Error("Empty response body");let s=no.fromWeb(o.body);await Ir(s,Rr(r))}function Rr(e){return io({cwd:e,strip:1,filter:t=>{let r=t.replace(/^[^/]+\//,"");return r?!Ar(r):!0},sync:!1})}import{readdir as Gt,readFile as ot,rm as xn,rmdir as so,writeFile as Et}from"fs/promises";import{join as H}from"path";async function Dn(e){let t;try{t=await Gt(e,{withFileTypes:!0})}catch{return!1}let r=!1;for(let n of t){let i=H(e,n.name);if(n.isDirectory()){await Dn(i)&&(r=!0);continue}if(n.name.startsWith("_")){r=!0;continue}await xn(i,{force:!0})}return r||await so(e).catch(()=>{}),r}async function Nn(e){let t=H(e,"packages/content"),r=[];try{r=(await Gt(t,{withFileTypes:!0})).filter(s=>s.isDirectory()).map(s=>s.name)}catch{return}let n=new Set;for(let s of r){let a=H(t,s),d;try{d=(await Gt(a,{withFileTypes:!0})).filter(m=>m.isDirectory())}catch{continue}for(let m of d)n.add(m.name),await Dn(H(a,m.name))}let i=await lo(e),o=new Set([...n].filter(s=>i===void 0||i.has(s)));await Promise.all([...o].map(s=>xn(H(e,"apps/web/public/images",s),{recursive:!0,force:!0}))),await uo(e,o)}var oo="packages/config/src/index.ts",ao=/\bcontent:\s*\{[\s\S]*?\bsections:\s*\[([\s\S]*?)\]/,co=/\bslug:\s*"([^"]+)"/g;async function lo(e){let t;try{t=await ot(H(e,oo),"utf-8")}catch{return}let r=ao.exec(t)?.[1];if(r===void 0)return;let n=[...r.matchAll(co)].map(i=>i[1]).filter(i=>i!==void 0);return n.length>0?new Set(n):void 0}var po="packages/translate/.meta/mdx-translation-meta.json";async function uo(e,t){if(t.size===0)return;let r=H(e,po),n;try{n=JSON.parse(await ot(r,"utf-8"))}catch{return}if(typeof n!="object"||n===null)return;let i=n;if(typeof i.files!="object"||i.files===null)return;let o=i.files,s={};for(let[a,d]of Object.entries(o)){let m=a.split("/"),w=m.length>1?m[0]:void 0,b=m[m.length-1]?.startsWith("_")===!0;w!==void 0&&t.has(w)&&!b||(s[a]=d)}await Et(r,`${JSON.stringify({...i,files:s},null," ")}
11
- `)}var mo="packages/config/src/blog.ts";async function Cn(e){let t=H(e,mo),r=await ot(t,"utf-8"),n=On(On(r,"blogCategories",t),"blogAuthors",t);await Et(t,n)}function On(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 Ln(e){let t=H(e,"packages/i18n/translations"),r;try{r=await Gt(t)}catch{return}for(let n of r){let i=H(t,n,"web.json"),o;try{o=await ot(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 ho="packages/config/src/ai/tasks.ts",fo="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.",go="The array starts EMPTY, which hides the Tasks tab until you declare your first task.";async function $n(e){let t=H(e,ho),r=await ot(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(fo,go);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 jn(e){let t=H(e,".claude","settings.json"),r;try{r=await ot(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(yo)),await Et(t,`${JSON.stringify(n,null," ")}
13
- `)}function yo(e){return!(e.startsWith("mcp__")||e.includes("nuxt"))}import{readFileSync as Ro}from"fs";import{dirname as To,join as _r}from"path";import{fileURLToPath as _o}from"url";import{existsSync as bo}from"fs";import{join as Un}from"path";function Kt(e,t,r){let n=Un(e,...t);return bo(n)?n:Un(e,r)}import{mkdir as wo,writeFile as vo,readdir as ko,rm as Eo,rmdir as So}from"fs/promises";import{dirname as Ht,join as Po,relative as Ao,sep as Io}from"path";function Be(e){return e.split(Io).join("/")}async function Yt(e){await wo(e,{recursive:!0})}async function c(e,t){await Yt(Ht(e)),await vo(e,t,"utf-8")}async function at(e,t){await Eo(e,{force:!0});let r=Ht(e);for(;r!==t&&r!==Ht(r);){try{await So(r)}catch{return}r=Ht(r)}}async function Ee(e,t,r,n){let i=[],o=await ko(e,{withFileTypes:!0});for(let s of o){let a=Po(e,s.name),d=Be(Ao(t,a));r(d)||(s.isDirectory()?i.push(...await Ee(a,t,r,n)):s.isFile()&&(n===void 0||n(d))&&i.push(a))}return i}var Oo={postgres:"Postgres",neon:"Neon (managed Postgres)",supabase:"Supabase (managed Postgres)"},xo={resend:"Resend",ses:"Amazon SES",smtp:"SMTP"},Do={redis:"Redis",upstash:"Upstash Redis"},No={node:"Node.js / Docker",vercel:"Vercel"},Tr="apps/web",Co="Next.js 16",Lo="`app/` routes, `components/`, `lib/`",$o={stripe:"Stripe",polar:"Polar"};function jo(e){let t=e.architecture==="fullstack",r=t?"(fullstack - Hono API mounted inside the app)":"(separate - standalone Hono backend)",n=t?`Mounted inside \`${Tr}\`. 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=Do[e.cacheProvider],o=No[e.deploymentTarget],s=e.paymentProvider==="none"?"":`
14
- - **Payments:** ${$o[e.paymentProvider]}`,a=e.desktop?e.mobile?", the desktop app (built with Electron) under `docs/desktop/` and the mobile app (built with Expo) under `docs/mobile/`":", and the desktop app (built with Electron) under `docs/desktop/`":e.mobile?", and the mobile app (built with Expo) under `docs/mobile/`":"",d=e.runner?"\n- **Runner daemon** - your users install AgentRunner on a machine they control and pair it with their account. Everything you own lives in this repo: the `/runner/*` routes, the relay, the Runners page, and the capability layer runs get. The daemon itself is published separately and auto-updates - there is nothing to build or release here.":"",m=`\`useTranslations()\` from \`next-intl\` in components; messages are loaded in \`${Tr}/i18n/request.ts\`.`;return Mo({archSuffix:r,apiLocation:n,databaseName:Oo[e.databaseProvider],cacheName:i,paymentLine:s,emailName:xo[e.emailProvider],deployName:o,runnerBullet:d,appDocsRef:a,i18nRule:m,webAppDir:Tr,webAppName:Co,webAppLayout:Lo})}function Uo(){return Kt(To(_o(import.meta.url)),["generators","content"],"content")}function Mo(e){let t=Ro(_r(Uo(),"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 Mn(e){await c(_r(e.projectDir,"AGENTS.md"),jo(e)),await c(_r(e.projectDir,"CLAUDE.md"),`@AGENTS.md
15
- `)}import{join as Fo}from"path";var Fn="apps/web",Or="Next.js 16",Vo={postgres:"Postgres (self-hosted)",neon:"Neon (managed Postgres)",supabase:"Supabase (managed Postgres)"};function Bo(e){let t=e.appName.trim()||e.projectName,r=Vo[e.databaseProvider],n=e.architecture==="fullstack"?`${Or} app at \`${Fn}/\` 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.`:`${Or} app at \`${Fn}/\` and a separate Hono backend at \`apps/backend/\`.`,i=e.architecture==="fullstack"?`- App + API: http://localhost:3000
8
+ `),"Summary");let rn=await h.confirm({message:"Proceed with these settings?"});(h.isCancel(rn)||!rn)&&(h.cancel("Setup cancelled."),process.exit(0))}return{projectName:n,appName:i,projectDir:o,architecture:I,deploymentTarget:a,databaseProvider:_,cacheProvider:f,paymentProvider:O,emailProvider:q,observability:J,multiTenancy:xe,projects:De,docs:Ne,desktop:v,mobile:G,mobilePurchases:se,ai:N,webAi:Ce,runner:ue,revenueSharing:D,credits:ht,defaultCurrency:Oe,...Object.keys(ft).length>0?{credentials:ft}:{},...e?.baseUrl!==void 0?{baseUrl:e.baseUrl}:{},...pr!==void 0?{demo:pr}:{}}}import{createReadStream as xn,existsSync as eo}from"fs";import{mkdir as to}from"fs/promises";import{join as ro}from"path";import{Readable as no}from"stream";import{pipeline as Ir}from"stream/promises";import{extract as io}from"tar";import{join as Fe}from"path";import{homedir as Hs}from"os";var wt=process.env.GENERATESAAS_API_URL??"https://cli.generatesaas.com",Q=".generatesaas",we=Fe(Q,"manifest.json"),kn="nextjs",br="nuxt",wr="2.4.1",En=Fe(Q,"hashes.json"),Mt=Fe(Q,"template-hashes.json"),Ft=Fe(Q,"template"),Sn=Fe(Q,"staging"),Pn=Fe(Q,"staging.json"),ve=Fe(Hs(),".generatesaas");var F=class extends Error{constructor(r,n,i){super(n);this.status=r;this.body=i}status;body;name="ApiError"};function ke(e){return{apiKey:e,baseUrl:wt}}async function Ie(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.11.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 F(i.status,o,s)}return i}import{existsSync as Ys,mkdirSync as Ws,readFileSync as zs,writeFileSync as qs}from"fs";import{dirname as Js}from"path";import*as Re from"@clack/prompts";function vt(){if(!Ys(ve))return null;try{let e=JSON.parse(zs(ve,"utf-8"));return e.apiKey?e.apiKey:(e.token&&!e.apiKey&&Re.log.warning(`Found old GitHub token in ${ve}. Run 'generatesaas init' to set up your API key.`),null)}catch{return null}}function Ve(e){Ws(Js(ve),{recursive:!0}),qs(ve,`${JSON.stringify({apiKey:e},null," ")}
9
+ `,{mode:384})}async function ot(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 Re.text({message:"Enter your GenerateSaaS API key:",placeholder:"gs_live_...",validate:t=>{if(!t?.trim())return"API key is required."}});return Re.isCancel(e)&&(Re.cancel("Setup cancelled."),process.exit(0)),e.trim()}import{readFile as Xs}from"fs/promises";async function Te(e){let t=process.env.GENERATESAAS_VERSION_INDEX;return t?JSON.parse(await Xs(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 Ie(e,"/versions")).json()}async function An(e,t){if(process.env.GENERATESAAS_OFFLINE_LICENSE==="1")return null;try{return await(await Ie(e,`/changelog/${encodeURIComponent(t)}`)).text()}catch(r){if(r instanceof F&&r.status===404)return null;throw r}}async function In(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{skills:{"generatesaas-update":{skillMd:`# Offline skill stub
10
+ `,scripts:{},references:{}}}}:await(await Ie(e,`/skills/${encodeURIComponent(t)}`)).json()}function Vt(e){if(!(e instanceof F)||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 vr="nextjs";function Rn(e){return{frontend:vr,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:e.runner,credits:e.credits,revenueSharing:e.revenueSharing,currency:e.defaultCurrency}}async function kr(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{token:"offline-test-token",licenseId:"offline-test-license-id",installId:t.installId}:await(await Ie(e,"/license/sign",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json()}async function Tn(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{token:t.currentToken}:await(await Ie(e,"/license/refresh",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json()}async function Er(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 _n(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 Sr=new Set([".git","node_modules",".pnpm-store",".env",".env.test",".turbo",".data","dist",".next",".next-e2e-web",".next-e2e-desktop",".svelte-kit",".wrangler",".devcontainer","playwright-report","test-results",".drive-out",".mastra"]),Pr=new Set(["pnpm-lock.yaml"]);function at(e){if(Ar(e))return!0;for(let t of e.split("/"))if(Pr.has(t))return!0;return!1}var Zs=new Set(["data","mksaas","references","scripts",".cursor",".agents",".codex",".generatesaas",".vscode",".mcp.json","vitest.config.ts","README.md","TODO.md","OVERVIEW.md","HANDOFF.md"]),On=["scripts/docs-lint.ts"],Qs=["docs/superpowers","packages/cli","packages/cli-api","packages/config/tests/runner-brand-lockstep.test.ts","packages/database/tests/no-migration-history.test.ts","apps/runner","docs/agentrunner","infra/docker-compose.yml",".claude/commands",".claude/skills/web-port",".claude/skills/web-port-workspace",".claude/settings.local.json",".claude/worktrees"];function Ar(e){let t=e.split("/");for(let r of t)if(Sr.has(r))return!0;if(On.includes(e)||On.some(r=>r.startsWith(`${e}/`)))return!1;if(Zs.has(t[0]))return!0;for(let r of Qs)if(e===r||e.startsWith(`${r}/`))return!0;return!1}async function Bt(e,t,r){await to(r,{recursive:!0});let n=process.env.GENERATESAAS_TEMPLATE_TARBALL_DIR;if(n){let a=ro(n,`v${t}.tar.gz`);if(!eo(a))throw new Error(`GENERATESAAS_TEMPLATE_TARBALL_DIR is set but ${a} does not exist.`);await Ir(xn(a),Rr(r));return}let i=process.env.GENERATESAAS_TEMPLATE_TARBALL;if(i){await Ir(xn(i),Rr(r));return}let o=await Ie(e,`/template/${encodeURIComponent(t)}`);if(!o.body)throw new Error("Empty response body");let s=no.fromWeb(o.body);await Ir(s,Rr(r))}function Rr(e){return io({cwd:e,strip:1,filter:t=>{let r=t.replace(/^[^/]+\//,"");return r?!Ar(r):!0},sync:!1})}import{readdir as Gt,readFile as ct,rm as Nn,rmdir as so,writeFile as Et}from"fs/promises";import{join as W}from"path";async function Cn(e){let t;try{t=await Gt(e,{withFileTypes:!0})}catch{return!1}let r=!1;for(let n of t){let i=W(e,n.name);if(n.isDirectory()){await Cn(i)&&(r=!0);continue}if(n.name.startsWith("_")){r=!0;continue}await Nn(i,{force:!0})}return r||await so(e).catch(()=>{}),r}async function Ln(e){let t=W(e,"packages/content"),r=[];try{r=(await Gt(t,{withFileTypes:!0})).filter(s=>s.isDirectory()).map(s=>s.name)}catch{return}let n=new Set;for(let s of r){let a=W(t,s),d;try{d=(await Gt(a,{withFileTypes:!0})).filter(u=>u.isDirectory())}catch{continue}for(let u of d)n.add(u.name),await Cn(W(a,u.name))}let i=await lo(e),o=new Set([...n].filter(s=>i===void 0||i.has(s)));await Promise.all([...o].map(s=>Nn(W(e,"apps/web/public/images",s),{recursive:!0,force:!0}))),await uo(e,o)}var oo="packages/config/src/index.ts",ao=/\bcontent:\s*\{[\s\S]*?\bsections:\s*\[([\s\S]*?)\]/,co=/\bslug:\s*"([^"]+)"/g;async function lo(e){let t;try{t=await ct(W(e,oo),"utf-8")}catch{return}let r=ao.exec(t)?.[1];if(r===void 0)return;let n=[...r.matchAll(co)].map(i=>i[1]).filter(i=>i!==void 0);return n.length>0?new Set(n):void 0}var po="packages/translate/.meta/mdx-translation-meta.json";async function uo(e,t){if(t.size===0)return;let r=W(e,po),n;try{n=JSON.parse(await ct(r,"utf-8"))}catch{return}if(typeof n!="object"||n===null)return;let i=n;if(typeof i.files!="object"||i.files===null)return;let o=i.files,s={};for(let[a,d]of Object.entries(o)){let u=a.split("/"),w=u.length>1?u[0]:void 0,y=u[u.length-1]?.startsWith("_")===!0;w!==void 0&&t.has(w)&&!y||(s[a]=d)}await Et(r,`${JSON.stringify({...i,files:s},null," ")}
11
+ `)}var mo="packages/config/src/blog.ts";async function $n(e){let t=W(e,mo),r=await ct(t,"utf-8"),n=Dn(Dn(r,"blogCategories",t),"blogAuthors",t);await Et(t,n)}function Dn(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 jn(e){let t=W(e,"packages/i18n/translations"),r;try{r=await Gt(t)}catch{return}for(let n of r){let i=W(t,n,"web.json"),o;try{o=await ct(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 ho="packages/config/src/ai/tasks.ts",fo="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.",go="The array starts EMPTY, which hides the Tasks tab until you declare your first task.";async function Un(e){let t=W(e,ho),r=await ct(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(fo,go);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 Mn(e){let t=W(e,".claude","settings.json"),r;try{r=await ct(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(yo)),await Et(t,`${JSON.stringify(n,null," ")}
13
+ `)}function yo(e){return!(e.startsWith("mcp__")||e.includes("nuxt"))}import{readFileSync as Ro}from"fs";import{dirname as To,join as _r}from"path";import{fileURLToPath as _o}from"url";import{existsSync as bo}from"fs";import{join as Fn}from"path";function Kt(e,t,r){let n=Fn(e,...t);return bo(n)?n:Fn(e,r)}import{mkdir as wo,writeFile as vo,readdir as ko,rm as Eo,rmdir as So}from"fs/promises";import{dirname as Ht,join as Po,relative as Ao,sep as Io}from"path";function Be(e){return e.split(Io).join("/")}async function Yt(e){await wo(e,{recursive:!0})}async function c(e,t){await Yt(Ht(e)),await vo(e,t,"utf-8")}async function lt(e,t){await Eo(e,{force:!0});let r=Ht(e);for(;r!==t&&r!==Ht(r);){try{await So(r)}catch{return}r=Ht(r)}}async function Ee(e,t,r,n){let i=[],o=await ko(e,{withFileTypes:!0});for(let s of o){let a=Po(e,s.name),d=Be(Ao(t,a));r(d)||(s.isDirectory()?i.push(...await Ee(a,t,r,n)):s.isFile()&&(n===void 0||n(d))&&i.push(a))}return i}var Oo={postgres:"Postgres",neon:"Neon (managed Postgres)",supabase:"Supabase (managed Postgres)"},xo={resend:"Resend",ses:"Amazon SES",smtp:"SMTP"},Do={redis:"Redis",upstash:"Upstash Redis"},No={node:"Node.js / Docker",vercel:"Vercel"},Tr="apps/web",Co="Next.js 16",Lo="`app/` routes, `components/`, `lib/`",$o={stripe:"Stripe",polar:"Polar"};function jo(e){let t=e.architecture==="fullstack",r=t?"(fullstack - Hono API mounted inside the app)":"(separate - standalone Hono backend)",n=t?`Mounted inside \`${Tr}\`. 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=Do[e.cacheProvider],o=No[e.deploymentTarget],s=e.paymentProvider==="none"?"":`
14
+ - **Payments:** ${$o[e.paymentProvider]}`,a=e.desktop?e.mobile?", the desktop app (built with Electron) under `docs/desktop/` and the mobile app (built with Expo) under `docs/mobile/`":", and the desktop app (built with Electron) under `docs/desktop/`":e.mobile?", and the mobile app (built with Expo) under `docs/mobile/`":"",d=e.runner?"\n- **Runner daemon** - your users install AgentRunner on a machine they control and pair it with their account. Everything you own lives in this repo: the `/runner/*` routes, the relay, the Runners page, and the capability layer runs get. The daemon itself is published separately and auto-updates - there is nothing to build or release here.":"",u=e.desktop?" With the desktop app on, both shells render the same body, so one change lands in both.":"",w=`\`useTranslations()\` from \`next-intl\` in components; messages are loaded in \`${Tr}/i18n/request.ts\`.`;return Mo({archSuffix:r,apiLocation:n,databaseName:Oo[e.databaseProvider],cacheName:i,paymentLine:s,emailName:xo[e.emailProvider],deployName:o,runnerBullet:d,appDocsRef:a,sharedScreensBothShells:u,i18nRule:w,webAppDir:Tr,webAppName:Co,webAppLayout:Lo})}function Uo(){return Kt(To(_o(import.meta.url)),["generators","content"],"content")}function Mo(e){let t=Ro(_r(Uo(),"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 Vn(e){await c(_r(e.projectDir,"AGENTS.md"),jo(e)),await c(_r(e.projectDir,"CLAUDE.md"),`@AGENTS.md
15
+ `)}import{join as Fo}from"path";var Bn="apps/web",Or="Next.js 16",Vo={postgres:"Postgres (self-hosted)",neon:"Neon (managed Postgres)",supabase:"Supabase (managed Postgres)"};function Bo(e){let t=e.appName.trim()||e.projectName,r=Vo[e.databaseProvider],n=e.architecture==="fullstack"?`${Or} app at \`${Bn}/\` 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.`:`${Or} app at \`${Bn}/\` and a separate Hono backend at \`apps/backend/\`.`,i=e.architecture==="fullstack"?`- App + API: http://localhost:3000
16
16
  - Inngest dev server: http://127.0.0.1:8288`:`- App: http://localhost:3000
17
17
  - API: http://localhost:3010
18
18
  - 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)
@@ -75,10 +75,10 @@ pnpm dlx generatesaas eject
75
75
  ## Updates
76
76
 
77
77
  To pull the latest boilerplate changes into this project, open it in your AI coding agent and ask: \`update my GenerateSaaS project\`.
78
- `}async function Vn(e){await c(Fo(e.projectDir,"README.md"),Bo(e))}import{access as Go}from"fs/promises";import{join as St}from"path";async function Ko(e,t,r){let n=St(e,"apps/desktop/dev-app-update.yml");try{await Go(n)}catch{throw new Error(`Cannot neutralize the desktop dev update feed: ${n} is missing (boilerplate drift).`)}await c(n,`provider: generic
78
+ `}async function Gn(e){await c(Fo(e.projectDir,"README.md"),Bo(e))}import{access as Go}from"fs/promises";import{join as St}from"path";async function Ko(e,t,r){let n=St(e,"apps/desktop/dev-app-update.yml");try{await Go(n)}catch{throw new Error(`Cannot neutralize the desktop dev update feed: ${n} is missing (boilerplate drift).`)}await c(n,`provider: generic
79
79
  url: ${t}
80
80
  updaterCacheDirName: ${r}
81
- `)}function Ho(e){let t=e.split(".");return t.length>=3?t.slice(1).join("."):e}function Yo(e,t){let r=fr(e,"app");return{appId:`${t.split(".").reverse().join(".")}.${r.replace(/-/g,"")}`,productName:e,protocol:r}}function Wo(e){let t=e.toLowerCase().replace(/[^a-z0-9_]/g,"");return/^[a-z]/.test(t)?t:`app${t}`}function zo(e,t){let r=fr(e,"app");return{appName:e,slug:r,bundleId:[...t.split(".").reverse(),r.replace(/-/g,"")].map(Wo).join("."),scheme:/^[a-z]/.test(r)?r:`app-${r}`}}var ct={name:"AgentRunner",binary:"agentrunner",envPrefix:"AGENTRUNNER",repoUrl:"https://github.com/AlexChelan/AgentRunner",installBase:"https://github.com/AlexChelan/AgentRunner/releases/latest/download",image:"ghcr.io/alexchelan/agentrunner"};function qo(e){return e.runner?["{"," enabled: true,",' clientId: "runner",'," daemon: {",` name: ${JSON.stringify(ct.name)},`,` binary: ${JSON.stringify(ct.binary)},`,` envPrefix: ${JSON.stringify(ct.envPrefix)},`,` repoUrl: ${JSON.stringify(ct.repoUrl)},`,` installBase: ${JSON.stringify(ct.installBase)},`,` image: ${JSON.stringify(ct.image)}`," }"," }"].join(`
81
+ `)}function Ho(e){let t=e.split(".");return t.length>=3?t.slice(1).join("."):e}function Yo(e,t){let r=fr(e,"app");return{appId:`${t.split(".").reverse().join(".")}.${r.replace(/-/g,"")}`,productName:e,protocol:r}}function Wo(e){let t=e.toLowerCase().replace(/[^a-z0-9_]/g,"");return/^[a-z]/.test(t)?t:`app${t}`}function zo(e,t){let r=fr(e,"app");return{appName:e,slug:r,bundleId:[...t.split(".").reverse(),r.replace(/-/g,"")].map(Wo).join("."),scheme:/^[a-z]/.test(r)?r:`app-${r}`}}var pt={name:"AgentRunner",binary:"agentrunner",envPrefix:"AGENTRUNNER",repoUrl:"https://github.com/AlexChelan/AgentRunner",installBase:"https://github.com/AlexChelan/AgentRunner/releases/latest/download",image:"ghcr.io/alexchelan/agentrunner"};function qo(e){return e.runner?["{"," enabled: true,",' clientId: "runner",'," daemon: {",` name: ${JSON.stringify(pt.name)},`,` binary: ${JSON.stringify(pt.binary)},`,` envPrefix: ${JSON.stringify(pt.envPrefix)},`,` repoUrl: ${JSON.stringify(pt.repoUrl)},`,` installBase: ${JSON.stringify(pt.installBase)},`,` image: ${JSON.stringify(pt.image)}`," }"," }"].join(`
82
82
  `):'{ enabled: false, clientId: "runner" }'}function Jo(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(`
83
83
  `),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(`
84
84
  `)),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(`
@@ -86,17 +86,17 @@ updaterCacheDirName: ${r}
86
86
  observability: {
87
87
  ${r.join(`,
88
88
  `)}
89
- },`}async function Bn(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=Ho(i),s=e.demo?"false":"true",a=e.multiTenancy?`{
89
+ },`}async function Kn(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=Ho(i),s=e.demo?"false":"true",a=e.multiTenancy?`{
90
90
  multiTenant: true,
91
91
  organizationLimit: 5,
92
92
  defaultOrganizationName: "Personal"
93
- }`:"{ multiTenant: false }",d=e.projects?"{ enabled: true }":"{ enabled: false }",m=Jo(e.observability),w=e.demo?`{
93
+ }`:"{ multiTenant: false }",d=e.projects?"{ enabled: true }":"{ enabled: false }",u=Jo(e.observability),w=e.demo?`{
94
94
  enableInDev: true,
95
95
  chatwoot: {
96
96
  baseUrl: "https://support.alexchelan.com",
97
97
  websiteToken: "1uWvJLHkhWLihkK2bxLaj2Fg"
98
98
  }
99
- }`:"{}",b=e.architecture==="fullstack"?"false":"true",P=Yo(t,o),I=`https://cdn.${o}/desktop`,_=zo(t,o),f=qo(e),O=` // Store purchases (RevenueCat) for the mobile app - ADDITIVE to the web provider, never a
99
+ }`:"{}",y=e.architecture==="fullstack"?"false":"true",P=Yo(t,o),I=`https://cdn.${o}/desktop`,_=zo(t,o),f=qo(e),O=` // Store purchases (RevenueCat) for the mobile app - ADDITIVE to the web provider, never a
100
100
  // replacement: store rules require digital goods to be sold through in-app purchase.
101
101
  mobile: {
102
102
  enabled: ${e.mobilePurchases==="revenuecat"},
@@ -201,8 +201,8 @@ ${O}
201
201
  prefix: "key_"
202
202
  },
203
203
  apiDocs: true,
204
- performanceMonitor: { enabled: ${b} },
205
- ${m}
204
+ performanceMonitor: { enabled: ${y} },
205
+ ${u}
206
206
  notifications: {
207
207
  enabled: NOTIFICATIONS_ENABLED,
208
208
  maxPerUser: 100,
@@ -418,6 +418,12 @@ ${m}
418
418
  settingsRunners: "/settings/runners",
419
419
  settingsMcp: "/settings/mcp",
420
420
  settingsBilling: "/settings/billing",
421
+ settingsBillingHistory: "/settings/billing/history",
422
+ settingsDevelopers: "/settings/developers",
423
+ settingsOrganization: "/settings/organization",
424
+ settingsOrganizationActivity: "/settings/organization-activity",
425
+ settingsProject: "/settings/project",
426
+ settingsSecurity: "/settings/security",
421
427
  notifications: "/notifications",
422
428
  admin: "/admin/users",
423
429
  adminOrganizations: "/admin/organizations",
@@ -632,7 +638,7 @@ export const SETTINGS_APP_LOCK_PATH = "/settings/app-lock";
632
638
  export const SETTINGS_ABOUT_PATH = "/settings/about";
633
639
  `),e.desktop&&await Ko(e.projectDir,I,`${P.protocol}-updater`)}import{join as Xo}from"path";function Zo(e,t){let r=[e==="stripe"?' stripePriceId: "",':' polarProductId: "",'];return t&&r.push(' appleProductId: "",',' googleProductId: "",'," storeAmounts: {},"),r.join(`
634
640
  `)}function xr(e){let t=[];return e.withCredits&&(t.push(` credits: ${e.credits},`),e.recurring!==!1&&t.push(" creditInterval: 30,")),e.maxConcurrentRuns!==void 0?(t.push(` apiRateLimit: { maxRequests: ${e.rateLimit} },`),t.push(` maxConcurrentRuns: ${e.maxConcurrentRuns}`)):t.push(` apiRateLimit: { maxRequests: ${e.rateLimit} }`),t.join(`
635
- `)}async function Gn(e){let t=Xo(e.projectDir,"packages/config/src/pricing.ts"),r=e.defaultCurrency;if(e.paymentProvider==="none"){let I=`import type { PricingConfig } from "@repo/config/types";
641
+ `)}async function Hn(e){let t=Xo(e.projectDir,"packages/config/src/pricing.ts"),r=e.defaultCurrency;if(e.paymentProvider==="none"){let I=`import type { PricingConfig } from "@repo/config/types";
636
642
 
637
643
  export const pricingConfig: PricingConfig = {
638
644
  defaultPlan: "free",
@@ -661,7 +667,7 @@ export const pricingConfig: PricingConfig = {
661
667
  credits: { enabled: false },
662
668
  products: { enabled: false, items: [] }
663
669
  };
664
- `;await c(t,I);return}let n=e.paymentProvider,i=Zo(n,e.mobilePurchases==="revenuecat"),o=e.credits,s=!!e.ai,a=xr({credits:5,rateLimit:100,withCredits:o,recurring:!1,...s&&{maxConcurrentRuns:2}}),d=xr({credits:10,rateLimit:1e3,withCredits:o,...s&&{maxConcurrentRuns:5}}),m=xr({credits:40,rateLimit:5e3,withCredits:o,...s&&{maxConcurrentRuns:10}}),w=r==="USD"?"":` // !! ${r} pricing WARNING: creditsPerUsd anchors credit cost to USD (AI providers bill in
670
+ `;await c(t,I);return}let n=e.paymentProvider,i=Zo(n,e.mobilePurchases==="revenuecat"),o=e.credits,s=!!e.ai,a=xr({credits:5,rateLimit:100,withCredits:o,recurring:!1,...s&&{maxConcurrentRuns:2}}),d=xr({credits:10,rateLimit:1e3,withCredits:o,...s&&{maxConcurrentRuns:5}}),u=xr({credits:40,rateLimit:5e3,withCredits:o,...s&&{maxConcurrentRuns:10}}),w=r==="USD"?"":` // !! ${r} pricing WARNING: creditsPerUsd anchors credit cost to USD (AI providers bill in
665
671
  // !! USD), but your plan prices and credit purchases are denominated in ${r}. Verify that the
666
672
  // !! ${r} amounts above cover the USD cost per credit (~0.50 USD at creditsPerUsd 1 with the
667
673
  // !! 100% markup) - and raise prices or creditsPerUsd if they do not.
@@ -670,7 +676,7 @@ export const pricingConfig: PricingConfig = {
670
676
  !! plan prices and credit purchases are denominated in ${r}. At the shipped economics 1 credit
671
677
  !! carries ~0.50 USD of AI cost - verify every ${r} price still covers it (see the comment on the
672
678
  !! credits block in packages/config/src/pricing.ts), or raise prices / creditsPerUsd.
673
- `);let b=o?` // creditsPerUsd scales USD cost -> credits (1 = 1 credit carries ~0.50 USD of cost after the
679
+ `);let y=o?` // creditsPerUsd scales USD cost -> credits (1 = 1 credit carries ~0.50 USD of cost after the
674
680
  // 100% markup); markupPercent is the DEFAULT margin for everything that debits credits (AI,
675
681
  // external APIs, your own features), and credits.markupByCategory overrides it per metered
676
682
  // service ("ai", "webSearch", "webExtract"). Two optional knobs shape each debit's size:
@@ -762,21 +768,21 @@ ${i}
762
768
  anchorAmounts: { ${r}: 349 }
763
769
  }
764
770
  ],
765
- ${m}
771
+ ${u}
766
772
  }
767
773
  ],
768
- ${b},
774
+ ${y},
769
775
  products: {
770
776
  enabled: false,
771
777
  items: []
772
778
  }
773
779
  };
774
- `;await c(t,P)}var Qo={smtp:[{key:"SMTP_HOST",defaultValue:"localhost"},{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"}],resend:[{key:"RESEND_API_KEY",comment:"# TODO: Add your Resend API key"}]},ea={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."}],polar:[{key:"POLAR_ACCESS_TOKEN",comment:"# TODO: Add your Polar keys"},{key:"POLAR_WEBHOOK_SECRET"}]};function Wt(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 Dr(e){return Array.from(crypto.getRandomValues(new Uint8Array(e))).map(t=>t.toString(16).padStart(2,"0")).join("")}function Nr(e){return e.architecture==="fullstack"?{apiUrl:"http://localhost:3000/api",baseUrl:"http://localhost:3000"}:{apiUrl:"http://localhost:3010",baseUrl:"http://localhost:3000"}}var ta="https://your-app.example.com/api";function zt(e,t,r,n){e.push(n==="example"?`${t}=`:`${t}=${r}`)}function Kn(e,t){let r=t==="example"?void 0:e.credentials,{apiUrl:n,baseUrl:i}=Nr(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(Wt($e[e.databaseProvider].envVars,r),o),o.push("","# Cache"),Pt(Wt(je[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`"),zt(o,"BETTER_AUTH_SECRET",crypto.randomUUID(),t),o.push("","# Content API (random secret; required when contentApi feature is enabled in @repo/config)"),zt(o,"CONTENT_API_KEY",Dr(32),t),o.push("","# Job Queue - Inngest","INNGEST_APP_ID=api"),zt(o,"INNGEST_EVENT_KEY",Dr(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."),zt(o,"INNGEST_SIGNING_KEY",Dr(32),t),o.push("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=Qo[e.emailProvider];if(s&&(o.push("","# Email"),Pt(Wt(s,r),o)),e.paymentProvider!=="none"){let d=ea[e.paymentProvider];d&&(o.push("","# Payment"),Pt(Wt(d,r),o))}o.push("","# Storage - S3 Compatible (required for uploads: avatars, files)","# Works with AWS S3, Cloudflare R2, MinIO, and other S3-compatible services.","# Uploads fail until these are set - storage is enabled in @repo/config by default.","#STORAGE_REGION=us-east-1","#STORAGE_ENDPOINT=https://your-account.r2.cloudflarestorage.com","#STORAGE_ACCESS_KEY_ID=","#STORAGE_SECRET_ACCESS_KEY=","# Two buckets: one publicly readable (avatars, assets), one credentials-only (private","# uploads served through the app). The bucket boundary is the privacy guarantee.","#STORAGE_PUBLIC_BUCKET=","#STORAGE_PRIVATE_BUCKET=",'# Public base URL for the public bucket. Public file URLs are STORAGE_PUBLIC_URL + "/" + key.',"#STORAGE_PUBLIC_URL=https://cdn.example.com","","# Storage - Local Filesystem (optional overrides)","# Defaults work out of the box; override for Docker volume mounts.","#STORAGE_LOCAL_PATH=/data","#STORAGE_LOCAL_PUBLIC_URL=https://cdn.example.com/files"),o.push("","# Admin Notifications (optional)","# Real-time notifications when business events occur (signups, purchases, etc.).","# Each provider is auto-enabled when its env vars are set.","#DISCORD_WEBHOOK_URL=https://discord.com/api/webhooks/...","#SLACK_WEBHOOK_URL=https://hooks.slack.com/services/...","#TELEGRAM_BOT_TOKEN=123456789:ABCdefGHIjklMNOpqrsTUVwxyz","#TELEGRAM_CHAT_ID=-1001234567890","#TELEGRAM_TOPIC_ID=123"),o.push("","# Social sign-in (optional)","# Enable the matching provider in @repo/config, then set its pair here.","#GOOGLE_CLIENT_ID=","#GOOGLE_CLIENT_SECRET=","#GITHUB_CLIENT_ID=","#GITHUB_CLIENT_SECRET=","# Apple needs four values rather than a pair, and they also back the mobile app's native","# Sign in with Apple - the same client is what the backend accepts a native token from.","#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"),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)."}),a.length>0&&(o.push("","# Error and product reporting (optional)"),Pt(a,o)),o.push("","# AI base (optional)","# Enable config.ai in packages/config. Built-in AI resolves through OpenRouter only,","# so OPENROUTER_API_KEY above is the only MODEL provider key the backend reads.","# BYOK is per-user and never an env var: users paste their own key in the app and it","# is stored encrypted in the database.","# Override the OpenRouter API base - a gateway or a proxy of your own. It must carry the","# /api/v1 suffix. Unset uses the hosted API.","#OPENROUTER_BASE_URL=https://openrouter.ai/api/v1","","# AI web tools (optional)","# Give the assistant its own web access. A key's presence is the whole switch: set one","# and the model gets its tools, set neither and chat is unchanged. Users still opt in","# per chat with the composer's web-search toggle, and config.ai.webSearch: false","# disables both. Calls bill to user credits - set the price and engine in","# config.ai.webTools.","# ANY one key alone covers both capabilities. Firecrawl is the recommended one, so a","# single signup is the whole setup, and with several keys set Firecrawl serves search","# and extract.","# Firecrawl (recommended) - `web_search` AND `web_extract` (reads one page).","# https://firecrawl.dev/","#FIRECRAWL_API_KEY=","# Parallel (optional) - both tools, cheaper 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. Set config.ai.webTools.searchEngine or .extractEngine to",'# "parallel" to use it alongside a Firecrawl key.',"# https://platform.parallel.ai/","#PARALLEL_API_KEY=","# TinyFish (optional) - both tools at a $0 list price, rate-limited instead (30 searches","# and 150 pages a minute per API key by default, shared by every user), so a call bills","# the user nothing unless you set a price in config.ai.webTools. Note its terms include","# a license to train on submitted content. Set config.ai.webTools.searchEngine or",'# .extractEngine to "tinyfish" to use it alongside another key.',"# https://agent.tinyfish.ai/","#TINYFISH_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.","#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(`
775
- `)}var Hn="NEXT_PUBLIC_API_URL";function ra(e){let{apiUrl:t}=Nr(e),r=["# API Configuration",`${Hn}=${t}`];return e.architecture==="separate"&&r.push("","# Production (uncomment and replace with your deployed hostnames):",`# ${Hn}=${ta}`),r.push(""),r.join(`
780
+ `;await c(t,P)}var Qo={smtp:[{key:"SMTP_HOST",defaultValue:"localhost"},{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"}],resend:[{key:"RESEND_API_KEY",comment:"# TODO: Add your Resend API key"}]},ea={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."}],polar:[{key:"POLAR_ACCESS_TOKEN",comment:"# TODO: Add your Polar keys"},{key:"POLAR_WEBHOOK_SECRET"}]};function Wt(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 Dr(e){return Array.from(crypto.getRandomValues(new Uint8Array(e))).map(t=>t.toString(16).padStart(2,"0")).join("")}function Nr(e){return e.architecture==="fullstack"?{apiUrl:"http://localhost:3000/api",baseUrl:"http://localhost:3000"}:{apiUrl:"http://localhost:3010",baseUrl:"http://localhost:3000"}}var ta="https://your-app.example.com/api";function zt(e,t,r,n){e.push(n==="example"?`${t}=`:`${t}=${r}`)}function Yn(e,t){let r=t==="example"?void 0:e.credentials,{apiUrl:n,baseUrl:i}=Nr(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(Wt($e[e.databaseProvider].envVars,r),o),o.push("","# Cache"),Pt(Wt(je[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`"),zt(o,"BETTER_AUTH_SECRET",crypto.randomUUID(),t),o.push("","# Content API (random secret; required when contentApi feature is enabled in @repo/config)"),zt(o,"CONTENT_API_KEY",Dr(32),t),o.push("","# Job Queue - Inngest","INNGEST_APP_ID=api"),zt(o,"INNGEST_EVENT_KEY",Dr(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."),zt(o,"INNGEST_SIGNING_KEY",Dr(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=Qo[e.emailProvider];if(s&&(o.push("","# Email"),Pt(Wt(s,r),o)),e.paymentProvider!=="none"){let d=ea[e.paymentProvider];d&&(o.push("","# Payment"),Pt(Wt(d,r),o))}o.push("","# Storage - S3 Compatible (required for uploads: avatars, files)","# Works with AWS S3, Cloudflare R2, MinIO, and other S3-compatible services.","# Uploads fail until these are set - storage is enabled in @repo/config by default.","#STORAGE_REGION=us-east-1","#STORAGE_ENDPOINT=https://your-account.r2.cloudflarestorage.com","#STORAGE_ACCESS_KEY_ID=","#STORAGE_SECRET_ACCESS_KEY=","# Two buckets: one publicly readable (avatars, assets), one credentials-only (private","# uploads served through the app). The bucket boundary is the privacy guarantee.","#STORAGE_PUBLIC_BUCKET=","#STORAGE_PRIVATE_BUCKET=",'# Public base URL for the public bucket. Public file URLs are STORAGE_PUBLIC_URL + "/" + key.',"#STORAGE_PUBLIC_URL=https://cdn.example.com","","# Storage - Local Filesystem (optional overrides)","# Defaults work out of the box; override for Docker volume mounts.","#STORAGE_LOCAL_PATH=/data","#STORAGE_LOCAL_PUBLIC_URL=https://cdn.example.com/files"),o.push("","# Admin Notifications (optional)","# Real-time notifications when business events occur (signups, purchases, etc.).","# Each provider is auto-enabled when its env vars are set.","#DISCORD_WEBHOOK_URL=https://discord.com/api/webhooks/...","#SLACK_WEBHOOK_URL=https://hooks.slack.com/services/...","#TELEGRAM_BOT_TOKEN=123456789:ABCdefGHIjklMNOpqrsTUVwxyz","#TELEGRAM_CHAT_ID=-1001234567890","#TELEGRAM_TOPIC_ID=123"),o.push("","# Social sign-in (optional)","# Enable the matching provider in @repo/config, then set its pair here.","#GOOGLE_CLIENT_ID=","#GOOGLE_CLIENT_SECRET=","#GITHUB_CLIENT_ID=","#GITHUB_CLIENT_SECRET=","# Apple needs four values rather than a pair, and they also back the mobile app's native","# Sign in with Apple - the same client is what the backend accepts a native token from.","#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"),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)."}),a.length>0&&(o.push("","# Error and product reporting (optional)"),Pt(a,o)),o.push("","# AI base (optional)","# Enable config.ai in packages/config. Built-in AI resolves through OpenRouter only,","# so OPENROUTER_API_KEY above is the only MODEL provider key the backend reads.","# BYOK is per-user and never an env var: users paste their own key in the app and it","# is stored encrypted in the database.","# Override the OpenRouter API base - a gateway or a proxy of your own. It must carry the","# /api/v1 suffix. Unset uses the hosted API.","#OPENROUTER_BASE_URL=https://openrouter.ai/api/v1","","# AI web tools (optional)","# Give the assistant its own web access. A key's presence is the whole switch: set one","# and the model gets its tools, set neither and chat is unchanged. Users still opt in","# per chat with the composer's web-search toggle, and config.ai.webSearch: false","# disables both. Calls bill to user credits - set the price and engine in","# config.ai.webTools.","# ANY one key alone covers both capabilities. Firecrawl is the recommended one, so a","# single signup is the whole setup, and with several keys set Firecrawl serves search","# and extract.","# Firecrawl (recommended) - `web_search` AND `web_extract` (reads one page).","# https://firecrawl.dev/","#FIRECRAWL_API_KEY=","# Parallel (optional) - both tools, cheaper 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. Set config.ai.webTools.searchEngine or .extractEngine to",'# "parallel" to use it alongside a Firecrawl key.',"# https://platform.parallel.ai/","#PARALLEL_API_KEY=","# TinyFish (optional) - both tools at a $0 list price, rate-limited instead (30 searches","# and 150 pages a minute per API key by default, shared by every user), so a call bills","# the user nothing unless you set a price in config.ai.webTools. Note its terms include","# a license to train on submitted content. Set config.ai.webTools.searchEngine or",'# .extractEngine to "tinyfish" to use it alongside another key.',"# https://agent.tinyfish.ai/","#TINYFISH_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.","#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(`
781
+ `)}var Wn="NEXT_PUBLIC_API_URL";function ra(e){let{apiUrl:t}=Nr(e),r=["# API Configuration",`${Wn}=${t}`];return e.architecture==="separate"&&r.push("","# Production (uncomment and replace with your deployed hostnames):",`# ${Wn}=${ta}`),r.push(""),r.join(`
776
782
  `)}function na(e){let{apiUrl:t,baseUrl:r}=Nr(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(`
777
- `)}async function Yn(e){let t=ra(e);if(await c(`${e.projectDir}/.env`,`${t}
778
- ${Kn(e,"env")}`),await c(`${e.projectDir}/.env.example`,`${t}
779
- ${Kn(e,"example")}`),e.mobile){let r=na(e);await c(`${e.projectDir}/apps/mobile/.env`,r),await c(`${e.projectDir}/apps/mobile/.env.example`,r)}}import{join as ia}from"path";async function Wn(e){let t=Qe(e),r=[],n=[];if(t.includes("postgres")&&(r.push(` postgres:
783
+ `)}async function zn(e){let t=ra(e);if(await c(`${e.projectDir}/.env`,`${t}
784
+ ${Yn(e,"env")}`),await c(`${e.projectDir}/.env.example`,`${t}
785
+ ${Yn(e,"example")}`),e.mobile){let r=na(e);await c(`${e.projectDir}/apps/mobile/.env`,r),await c(`${e.projectDir}/apps/mobile/.env.example`,r)}}import{join as ia}from"path";async function qn(e){let t=tt(e),r=[],n=[];if(t.includes("postgres")&&(r.push(` postgres:
780
786
  image: postgres:18-alpine
781
787
  restart: unless-stopped
782
788
  ports:
@@ -838,13 +844,13 @@ ${r.join(`
838
844
  volumes:
839
845
  ${n.join(`
840
846
  `)}
841
- `),await c(ia(e.projectDir,"infra/docker-compose.yml"),o)}import{join as sa}from"path";var At="Next.js";function oa(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 aa(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 zn(e){let t={version:"0.2.0",configurations:oa(e),compounds:aa(e)};await c(sa(e.projectDir,".vscode/launch.json"),`${JSON.stringify(t,null," ")}
842
- `)}import{readFile as Jn}from"fs/promises";import{join as Xn}from"path";var Cr='import { drizzle } from "drizzle-orm/node-postgres";',Lr=`export const db = drizzle(parsed.data.DATABASE_URL, { schema });
847
+ `),await c(ia(e.projectDir,"infra/docker-compose.yml"),o)}import{join as sa}from"path";var At="Next.js";function oa(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 aa(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 Jn(e){let t={version:"0.2.0",configurations:oa(e),compounds:aa(e)};await c(sa(e.projectDir,".vscode/launch.json"),`${JSON.stringify(t,null," ")}
848
+ `)}import{readFile as Zn}from"fs/promises";import{join as Qn}from"path";var Cr='import { drizzle } from "drizzle-orm/node-postgres";',Lr=`export const db = drizzle(parsed.data.DATABASE_URL, { schema });
843
849
  export const pool = db.$client;`,ca={postgres:{importLine:Cr,instantiation:Lr},neon:{importLine:`import { Pool } from "@neondatabase/serverless";
844
850
  import { drizzle } from "drizzle-orm/neon-serverless";`,instantiation:`const pool = new Pool({ connectionString: parsed.data.DATABASE_URL });
845
851
  export const db = drizzle(pool, { schema });`},supabase:{importLine:`import { drizzle } from "drizzle-orm/postgres-js";
846
852
  import postgres from "postgres";`,instantiation:`const client = postgres(parsed.data.DATABASE_URL);
847
- export const db = drizzle(client, { schema });`}};async function Zn(e){let t=Xn(e.projectDir,"packages/database/src/index.ts"),r=await Jn(t,"utf-8");if(!r.includes(Cr)||!r.includes(Lr))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=ca[e.databaseProvider],i=r.replace(Cr,n.importLine).replace(Lr,n.instantiation);await c(t,i),await pa(e)}var qn='import { Client } from "pg";',$r=` const client = new Client({ connectionString });
853
+ export const db = drizzle(client, { schema });`}};async function ei(e){let t=Qn(e.projectDir,"packages/database/src/index.ts"),r=await Zn(t,"utf-8");if(!r.includes(Cr)||!r.includes(Lr))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=ca[e.databaseProvider],i=r.replace(Cr,n.importLine).replace(Lr,n.instantiation);await c(t,i),await pa(e)}var Xn='import { Client } from "pg";',$r=` const client = new Client({ connectionString });
848
854
  await client.connect();
849
855
  return {
850
856
  query: async (text) => ({ rows: (await client.query<LiveColumnRow>(text)).rows }),
@@ -853,7 +859,7 @@ export const db = drizzle(client, { schema });`}};async function Zn(e){let t=Xn(
853
859
  return {
854
860
  query: async (text) => ({ rows: await sql.unsafe(text) }),
855
861
  end: () => sql.end()
856
- };`}};async function pa(e){let t=la[e.databaseProvider];if(!t)return;let r=Xn(e.projectDir,"packages/database/src/db-verify.ts"),n=await Jn(r,"utf-8");if(!n.includes(qn)||!n.includes($r))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 c(r,n.replace(qn,t.importLine).replace($r,t.open))}import{join as Qn}from"path";async function ei(e){e.cacheProvider==="upstash"&&(await da(e),await ua(e))}async function da(e){await c(Qn(e.projectDir,"packages/runtime/src/redis.ts"),`import { Redis } from "@upstash/redis";
862
+ };`}};async function pa(e){let t=la[e.databaseProvider];if(!t)return;let r=Qn(e.projectDir,"packages/database/src/db-verify.ts"),n=await Zn(r,"utf-8");if(!n.includes(Xn)||!n.includes($r))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 c(r,n.replace(Xn,t.importLine).replace($r,t.open))}import{join as ti}from"path";async function ri(e){e.cacheProvider==="upstash"&&(await da(e),await ua(e))}async function da(e){await c(ti(e.projectDir,"packages/runtime/src/redis.ts"),`import { Redis } from "@upstash/redis";
857
863
  import type { Store } from "hono-rate-limiter";
858
864
  import { env } from "./env";
859
865
 
@@ -1023,7 +1029,7 @@ export function createLimiterStore(): Store {
1023
1029
 
1024
1030
  /** No persistent connection to close with Upstash REST. */
1025
1031
  export async function closeRedis(): Promise<void> {}
1026
- `)}async function ua(e){await c(Qn(e.projectDir,"packages/runtime/src/mutex.ts"),`import { Lock } from "@upstash/lock";
1032
+ `)}async function ua(e){await c(ti(e.projectDir,"packages/runtime/src/mutex.ts"),`import { Lock } from "@upstash/lock";
1027
1033
  import { redis } from "./redis";
1028
1034
 
1029
1035
  export class MutexTimeoutError extends Error {
@@ -1101,23 +1107,23 @@ export async function withMutex<T>(
1101
1107
  });
1102
1108
  }
1103
1109
  }
1104
- `)}import{readFile as ma}from"fs/promises";import{join as ha}from"path";var ti=" REDIS_URL: z.string(),",fa=` UPSTASH_REDIS_REST_URL: z.string(),
1105
- UPSTASH_REDIS_REST_TOKEN: z.string(),`;async function ri(e){let t=ha(e.projectDir,"packages/runtime/src/env.ts"),r=await ma(t,"utf-8");if(!r.includes(ti))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(ti,fa):r;await c(t,n)}import{readFile as ci}from"fs/promises";import{join as V}from"path";import{readFile as ii,rm as ka}from"fs/promises";import{join as lt}from"path";import{readFile as Rt,rm as ga}from"fs/promises";import{join as It}from"path";function ya(e){return new RegExp(`^[ \\t]*(?:\\/\\/|\\{\\/\\*|\\*) gsaas:${e}-start(?: \\*\\/\\})?[ \\t]*\\r?\\n[\\s\\S]*?^[ \\t]*(?:\\/\\/|\\{\\/\\*|\\*) gsaas:${e}-end(?: \\*\\/\\})?[ \\t]*\\r?\\n`,"gm")}function Y(e,t,r,n){let i=ya(r);if(e.match(i)===null)throw new Error(`${n}: expected gsaas ${r} markers in ${t}, but found none (boilerplate drift).`);let o=e.replace(i,"");if(o.includes(`gsaas:${r}-start`)||o.includes(`gsaas:${r}-end`))throw new Error(`${n}: an unbalanced gsaas ${r} marker is left in ${t} (boilerplate drift).`);return o.replace(/\n{3,}/g,`
1110
+ `)}import{readFile as ma}from"fs/promises";import{join as ha}from"path";var ni=" REDIS_URL: z.string(),",fa=` UPSTASH_REDIS_REST_URL: z.string(),
1111
+ UPSTASH_REDIS_REST_TOKEN: z.string(),`;async function ii(e){let t=ha(e.projectDir,"packages/runtime/src/env.ts"),r=await ma(t,"utf-8");if(!r.includes(ni))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(ni,fa):r;await c(t,n)}import{readFile as li}from"fs/promises";import{join as V}from"path";import{readFile as jr,rm as ka}from"fs/promises";import{join as Ge}from"path";import{readFile as Rt,rm as ga}from"fs/promises";import{join as It}from"path";function ya(e){return new RegExp(`^[ \\t]*(?:\\/\\/|\\{\\/\\*|\\*) gsaas:${e}-start(?: \\*\\/\\})?[ \\t]*\\r?\\n[\\s\\S]*?^[ \\t]*(?:\\/\\/|\\{\\/\\*|\\*) gsaas:${e}-end(?: \\*\\/\\})?[ \\t]*\\r?\\n`,"gm")}function K(e,t,r,n){let i=ya(r);if(e.match(i)===null)throw new Error(`${n}: expected gsaas ${r} markers in ${t}, but found none (boilerplate drift).`);let o=e.replace(i,"");if(o.includes(`gsaas:${r}-start`)||o.includes(`gsaas:${r}-end`))throw new Error(`${n}: an unbalanced gsaas ${r} marker is left in ${t} (boilerplate drift).`);return o.replace(/\n{3,}/g,`
1106
1112
 
1107
- `).replace(/,(\r?\n[ \t]*[\]})])/g,"$1")}async function E(e,t,r,n,i){let o=await Rt(e,"utf-8"),s=o.indexOf(t);if(s===-1)throw new Error(`${i}: expected to find the ${n} seam, but it was missing (boilerplate drift).`);if(o.includes(t,s+t.length))throw new Error(`${i}: the ${n} seam appears more than once (boilerplate drift).`);await c(e,o.slice(0,s)+r+o.slice(s+t.length))}async function Se(e,t,r,n){let i=/\n([\t ]+)"/.exec(await Rt(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 c(e,`${JSON.stringify(t,null,r)}
1113
+ `).replace(/,(\r?\n[ \t]*[\]})])/g,"$1")}async function k(e,t,r,n,i){let o=await Rt(e,"utf-8"),s=o.indexOf(t);if(s===-1)throw new Error(`${i}: expected to find the ${n} seam, but it was missing (boilerplate drift).`);if(o.includes(t,s+t.length))throw new Error(`${i}: the ${n} seam appears more than once (boilerplate drift).`);await c(e,o.slice(0,s)+r+o.slice(s+t.length))}async function Se(e,t,r,n){let i=/\n([\t ]+)"/.exec(await Rt(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 c(e,`${JSON.stringify(t,null,r)}
1108
1114
  `)}async function ba(e,t,r){let n=It(e,"ai.mdx"),o=(await Rt(n,"utf-8")).split(`
1109
- `).find(s=>s.includes(`href="${t}"`));if(o===void 0)throw new Error(`${r}: expected the ai.mdx card linking to ${t} (boilerplate drift).`);await E(n,`${o}
1115
+ `).find(s=>s.includes(`href="${t}"`));if(o===void 0)throw new Error(`${r}: expected the ai.mdx card linking to ${t} (boilerplate drift).`);await k(n,`${o}
1110
1116
  `,"",`ai.mdx ${t} card`,r)}async function wa(e,t,r){let n=It(e,"ai.mdx"),i=`| **${t}** |`,s=(await Rt(n,"utf-8")).split(`
1111
- `).find(a=>a.startsWith(i));if(s===void 0)throw new Error(`${r}: expected the ai.mdx "${t}" hub-table row (boilerplate drift).`);await E(n,`${s}
1112
- `,"",`ai.mdx ${t} hub-table row`,r)}async function ni(e,t,r,n,i){let o=It(e,"docs/(platform)");await ga(It(o,t),{recursive:!0}),await E(It(o,"meta.json"),` "${t}",
1117
+ `).find(a=>a.startsWith(i));if(s===void 0)throw new Error(`${r}: expected the ai.mdx "${t}" hub-table row (boilerplate drift).`);await k(n,`${s}
1118
+ `,"",`ai.mdx ${t} hub-table row`,r)}async function si(e,t,r,n,i){let o=It(e,"docs/(platform)");await ga(It(o,t),{recursive:!0}),await k(It(o,"meta.json"),` "${t}",
1113
1119
  `,"",`docs meta.json ${t} nav entry`,n);for(let s of r)await ba(o,s,n);i!==void 0&&await wa(o,i,n)}function va(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]!==`
1114
1120
  `;)r++;continue}if(n==="/"&&i==="*"){for(r+=2;r<e.length&&!(e[r]==="*"&&e[r+1]==="/");)e[r]===`
1115
1121
  `&&(t+=`
1116
1122
  `),r++;r+=2;continue}if(n==='"'||n==="'"||n==="`"){let o=n;for(r++;r<e.length&&e[r]!==o;)e[r]==="\\"?r++:e[r]===`
1117
1123
  `&&(t+=`
1118
1124
  `),r++;r++;continue}t+=n,r++}return t}async function qt(e){let t=`import { config } from "@repo/config";
1119
- `,r=await Rt(e,"utf-8");if(!r.includes(t))return;let n=r.replace(t,""),i=va(n);/\bconfig\b/.test(i)||await c(e,n)}var pt="stripMobileObservability",si=["apps/mobile/lib/observability.ts","apps/mobile/types/env.d.ts","apps/mobile/tests/settings-privacy-screen.test.tsx"],oi="apps/mobile/tests/observability.test.ts",Ea="mobile-obs-any",Sa=["apps/mobile/tests/settings-privacy-screen.test.tsx"],Jt={sentry:["@sentry/react-native"],posthog:["posthog-react-native"]},Pa=`,
1120
- "@sentry/react-native/expo"`,Aa="|@sentry/react-native",Ia=` * DUAL-PROVIDER, the way \`packages/observability\` is. This repo carries the Sentry and the PostHog
1125
+ `,r=await Rt(e,"utf-8");if(!r.includes(t))return;let n=r.replace(t,""),i=va(n);/\bconfig\b/.test(i)||await c(e,n)}var Ke="stripMobileObservability",oi=["apps/mobile/lib/observability.ts","apps/mobile/types/env.d.ts","apps/mobile/tests/settings-privacy-screen.test.tsx"],ai="apps/mobile/tests/observability.test.ts",Ea="mobile-obs-any",Sa=["apps/mobile/tests/settings-privacy-screen.test.tsx"],Jt={sentry:["@sentry/react-native","@sentry/cli"],posthog:["posthog-react-native"]},Pa=`,
1126
+ ...sentryExpoPlugin()`,Aa=["apps/mobile/app.config.ts"],Ia="|@sentry/react-native",Ra=` * DUAL-PROVIDER, the way \`packages/observability\` is. This repo carries the Sentry and the PostHog
1121
1127
  * halves at once so dev and the test suite exercise both. A generated project carries only the
1122
1128
  * providers its \`observability\` manifest option names: the CLI removes the other one's marked region
1123
1129
  * from this file, its SDK from \`apps/mobile/package.json\` and, for Sentry, its Expo config plugin
@@ -1128,7 +1134,7 @@ export async function withMutex<T>(
1128
1134
  * cross-provider \`{@link}\` and every paragraph about one provider's credentials sits INSIDE that
1129
1135
  * provider's own region, and what is left between them is provider-neutral - the {@link PROVIDERS}
1130
1136
  * list and the two exported entry points that walk it, which is what a project generated with
1131
- * \`observability: []\` keeps and starts nothing with.`,Ra='import { readPrivacySettings, type PrivacySettings } from "@/lib/privacy";',Ta='import type { PrivacySettings } from "@/lib/privacy";';function _a(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
1137
+ * \`observability: []\` keeps and starts nothing with.`,Ta='import { readPrivacySettings, type PrivacySettings } from "@/lib/privacy";',_a='import type { PrivacySettings } from "@/lib/privacy";';function Oa(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
1132
1138
  * and no reporting SDK: {@link PROVIDERS} is empty, and both functions below are no-ops that load
1133
1139
  * nothing and send nothing.`:` * This app reports to ${t}. No other provider's start, SDK or Expo config plugin was
1134
1140
  * generated, so there is nothing here for Metro to fold away and nothing for pnpm to install.`}
@@ -1136,9 +1142,9 @@ export async function withMutex<T>(
1136
1142
  * To change providers, edit \`observability\` in .generatesaas/manifest.json and run
1137
1143
  * \`generatesaas update\`: re-shaping brings that provider's half of this file, its SDK and its env
1138
1144
  * key back. Pasting the other provider's credential into \`config.observability\` on its own cannot -
1139
- * the start it would need is not here.`}async function ai(e){if(!e.mobile)return;let t=e.projectDir,r=["sentry","posthog"].filter(o=>!e.observability.includes(o));e.observability.length===0&&await ka(lt(t,oi),{force:!0});let n=e.observability.length===0?si:[...si,oi];for(let o of r)for(let s of n){let a=lt(t,s);await c(a,Y(await ii(a,"utf-8"),s,`mobile-obs-${o}`,pt))}if(e.observability.length===0)for(let o of Sa){let s=lt(t,o);await c(s,Y(await ii(s,"utf-8"),o,Ea,pt))}r.includes("sentry")&&(await E(lt(t,"apps/mobile/app.config.ts"),Pa,"","app.config.ts Sentry Expo plugin",pt),await E(lt(t,"apps/mobile/jest.config.js"),Aa,"","jest.config.js Sentry transform allowance",pt));let i=lt(t,"apps/mobile/lib/observability.ts");await E(i,Ia,_a(e.observability),"lib/observability.ts dual-provider note",pt),e.observability.length===0&&(await E(i,Ra,Ta,"lib/observability.ts privacy import",pt),await qt(i))}var Xt={"@upstash/redis":"^1.37.0","@upstash/lock":"^0.2.1","@neondatabase/serverless":"^1.0.1",postgres:"^3.4.7"};async function ae(e){let t=await ci(e,"utf-8");return JSON.parse(t)}async function ce(e,t){let r=/\n([\t ]+)"/.exec(await ci(e,"utf-8"))?.[1]??" ";await c(e,`${JSON.stringify(t,null,r)}
1140
- `)}function ee(e,t){for(let r of t)delete e.dependencies?.[r],delete e.devDependencies?.[r]}function Oa(e){e.dependencies&&Object.keys(e.dependencies).length===0&&delete e.dependencies,e.devDependencies&&Object.keys(e.devDependencies).length===0&&delete e.devDependencies}function Tt(e,t,r,n=!1){let i=n?"devDependencies":"dependencies";e[i]||(e[i]={}),e[i][t]=r}async function li(e){await Da(e),await Na(e),await Ca(e),await Ua(e),await Ma(e),await Ga(e),await xa(e)}async function xa(e){if(!e.mobile){let t=V(e.projectDir,"packages/auth/package.json"),r=await ae(t);ee(r,["@better-auth/expo"]),await ce(t,r);let n=V(e.projectDir,"tooling/styles/package.json"),i=await ae(n);ee(i,["tsx"]),Oa(i),await ce(n,i)}if(e.mobile&&e.mobilePurchases!=="revenuecat"){let t=V(e.projectDir,"apps/mobile/package.json"),r=await ae(t);ee(r,["react-native-purchases","react-native-purchases-ui"]),await ce(t,r)}}async function Da(e){let t=V(e.projectDir,"packages/api/package.json"),r=await ae(t);ee(r,["sharp","@types/sharp"]),e.cacheProvider==="upstash"&&ee(r,["ioredis"]),await ce(t,r)}async function Na(e){let t=V(e.projectDir,"apps/web/package.json"),r=await ae(t);ee(r,["@upstash/ratelimit","@upstash/redis"]),await ce(t,r)}async function Ca(e){let t=V(e.projectDir,"packages/runtime/package.json"),r=await ae(t);e.cacheProvider==="upstash"&&(ee(r,["ioredis","rate-limit-redis","redis-semaphore"]),Tt(r,"@upstash/redis",Xt["@upstash/redis"]),Tt(r,"@upstash/lock",Xt["@upstash/lock"])),await ce(t,r)}var jr={sentry:["@sentry/node","@sentry/browser","@sentry/electron"],posthog:["posthog-node","posthog-js"]},La=["@sentry/electron"],$a=[...jr.sentry,...jr.posthog],ja=[...Jt.sentry,...Jt.posthog];async function Ua(e){let t=V(e.projectDir,"packages/observability/package.json"),r=await ae(t),n=new Set(e.observability.flatMap(a=>jr[a]));if(!e.desktop)for(let a of La)n.delete(a);if(ee(r,$a.filter(a=>!n.has(a))),await ce(t,r),!e.mobile)return;let i=V(e.projectDir,"apps/mobile/package.json"),o=await ae(i),s=new Set(e.observability.flatMap(a=>Jt[a]));ee(o,ja.filter(a=>!s.has(a))),await ce(i,o)}async function Ma(e){let t=V(e.projectDir,"packages/database/package.json"),r=await ae(t);e.databaseProvider==="neon"?(ee(r,["pg","@types/pg"]),Tt(r,"@neondatabase/serverless",Xt["@neondatabase/serverless"])):e.databaseProvider==="supabase"&&(ee(r,["pg","@types/pg"]),Tt(r,"postgres",Xt.postgres)),await ce(t,r)}var Fa=["app/.well-known/oauth-authorization-server/[[...path]]/route.ts","app/.well-known/oauth-protected-resource/[[...path]]/route.ts"];async function Va(e){let t=await ae(e),r=t.dependencies?.["@repo/api"];r&&(delete t.dependencies?.["@repo/api"],Tt(t,"@repo/api",r,!0),await ce(e,t))}var Ba=["instrumentation.ts","tests/instrumentation.test.ts"];async function Ga(e){if(e.architecture!=="separate")return;let t=V(e.projectDir,"apps/web");await at(V(t,"app/api/[[...rest]]/route.ts"),t);for(let r of Fa)await at(V(t,r),t);for(let r of Ba)await at(V(t,r),t);await Va(V(t,"package.json"))}import{readFile as Ka}from"fs/promises";import{join as Ha}from"path";var Ya=["base.json","node.json","next.json"],pi="GenerateSaaS ";async function di(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(pi)||(i.display=i.display.slice(pi.length),await c(r,`${JSON.stringify(i,null," ")}
1141
- `))}}import{readFile as mi,rm as Wa}from"fs/promises";import{join as _t}from"path";async function hi(e){e.cacheProvider==="upstash"&&(await Promise.all([ui(_t(e.projectDir,"packages/runtime/tests/setup.ts")),ui(_t(e.projectDir,"packages/mail/tests/setup.ts")),qa(e.projectDir),Wa(_t(e.projectDir,"packages/runtime/tests/redis.test.ts"),{force:!0})]),await za(e.projectDir))}async function za(e){await c(_t(e,"packages/runtime/tests/redis.test.ts"),`import { beforeEach, describe, expect, it, vi } from "vitest";
1145
+ * the start it would need is not here.`}async function ci(e){if(!e.mobile)return;let t=e.projectDir,r=["sentry","posthog"].filter(o=>!e.observability.includes(o));e.observability.length===0&&await ka(Ge(t,ai),{force:!0});let n=e.observability.length===0?oi:[...oi,ai];for(let o of r)for(let s of n){let a=Ge(t,s);await c(a,K(await jr(a,"utf-8"),s,`mobile-obs-${o}`,Ke))}if(e.observability.length===0)for(let o of Sa){let s=Ge(t,o);await c(s,K(await jr(s,"utf-8"),o,Ea,Ke))}if(r.includes("sentry")){for(let o of Aa){let s=Ge(t,o);await c(s,K(await jr(s,"utf-8"),o,"mobile-obs-sentry",Ke))}await k(Ge(t,"apps/mobile/app.config.ts"),Pa,"","app.config.ts Sentry Expo plugin",Ke),await k(Ge(t,"apps/mobile/jest.config.js"),Ia,"","jest.config.js Sentry transform allowance",Ke)}let i=Ge(t,"apps/mobile/lib/observability.ts");await k(i,Ra,Oa(e.observability),"lib/observability.ts dual-provider note",Ke),e.observability.length===0&&(await k(i,Ta,_a,"lib/observability.ts privacy import",Ke),await qt(i))}var Xt={"@upstash/redis":"^1.37.0","@upstash/lock":"^0.2.1","@neondatabase/serverless":"^1.0.1",postgres:"^3.4.7"};async function ae(e){let t=await li(e,"utf-8");return JSON.parse(t)}async function ce(e,t){let r=/\n([\t ]+)"/.exec(await li(e,"utf-8"))?.[1]??" ";await c(e,`${JSON.stringify(t,null,r)}
1146
+ `)}function ee(e,t){for(let r of t)delete e.dependencies?.[r],delete e.devDependencies?.[r]}function xa(e){e.dependencies&&Object.keys(e.dependencies).length===0&&delete e.dependencies,e.devDependencies&&Object.keys(e.devDependencies).length===0&&delete e.devDependencies}function Tt(e,t,r,n=!1){let i=n?"devDependencies":"dependencies";e[i]||(e[i]={}),e[i][t]=r}async function pi(e){await Na(e),await Ca(e),await La(e),await Ma(e),await Fa(e),await Ka(e),await Da(e)}async function Da(e){if(!e.mobile){let t=V(e.projectDir,"packages/auth/package.json"),r=await ae(t);ee(r,["@better-auth/expo"]),await ce(t,r);let n=V(e.projectDir,"tooling/styles/package.json"),i=await ae(n);ee(i,["tsx"]),xa(i),await ce(n,i)}if(e.mobile&&e.mobilePurchases!=="revenuecat"){let t=V(e.projectDir,"apps/mobile/package.json"),r=await ae(t);ee(r,["react-native-purchases","react-native-purchases-ui"]),await ce(t,r)}}async function Na(e){let t=V(e.projectDir,"packages/api/package.json"),r=await ae(t);ee(r,["sharp","@types/sharp"]),e.cacheProvider==="upstash"&&ee(r,["ioredis"]),await ce(t,r)}async function Ca(e){let t=V(e.projectDir,"apps/web/package.json"),r=await ae(t);ee(r,["@upstash/ratelimit","@upstash/redis"]),await ce(t,r)}async function La(e){let t=V(e.projectDir,"packages/runtime/package.json"),r=await ae(t);e.cacheProvider==="upstash"&&(ee(r,["ioredis","rate-limit-redis","redis-semaphore"]),Tt(r,"@upstash/redis",Xt["@upstash/redis"]),Tt(r,"@upstash/lock",Xt["@upstash/lock"])),await ce(t,r)}var Ur={sentry:["@sentry/node","@sentry/browser","@sentry/electron"],posthog:["posthog-node","posthog-js"]},$a=["@sentry/electron"],ja=[...Ur.sentry,...Ur.posthog],Ua=[...Jt.sentry,...Jt.posthog];async function Ma(e){let t=V(e.projectDir,"packages/observability/package.json"),r=await ae(t),n=new Set(e.observability.flatMap(a=>Ur[a]));if(!e.desktop)for(let a of $a)n.delete(a);if(ee(r,ja.filter(a=>!n.has(a))),await ce(t,r),!e.mobile)return;let i=V(e.projectDir,"apps/mobile/package.json"),o=await ae(i),s=new Set(e.observability.flatMap(a=>Jt[a]));ee(o,Ua.filter(a=>!s.has(a))),await ce(i,o)}async function Fa(e){let t=V(e.projectDir,"packages/database/package.json"),r=await ae(t);e.databaseProvider==="neon"?(ee(r,["pg","@types/pg"]),Tt(r,"@neondatabase/serverless",Xt["@neondatabase/serverless"])):e.databaseProvider==="supabase"&&(ee(r,["pg","@types/pg"]),Tt(r,"postgres",Xt.postgres)),await ce(t,r)}var Va=["app/.well-known/oauth-authorization-server/[[...path]]/route.ts","app/.well-known/oauth-protected-resource/[[...path]]/route.ts"];async function Ba(e){let t=await ae(e),r=t.dependencies?.["@repo/api"];r&&(delete t.dependencies?.["@repo/api"],Tt(t,"@repo/api",r,!0),await ce(e,t))}var Ga=["instrumentation.ts","tests/instrumentation.test.ts"];async function Ka(e){if(e.architecture!=="separate")return;let t=V(e.projectDir,"apps/web");await lt(V(t,"app/api/[[...rest]]/route.ts"),t);for(let r of Va)await lt(V(t,r),t);for(let r of Ga)await lt(V(t,r),t);await Ba(V(t,"package.json"))}import{readFile as Ha}from"fs/promises";import{join as Ya}from"path";var Wa=["base.json","node.json","next.json"],di="GenerateSaaS ";async function ui(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(di)||(i.display=i.display.slice(di.length),await c(r,`${JSON.stringify(i,null," ")}
1147
+ `))}}import{readFile as hi,rm as za}from"fs/promises";import{join as _t}from"path";async function fi(e){e.cacheProvider==="upstash"&&(await Promise.all([mi(_t(e.projectDir,"packages/runtime/tests/setup.ts")),mi(_t(e.projectDir,"packages/mail/tests/setup.ts")),Ja(e.projectDir),za(_t(e.projectDir,"packages/runtime/tests/redis.test.ts"),{force:!0})]),await qa(e.projectDir))}async function qa(e){await c(_t(e,"packages/runtime/tests/redis.test.ts"),`import { beforeEach, describe, expect, it, vi } from "vitest";
1142
1148
 
1143
1149
  /**
1144
1150
  * Regression guards for the Upstash-backed cache layer in src/redis.ts.
@@ -1260,9 +1266,9 @@ describe("cacheScan", () => {
1260
1266
  expect(seen.sort()).toEqual(["scan:1", "scan:2", "scan:3"]);
1261
1267
  });
1262
1268
  });
1263
- `)}async function ui(e){let t;try{t=await mi(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",
1269
+ `)}async function mi(e){let t;try{t=await hi(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",
1264
1270
  UPSTASH_REDIS_REST_TOKEN: "test-token",
1265
- `);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 c(e,r)}async function qa(e){let t=_t(e,"packages/api/tests/setup.ts"),r;try{r=await mi(t,"utf-8")}catch{throw new Error(`pruneCacheTests: expected ${t} for the Upstash cache swap (boilerplate drift).`)}let n=r;if(n=n.replace(/\tREDIS_URL:\s*"[^"]*",?\n/g,` UPSTASH_REDIS_REST_URL: "https://test.upstash.io",
1271
+ `);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 c(e,r)}async function Ja(e){let t=_t(e,"packages/api/tests/setup.ts"),r;try{r=await hi(t,"utf-8")}catch{throw new Error(`pruneCacheTests: expected ${t} for the Upstash cache swap (boilerplate drift).`)}let n=r;if(n=n.replace(/\tREDIS_URL:\s*"[^"]*",?\n/g,` UPSTASH_REDIS_REST_URL: "https://test.upstash.io",
1266
1272
  UPSTASH_REDIS_REST_TOKEN: "test-token",
1267
1273
  `),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",
1268
1274
  UPSTASH_REDIS_REST_TOKEN: "test-token",
@@ -1291,34 +1297,36 @@ vi.mock("@upstash/lock", () => {
1291
1297
  return { Lock };
1292
1298
  });
1293
1299
 
1294
- $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).`);await c(t,n)}import{readFile as Ja}from"fs/promises";var Xa=/^[ \t]*(?:\/\/|\{\/\*|\*) gsaas:[a-z0-9-]+-(?:start|end)(?: \*\/\})?[ \t]*\r?\n/gm,Za=new Set([".ts",".tsx",".vue",".mjs",".js",".jsx",".md",".mdx"]),fi=32;function Qa(e){let t=e.lastIndexOf(".");return t>=0&&Za.has(e.slice(t))}async function ec(e){let t=await Ja(e,"utf-8");if(!t.includes("gsaas:"))return;let r=t.replace(Xa,"");r!==t&&await c(e,r)}async function gi(e){let t=await Ee(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+=fi)await Promise.all(t.slice(r,r+fi).map(ec))}import{readdir as Qt,readFile as le,rm as S}from"fs/promises";import{join as p}from"path";import{readFile as bi,rm as T}from"fs/promises";import{join as A}from"path";import{readFile as Ot}from"fs/promises";import{join as xt}from"path";async function yi(e,t){let r=xt(e,"packages/api/src/routes/internal/index.ts");await c(r,Y(await Ot(r,"utf-8"),"internal router","runner",t)),await qt(r);let n=xt(e,"packages/api/src/ai/automation-runner.ts");await c(n,Y(await Ot(n,"utf-8"),"automation-runner.ts","runner",t));for(let s of["packages/api/src/index.ts","packages/api/src/routes/internal/ai/chat-router.ts","packages/api/src/routes/internal/ai/automations-router.ts","packages/api/src/ai/byok.ts","packages/api/tests/ai/automations.test.ts","packages/api/tests/ai/automations-runs-route.test.ts","packages/api/tests/routes/ai.test.ts","packages/api/tests/ai/summarize-cap.test.ts"]){let a=xt(e,s);await c(a,Y(await Ot(a,"utf-8"),s,"runner",t))}let i=xt(e,"packages/api/src/ai/settings-store.ts");await c(i,Y(await Ot(i,"utf-8"),"settings-store.ts","runner",t));let o=xt(e,"packages/api/tests/ai/settings-store.test.ts");await c(o,Y(await Ot(o,"utf-8"),"settings-store.test.ts","runner",t))}async function Ur(e){if(e.runner)return;let t=e.projectDir,r="stripRunner";await T(A(t,"packages/api/src/relay"),{recursive:!0}),await T(A(t,"packages/api/src/runner"),{recursive:!0}),await T(A(t,"packages/api/src/ai/runner-model.ts")),await T(A(t,"packages/api/src/ai/runner-routing.ts")),await T(A(t,"packages/api/tests/relay"),{recursive:!0}),await T(A(t,"packages/api/tests/runner"),{recursive:!0}),await T(A(t,"packages/api/src/routes/internal/runner.ts")),await T(A(t,"packages/api/src/routes/internal/runner-transport.ts")),await T(A(t,"packages/api/src/routes/internal/runner-limits.ts")),await T(A(t,"packages/api/tests/routes/runner.test.ts")),await T(A(t,"packages/api/tests/routes/runner-transport-harness.ts")),await T(A(t,"packages/api/tests/routes/runner-transport-connect.test.ts")),await T(A(t,"packages/api/tests/routes/runner-transport-events.test.ts")),await T(A(t,"packages/api/tests/ai/automation-coalesce.test.ts")),await T(A(t,"packages/api/tests/ai/automations-lazy-expiry.test.ts")),await T(A(t,"packages/api/tests/ai/runner-model.test.ts")),await T(A(t,"packages/api/tests/unit/runner-offline-routing.test.ts")),await T(A(t,"packages/api/tests/unit/runner-offline-interactive.test.ts")),await T(A(t,"packages/api/tests/unit/runner-unavailable-routing.test.ts")),await T(A(t,"packages/api/tests/unit/runner-unavailable-interactive.test.ts")),await T(A(t,"packages/api/tests/unit/runner-arm-harness.ts")),await T(A(t,"packages/api/tests/ai/runner-chat.test.ts")),await T(A(t,"packages/api/tests/helpers/runner-protocol.ts")),await T(A(t,"packages/api/tests/helpers/runner-frames.ts")),await T(A(t,"packages/api/tests/helpers/relay-runtime-mock.ts"));let n=A(t,"packages/api/package.json"),i=JSON.parse(await bi(n,"utf-8"));if(!i.exports?.["./runner"])throw new Error(`${r}: expected packages/api/package.json to carry the ./runner export`);delete i.exports["./runner"],await Se(n,i," ",r),await yi(t,r),await ni(t,"runner",["/runner"],r,"Runners"),await E(A(t,"docs/(platform)/ai.mdx"),"Runs on a paired [runner](/runner) CLI are never metered either - the user's own subscription executes them. ","","ai.mdx runner metering sentence",r),await E(A(t,"docs/(platform)/caching.mdx")," - see [per-runner request budgets](/runner/install#per-runner-request-budgets)","","caching.mdx runner budgets link",r);let o=A(t,"docs/(platform)/configuration.mdx"),s="| `runner.enabled` |",a=(await bi(o,"utf-8")).split(`
1295
- `).find(d=>d.startsWith(s));if(a===void 0)throw new Error(`${r}: expected the configuration.mdx \`runner.enabled\` row (boilerplate drift).`);await E(o,`${a}
1296
- `,"","configuration.mdx runner config-table row",r)}var tc=new Set(["ci.yml","desktop-release.yml","mobile-release.yml"]),rc=["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"],nc=["packages/auth/src/config.ts","packages/api/src/routes/internal/index.ts","packages/api/src/index.ts"],ic=["packages/api/src/routes/internal/index.ts","packages/api/src/routes/inngest.ts","packages/notifications/src/index.ts","packages/config/src/cache.ts"],sc=["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"],oc=["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/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"],ac=["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"],cc=["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"],lc=[{dir:"apps/mobile/components/billing",prefixes:["paywall","credit-packs","store-"]},{dir:"apps/mobile/tests",prefixes:["purchases-"]}],pc=["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"],dc=[","," {",' 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(`
1297
- `),uc=[["## 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(`
1300
+ $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).`);await c(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",".vue",".mjs",".js",".jsx",".md",".mdx"]),gi=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 c(e,r)}async function yi(e){let t=await Ee(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+=gi)await Promise.all(t.slice(r,r+gi).map(tc))}import{readdir as Qt,readFile as le,rm as E}from"fs/promises";import{join as p}from"path";import{existsSync as rc}from"fs";import{readFile as Mr,rm as T}from"fs/promises";import{join as A}from"path";import{readFile as Ot}from"fs/promises";import{join as xt}from"path";async function bi(e,t){let r=xt(e,"packages/api/src/routes/internal/index.ts");await c(r,K(await Ot(r,"utf-8"),"internal router","runner",t)),await qt(r);let n=xt(e,"packages/api/src/ai/automation-runner.ts");await c(n,K(await Ot(n,"utf-8"),"automation-runner.ts","runner",t));for(let s of["packages/api/src/index.ts","packages/api/src/routes/internal/ai/chat-router.ts","packages/api/src/routes/internal/ai/automations-router.ts","packages/api/src/ai/byok.ts","packages/api/tests/ai/automations.test.ts","packages/api/tests/ai/automations-runs-route.test.ts","packages/api/tests/routes/ai.test.ts","packages/api/tests/ai/summarize-cap.test.ts"]){let a=xt(e,s);await c(a,K(await Ot(a,"utf-8"),s,"runner",t))}let i=xt(e,"packages/api/src/ai/settings-store.ts");await c(i,K(await Ot(i,"utf-8"),"settings-store.ts","runner",t));let o=xt(e,"packages/api/tests/ai/settings-store.test.ts");await c(o,K(await Ot(o,"utf-8"),"settings-store.test.ts","runner",t))}async function Fr(e){if(e.runner)return;let t=e.projectDir,r="stripRunner";await T(A(t,"packages/api/src/relay"),{recursive:!0}),await T(A(t,"packages/api/src/runner"),{recursive:!0}),await T(A(t,"packages/api/src/ai/runner-model.ts")),await T(A(t,"packages/api/src/ai/runner-routing.ts")),await T(A(t,"packages/api/tests/relay"),{recursive:!0}),await T(A(t,"packages/api/tests/runner"),{recursive:!0}),await T(A(t,"packages/api/src/routes/internal/runner.ts")),await T(A(t,"packages/api/src/routes/internal/runner-transport.ts")),await T(A(t,"packages/api/src/routes/internal/runner-limits.ts")),await T(A(t,"packages/api/tests/routes/runner.test.ts")),await T(A(t,"packages/api/tests/routes/runner-transport-harness.ts")),await T(A(t,"packages/api/tests/routes/runner-transport-connect.test.ts")),await T(A(t,"packages/api/tests/routes/runner-transport-events.test.ts")),await T(A(t,"packages/api/tests/ai/automation-coalesce.test.ts")),await T(A(t,"packages/api/tests/ai/automations-lazy-expiry.test.ts")),await T(A(t,"packages/api/tests/ai/runner-model.test.ts")),await T(A(t,"packages/api/tests/unit/runner-offline-routing.test.ts")),await T(A(t,"packages/api/tests/unit/runner-offline-interactive.test.ts")),await T(A(t,"packages/api/tests/unit/runner-unavailable-routing.test.ts")),await T(A(t,"packages/api/tests/unit/runner-unavailable-interactive.test.ts")),await T(A(t,"packages/api/tests/unit/runner-arm-harness.ts")),await T(A(t,"packages/api/tests/ai/runner-chat.test.ts")),await T(A(t,"packages/api/tests/helpers/runner-protocol.ts")),await T(A(t,"packages/api/tests/helpers/runner-frames.ts")),await T(A(t,"packages/api/tests/helpers/relay-runtime-mock.ts"));let n=A(t,"packages/api/package.json"),i=JSON.parse(await Mr(n,"utf-8"));if(!i.exports?.["./runner"])throw new Error(`${r}: expected packages/api/package.json to carry the ./runner export`);delete i.exports["./runner"],await Se(n,i," ",r),await bi(t,r),await si(t,"runner",["/runner"],r,"Runners"),await k(A(t,"docs/(platform)/ai.mdx"),"Runs on a paired [runner](/runner) CLI are never metered either - the user's own subscription executes them. ","","ai.mdx runner metering sentence",r),await k(A(t,"docs/(platform)/caching.mdx")," - see [per-runner request budgets](/runner/install#per-runner-request-budgets)","","caching.mdx runner budgets link",r);let o=A(t,"docs/(platform)/configuration.mdx"),s="| `runner.enabled` |",a=(await Mr(o,"utf-8")).split(`
1301
+ `).find(u=>u.startsWith(s));if(a===void 0)throw new Error(`${r}: expected the configuration.mdx \`runner.enabled\` row (boilerplate drift).`);await k(o,`${a}
1302
+ `,"","configuration.mdx runner config-table row",r);let d=A(t,"docs/desktop/ai/index.mdx");if(rc(d)){let u="| **Runners** | Settings |",w=(await Mr(d,"utf-8")).split(`
1303
+ `).find(y=>y.startsWith(u));if(w===void 0)throw new Error(`${r}: expected the desktop AI index \`Runners\` row (boilerplate drift).`);await k(d,`${w}
1304
+ `,"","desktop AI index Runners row",r)}}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/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(`
1305
+ `),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(`
1298
1306
  `),["#### 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(`
1299
1307
  `),["#### 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(`
1300
- `)],mc=["apps/web/app/[locale]/(marketing)/download","apps/web/tests/routes/download-page.test.tsx"],hc=["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","runner:export","runner:verify","runner:publish"];async function wi(e){let t=p(e.projectDir,".github/workflows"),r=await Qt(t).catch(()=>[]);for(let n of r)tc.has(n)||await S(p(t,n),{recursive:!0,force:!0})}async function fc(e,t){let r=p(e,"package.json"),n=JSON.parse(await le(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 le(r,"utf-8"))?.[1]??" ";await c(r,`${JSON.stringify(n,null,o)}
1301
- `)}async function vi(e){await fc(e.projectDir,[...hc])}async function ki(e){let t=p(e.projectDir,"package.json"),r=await le(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 c(t,`${JSON.stringify(n,null," ")}
1308
+ `)],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","runner:export","runner:verify","runner:publish"];async function wi(e){let t=p(e.projectDir,".github/workflows"),r=await Qt(t).catch(()=>[]);for(let n of r)nc.has(n)||await E(p(t,n),{recursive:!0,force:!0})}async function yc(e,t){let r=p(e,"package.json"),n=JSON.parse(await le(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 le(r,"utf-8"))?.[1]??" ";await c(r,`${JSON.stringify(n,null,o)}
1309
+ `)}async function vi(e){await yc(e.projectDir,[...gc])}async function ki(e){let t=p(e.projectDir,"package.json"),r=await le(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 c(t,`${JSON.stringify(n,null," ")}
1302
1310
  `))}async function Ei(e){let t=p(e.projectDir,"package.json"),r=JSON.parse(await le(t,"utf-8")),n=r.scripts?.test;if(n!=="turbo run test --concurrency=4 && vitest run")throw new Error(`rewriteRootTestScript: expected the root test script to be "turbo run test --concurrency=4 && vitest run", got ${JSON.stringify(n)} (boilerplate drift).`);r.scripts.test="turbo run test --concurrency=4",await c(t,`${JSON.stringify(r,null," ")}
1303
- `)}async function Si(e){e.docs||await S(p(e.projectDir,"apps/docs"),{recursive:!0})}async function Pi(e){let t=p(e.projectDir,"docs/(platform)/meta.json"),r=JSON.parse(await le(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 Se(t,r," ","stripUnusedDocsSilo"),e.desktop||await S(p(e.projectDir,"docs/desktop"),{recursive:!0,force:!0}),e.mobile||await S(p(e.projectDir,"docs/mobile"),{recursive:!0,force:!0}),await gc(e),await wc(e)}async function W(e,t,r,n){await c(e,Y(await le(e,"utf-8"),t,r,n))}async function gc(e){let t=e.projectDir,r="stripUnusedDocsSilo",n=p(t,"docs/(platform)/configuration.mdx"),i=e.desktop,o=e.desktop&&e.ai;e.desktop||(await E(n,"| Desktop app + device sign-in - see [desktop app](/desktop) |","| Desktop app + device sign-in |","configuration.mdx desktop config-table link",r),await W(n,"configuration.mdx desktop TRUSTED_ORIGINS callout","desktop-origins-docs",r),await E(p(t,"docs/cli/init.mdx"),"the [desktop app](/desktop), AI features","the desktop app, AI features","cli init.mdx desktop app link",r),await W(p(t,"docs/(platform)/payments/organizations.mdx"),"payments organizations.mdx desktop tenancy callout","desktop-tenancy-docs",r),await W(p(t,"docs/(platform)/projects.mdx"),"projects.mdx desktop scoping callout","desktop-projects-docs",r),await W(p(t,"docs/(platform)/client-architecture.mdx"),"client-architecture.mdx desktop card","desktop-architecture-docs",r),await W(p(t,"docs/(platform)/testing/e2e.mdx"),"testing/e2e.mdx desktop e2e callout","desktop-testing-docs",r),await E(p(t,"docs/(platform)/index.mdx"),` <Card href="/desktop" title="Desktop app" description="Cross-platform desktop app with device sign-in and AI agents." />
1304
- `,"","index.mdx desktop app card",r),await W(p(t,"docs/(platform)/ai.mdx"),"ai.mdx automation lanes row + section","desktop-lanes-docs",r)),i||(await W(n,"configuration.mdx desktop-AI paragraph","desktop-ai-docs",r),await E(p(t,"docs/(platform)/navigation.mdx"),"gates the desktop app's Chat and Automations, see [desktop AI](/desktop/ai) |","gates the desktop app's Chat and Automations |","navigation.mdx sidebar-flag agents-row link",r)),!o&&e.runner&&(await W(p(t,"docs/(platform)/runner/index.mdx"),"runner index.mdx desktop-setup section","desktop-setup-docs",r),await W(p(t,"docs/(platform)/runner/terminal.mdx"),"runner terminal.mdx desktop-panel section","desktop-terminal-docs",r))}async function Ai(e){if(e.desktop)return;await S(p(e.projectDir,"apps/desktop"),{recursive:!0});let t=p(e.projectDir,"packages/i18n/translations");for(let i of await Qt(t,{withFileTypes:!0}))i.isDirectory()&&await S(p(t,i.name,"desktop.json"),{force:!0});await S(p(e.projectDir,".github/workflows/desktop-release.yml"));for(let i of mc)await S(p(e.projectDir,i),{recursive:!0});await S(p(e.projectDir,"packages/utils/src/desktop-download.ts")),await S(p(e.projectDir,"packages/utils/tests/desktop-download.test.ts"));let r=p(e.projectDir,"packages/utils/package.json"),n=JSON.parse(await le(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 Se(r,n," ","stripDesktopApp")}function yc(e){return e.desktop}async function Ii(e){yc(e)||await S(p(e.projectDir,"packages/agent-core"),{recursive:!0})}async function bc(e,t,r,n){let i=await Qt(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 S(p(e,a),{recursive:!0})}}async function Zt(e,t,r,n){await c(e,Y(await le(e,"utf-8"),t,r,n))}async function wc(e){let t=e.projectDir,r="stripUnusedDocsSilo",n=e.mobile&&e.mobilePurchases==="revenuecat";e.mobile||(await E(p(t,"docs/(platform)/index.mdx"),` <Card href="/mobile" title="Mobile app" description="Cross-platform iOS and Android app with push, universal links, and store billing." />
1305
- `,"","index.mdx mobile app card",r),await E(p(t,"docs/(platform)/configuration.mdx")," - see [mobile app](/mobile)","","configuration.mdx mobile config-table link",r),await E(p(t,"docs/(platform)/client-architecture.mdx"),` <Card href="/mobile" title="Mobile app">The Expo app - the third surface this client core serves.</Card>
1306
- `,"","client-architecture.mdx mobile app card",r),await E(p(t,"docs/cli/init.mdx"),"The [mobile app](/mobile) (`apps/mobile`, built with Expo)","The mobile app (`apps/mobile`, built with Expo)","cli init.mdx mobile app link",r),await E(p(t,"docs/(platform)/notifications.mdx"),"- **On a phone too.** With the [mobile app](/mobile) shipped and `config.mobile.push.enabled` on, the same notification is delivered to the user's registered devices as a push - see [mobile notifications](/mobile/notifications).\n\n","","notifications.mdx mobile push bullet",r),await E(p(t,"docs/(platform)/authentication/social-oauth.mdx")," - the native flow adds `APPLE_APP_BUNDLE_IDENTIFIER`, see [mobile auth](/mobile/auth) |"," |","social-oauth.mdx Apple native-flow tail",r),await E(p(t,"docs/(platform)/authentication/two-factor-and-passkeys.mdx"),"- **On the [mobile app](/mobile/auth)**, passkeys use the platform's own biometrics and are claimed by the same `.well-known` association files. The app's biometric **App lock** is a separate device gate, never a second factor.\n\n","","two-factor-and-passkeys.mdx mobile passkeys bullet",r),await E(p(t,"docs/(platform)/project-structure.mdx"),"the web, desktop and mobile apps","the web and desktop apps","project-structure.mdx surface list",r),await W(p(t,"docs/(platform)/testing/e2e.mdx"),"testing e2e.mdx mobile Maestro section","mobile-testing-docs",r),await W(p(t,"docs/(platform)/environment-variables/index.mdx"),"environment-variables mobile section","mobile-env-docs",r)),n||(await E(p(t,"docs/(platform)/payments/meta.json"),', "mobile-billing"',"","payments meta.json mobile-billing entry",r),await E(p(t,"docs/(platform)/payments/index.mdx"),` <Card href="/payments/mobile-billing" title="Mobile store billing" description="In-app purchases through RevenueCat, additive to your web provider." />
1307
- `,"","payments index.mdx mobile store billing card",r),await S(p(t,"docs/(platform)/payments/mobile-billing.mdx"))),e.mobile&&!n&&(await E(p(t,"docs/mobile/meta.json"),', "billing"',"","mobile meta.json billing entry",r),await E(p(t,"docs/mobile/index.mdx"),` <Card href="/mobile/billing" title="Billing" description="Store purchases through RevenueCat, and the web-billing shape." />
1308
- `,"","mobile index.mdx billing card",r),await W(p(t,"docs/mobile/index.mdx"),"mobile index.mdx store-purchases block","mobile-purchases-docs",r),await S(p(t,"docs/mobile/billing"),{recursive:!0,force:!0}))}async function Ri(e){if(e.mobile)return;await S(p(e.projectDir,"apps/mobile"),{recursive:!0});let t=p(e.projectDir,"packages/i18n/translations");for(let i of await Qt(t,{withFileTypes:!0}))i.isDirectory()&&await S(p(t,i.name,"mobile.json"),{force:!0});await S(p(e.projectDir,"packages/i18n/tests/mobile-notification-labels.test.ts")),await S(p(e.projectDir,"packages/i18n/tests/mobile-brand-literals.test.ts")),await S(p(e.projectDir,"packages/auth/tests/expo-plugin.test.ts")),await S(p(e.projectDir,"packages/auth/tests/expo-authorization-allowlist.test.ts")),await S(p(e.projectDir,"packages/auth/src/expo-authorization-allowlist.ts")),await S(p(e.projectDir,".github/workflows/mobile-release.yml")),await S(p(e.projectDir,"tooling/styles/scripts/build-mobile-css.ts"));let r=p(e.projectDir,"tooling/styles/package.json"),n=JSON.parse(await le(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 Se(r,n," ","stripMobileApp");for(let i of rc)await at(p(e.projectDir,i),p(e.projectDir,"apps/web"));await S(p(e.projectDir,"packages/api/src/routes/internal/well-known.ts")),await S(p(e.projectDir,"packages/api/tests/routes/well-known-mobile.test.ts")),await S(p(e.projectDir,"packages/api/src/routes/internal/mobile-auth.ts")),await S(p(e.projectDir,"packages/api/tests/routes/mobile-auth.test.ts")),await S(p(e.projectDir,"apps/web/public/images/stores"),{recursive:!0});for(let i of nc)await Zt(p(e.projectDir,i),i,"mobile-auth","stripMobileApp");for(let i of ic)await Zt(p(e.projectDir,i),i,"mobile-push","stripMobileApp");for(let i of sc)await S(p(e.projectDir,i),{recursive:!0})}async function Ti(e){if(e.mobile&&e.mobilePurchases==="revenuecat")return;for(let n of oc)await S(p(e.projectDir,n),{recursive:!0});let t=p(e.projectDir,"packages/payments/package.json"),r=JSON.parse(await le(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 Se(t,r," ","stripMobilePurchases");for(let n of ac)await Zt(p(e.projectDir,n),n,"mobile-purchases","stripMobilePurchases");if(e.mobile){for(let n of cc)await S(p(e.projectDir,n),{recursive:!0});for(let{dir:n,prefixes:i}of lc)await bc(p(e.projectDir,n),i,n,"stripMobilePurchases");for(let n of pc)await Zt(p(e.projectDir,n),n,"mobile-purchases","stripMobilePurchases");for(let n of uc)await E(p(e.projectDir,"apps/mobile/e2e/README.md"),n,"","e2e README purchases row block","stripMobilePurchases");await E(p(e.projectDir,"apps/mobile/e2e/tags.ts"),dc,`
1309
- `,"e2e tags.ts purchases inventory entries","stripMobilePurchases")}}import{readFile as vc}from"fs/promises";import{join as kc}from"path";var _i=`on:
1311
+ `)}async function Si(e){e.docs||await E(p(e.projectDir,"apps/docs"),{recursive:!0})}async function Pi(e){let t=p(e.projectDir,"docs/(platform)/meta.json"),r=JSON.parse(await le(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 Se(t,r," ","stripUnusedDocsSilo"),e.desktop||await E(p(e.projectDir,"docs/desktop"),{recursive:!0,force:!0}),e.mobile||await E(p(e.projectDir,"docs/mobile"),{recursive:!0,force:!0}),await bc(e),await kc(e)}async function H(e,t,r,n){await c(e,K(await le(e,"utf-8"),t,r,n))}async function bc(e){let t=e.projectDir,r="stripUnusedDocsSilo",n=p(t,"docs/(platform)/configuration.mdx"),i=e.desktop,o=e.desktop&&e.ai;e.desktop||(await k(n,"| Desktop app + device sign-in - see [desktop app](/desktop) |","| Desktop app + device sign-in |","configuration.mdx desktop config-table link",r),await H(n,"configuration.mdx desktop TRUSTED_ORIGINS callout","desktop-origins-docs",r),await k(p(t,"docs/cli/init.mdx"),"the [desktop app](/desktop), AI features","the desktop app, AI features","cli init.mdx desktop app link",r),await H(p(t,"docs/(platform)/payments/organizations.mdx"),"payments organizations.mdx desktop tenancy callout","desktop-tenancy-docs",r),await H(p(t,"docs/(platform)/projects.mdx"),"projects.mdx desktop scoping callout","desktop-projects-docs",r),await H(p(t,"docs/(platform)/client-architecture.mdx"),"client-architecture.mdx desktop card","desktop-architecture-docs",r),await H(p(t,"docs/(platform)/screens.mdx"),"screens.mdx desktop halves","screens-desktop-docs",r),await H(p(t,"docs/(platform)/testing/e2e.mdx"),"testing/e2e.mdx desktop e2e callout","desktop-testing-docs",r),await k(p(t,"docs/(platform)/index.mdx"),` <Card href="/desktop" title="Desktop app" description="Cross-platform desktop app with device sign-in and AI agents." />
1312
+ `,"","index.mdx desktop app card",r),await H(p(t,"docs/(platform)/ai.mdx"),"ai.mdx automation lanes row + section","desktop-lanes-docs",r)),i||(await H(n,"configuration.mdx desktop-AI paragraph","desktop-ai-docs",r),await k(p(t,"docs/(platform)/navigation.mdx"),"gates the desktop app's Chat and Automations, see [desktop AI](/desktop/ai) |","gates the desktop app's Chat and Automations |","navigation.mdx sidebar-flag agents-row link",r)),!o&&e.runner&&(await H(p(t,"docs/(platform)/runner/index.mdx"),"runner index.mdx desktop-setup section","desktop-setup-docs",r),await H(p(t,"docs/(platform)/runner/terminal.mdx"),"runner terminal.mdx desktop-panel section","desktop-terminal-docs",r))}async function Ai(e){if(e.desktop)return;await E(p(e.projectDir,"apps/desktop"),{recursive:!0});let t=p(e.projectDir,"packages/i18n/translations");for(let i of await Qt(t,{withFileTypes:!0}))i.isDirectory()&&await E(p(t,i.name,"desktop.json"),{force:!0});await E(p(e.projectDir,".github/workflows/desktop-release.yml"));for(let i of fc)await E(p(e.projectDir,i),{recursive:!0});await E(p(e.projectDir,"packages/utils/src/desktop-download.ts")),await E(p(e.projectDir,"packages/utils/tests/desktop-download.test.ts"));let r=p(e.projectDir,"packages/utils/package.json"),n=JSON.parse(await le(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 Se(r,n," ","stripDesktopApp")}function wc(e){return e.desktop}async function Ii(e){wc(e)||await E(p(e.projectDir,"packages/agent-core"),{recursive:!0})}async function vc(e,t,r,n){let i=await Qt(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 E(p(e,a),{recursive:!0})}}async function Zt(e,t,r,n){await c(e,K(await le(e,"utf-8"),t,r,n))}async function kc(e){let t=e.projectDir,r="stripUnusedDocsSilo",n=e.mobile&&e.mobilePurchases==="revenuecat";e.mobile||(await k(p(t,"docs/(platform)/index.mdx"),` <Card href="/mobile" title="Mobile app" description="Cross-platform iOS and Android app with push, universal links, and store billing." />
1313
+ `,"","index.mdx mobile app card",r),await k(p(t,"docs/(platform)/configuration.mdx")," - see [mobile app](/mobile)","","configuration.mdx mobile config-table link",r),await k(p(t,"docs/(platform)/client-architecture.mdx"),` <Card href="/mobile" title="Mobile app">The Expo app - the third surface this client core serves.</Card>
1314
+ `,"","client-architecture.mdx mobile app card",r),await k(p(t,"docs/cli/init.mdx"),"The [mobile app](/mobile) (`apps/mobile`, built with Expo)","The mobile app (`apps/mobile`, built with Expo)","cli init.mdx mobile app link",r),await k(p(t,"docs/(platform)/notifications.mdx"),"- **On a phone too.** With the [mobile app](/mobile) shipped and `config.mobile.push.enabled` on, the same notification is delivered to the user's registered devices as a push - see [mobile notifications](/mobile/notifications).\n\n","","notifications.mdx mobile push bullet",r),await k(p(t,"docs/(platform)/authentication/social-oauth.mdx")," - the native flow adds `APPLE_APP_BUNDLE_IDENTIFIER`, see [mobile auth](/mobile/auth) |"," |","social-oauth.mdx Apple native-flow tail",r),await k(p(t,"docs/(platform)/authentication/two-factor-and-passkeys.mdx"),"- **On the [mobile app](/mobile/auth)**, passkeys use the platform's own biometrics and are claimed by the same `.well-known` association files. The app's biometric **App lock** is a separate device gate, never a second factor.\n\n","","two-factor-and-passkeys.mdx mobile passkeys bullet",r),await k(p(t,"docs/(platform)/project-structure.mdx"),"the web, desktop and mobile apps","the web and desktop apps","project-structure.mdx surface list",r),await H(p(t,"docs/(platform)/testing/e2e.mdx"),"testing e2e.mdx mobile Maestro section","mobile-testing-docs",r),await H(p(t,"docs/(platform)/environment-variables/index.mdx"),"environment-variables mobile section","mobile-env-docs",r)),n||(await k(p(t,"docs/(platform)/payments/meta.json"),', "mobile-billing"',"","payments meta.json mobile-billing entry",r),await k(p(t,"docs/(platform)/payments/index.mdx"),` <Card href="/payments/mobile-billing" title="Mobile store billing" description="In-app purchases through RevenueCat, additive to your web provider." />
1315
+ `,"","payments index.mdx mobile store billing card",r),await E(p(t,"docs/(platform)/payments/mobile-billing.mdx"))),e.mobile&&!n&&(await k(p(t,"docs/mobile/meta.json"),', "billing"',"","mobile meta.json billing entry",r),await k(p(t,"docs/mobile/index.mdx"),` <Card href="/mobile/billing" title="Billing" description="Store purchases through RevenueCat, and the web-billing shape." />
1316
+ `,"","mobile index.mdx billing card",r),await H(p(t,"docs/mobile/index.mdx"),"mobile index.mdx store-purchases block","mobile-purchases-docs",r),await E(p(t,"docs/mobile/billing"),{recursive:!0,force:!0}))}async function Ri(e){if(e.mobile)return;await E(p(e.projectDir,"apps/mobile"),{recursive:!0});let t=p(e.projectDir,"packages/i18n/translations");for(let i of await Qt(t,{withFileTypes:!0}))i.isDirectory()&&await E(p(t,i.name,"mobile.json"),{force:!0});await E(p(e.projectDir,"packages/i18n/tests/mobile-notification-labels.test.ts")),await E(p(e.projectDir,"packages/i18n/tests/mobile-brand-literals.test.ts")),await E(p(e.projectDir,"packages/i18n/tests/mobile-shared-merge.test.ts")),await E(p(e.projectDir,"packages/auth/tests/expo-plugin.test.ts")),await E(p(e.projectDir,"packages/auth/tests/expo-authorization-allowlist.test.ts")),await E(p(e.projectDir,"packages/auth/src/expo-authorization-allowlist.ts")),await E(p(e.projectDir,".github/workflows/mobile-release.yml")),await E(p(e.projectDir,"tooling/styles/scripts/build-mobile-css.ts"));let r=p(e.projectDir,"tooling/styles/package.json"),n=JSON.parse(await le(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 Se(r,n," ","stripMobileApp");for(let i of ic)await lt(p(e.projectDir,i),p(e.projectDir,"apps/web"));await E(p(e.projectDir,"packages/api/src/routes/internal/well-known.ts")),await E(p(e.projectDir,"packages/api/tests/routes/well-known-mobile.test.ts")),await E(p(e.projectDir,"packages/api/src/routes/internal/mobile-auth.ts")),await E(p(e.projectDir,"packages/api/tests/routes/mobile-auth.test.ts")),await E(p(e.projectDir,"apps/web/public/images/stores"),{recursive:!0});for(let i of sc)await Zt(p(e.projectDir,i),i,"mobile-auth","stripMobileApp");for(let i of oc)await Zt(p(e.projectDir,i),i,"mobile-push","stripMobileApp");for(let i of ac)await E(p(e.projectDir,i),{recursive:!0})}async function Ti(e){if(e.mobile&&e.mobilePurchases==="revenuecat")return;for(let n of cc)await E(p(e.projectDir,n),{recursive:!0});let t=p(e.projectDir,"packages/payments/package.json"),r=JSON.parse(await le(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 Se(t,r," ","stripMobilePurchases");for(let n of lc)await Zt(p(e.projectDir,n),n,"mobile-purchases","stripMobilePurchases");if(e.mobile){for(let n of pc)await E(p(e.projectDir,n),{recursive:!0});for(let{dir:n,prefixes:i}of dc)await vc(p(e.projectDir,n),i,n,"stripMobilePurchases");for(let n of uc)await Zt(p(e.projectDir,n),n,"mobile-purchases","stripMobilePurchases");for(let n of hc)await k(p(e.projectDir,"apps/mobile/e2e/README.md"),n,"","e2e README purchases row block","stripMobilePurchases");await k(p(e.projectDir,"apps/mobile/e2e/tags.ts"),mc,`
1317
+ `,"e2e tags.ts purchases inventory entries","stripMobilePurchases")}}import{readFile as Ec}from"fs/promises";import{join as Sc}from"path";var _i=`on:
1310
1318
  workflow_run:
1311
1319
  workflows: ["Tag Release"]
1312
1320
  branches: [main]
1313
1321
  types: [completed]
1314
- workflow_dispatch:`,Ec=`on:
1315
- workflow_dispatch:`;async function Oi(e){if(!e.desktop)return;let t=kc(e.projectDir,".github/workflows/desktop-release.yml"),r=await vc(t,"utf8");if(!r.includes(_i))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 c(t,r.replace(_i,Ec))}import{readFile as Sc}from"fs/promises";import{join as Pc}from"path";var xi=`on:
1322
+ workflow_dispatch:`,Pc=`on:
1323
+ workflow_dispatch:`;async function Oi(e){if(!e.desktop)return;let t=Sc(e.projectDir,".github/workflows/desktop-release.yml"),r=await Ec(t,"utf8");if(!r.includes(_i))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 c(t,r.replace(_i,Pc))}import{readFile as Ac}from"fs/promises";import{join as Ic}from"path";var xi=`on:
1316
1324
  workflow_run:
1317
1325
  workflows: ["Tag Release"]
1318
1326
  branches: [main]
1319
1327
  types: [completed]
1320
- workflow_dispatch:`,Ac=`on:
1321
- workflow_dispatch:`;async function Di(e){if(!e.mobile)return;let t=Pc(e.projectDir,".github/workflows/mobile-release.yml"),r=await Sc(t,"utf8");if(!r.includes(xi))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 c(t,r.replace(xi,Ac))}import{join as Ic}from"path";async function Li(e){let t=Rc(e);await c(Ic(e.projectDir,".github/workflows/ci.yml"),t)}function Ni(e){return e.databaseProvider!=="neon"&&e.cacheProvider!=="upstash"}function Ci(e,t,r){return` - uses: actions/upload-artifact@v4
1328
+ workflow_dispatch:`,Rc=`on:
1329
+ workflow_dispatch:`;async function Di(e){if(!e.mobile)return;let t=Ic(e.projectDir,".github/workflows/mobile-release.yml"),r=await Ac(t,"utf8");if(!r.includes(xi))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 c(t,r.replace(xi,Rc))}import{join as Tc}from"path";async function Li(e){let t=_c(e);await c(Tc(e.projectDir,".github/workflows/ci.yml"),t)}function Ni(e){return e.databaseProvider!=="neon"&&e.cacheProvider!=="upstash"}function Ci(e,t,r){return` - uses: actions/upload-artifact@v4
1322
1330
  if: \${{ ${r} }}
1323
1331
  with:
1324
1332
  name: playwright-report-${e}
@@ -1327,7 +1335,7 @@ $1`),n===r){if(r.includes("UPSTASH_REDIS_REST_URL"))return;throw new Error(`prun
1327
1335
  ${t}/test-results
1328
1336
  if-no-files-found: ignore
1329
1337
  retention-days: 7
1330
- `}function Rc(e){let t=e.cacheProvider==="upstash",r=t?"":` redis:
1338
+ `}function _c(e){let t=e.cacheProvider==="upstash",r=t?"":` redis:
1331
1339
  image: redis:8-alpine
1332
1340
  ports:
1333
1341
  - 6379:6379
@@ -1440,7 +1448,7 @@ ${a}
1440
1448
  env:
1441
1449
  NODE_OPTIONS: --max-old-space-size=6144
1442
1450
 
1443
- ${Ci("desktop","apps/desktop","failure()")}`:"",b=e.databaseProvider==="neon"?`
1451
+ ${Ci("desktop","apps/desktop","failure()")}`:"",y=e.databaseProvider==="neon"?`
1444
1452
  # Required for neon: the api suite's embedded Postgres is TCP-only and the neon
1445
1453
  # websocket driver cannot reach it. Add this repository secret (any Postgres this
1446
1454
  # suite may CREATE DATABASE on - a Neon branch works).
@@ -1485,7 +1493,7 @@ jobs:
1485
1493
  # "cancelled", which reads as a mystery rather than as a timeout. 40 is roughly double that.
1486
1494
  timeout-minutes: 40
1487
1495
  ${n} env:
1488
- CONTENT_API_KEY: test-contentapi-key-16chars${b}${P}${I}
1496
+ CONTENT_API_KEY: test-contentapi-key-16chars${y}${P}${I}
1489
1497
  STORAGE_REGION: test
1490
1498
  STORAGE_ENDPOINT: http://test
1491
1499
  STORAGE_ACCESS_KEY_ID: test
@@ -1501,22 +1509,22 @@ ${n} env:
1501
1509
  - run: pnpm check-types
1502
1510
 
1503
1511
  - run: pnpm test
1504
- ${d}${w}`}import{readFile as $i}from"fs/promises";import{existsSync as Tc}from"fs";import{join as Mr}from"path";var ji="@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 Oc(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 xc(e,t,r){let n=await $i(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(ji)||(i.scripts={...i.scripts,[t]:`${r} && ${o}`},await c(e,`${JSON.stringify(i,null," ")}
1505
- `))}async function Dc(e,t){let r=Tc(e)?JSON.parse(await $i(e,"utf-8")):{$schema:"https://openapi.vercel.sh/vercel.json"},n=r.buildCommand?.trim()||"pnpm build";n.includes(ji)||(r.buildCommand=`${t} && ${n}`,await c(e,`${JSON.stringify(r,null," ")}
1506
- `))}async function Ui(e){let t=_c(e.demo===!0),r=Oc(e.architecture),n=Mr(e.projectDir,"apps",r);switch(e.deploymentTarget){case"node":await xc(Mr(n,"package.json"),"start",t);return;case"vercel":await Dc(Mr(n,"vercel.json"),t);return;default:{let i=e.deploymentTarget;throw new Error(`generateDeployScripts: unhandled deployment target "${String(i)}"`)}}}import{readFile as Nc}from"fs/promises";import{existsSync as Cc}from"fs";import{join as er}from"path";var Mi=["stripe","polar"],Lc=[...Mi,"none"];async function Fi(e){let t=er(e.projectDir,"packages/payments/src"),r=e.paymentProvider,i=`// Active payment provider. To switch, change the path below to
1507
- // ${Lc.filter(o=>o!==r).map(o=>`"./${o}/index"`).join(" or ")} (other folders are kept in place).
1512
+ ${d}${w}`}import{readFile as $i}from"fs/promises";import{existsSync as Oc}from"fs";import{join as Vr}from"path";var ji="@repo/database";function xc(e){return e?"pnpm -F @repo/database reset && pnpm -F @repo/database run deploy -- --push":"pnpm -F @repo/database run deploy"}function Dc(e){switch(e){case"fullstack":return"web";case"separate":return"backend";default:{let t=e;throw new Error(`schemaOwnerApp: unhandled architecture "${String(t)}"`)}}}async function Nc(e,t,r){let n=await $i(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(ji)||(i.scripts={...i.scripts,[t]:`${r} && ${o}`},await c(e,`${JSON.stringify(i,null," ")}
1513
+ `))}async function Cc(e,t){let r=Oc(e)?JSON.parse(await $i(e,"utf-8")):{$schema:"https://openapi.vercel.sh/vercel.json"},n=r.buildCommand?.trim()||"pnpm build";n.includes(ji)||(r.buildCommand=`${t} && ${n}`,await c(e,`${JSON.stringify(r,null," ")}
1514
+ `))}async function Ui(e){let t=xc(e.demo===!0),r=Dc(e.architecture),n=Vr(e.projectDir,"apps",r);switch(e.deploymentTarget){case"node":await Nc(Vr(n,"package.json"),"start",t);return;case"vercel":await Cc(Vr(n,"vercel.json"),t);return;default:{let i=e.deploymentTarget;throw new Error(`generateDeployScripts: unhandled deployment target "${String(i)}"`)}}}import{readFile as Lc}from"fs/promises";import{existsSync as $c}from"fs";import{join as er}from"path";var Mi=["stripe","polar"],jc=[...Mi,"none"];async function Fi(e){let t=er(e.projectDir,"packages/payments/src"),r=e.paymentProvider,i=`// Active payment provider. To switch, change the path below to
1515
+ // ${jc.filter(o=>o!==r).map(o=>`"./${o}/index"`).join(" or ")} (other folders are kept in place).
1508
1516
  export { ops } from "./${r}/index";
1509
- `;await c(er(t,"providers/index.ts"),i),await c(er(t,"index.ts"),await $c(t,r))}async function $c(e,t){let r=er(e,"index.ts");if(!Cc(r))throw new Error(`generatePaymentBarrel: expected ${r} to exist - did packages/payments move?`);let n=await Nc(r,"utf-8"),i=Mi.filter(s=>s!==t);return n.split(`
1517
+ `;await c(er(t,"providers/index.ts"),i),await c(er(t,"index.ts"),await Uc(t,r))}async function Uc(e,t){let r=er(e,"index.ts");if(!$c(r))throw new Error(`generatePaymentBarrel: expected ${r} to exist - did packages/payments move?`);let n=await Lc(r,"utf-8"),i=Mi.filter(s=>s!==t);return n.split(`
1510
1518
  `).filter(s=>!i.some(a=>s.includes(`./providers/${a}/`))).join(`
1511
- `)}import{access as jc,readFile as nr,rm as tr}from"fs/promises";import{join as te}from"path";var Hi=["sentry","posthog"],Fr={sentry:"src/providers/sentry",posthog:"src/providers/posthog"},rr={sentry:["tests/sentry-load-guard.test.ts"],posthog:["tests/posthog-load-guard.test.ts","tests/llm-analytics.test.ts"]},Uc=["tests/resolution.test.ts","tests/export-isolation.test.ts"],Mc=["src/providers/sentry/desktop-main.ts","src/providers/sentry/desktop-renderer.ts","src/resolve-desktop-main.ts","src/resolve-desktop-renderer.ts"],Fc=["./desktop-main","./desktop-renderer"],Vc=[`vi.mock("@sentry/electron/main", sdk.factories["@sentry/electron/main"]);
1519
+ `)}import{access as Mc,readFile as nr,rm as tr}from"fs/promises";import{join as te}from"path";var Hi=["sentry","posthog"],Br={sentry:"src/providers/sentry",posthog:"src/providers/posthog"},rr={sentry:["tests/sentry-load-guard.test.ts"],posthog:["tests/posthog-load-guard.test.ts","tests/llm-analytics.test.ts"]},Fc=["tests/resolution.test.ts","tests/export-isolation.test.ts"],Vc=["src/providers/sentry/desktop-main.ts","src/providers/sentry/desktop-renderer.ts","src/resolve-desktop-main.ts","src/resolve-desktop-renderer.ts"],Bc=["./desktop-main","./desktop-renderer"],Gc=[`vi.mock("@sentry/electron/main", sdk.factories["@sentry/electron/main"]);
1512
1520
  `,`vi.mock("@sentry/electron/renderer", sdk.factories["@sentry/electron/renderer"]);
1513
- `],Bc=[' describeGate("desktop main", "electronMain", async () => {',' describeGate("desktop renderer", "electronRenderer", async () => {',' describe("the desktop main init options", () => {',' describe("the desktop renderer init", () => {'],Vi=`
1521
+ `],Kc=[' describeGate("desktop main", "electronMain", async () => {',' describeGate("desktop renderer", "electronRenderer", async () => {',' describe("the desktop main init options", () => {',' describe("the desktop renderer init", () => {'],Vi=`
1514
1522
  });
1515
- `,Gc=" ";async function Yi(e){let t=te(e.projectDir,"packages/observability");await Bi(t,"packages/observability");let r=e.observability,n=r.filter(s=>!K.includes(s));if(n.length>0)throw new Error(`observability names ${JSON.stringify(n)}, which is not a reporting provider. Every entry must be one of: ${K.join(", ")}. Shaping stops here so the project is not left half-stripped.`);for(let s of r)await Bi(te(t,Fr[s]),`packages/observability/${Fr[s]}`);let i=e.desktop?[...Ki,...Ll]:Ki,o=new Map;for(let s of i)o.set(s.file,await nr(te(t,s.file),"utf-8"));for(let s of Qc(r,e.desktop))await el(t,s);for(let s of Hi)if(!r.includes(s)){await tr(te(t,Fr[s]),{recursive:!0,force:!0});for(let a of rr[s])await tr(te(t,a),{force:!0})}for(let s of Uc)await tr(te(t,s),{force:!0});e.desktop||await Kc(t,r);for(let s of i){let a=o.get(s.file);a!==void 0&&await c(te(t,s.file),Wc(a,s,r))}}async function Bi(e,t){try{await jc(e)}catch{throw new Error(`generateObservabilityProvider: expected ${t} to exist - did the observability package move?`)}}async function Kc(e,t){for(let i of Mc)await tr(te(e,i),{force:!0});t.includes("sentry")&&await Hc(e);let r=te(e,"package.json"),n=JSON.parse(await nr(r,"utf-8"));for(let i of Fc){if(!n.exports?.[i])throw new Error(`generateObservabilityProvider: expected packages/observability/package.json to carry the ${i} export`);delete n.exports[i]}await Se(r,n," ","generateObservabilityProvider")}async function Hc(e){let t=te(e,rr.sentry[0]),r=await nr(t,"utf-8");r=Vr(r,Vc.map(n=>({find:n,replace:""})),rr.sentry[0]);for(let n of Bc)r=Yc(r,n,rr.sentry[0]);await c(t,r)}function Yc(e,t,r){let n=e.indexOf(t),i=n===-1?-1:e.indexOf(Vi,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(`
1516
- `).find(a=>a.trim().length>0&&!a.startsWith(`${Gc} `));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+Vi.length;return e[s]===`
1517
- `&&(s+=1),e.slice(0,n)+e.slice(s)}function Wc(e,t,r){let n=Hi.filter(s=>!r.includes(s)),i=e,o=[];for(let s of n){let a=zc(i,s);i=a.source,o.push(...a.bindings)}t.dualMode!==!1&&(i=Vr(i,[{find:Jc,replace:Xc(r)}],t.file)),i=Vr(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 Vr(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(`
1523
+ `,Hc=" ";async function Yi(e){let t=te(e.projectDir,"packages/observability");await Bi(t,"packages/observability");let r=e.observability,n=r.filter(s=>!Y.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: ${Y.join(", ")}. Shaping stops here so the project is not left half-stripped.`);for(let s of r)await Bi(te(t,Br[s]),`packages/observability/${Br[s]}`);let i=e.desktop?[...Ki,...jl]:Ki,o=new Map;for(let s of i)o.set(s.file,await nr(te(t,s.file),"utf-8"));for(let s of tl(r,e.desktop))await rl(t,s);for(let s of Hi)if(!r.includes(s)){await tr(te(t,Br[s]),{recursive:!0,force:!0});for(let a of rr[s])await tr(te(t,a),{force:!0})}for(let s of Fc)await tr(te(t,s),{force:!0});e.desktop||await Yc(t,r);for(let s of i){let a=o.get(s.file);a!==void 0&&await c(te(t,s.file),qc(a,s,r))}}async function Bi(e,t){try{await Mc(e)}catch{throw new Error(`generateObservabilityProvider: expected ${t} to exist - did the observability package move?`)}}async function Yc(e,t){for(let i of Vc)await tr(te(e,i),{force:!0});t.includes("sentry")&&await Wc(e);let r=te(e,"package.json"),n=JSON.parse(await nr(r,"utf-8"));for(let i of Bc){if(!n.exports?.[i])throw new Error(`generateObservabilityProvider: expected packages/observability/package.json to carry the ${i} export`);delete n.exports[i]}await Se(r,n," ","generateObservabilityProvider")}async function Wc(e){let t=te(e,rr.sentry[0]),r=await nr(t,"utf-8");r=Gr(r,Gc.map(n=>({find:n,replace:""})),rr.sentry[0]);for(let n of Kc)r=zc(r,n,rr.sentry[0]);await c(t,r)}function zc(e,t,r){let n=e.indexOf(t),i=n===-1?-1:e.indexOf(Vi,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(`
1524
+ `).find(a=>a.trim().length>0&&!a.startsWith(`${Hc} `));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+Vi.length;return e[s]===`
1525
+ `&&(s+=1),e.slice(0,n)+e.slice(s)}function qc(e,t,r){let n=Hi.filter(s=>!r.includes(s)),i=e,o=[];for(let s of n){let a=Jc(i,s);i=a.source,o.push(...a.bindings)}t.dualMode!==!1&&(i=Gr(i,[{find:Zc,replace:Qc(r)}],t.file)),i=Gr(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 Gr(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(`
1518
1526
  `)[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(`
1519
- `)[0]}`);n=i.all===!0?n.replaceAll(i.find,i.replace):n.replace(i.find,i.replace)}return n}function zc(e,t){let r=new RegExp(String.raw`^import[^;]*?from "\./providers/${t}/[^"]*";\n`,"gm"),n=[];return{source:e.replace(r,o=>(n.push(...qc(o)),"")),bindings:n}}function qc(e){let t=/^import\s+(?:type\s+)?(\S(?:[\s\S]*?\S)?)\s+from\s/.exec(e)?.[1]??"",r=[],n=/\{([\s\S]*?)\}/.exec(t);n?.[1]&&r.push(...n[1].split(",").map(s=>s.trim().replace(/^type\s+/,"")).map(s=>s.split(/\s+as\s+/).at(-1)??"").filter(s=>s.length>0));let i=t.replace(/\{[\s\S]*?\}/,"").replace(/,/g," ").trim(),o=/^\*\s+as\s+([A-Za-z_$][\w$]*)$/.exec(i);return o?.[1]?r.push(o[1]):/^[A-Z_$][\w$]*$/i.test(i)&&r.push(i),r}var Jc=" * DUAL-MODE, exactly as `packages/payments/src/providers/index.ts` does it. This repo resolves the\n * provider at RUNTIME so dev and the test suite exercise every one of them. A generated project has\n * exactly one provider, so the CLI overwrites this file with a direct re-export of it and the rest\n * become unreachable and are pruned; the generator is the observability twin of\n * `packages/cli/src/generators/payment-barrel.ts` and lands with the manifest option.";function Xc(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
1527
+ `)[0]}`);n=i.all===!0?n.replaceAll(i.find,i.replace):n.replace(i.find,i.replace)}return n}function Jc(e,t){let r=new RegExp(String.raw`^import[^;]*?from "\./providers/${t}/[^"]*";\n`,"gm"),n=[];return{source:e.replace(r,o=>(n.push(...Xc(o)),"")),bindings:n}}function Xc(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 Zc=" * 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 Qc(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
1520
1528
  * 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
1521
1529
  * there is nothing here for a bundler to fold away and nothing for pnpm to install.`}
1522
1530
  *
@@ -1524,28 +1532,28 @@ export { ops } from "./${r}/index";
1524
1532
  * run \`generatesaas update\`: re-shaping brings that provider's adapter and its dependency back. The
1525
1533
  * update stages nothing while you are already on the latest version, so the switch lands with the
1526
1534
  * next release. Pasting the other provider's credential into \`config.observability\` on its own
1527
- * cannot: the adapter it would need is not here.`}var Gi={source:"src/providers/sentry/browser.ts",name:"SentryBrowserInitOptions",fields:["environment: string;"]},Zc={source:"src/providers/sentry/desktop-main.ts",name:"SentryDesktopMainInitOptions",fields:["environment: string;","appIsReady: boolean;"]};function Qc(e,t){return e.includes("sentry")?[]:t?[Gi,Zc]:[Gi]}async function el(e,t){let r=await nr(te(e,t.source),"utf-8"),n=`export interface ${t.name} {
1535
+ * cannot: the adapter it would need is not here.`}var Gi={source:"src/providers/sentry/browser.ts",name:"SentryBrowserInitOptions",fields:["environment: string;"]},el={source:"src/providers/sentry/desktop-main.ts",name:"SentryDesktopMainInitOptions",fields:["environment: string;","appIsReady: boolean;"]};function tl(e,t){return e.includes("sentry")?[]:t?[Gi,el]:[Gi]}async function rl(e,t){let r=await nr(te(e,t.source),"utf-8"),n=`export interface ${t.name} {
1528
1536
  `,i=r.indexOf(n),o=r.indexOf(`
1529
1537
  }
1530
1538
  `,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(`
1531
- `).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 tl=" into every browser bundle. `tests/export-isolation.test.ts` walks the real module graph to keep\n * that from ever landing quietly.",rl=` if (resolveSentryDsn(observability, process.env.SENTRY_DSN)) ops.push(sentryServerOps);
1532
- `,nl=` if (resolvePosthogCredentials(observability, process.env.POSTHOG_API_KEY)) {
1539
+ `).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 nl=" into every browser bundle. `tests/export-isolation.test.ts` walks the real module graph to keep\n * that from ever landing quietly.",il=` if (resolveSentryDsn(observability, process.env.SENTRY_DSN)) ops.push(sentryServerOps);
1540
+ `,sl=` if (resolvePosthogCredentials(observability, process.env.POSTHOG_API_KEY)) {
1533
1541
  ops.push(posthogServerOps);
1534
1542
  }
1535
- `,il=` if (resolveSentryDsn(config.observability, process.env.SENTRY_DSN)) {
1543
+ `,ol=` if (resolveSentryDsn(config.observability, process.env.SENTRY_DSN)) {
1536
1544
  await initSentryServer();
1537
1545
  }
1538
- `,sl=` if (observability?.sentry?.dsn) ops.push(sentryBrowserOps);
1539
- `,ol=` if (observability?.posthog?.publicKey) ops.push(posthogBrowserOps);
1540
- `,al=` if (config.observability?.sentry?.dsn) await initSentryBrowser(options);
1541
- `,cl=` if (observability?.posthog?.publicKey && !observability?.sentry?.dsn) {
1546
+ `,al=` if (observability?.sentry?.dsn) ops.push(sentryBrowserOps);
1547
+ `,cl=` if (observability?.posthog?.publicKey) ops.push(posthogBrowserOps);
1548
+ `,ll=` if (config.observability?.sentry?.dsn) await initSentryBrowser(options);
1549
+ `,pl=` if (observability?.posthog?.publicKey && !observability?.sentry?.dsn) {
1542
1550
  announceMissingDesktopSdk("posthog");
1543
1551
  }
1544
- `,ll=` // PostHog ships no desktop SDK, so a project configured ONLY for PostHog reports nothing here -
1552
+ `,dl=` // PostHog ships no desktop SDK, so a project configured ONLY for PostHog reports nothing here -
1545
1553
  // announced rather than silent, because a desktop build that quietly drops every error looks
1546
1554
  // identical to one with reporting off.
1547
- `,pl=`import { createProviderGapAnnouncer } from "./announce";
1548
- `,dl=`/**
1555
+ `,ul=`import { createProviderGapAnnouncer } from "./announce";
1556
+ `,ml=`/**
1549
1557
  * Say once that the selected provider cannot report from the desktop main process.
1550
1558
  *
1551
1559
  * A WARNING and never an error: PostHog ships no Electron SDK, and a buyer running PostHog on the
@@ -1563,7 +1571,7 @@ const announceMissingDesktopSdk = createProviderGapAnnouncer({
1563
1571
  remedy: "Select sentry to report errors from the desktop app."
1564
1572
  });
1565
1573
 
1566
- `,ul=`/**
1574
+ `,hl=`/**
1567
1575
  * Say once that the selected provider cannot report from the desktop renderer.
1568
1576
  *
1569
1577
  * A WARNING and never an error: PostHog ships no Electron SDK, and a buyer running PostHog on the
@@ -1577,93 +1585,93 @@ const announceMissingDesktopSdk = createProviderGapAnnouncer({
1577
1585
  remedy: "Select sentry to report errors from the desktop app."
1578
1586
  });
1579
1587
 
1580
- `,ml=` const observability = config.observability;
1581
- `,hl=`import { config } from "@repo/config";
1582
- `,fl=` // No error-reporting adapter was generated for this project, so there is nothing to arm.
1583
- `,gl="export type BrowserReportingOptions = SentryBrowserInitOptions;",yl=`export interface BrowserReportingOptions {
1588
+ `,fl=` const observability = config.observability;
1589
+ `,gl=`import { config } from "@repo/config";
1590
+ `,yl=` // No error-reporting adapter was generated for this project, so there is nothing to arm.
1591
+ `,bl="export type BrowserReportingOptions = SentryBrowserInitOptions;",wl=`export interface BrowserReportingOptions {
1584
1592
  /** The deployment environment reports are tagged with. */
1585
1593
  environment: string;
1586
- }`,bl=` return observability?.sentry?.dsn ? [sentryDesktopMainOps] : [];
1587
- `,wl=` if (observability?.sentry?.dsn) await initSentryDesktopMain(options);
1588
- `,vl="export type DesktopMainReportingOptions = SentryDesktopMainInitOptions;",kl=`export interface DesktopMainReportingOptions {
1594
+ }`,vl=` return observability?.sentry?.dsn ? [sentryDesktopMainOps] : [];
1595
+ `,kl=` if (observability?.sentry?.dsn) await initSentryDesktopMain(options);
1596
+ `,El="export type DesktopMainReportingOptions = SentryDesktopMainInitOptions;",Sl=`export interface DesktopMainReportingOptions {
1589
1597
  /** The deployment environment reports are tagged with. */
1590
1598
  environment: string;
1591
1599
  /** Whether Electron's \`app\` has emitted \`ready\` yet. */
1592
1600
  appIsReady: boolean;
1593
- }`,El=` return observability?.sentry?.dsn ? [sentryDesktopRendererOps] : [];
1594
- `,Sl=` if (observability?.sentry?.dsn) await initSentryDesktopRenderer();
1595
- `;function Wi(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 Pl(e){let t=[{find:tl,replace:" into every browser bundle."},...Wi(e,{sentry:rl,posthog:nl})];return e.includes("sentry")||t.push({find:il,replace:""}),t}function Al(e){let t=[...Wi(e,{sentry:sl,posthog:ol})];return e.includes("sentry")||t.push({find:al,replace:""},Il),t}var Il={find:gl,replace:yl};function Rl(e){let t=[...zi(e,dl)];return e.includes("sentry")||t.push({find:bl,replace:` return [];
1596
- `},{find:wl,replace:Ji(e)},{find:vl,replace:kl}),t.push(...qi(e)),t}function Tl(e){let t=[...zi(e,ul)];return e.includes("sentry")||t.push({find:El,replace:` return [];
1597
- `},{find:Sl,replace:Ji(e)}),t.push(...qi(e)),t}function zi(e,t){return e.includes("posthog")?[]:[{find:ll,replace:""},{find:cl,replace:"",all:!0},{find:t,replace:""},{find:pl,replace:""}]}function qi(e){return e.length>0?[]:[{find:ml,replace:"",all:!0},{find:hl,replace:""}]}function Ji(e){return e.length>0?"":fl}var _l=` if (!posthogConfigured()) return;
1601
+ }`,Pl=` return observability?.sentry?.dsn ? [sentryDesktopRendererOps] : [];
1602
+ `,Al=` if (observability?.sentry?.dsn) await initSentryDesktopRenderer();
1603
+ `;function Wi(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 Il(e){let t=[{find:nl,replace:" into every browser bundle."},...Wi(e,{sentry:il,posthog:sl})];return e.includes("sentry")||t.push({find:ol,replace:""}),t}function Rl(e){let t=[...Wi(e,{sentry:al,posthog:cl})];return e.includes("sentry")||t.push({find:ll,replace:""},Tl),t}var Tl={find:bl,replace:wl};function _l(e){let t=[...zi(e,ml)];return e.includes("sentry")||t.push({find:vl,replace:` return [];
1604
+ `},{find:kl,replace:Ji(e)},{find:El,replace:Sl}),t.push(...qi(e)),t}function Ol(e){let t=[...zi(e,hl)];return e.includes("sentry")||t.push({find:Pl,replace:` return [];
1605
+ `},{find:Al,replace:Ji(e)}),t.push(...qi(e)),t}function zi(e,t){return e.includes("posthog")?[]:[{find:dl,replace:""},{find:pl,replace:"",all:!0},{find:t,replace:""},{find:ul,replace:""}]}function qi(e){return e.length>0?[]:[{find:fl,replace:"",all:!0},{find:gl,replace:""}]}function Ji(e){return e.length>0?"":yl}var xl=` if (!posthogConfigured()) return;
1598
1606
  try {
1599
1607
  const { captureAiGeneration: capture } = await import("./providers/posthog/llm");
1600
1608
  await capture(event);
1601
1609
  } catch (reportingError) {
1602
1610
  logReportingFailure("[observability] failed to report an AI generation", reportingError);
1603
1611
  }
1604
- `,Ol=` // No PostHog adapter was generated for this project, so there is nothing to report to.
1605
- `,xl=` // No PostHog adapter was generated for this project, so there is nothing queued to drain.
1606
- `,Dl=`/** Whether PostHog is configured on this server, without touching the PostHog folder. */
1612
+ `,Dl=` // No PostHog adapter was generated for this project, so there is nothing to report to.
1613
+ `,Nl=` // No PostHog adapter was generated for this project, so there is nothing queued to drain.
1614
+ `,Cl=`/** Whether PostHog is configured on this server, without touching the PostHog folder. */
1607
1615
  function posthogConfigured(): boolean {
1608
1616
  return Boolean(process.env.POSTHOG_API_KEY || config.observability?.posthog?.publicKey);
1609
1617
  }
1610
1618
 
1611
- `,Nl=` if (!posthogConfigured()) return;
1619
+ `,Ll=` if (!posthogConfigured()) return;
1612
1620
  try {
1613
1621
  const { flushAiGenerations: flush } = await import("./providers/posthog/llm");
1614
1622
  await flush();
1615
1623
  } catch (reportingError) {
1616
1624
  logReportingFailure("[observability] failed to flush queued AI generations", reportingError);
1617
1625
  }
1618
- `;function Cl(e){return e.includes("posthog")?[]:[{find:_l,replace:Ol},{find:Nl,replace:xl},{find:Dl,replace:""},{find:`import { logReportingFailure } from "./logger";
1626
+ `;function $l(e){return e.includes("posthog")?[]:[{find:xl,replace:Dl},{find:Ll,replace:Nl},{find:Cl,replace:""},{find:`import { logReportingFailure } from "./logger";
1619
1627
  `,replace:""},{find:`import { config } from "@repo/config";
1620
- `,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 Ki=[{file:"src/resolve-server.ts",edits:Pl},{file:"src/resolve-browser.ts",edits:Al},{file:"src/llm-analytics.ts",edits:Cl,dualMode:!1}],Ll=[{file:"src/resolve-desktop-main.ts",edits:Rl},{file:"src/resolve-desktop-renderer.ts",edits:Tl}];import{readdir as $l,readFile as jl}from"fs/promises";import{join as Xi}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=Xi(e.projectDir,"packages/i18n/translations"),i;try{i=await $l(n)}catch{return}for(let o of i){let s=Xi(n,o,"web.json"),a;try{a=await jl(s,"utf-8")}catch{continue}let d=a.replaceAll("GenerateSaaS",()=>r);d!==a&&await c(s,d)}}async function ir(e){let t=e.projectDir;e.demo||(await Nn(t),await Cn(t),await Ln(t),await $n(t)),await jn(t),await Mn(e),await Vn(e),await Bn(e),e.demo||await Gn(e),await Yn(e),await Wn(e),await zn(e),await Zn(e),await ei(e),await ri(e),await li(e),await di(e),await hi(e),await wi(e),await Li(e),await vi(e),await ki(e),await Ei(e),await Si(e),await Pi(e),await Ai(e),await Ii(e),await Oi(e),await Ri(e),await Ti(e),await Di(e),await Ur(e),await Ui(e),await Fi(e),await Yi(e),await ai(e),await Zi(e),await gi(e)}import{basename as es,join as ts,relative as Ml}from"path";import{createHash as Qi}from"crypto";import{readFile as Ul}from"fs/promises";async function sr(e){let t=await Ul(e);return Qi("sha256").update(t).digest("hex")}function Br(e){return Qi("sha256").update(e).digest("hex")}var Fl=new Set(["data",Q]);function Vl(e){let t=e.split("/");for(let r of t)if(Sr.has(r)||Pr.has(r)||Fl.has(r)||r.startsWith(".env")&&!r.includes("example"))return!0;return!1}function rs(e,t){return{projectName:e.projectName??es(t),appName:e.appName??e.projectName??es(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,runner:e.runner??!1,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 Bl(e,t){return{version:e.version,initialVersion:e.version,appName:e.appName,projectName:e.projectName,frontend:wn,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&&oe(e)?{mobilePurchases:e.mobilePurchases}:{},ai:e.ai,webAi:e.webAi,runner:e.runner,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 ns(e,t){let n=(await Ee(e.projectDir,e.projectDir,Vl)).sort(),i=await Promise.all(n.map(async a=>[Be(Ml(e.projectDir,a)),await sr(a)])),o=Object.fromEntries(i),s=Bl(e,t);await c(ts(e.projectDir,we),`${JSON.stringify(s,null," ")}
1621
- `),await c(ts(e.projectDir,vn),`${JSON.stringify(o,null," ")}
1622
- `)}import{relative as Gl}from"path";async function dt(e){let r=(await Ee(e,e,st)).sort(),n=await Promise.all(r.map(async i=>[Be(Gl(e,i)),await sr(i)]));return Object.fromEntries(n)}import{copyFile as Kl,mkdir as Hl,rm as Yl}from"fs/promises";import{dirname as Wl,join as is,relative as zl}from"path";import{existsSync as ql}from"fs";async function Gr(e,t){ql(t)&&await Yl(t,{recursive:!0,force:!0});let n=(await Ee(e,e,st)).map(i=>({file:i,dest:is(t,Be(zl(e,i)))}));await Promise.all([...new Set(n.map(({dest:i})=>Wl(i)))].map(i=>Hl(i,{recursive:!0}))),await Promise.all(n.map(({file:i,dest:o})=>Kl(i,o)))}async function ss(e,t){await Gr(e,is(t,Ft))}import{readdir as Jl,readFile as as}from"fs/promises";import{existsSync as Xl}from"fs";import{dirname as Zl,join as pe,resolve as Kr,sep as Hr}from"path";import{fileURLToPath as Ql}from"url";var ep={"claude-code":".claude/skills",cursor:".cursor/skills",codex:".agents/skills","gemini-cli":".gemini/skills",windsurf:".windsurf/skills"},Ge=Object.values(ep),Yr=["generatesaas-update"],tp=Zl(Ql(import.meta.url));function rp(){return Kt(tp,["skill","content"],"content")}async function Wr(e,t){for(let r of Ge){let n=pe(e,r);for(let[i,o]of Object.entries(t)){let s=Kr(n,i);if(!s.startsWith(n+Hr))continue;let a=pe(s,"scripts"),d=pe(s,"references");await Yt(a),await Yt(d),await c(pe(s,"SKILL.md"),o.skillMd.replaceAll("__SKILL_ROOT__",r));for(let[w,b]of Object.entries(o.scripts)){let P=Kr(a,w);P.startsWith(a+Hr)&&await c(P,b)}let m=Object.entries(o.references);m.length===0&&await c(pe(d,".gitkeep"),"");for(let[w,b]of m){let P=Kr(d,w);P.startsWith(d+Hr)&&await c(P,b)}}}}async function os(e){if(!Xl(e))return{};let t={};for(let r of await Jl(e))r!==".gitkeep"&&(t[r]=await as(pe(e,r),"utf-8"));return t}async function cs(e){let t=rp(),r={};for(let n of Yr){let i=pe(t,n);r[n]={skillMd:await as(pe(i,"SKILL.md"),"utf-8"),scripts:await os(pe(i,"scripts")),references:await os(pe(i,"references"))}}await Wr(e,r)}import{execFile as np,execFileSync as ip}from"child_process";import{access as ls,readFile as sp}from"fs/promises";import{join as zr}from"path";import*as U from"@clack/prompts";function He(e){try{let t=process.platform==="win32"?"where":"which";return ip(t,[e],{stdio:"ignore"}),!0}catch{return!1}}function Ke(e,t,r,n=3e5){return new Promise((i,o)=>{np(e,t,{cwd:r,timeout:n,maxBuffer:50*1024*1024},(s,a,d)=>{if(s){let m=String(a||"").trim(),b=[String(d||"").trim(),m].filter(Boolean).join(`
1623
- `);o(new Error(b?`${s.message}
1624
- ${b}`:s.message))}else i()})})}async function ps(e){if(!He("pnpm"))return U.log.warn("pnpm not found. Skipping lockfile regeneration."),!1;try{return await Ke("pnpm",["install","--lockfile-only","--no-frozen-lockfile","--config.minimumReleaseAge=0"],e),!0}catch(t){let r=t instanceof Error?t.message:String(t);return U.log.warn(`Lockfile regeneration failed: ${r}`),U.log.warn("Deploys using --frozen-lockfile may fail."),!1}}async function ds(e){if(!He("pnpm"))return U.log.warn("pnpm not found. Skipping dependency installation."),U.log.info("Install pnpm: https://pnpm.io/installation"),!1;let t=U.spinner();t.start("Installing dependencies (this may take a minute)...");try{return await Ke("pnpm",["install","--config.minimumReleaseAge=0"],e),t.stop("Dependencies installed."),!0}catch(r){t.stop("Dependency installation failed.");let n=r instanceof Error?r.message:String(r);return U.log.warn(`pnpm install failed: ${n}`),U.log.warn("You can run it manually later."),!1}}async function us(e){if(!He("pnpm"))return!1;let t=U.spinner();t.start("Generating baseline database migration...");try{return await Ke("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 U.log.warn(`Could not generate baseline migration: ${n}`),U.log.warn("Run 'pnpm -F @repo/database generate' before your first deploy."),!1}}async function ms(e){try{return await ls(zr(e,".git")),U.log.info("Git repository already exists, skipping init."),!0}catch{}if(!He("git"))return U.log.warn("git not found. Skipping repository initialization."),!1;let t=U.spinner();t.start("Initializing git repository...");try{return await Ke("git",["init"],e),await Ke("git",["add","-A"],e),await Ke("git",["commit","--no-verify","-m","Initial commit from GenerateSaaS"],e),t.stop("Git repository initialized."),!0}catch{return t.stop("Git initialization failed."),U.log.warn("You can run git init manually later."),!1}}async function hs(e){if(!He("pnpm"))return!1;try{await ls(zr(e,".git"))}catch{return!1}try{let t=JSON.parse(await sp(zr(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 Ke("pnpm",["exec","simple-git-hooks"],e),!0}catch{return U.log.warn("Could not install git hooks. Run 'pnpm exec simple-git-hooks' manually."),!1}}import*as Ye from"@clack/prompts";import re from"picocolors";function fs(e,t){let r=Qe(e);t.dockerAvailable||Ye.log.warn("Docker not found. Install Docker to run local services: https://docs.docker.com/get-docker/"),t.baselineMigrationMissing&&Ye.log.warn("No database migration was generated (the install did not complete). Run `pnpm install` then `pnpm --filter @repo/database generate` and commit the result BEFORE deploying - otherwise your first deploy pushes the schema untracked.");let n=[];n.push(`cd ${e.projectDir}`),t.pnpmInstalled||n.push("pnpm install"),n.push(`pnpm infra ${re.dim(`# ${r.map(a=>sn[a].label).join(", ")}`)}`),n.push(`pnpm dev ${re.dim("# http://localhost:3000")}`),t.skippedCredentials.length>0&&(n.push(""),n.push(re.dim("Fill in remaining TODO values in .env"))),Ye.note(n.join(`
1625
- `),re.yellow("Start Development"));let i=[];i.push(`App ${re.cyan("http://localhost:3000")}`),e.architecture==="separate"&&i.push(`API ${re.cyan("http://localhost:3010")}`),r.includes("mailpit")&&i.push(`Mailpit ${re.cyan("http://localhost:8025")}`),r.includes("inngest")&&i.push(`Inngest ${re.cyan("http://localhost:8288")}`),Ye.note(i.join(`
1626
- `),re.yellow("Dev Tools"));let o=[],s=op(e);s.length>0&&o.push(`Set in production: ${re.dim(s.join(", "))}`),o.push("pnpm db:setup # Apply the database schema"),o.push(ap(e)),Ye.note(o.join(`
1627
- `),re.yellow("Deployment"))}function op(e){let t=["DATABASE_URL","BETTER_AUTH_SECRET","INNGEST_APP_ID","INNGEST_EVENT_KEY","INNGEST_BASE_URL","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 ap(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 ut(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=ut(e),n=ut(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 or(e,t){return e.versions.find(r=>r.version===t)?.cli}function gs(e){return process.env.GENERATESAAS_TEMPLATE_TARBALL||process.env.GENERATESAAS_TEMPLATE_TARBALL_DIR||process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?!0:ut(e)===null}function ar(e,t,r="3.10.0"){if(gs(r))return{ok:!0};let n=or(e,e.latest);return!n||ut(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 ys(e,t,r="3.10.0"){if(gs(r))return{ok:!0};let n=or(e,t);return!n||ut(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 mp from"picocolors";var hp="a10a6fb9d7cadde32e37dad52059d17b5d2b916b08c76d8fbcc99982e9a3d87f";async function fp(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 bs(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 ne("--architecture <type>","fullstack or separate").choices([...et])).addOption(new ne("--payment <provider>","payment provider").choices([...tt])).addOption(new ne("--email <provider>","email provider").choices([...rt])).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 ne("--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([...Me])).option("--ai","include the AI features (chat, models, automations, integrations); unlocks the runner").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, and cannot be combined with --runner").option("--runner","include the runner feature - your web users connect a machine that runs their own AI subscriptions for this app").option("--no-runner","exclude the backend runner feature").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 ne("--currency <code>","default currency for billing").choices([...fe])).addOption(new ne("--preset <preset>","infrastructure preset: serverless (Vercel + Neon + Upstash) or selfhost (Docker or Node + Postgres + Redis); --deploy/--database/--cache override it piecewise").choices([...Ue])).addOption(new ne("--deploy <target>","deployment target").choices([...ge])).addOption(new ne("--database <provider>","database provider").choices([...ye])).addOption(new ne("--cache <provider>","cache provider").choices([...be])).option("--observability <providers>",`comma-separated observability providers (${K.join(", ")}); anything unselected ships no SDK`).option("--api-key <key>","API key (skips interactive prompt)").option("--base-url <url>","public base URL (e.g. https://example.com) - bakes into canonical/og/sitemap").option("-y, --yes","accept defaults for unspecified options (non-interactive)").addOption(new ne("--demo","first-party demo build: keep sample content, mark site non-indexable - requires CI API key").hideHelp()).addOption(new ne("--no-db-migration","skip generating the baseline DB migration (internal: demos/CI/playground)").hideHelp()).action(async(t,r)=>{await gp(t?{...r,apiKey:t}:r)})}async function gp(e){let t=performance.now();rn("3.10.0");let r;try{r=gn(e)}catch(v){k.cancel(j(v)),process.exit(1)}let n=k.spinner(),i;try{i=await it({apiKey:e.apiKey,prompt:!e.yes})}catch(v){k.cancel(j(v)),process.exit(1)}e.demo&&Br(i)!==hp&&(k.cancel("--demo is restricted to first-party demo deployments."),process.exit(1));let o=ke(i),s,a=async()=>{s=await Te(o);let v=ar(s,"init");if(!v.ok)throw new Error(v.message);return{latestVersion:s.latest,selectedVersion:s.latest,desktopAllowed:s.entitlements?.desktopAllowed??!0,runnerAllowed:s.entitlements?.runnerAllowed??!0,mobileAllowed:s.entitlements?.mobileAllowed??!0}};n.start("Verifying access...");let d,m,w=!0,b=!0,P=!0;try{({latestVersion:d,selectedVersion:m,desktopAllowed:w,runnerAllowed:b,mobileAllowed:P}=await a()),n.stop("Access verified."),Ve(i)}catch(v){if(n.stop("Access verification failed."),v instanceof F&&v.status===401){e.yes&&(k.cancel("Invalid API key. Cannot prompt in non-interactive mode."),process.exit(1)),k.log.warning("Invalid API key."),i=await kt(),o=ke(i),n.start("Verifying access...");try{({latestVersion:d,selectedVersion:m,desktopAllowed:w,runnerAllowed:b,mobileAllowed:P}=await a()),n.stop("Access verified."),Ve(i)}catch(M){n.stop("Access verification failed."),k.cancel(M instanceof F&&M.status===401?"Invalid API key.":j(M)),process.exit(1)}}else k.cancel(j(v)),process.exit(1)}k.log.success(`Latest version: ${d}`),r.desktop===!0&&!w&&(k.cancel("The desktop app is available on the Pro plan and up. Upgrade your plan at generatesaas.com."),process.exit(1)),r.runner===!0&&!b&&(k.cancel("The runner is available on the Pro plan and up. Upgrade your plan at generatesaas.com."),process.exit(1)),r.mobile===!0&&!P&&(k.cancel("The mobile app is available on the Pro plan and up. Upgrade your plan at generatesaas.com."),process.exit(1));let I;e.yes?I=yn({...r,...w?{}:{desktop:!1},...b?{}:{runner:!1},...P?{}:{mobile:!1}}):I=await bn(r,{desktopAllowed:w,runnerAllowed:b,mobileAllowed:P});let _;n.start("Activating license...");try{let v=e.demo&&I.baseUrl?await fp(I.baseUrl):crypto.randomUUID(),M=()=>({frontend:vr,version:m,installId:v,projectName:I.projectName,options:An(I)}),G;try{G=await kr(o,M())}catch(se){let N=Vt(se);if(!N?.lastAllowedVersion||!s)throw se;n.stop("License activation failed.");let de=ys(s,N.lastAllowedVersion);if(de.ok||(k.cancel(`${N.message} ${de.message}`),process.exit(1)),e.yes){let ue=or(s,N.lastAllowedVersion);k.cancel(`${N.message} Re-run ${ue?`npx generatesaas@${ue} init`:"init"} without --yes to continue with v${N.lastAllowedVersion} (the last version your license covers).`),process.exit(1)}let X=await k.confirm({message:`Your update window has ended. Continue with v${N.lastAllowedVersion} (the last version your license covers)?`});(k.isCancel(X)||!X)&&(k.cancel("Setup cancelled."),process.exit(0)),m=N.lastAllowedVersion,n.start(`Activating license for v${m}...`),G=await kr(o,M())}_={token:G.token,keyHash:Br(i),installId:G.installId??v},n.stop("License activated.")}catch(v){n.stop("License activation failed."),k.cancel(j(v)),process.exit(1)}let f=up(I.projectDir);if(cp(f)&&lp(f).length>0)if(e.yes)k.log.info(`Directory ${f} is not empty. Merging (keeping existing files, overwriting conflicts).`);else{let M=await k.select({message:`Directory ${f} 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"}]});(k.isCancel(M)||M==="cancel")&&(k.cancel("Setup cancelled."),process.exit(0)),M==="overwrite"&&pp(f,{recursive:!0,force:!0})}let O={...I,projectDir:f,version:m,...e.demo?{docs:!1}:{}};n.start("Downloading template...");try{await Bt(o,m,f),n.stop("Template downloaded.")}catch(v){n.stop("Download failed."),k.cancel(j(v)),process.exit(1)}n.start("Generating project files...");try{if(await ir(O),!e.demo){let v=await dt(f);await c(dp(f,Mt),`${JSON.stringify(v,null," ")}
1628
- `),await ss(f,f)}await cs(f),await ns(O,_),n.stop("Project files generated.")}catch(v){n.stop("Generation failed."),k.cancel(j(v)),process.exit(1)}!await ps(f)&&O.demo===!0&&(k.cancel("Lockfile regeneration failed on a demo build - refusing to ship a stale lockfile."),process.exit(1));let q=await ds(f),J=O.demo!==!0&&e.dbMigration!==!1,xe=!1;J&&q&&(await us(f),xe=!0),await ms(f),q&&await hs(f);let De=He("docker"),Je=yr(O).map(v=>v.key).filter(v=>!O.credentials?.[v]);fs(O,{pnpmInstalled:q,dockerAvailable:De,skippedCredentials:Je,baselineMigrationMissing:J&&!xe}),nn(),k.log.info(mp.dim(`Done in ${((performance.now()-t)/1e3).toFixed(1)}s`))}import{existsSync as cr}from"fs";import{readFile as Ps}from"fs/promises";import{join as We,resolve as kp}from"path";import*as y from"@clack/prompts";import C from"picocolors";import{mkdtemp as yp,rm as bp}from"fs/promises";import{tmpdir as wp}from"os";import{join as vp}from"path";async function qr(e,t,r,n){let i=await yp(vp(wp(),"generatesaas-stage-"));try{await Bt(e,t,i),await ir({...r,projectDir:i}),await Gr(i,n)}finally{await bp(i,{recursive:!0,force:!0})}}function ws(e){return e?"ON":"OFF"}var mt="packages/config/src/index.ts";function vs(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 ks(e){return[...Qe({databaseProvider:e.databaseProvider??"postgres",cacheProvider:e.cacheProvider??"redis",emailProvider:e.emailProvider??"smtp"})].sort()}var Jr=[{key:"errorTracking",severity:"warn",normalize:e=>{e.errorTracking===void 0||e.observability!==void 0||(e.observability=e.errorTracking==="none"?[]:[e.errorTracking])},preserved:()=>!0,describe:()=>"Retired option `errorTracking`: it is now `observability`, an array, because a project may run more than one provider at once. Your recorded choice was migrated across automatically."},{key:"companion",severity:"warn",normalize:e=>{e.companion===void 0||e.runner!==void 0||(e.runner=e.companion)},preserved:()=>!0,describe:()=>"Retired option `companion`: it is now `runner`, because the daemon it names is AgentRunner. Your recorded choice was migrated across automatically - the feature itself is unchanged."},{key:"companionSource",severity:"warn",preserved:()=>!1,describe:e=>`Retired option \`companionSource\`: your project recorded a \`${String(e.companionSource)}\` daemon source. There is now one runner daemon - AgentRunner - which we publish and your users install from its own releases. Your project keeps the runner feature and its own pairing, dispatch and Runners page; it no longer holds or brands a daemon.`},{key:"companionName",severity:"warn",preserved:()=>!1,describe:e=>`Retired option \`companionName\`: your project recorded a branded daemon called ${e.companionName}. Buyers no longer brand or publish a daemon - your users install AgentRunner, which we maintain. Their existing install of your old daemon keeps running until they switch.`},{key:"companionRepoUrl",severity:"warn",preserved:()=>!1,describe:e=>`Retired option \`companionRepoUrl\`: your project pointed its install flow at ${e.companionRepoUrl}. It now points at AgentRunner, the one daemon we publish.`},{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 choice behind it - there is one runner daemon (AgentRunner) and we publish it, so nothing in your project is built from a local 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 ${mt} 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 ${mt} 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 ${mt}. 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===oe(e),describe:e=>`Retired option \`aiBuiltin\`: your project recorded built-in AI models ${ws(e.aiBuiltin)}, but it is now a plain config value generated ${ws(oe(e))} for a project ${oe(e)?"with":"without"} a payment provider. Set \`config.ai.builtin\` to \`${String(e.aiBuiltin===!0)}\` in ${mt} 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 ${mt} to keep it off.`},{key:"dockerServices",severity:"warn",preserved:e=>vs(e).join(",")===ks(e).join(","),describe:e=>`Retired option \`dockerServices\`: your project recorded ${vs(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 ${ks(e).join(", ")}. Add any extra service back by hand; the file is yours to edit.`},{key:"aiTools",severity:"warn",preserved:e=>(e.aiTools??[]).length===an.length,describe:e=>`Retired option \`aiTools\`: your project recorded ${(e.aiTools??[]).join(", ")||"no AI tools"}, but the \`generatesaas-update\` skill bundle now ships to every AI-tool root (${Ge.join(", ")}) so it is there whichever assistant you switch to. Delete the roots you do not use - they are plain text files with no runtime path.`},{key:"blog",severity:"warn",preserved:e=>e.blog!==!1,describe:()=>`Retired option \`blog\`: your project recorded the blog OFF, but content is no longer an option. This update adds the \`/blog\`, \`/alternatives\` and \`/compare\` route code to your project; every one of them 404s until you add a file under \`packages/content/{locale}/{section}/\`, and none of them appears in your navbar, footer, sitemap or llms.txt while it is empty. Delete an entry from \`config.content.sections\` in ${mt} to drop a section for good.`}],Jf=Jr.map(e=>e.key);function Es(e){for(let t of Jr)t.normalize?.(e)}function Ss(e){let t=[];for(let r of Jr){if(r.normalize?.(e),e[r.key]===void 0)continue;(!r.applies||r.applies(e))&&!r.preserved(e)&&t.push({key:r.key,message:r.describe(e),severity:r.severity}),delete e[r.key]}return t}function As(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",Ep,[]).action(async(t,r)=>{r.args.length>0&&y.log.warn("`auto` is now the default and the argument is ignored.");let n=Sp(t.answer),i=kp(t.cwd??process.cwd()),o=We(i,we),s;try{s=JSON.parse(await Ps(o,"utf-8"))}catch{y.cancel(".generatesaas/manifest.json not found. Run this from a GenerateSaaS project."),process.exit(1)}s.frontend===br&&(y.cancel(`This project was generated on the Nuxt frontend (\`.generatesaas/manifest.json\` records \`frontend: "${br}"\`).
1628
+ `,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 Ki=[{file:"src/resolve-server.ts",edits:Il},{file:"src/resolve-browser.ts",edits:Rl},{file:"src/llm-analytics.ts",edits:$l,dualMode:!1}],jl=[{file:"src/resolve-desktop-main.ts",edits:_l},{file:"src/resolve-desktop-renderer.ts",edits:Ol}];import{readdir as Ul,readFile as Ml}from"fs/promises";import{join as Xi}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=Xi(e.projectDir,"packages/i18n/translations"),i;try{i=await Ul(n)}catch{return}for(let o of i){let s=Xi(n,o,"web.json"),a;try{a=await Ml(s,"utf-8")}catch{continue}let d=a.replaceAll("GenerateSaaS",()=>r);d!==a&&await c(s,d)}}async function ir(e){let t=e.projectDir;e.demo||(await Ln(t),await $n(t),await jn(t),await Un(t)),await Mn(t),await Vn(e),await Gn(e),await Kn(e),e.demo||await Hn(e),await zn(e),await qn(e),await Jn(e),await ei(e),await ri(e),await ii(e),await pi(e),await ui(e),await fi(e),await wi(e),await Li(e),await vi(e),await ki(e),await Ei(e),await Si(e),await Pi(e),await Ai(e),await Ii(e),await Oi(e),await Ri(e),await Ti(e),await Di(e),await Fr(e),await Ui(e),await Fi(e),await Yi(e),await ci(e),await Zi(e),await yi(e)}import{basename as es,join as ts,relative as Vl}from"path";import{createHash as Qi}from"crypto";import{readFile as Fl}from"fs/promises";async function sr(e){let t=await Fl(e);return Qi("sha256").update(t).digest("hex")}function Kr(e){return Qi("sha256").update(e).digest("hex")}var Bl=new Set(["data",Q]);function Gl(e){let t=e.split("/");for(let r of t)if(Sr.has(r)||Pr.has(r)||Bl.has(r)||r.startsWith(".env")&&!r.includes("example"))return!0;return!1}function rs(e,t){return{projectName:e.projectName??es(t),appName:e.appName??e.projectName??es(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,runner:e.runner??!1,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 Kl(e,t){return{version:e.version,initialVersion:e.version,appName:e.appName,projectName:e.projectName,frontend:kn,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&&oe(e)?{mobilePurchases:e.mobilePurchases}:{},ai:e.ai,webAi:e.webAi,runner:e.runner,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 ns(e,t){let n=(await Ee(e.projectDir,e.projectDir,Gl)).sort(),i=await Promise.all(n.map(async a=>[Be(Vl(e.projectDir,a)),await sr(a)])),o=Object.fromEntries(i),s=Kl(e,t);await c(ts(e.projectDir,we),`${JSON.stringify(s,null," ")}
1629
+ `),await c(ts(e.projectDir,En),`${JSON.stringify(o,null," ")}
1630
+ `)}import{relative as Hl}from"path";async function dt(e){let r=(await Ee(e,e,at)).sort(),n=await Promise.all(r.map(async i=>[Be(Hl(e,i)),await sr(i)]));return Object.fromEntries(n)}import{copyFile as Yl,mkdir as Wl,rm as zl}from"fs/promises";import{dirname as ql,join as is,relative as Jl}from"path";import{existsSync as Xl}from"fs";async function Hr(e,t){Xl(t)&&await zl(t,{recursive:!0,force:!0});let n=(await Ee(e,e,at)).map(i=>({file:i,dest:is(t,Be(Jl(e,i)))}));await Promise.all([...new Set(n.map(({dest:i})=>ql(i)))].map(i=>Wl(i,{recursive:!0}))),await Promise.all(n.map(({file:i,dest:o})=>Yl(i,o)))}async function ss(e,t){await Hr(e,is(t,Ft))}import{readdir as Zl,readFile as as}from"fs/promises";import{existsSync as Ql}from"fs";import{dirname as ep,join as pe,resolve as Yr,sep as Wr}from"path";import{fileURLToPath as tp}from"url";var rp={"claude-code":".claude/skills",cursor:".cursor/skills",codex:".agents/skills","gemini-cli":".gemini/skills",windsurf:".windsurf/skills"},He=Object.values(rp),zr=["generatesaas-update"],np=ep(tp(import.meta.url));function ip(){return Kt(np,["skill","content"],"content")}async function qr(e,t){for(let r of He){let n=pe(e,r);for(let[i,o]of Object.entries(t)){let s=Yr(n,i);if(!s.startsWith(n+Wr))continue;let a=pe(s,"scripts"),d=pe(s,"references");await Yt(a),await Yt(d),await c(pe(s,"SKILL.md"),o.skillMd.replaceAll("__SKILL_ROOT__",r));for(let[w,y]of Object.entries(o.scripts)){let P=Yr(a,w);P.startsWith(a+Wr)&&await c(P,y)}let u=Object.entries(o.references);u.length===0&&await c(pe(d,".gitkeep"),"");for(let[w,y]of u){let P=Yr(d,w);P.startsWith(d+Wr)&&await c(P,y)}}}}async function os(e){if(!Ql(e))return{};let t={};for(let r of await Zl(e))r!==".gitkeep"&&(t[r]=await as(pe(e,r),"utf-8"));return t}async function cs(e){let t=ip(),r={};for(let n of zr){let i=pe(t,n);r[n]={skillMd:await as(pe(i,"SKILL.md"),"utf-8"),scripts:await os(pe(i,"scripts")),references:await os(pe(i,"references"))}}await qr(e,r)}import{execFile as sp,execFileSync as op}from"child_process";import{access as ls,readFile as ap}from"fs/promises";import{join as Jr}from"path";import*as U from"@clack/prompts";function We(e){try{let t=process.platform==="win32"?"where":"which";return op(t,[e],{stdio:"ignore"}),!0}catch{return!1}}function Ye(e,t,r,n=3e5){return new Promise((i,o)=>{sp(e,t,{cwd:r,timeout:n,maxBuffer:50*1024*1024},(s,a,d)=>{if(s){let u=String(a||"").trim(),y=[String(d||"").trim(),u].filter(Boolean).join(`
1631
+ `);o(new Error(y?`${s.message}
1632
+ ${y}`:s.message))}else i()})})}async function ps(e){if(!We("pnpm"))return U.log.warn("pnpm not found. Skipping lockfile regeneration."),!1;try{return await Ye("pnpm",["install","--lockfile-only","--no-frozen-lockfile","--config.minimumReleaseAge=0"],e),!0}catch(t){let r=t instanceof Error?t.message:String(t);return U.log.warn(`Lockfile regeneration failed: ${r}`),U.log.warn("Deploys using --frozen-lockfile may fail."),!1}}async function ds(e){if(!We("pnpm"))return U.log.warn("pnpm not found. Skipping dependency installation."),U.log.info("Install pnpm: https://pnpm.io/installation"),!1;let t=U.spinner();t.start("Installing dependencies (this may take a minute)...");try{return await Ye("pnpm",["install","--config.minimumReleaseAge=0"],e),t.stop("Dependencies installed."),!0}catch(r){t.stop("Dependency installation failed.");let n=r instanceof Error?r.message:String(r);return U.log.warn(`pnpm install failed: ${n}`),U.log.warn("You can run it manually later."),!1}}async function us(e){if(!We("pnpm"))return!1;let t=U.spinner();t.start("Generating baseline database migration...");try{return await Ye("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 U.log.warn(`Could not generate baseline migration: ${n}`),U.log.warn("Run 'pnpm -F @repo/database generate' before your first deploy."),!1}}async function ms(e){try{return await ls(Jr(e,".git")),U.log.info("Git repository already exists, skipping init."),!0}catch{}if(!We("git"))return U.log.warn("git not found. Skipping repository initialization."),!1;let t=U.spinner();t.start("Initializing git repository...");try{return await Ye("git",["init"],e),await Ye("git",["add","-A"],e),await Ye("git",["commit","--no-verify","-m","Initial commit from GenerateSaaS"],e),t.stop("Git repository initialized."),!0}catch{return t.stop("Git initialization failed."),U.log.warn("You can run git init manually later."),!1}}async function hs(e){if(!We("pnpm"))return!1;try{await ls(Jr(e,".git"))}catch{return!1}try{let t=JSON.parse(await ap(Jr(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 Ye("pnpm",["exec","simple-git-hooks"],e),!0}catch{return U.log.warn("Could not install git hooks. Run 'pnpm exec simple-git-hooks' manually."),!1}}import*as ze from"@clack/prompts";import re from"picocolors";function fs(e,t){let r=tt(e);t.dockerAvailable||ze.log.warn("Docker not found. Install Docker to run local services: https://docs.docker.com/get-docker/"),t.baselineMigrationMissing&&ze.log.warn("No database migration was generated (the install did not complete). Run `pnpm install` then `pnpm --filter @repo/database generate` and commit the result BEFORE deploying - otherwise your first deploy pushes the schema untracked.");let n=[];n.push(`cd ${e.projectDir}`),t.pnpmInstalled||n.push("pnpm install"),n.push(`pnpm infra ${re.dim(`# ${r.map(a=>an[a].label).join(", ")}`)}`),n.push(`pnpm dev ${re.dim("# http://localhost:3000")}`),t.skippedCredentials.length>0&&(n.push(""),n.push(re.dim("Fill in remaining TODO values in .env"))),ze.note(n.join(`
1633
+ `),re.yellow("Start Development"));let i=[];i.push(`App ${re.cyan("http://localhost:3000")}`),e.architecture==="separate"&&i.push(`API ${re.cyan("http://localhost:3010")}`),r.includes("mailpit")&&i.push(`Mailpit ${re.cyan("http://localhost:8025")}`),r.includes("inngest")&&i.push(`Inngest ${re.cyan("http://localhost:8288")}`),ze.note(i.join(`
1634
+ `),re.yellow("Dev Tools"));let o=[],s=cp(e);s.length>0&&o.push(`Set in production: ${re.dim(s.join(", "))}`),o.push("pnpm db:setup # Apply the database schema"),o.push(lp(e)),ze.note(o.join(`
1635
+ `),re.yellow("Deployment"))}function cp(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 lp(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 ut(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=ut(e),n=ut(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 or(e,t){return e.versions.find(r=>r.version===t)?.cli}function gs(e){return process.env.GENERATESAAS_TEMPLATE_TARBALL||process.env.GENERATESAAS_TEMPLATE_TARBALL_DIR||process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?!0:ut(e)===null}function ar(e,t,r="3.11.0"){if(gs(r))return{ok:!0};let n=or(e,e.latest);return!n||ut(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 ys(e,t,r="3.11.0"){if(gs(r))return{ok:!0};let n=or(e,t);return!n||ut(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 fp from"picocolors";var gp="a10a6fb9d7cadde32e37dad52059d17b5d2b916b08c76d8fbcc99982e9a3d87f";async function yp(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 bs(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 ne("--architecture <type>","fullstack or separate").choices([...rt])).addOption(new ne("--payment <provider>","payment provider").choices([...nt])).addOption(new ne("--email <provider>","email provider").choices([...it])).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 ne("--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([...Me])).option("--ai","include the AI features (chat, models, automations, integrations); unlocks the runner").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, and cannot be combined with --runner").option("--runner","include the runner feature - your web users connect a machine that runs their own AI subscriptions for this app").option("--no-runner","exclude the backend runner feature").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 ne("--currency <code>","default currency for billing").choices([...fe])).addOption(new ne("--preset <preset>","infrastructure preset: serverless (Vercel + Neon + Upstash) or selfhost (Docker or Node + Postgres + Redis); --deploy/--database/--cache override it piecewise").choices([...Ue])).addOption(new ne("--deploy <target>","deployment target").choices([...ge])).addOption(new ne("--database <provider>","database provider").choices([...ye])).addOption(new ne("--cache <provider>","cache provider").choices([...be])).option("--observability <providers>",`comma-separated observability providers (${Y.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 ne("--demo","first-party demo build: keep sample content, mark site non-indexable - requires CI API key").hideHelp()).addOption(new ne("--no-db-migration","skip generating the baseline DB migration (internal: demos/CI/playground)").hideHelp()).action(async(t,r)=>{await bp(t?{...r,apiKey:t}:r)})}async function bp(e){let t=performance.now();sn("3.11.0");let r;try{r=bn(e)}catch(v){S.cancel(j(v)),process.exit(1)}let n=S.spinner(),i;try{i=await ot({apiKey:e.apiKey,prompt:!e.yes})}catch(v){S.cancel(j(v)),process.exit(1)}e.demo&&Kr(i)!==gp&&(S.cancel("--demo is restricted to first-party demo deployments."),process.exit(1));let o=ke(i),s,a=async()=>{s=await Te(o);let v=ar(s,"init");if(!v.ok)throw new Error(v.message);return{latestVersion:s.latest,selectedVersion:s.latest,desktopAllowed:s.entitlements?.desktopAllowed??!0,runnerAllowed:s.entitlements?.runnerAllowed??!0,mobileAllowed:s.entitlements?.mobileAllowed??!0}};n.start("Verifying access...");let d,u,w=!0,y=!0,P=!0;try{({latestVersion:d,selectedVersion:u,desktopAllowed:w,runnerAllowed:y,mobileAllowed:P}=await a()),n.stop("Access verified."),Ve(i)}catch(v){if(n.stop("Access verification failed."),v instanceof F&&v.status===401){e.yes&&(S.cancel("Invalid API key. Cannot prompt in non-interactive mode."),process.exit(1)),S.log.warning("Invalid API key."),i=await kt(),o=ke(i),n.start("Verifying access...");try{({latestVersion:d,selectedVersion:u,desktopAllowed:w,runnerAllowed:y,mobileAllowed:P}=await a()),n.stop("Access verified."),Ve(i)}catch(M){n.stop("Access verification failed."),S.cancel(M instanceof F&&M.status===401?"Invalid API key.":j(M)),process.exit(1)}}else S.cancel(j(v)),process.exit(1)}S.log.success(`Latest version: ${d}`),r.desktop===!0&&!w&&(S.cancel("The desktop app is available on the Pro plan and up. Upgrade your plan at generatesaas.com."),process.exit(1)),r.runner===!0&&!y&&(S.cancel("The runner is available on the Pro plan and up. Upgrade your plan at generatesaas.com."),process.exit(1)),r.mobile===!0&&!P&&(S.cancel("The mobile app is available on the Pro plan and up. Upgrade your plan at generatesaas.com."),process.exit(1));let I;e.yes?I=wn({...r,...w?{}:{desktop:!1},...y?{}:{runner:!1},...P?{}:{mobile:!1}}):I=await vn(r,{desktopAllowed:w,runnerAllowed:y,mobileAllowed:P});let _;n.start("Activating license...");try{let v=e.demo&&I.baseUrl?await yp(I.baseUrl):crypto.randomUUID(),M=()=>({frontend:vr,version:u,installId:v,projectName:I.projectName,options:Rn(I)}),G;try{G=await kr(o,M())}catch(se){let N=Vt(se);if(!N?.lastAllowedVersion||!s)throw se;n.stop("License activation failed.");let de=ys(s,N.lastAllowedVersion);if(de.ok||(S.cancel(`${N.message} ${de.message}`),process.exit(1)),e.yes){let ue=or(s,N.lastAllowedVersion);S.cancel(`${N.message} Re-run ${ue?`npx generatesaas@${ue} init`:"init"} without --yes to continue with v${N.lastAllowedVersion} (the last version your license covers).`),process.exit(1)}let X=await S.confirm({message:`Your update window has ended. Continue with v${N.lastAllowedVersion} (the last version your license covers)?`});(S.isCancel(X)||!X)&&(S.cancel("Setup cancelled."),process.exit(0)),u=N.lastAllowedVersion,n.start(`Activating license for v${u}...`),G=await kr(o,M())}_={token:G.token,keyHash:Kr(i),installId:G.installId??v},n.stop("License activated.")}catch(v){n.stop("License activation failed."),S.cancel(j(v)),process.exit(1)}let f=hp(I.projectDir);if(pp(f)&&dp(f).length>0)if(e.yes)S.log.info(`Directory ${f} is not empty. Merging (keeping existing files, overwriting conflicts).`);else{let M=await S.select({message:`Directory ${f} is not empty.`,options:[{value:"merge",label:"Merge",hint:"keep existing files, overwrite conflicts"},{value:"overwrite",label:"Overwrite",hint:"delete everything and start fresh"},{value:"cancel",label:"Cancel"}]});(S.isCancel(M)||M==="cancel")&&(S.cancel("Setup cancelled."),process.exit(0)),M==="overwrite"&&up(f,{recursive:!0,force:!0})}let O={...I,projectDir:f,version:u,...e.demo?{docs:!1}:{}};n.start("Downloading template...");try{await Bt(o,u,f),n.stop("Template downloaded.")}catch(v){n.stop("Download failed."),S.cancel(j(v)),process.exit(1)}n.start("Generating project files...");try{if(await ir(O),!e.demo){let v=await dt(f);await c(mp(f,Mt),`${JSON.stringify(v,null," ")}
1636
+ `),await ss(f,f)}await cs(f),await ns(O,_),n.stop("Project files generated.")}catch(v){n.stop("Generation failed."),S.cancel(j(v)),process.exit(1)}!await ps(f)&&O.demo===!0&&(S.cancel("Lockfile regeneration failed on a demo build - refusing to ship a stale lockfile."),process.exit(1));let q=await ds(f),J=O.demo!==!0&&e.dbMigration!==!1,xe=!1;J&&q&&(await us(f),xe=!0),await ms(f),q&&await hs(f);let De=We("docker"),Ze=yr(O).map(v=>v.key).filter(v=>!O.credentials?.[v]);fs(O,{pnpmInstalled:q,dockerAvailable:De,skippedCredentials:Ze,baselineMigrationMissing:J&&!xe}),on(),S.log.info(fp.dim(`Done in ${((performance.now()-t)/1e3).toFixed(1)}s`))}import{existsSync as cr}from"fs";import{readFile as Ps}from"fs/promises";import{join as qe,resolve as Sp}from"path";import*as b from"@clack/prompts";import C from"picocolors";import{mkdtemp as wp,rm as vp}from"fs/promises";import{tmpdir as kp}from"os";import{join as Ep}from"path";async function Xr(e,t,r,n){let i=await wp(Ep(kp(),"generatesaas-stage-"));try{await Bt(e,t,i),await ir({...r,projectDir:i}),await Hr(i,n)}finally{await vp(i,{recursive:!0,force:!0})}}function ws(e){return e?"ON":"OFF"}var mt="packages/config/src/index.ts";function vs(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 ks(e){return[...tt({databaseProvider:e.databaseProvider??"postgres",cacheProvider:e.cacheProvider??"redis",emailProvider:e.emailProvider??"smtp"})].sort()}var Zr=[{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 is now `runner`, because the daemon it names is AgentRunner. Your recorded choice was migrated across automatically - the feature itself is unchanged."},{key:"companionSource",severity:"warn",preserved:()=>!1,describe:e=>`Retired option \`companionSource\`: your project recorded a \`${String(e.companionSource)}\` daemon source. There is now one runner daemon - AgentRunner - which we publish and your users install from its own releases. Your project keeps the runner feature and its own pairing, dispatch and Runners page; it no longer holds or brands a daemon.`},{key:"companionName",severity:"warn",preserved:()=>!1,describe:e=>`Retired option \`companionName\`: your project recorded a branded daemon called ${e.companionName}. Buyers no longer brand or publish a daemon - your users install AgentRunner, which we maintain. Their existing install of your old daemon keeps running until they switch.`},{key:"companionRepoUrl",severity:"warn",preserved:()=>!1,describe:e=>`Retired option \`companionRepoUrl\`: your project pointed its install flow at ${e.companionRepoUrl}. It now points at AgentRunner, the one daemon we publish.`},{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 choice behind it - there is one runner daemon (AgentRunner) and we publish it, so nothing in your project is built from a local 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 ${mt} 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 ${mt} 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 ${mt}. 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===oe(e),describe:e=>`Retired option \`aiBuiltin\`: your project recorded built-in AI models ${ws(e.aiBuiltin)}, but it is now a plain config value generated ${ws(oe(e))} for a project ${oe(e)?"with":"without"} a payment provider. Set \`config.ai.builtin\` to \`${String(e.aiBuiltin===!0)}\` in ${mt} 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 ${mt} to keep it off.`},{key:"dockerServices",severity:"warn",preserved:e=>vs(e).join(",")===ks(e).join(","),describe:e=>`Retired option \`dockerServices\`: your project recorded ${vs(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 ${ks(e).join(", ")}. Add any extra service back by hand; the file is yours to edit.`},{key:"aiTools",severity:"warn",preserved:e=>(e.aiTools??[]).length===ln.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 (${He.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 ${mt} to drop a section for good.`}],Qf=Zr.map(e=>e.key);function Es(e){for(let t of Zr)t.normalize?.(e)}function Ss(e){let t=[];for(let r of Zr){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 As(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",Pp,[]).action(async(t,r)=>{r.args.length>0&&b.log.warn("`auto` is now the default and the argument is ignored.");let n=Ap(t.answer),i=Sp(t.cwd??process.cwd()),o=qe(i,we),s;try{s=JSON.parse(await Ps(o,"utf-8"))}catch{b.cancel(".generatesaas/manifest.json not found. Run this from a GenerateSaaS project."),process.exit(1)}s.frontend===br&&(b.cancel(`This project was generated on the Nuxt frontend (\`.generatesaas/manifest.json\` records \`frontend: "${br}"\`).
1629
1637
 
1630
1638
  v${wr} is the last release that ships a Nuxt frontend, and this CLI cannot update or migrate a Nuxt project to Next.js.
1631
1639
 
1632
- Your project keeps working exactly as it is - stay on v${wr}, or start a fresh project on Next.js with ${C.cyan("generatesaas init")} when you are ready to move.`),process.exit(1));let a=ln(s);a.length>0&&(y.cancel(`.generatesaas/manifest.json carries a value this CLI cannot shape a project from:
1640
+ Your project keeps working exactly as it is - stay on v${wr}, or start a fresh project on Next.js with ${C.cyan("generatesaas init")} when you are ready to move.`),process.exit(1));let a=dn(s);a.length>0&&(b.cancel(`.generatesaas/manifest.json carries a value this CLI cannot shape a project from:
1633
1641
 
1634
1642
  ${a.map(f=>` - ${f}`).join(`
1635
1643
  `)}
1636
1644
 
1637
- Correct it there, then run ${C.cyan("generatesaas update")} again.`),process.exit(1)),Es(s);let d=me(s);d&&(y.cancel(`.generatesaas/manifest.json turns \`${d.feature}\` on with \`deploymentTarget: "${d.target}"\`, which cannot run it.
1645
+ Correct it there, then run ${C.cyan("generatesaas update")} again.`),process.exit(1)),Es(s);let d=me(s);d&&(b.cancel(`.generatesaas/manifest.json turns \`${d.feature}\` on with \`deploymentTarget: "${d.target}"\`, which cannot run it.
1638
1646
 
1639
1647
  ${d.reason}
1640
1648
 
1641
- Correct it there, then run ${C.cyan("generatesaas update")} again.`),process.exit(1));let m=mr(s);m.length>0&&(y.cancel(`.generatesaas/manifest.json records a combination this project cannot run:
1649
+ Correct it there, then run ${C.cyan("generatesaas update")} again.`),process.exit(1));let u=mr(s);u.length>0&&(b.cancel(`.generatesaas/manifest.json records a combination this project cannot run:
1642
1650
 
1643
- ${m.map(f=>` - ${f}`).join(`
1651
+ ${u.map(f=>` - ${f}`).join(`
1644
1652
  `)}
1645
1653
 
1646
- Correct it there, then run ${C.cyan("generatesaas update")} again.`),process.exit(1));let w=mn(s);w.length>0&&(y.cancel(`.generatesaas/manifest.json turns the web AI surface off (\`webAi: false\`) in a project that cannot run without it:
1654
+ Correct it there, then run ${C.cyan("generatesaas update")} again.`),process.exit(1));let w=fn(s);w.length>0&&(b.cancel(`.generatesaas/manifest.json turns the web AI surface off (\`webAi: false\`) in a project that cannot run without it:
1647
1655
 
1648
1656
  ${w.map(f=>` - ${f}`).join(`
1649
1657
  `)}
1650
1658
 
1651
- Correct it there, then run ${C.cyan("generatesaas update")} again.`),process.exit(1));let b=hn(s);b.length>0&&(y.cancel(`.generatesaas/manifest.json turns on mobile store purchases (\`mobilePurchases: "revenuecat"\`) in a project that cannot run them:
1659
+ Correct it there, then run ${C.cyan("generatesaas update")} again.`),process.exit(1));let y=gn(s);y.length>0&&(b.cancel(`.generatesaas/manifest.json turns on mobile store purchases (\`mobilePurchases: "revenuecat"\`) in a project that cannot run them:
1652
1660
 
1653
- ${b.map(f=>` - ${f}`).join(`
1661
+ ${y.map(f=>` - ${f}`).join(`
1654
1662
  `)}
1655
1663
 
1656
- Correct it there, then run ${C.cyan("generatesaas update")} again.`),process.exit(1));let P;try{P=await it()}catch(f){y.cancel(j(f)),process.exit(1)}let I=ke(P),_=y.spinner();try{_.start("Verifying access...");let f;try{f=await Te(I)}catch(D){throw D instanceof F&&D.status===401?new Error("Your saved API key was rejected. Run `generatesaas auth` to update it, or set GENERATESAAS_API_KEY."):D}let O=ar(f,"update");if(!O.ok)throw new Error(O.message);_.stop("Access verified."),Ve(P),_.start("Fetching latest skill files...");let Oe=await Pn(I,f.latest);await Wr(i,Oe.skills);let q=Ge;if(_.stop("Skills updated."),y.log.success(`Skill files installed to ${C.cyan(q.length.toString())} locations.`),s.version===f.latest){y.log.info(`Already on the latest version (${s.version}).`);return}_e(s.version,f.latest)>0&&(y.cancel(`This project is on ${s.version}, which is newer than the latest release (${f.latest}). Updating would stage the older template over it. Check that your API key points at the right account, or correct \`version\` in ${we}.`),process.exit(1));let J=f.entitlements;J&&(s.desktop&&!J.desktopAllowed&&(y.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.runner&&!J.runnerAllowed&&(y.cancel("This project includes the runner, which is available on the Pro plan and up. Upgrade your plan at generatesaas.com to keep updating it."),process.exit(1)),s.mobile&&J.mobileAllowed===!1&&(y.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 xe=JSON.stringify(s);un(s),await Pp(s,fn(s),n),await Ap(Ss(s),n);let De=cn(s),Ne=pn(s),Je=mr(Ne);Je.length>0&&(y.cancel(`.generatesaas/manifest.json is missing a provider key, and its default would create a combination this project cannot run:
1664
+ Correct it there, then run ${C.cyan("generatesaas update")} again.`),process.exit(1));let P;try{P=await ot()}catch(f){b.cancel(j(f)),process.exit(1)}let I=ke(P),_=b.spinner();try{_.start("Verifying access...");let f;try{f=await Te(I)}catch(D){throw D instanceof F&&D.status===401?new Error("Your saved API key was rejected. Run `generatesaas auth` to update it, or set GENERATESAAS_API_KEY."):D}let O=ar(f,"update");if(!O.ok)throw new Error(O.message);_.stop("Access verified."),Ve(P),_.start("Fetching latest skill files...");let Oe=await In(I,f.latest);await qr(i,Oe.skills);let q=He;if(_.stop("Skills updated."),b.log.success(`Skill files installed to ${C.cyan(q.length.toString())} locations.`),s.version===f.latest){b.log.info(`Already on the latest version (${s.version}).`);return}_e(s.version,f.latest)>0&&(b.cancel(`This project is on ${s.version}, which is newer than the latest release (${f.latest}). Updating would stage the older template over it. Check that your API key points at the right account, or correct \`version\` in ${we}.`),process.exit(1));let J=f.entitlements;J&&(s.desktop&&!J.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.runner&&!J.runnerAllowed&&(b.cancel("This project includes the runner, which is available on the Pro plan and up. Upgrade your plan at generatesaas.com to keep updating it."),process.exit(1)),s.mobile&&J.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 xe=JSON.stringify(s);hn(s),await Ip(s,yn(s),n),await Rp(Ss(s),n);let De=pn(s),Ne=un(s),Ze=mr(Ne);Ze.length>0&&(b.cancel(`.generatesaas/manifest.json is missing a provider key, and its default would create a combination this project cannot run:
1657
1665
 
1658
- ${Je.map(D=>` - ${D}`).join(`
1666
+ ${Ze.map(D=>` - ${D}`).join(`
1659
1667
  `)}
1660
1668
 
1661
- 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 v=JSON.stringify(Ne)!==xe;if(s=Ne,s.licenseToken)try{let D=await In(I,{currentToken:s.licenseToken,newVersion:f.latest});s.licenseToken=D.token,D.licenseKeyHash&&(s.licenseKeyHash=D.licenseKeyHash),await c(o,`${JSON.stringify(s,null," ")}
1662
- `),v=!1,y.log.success("License refreshed.")}catch(D){let ht=Vt(D);ht&&(y.cancel(ht.message),process.exit(1)),y.log.warn("License refresh skipped.")}v&&await c(o,`${JSON.stringify(s,null," ")}
1663
- `);let M=rs(s,i),G=We(i,kn);_.start(`Staging v${f.latest} (shaped for your config)...`),await qr(I,f.latest,M,G),_.stop("Template staged.");let{text:se,title:N}=await Tp(I,f,s.version);se&&y.note(se,N);let de=We(i,Mt),X=We(i,Ft),ue=!cr(X),Ce=!cr(de);if(ue){if(_.start("Building baseline template (one-time migration)..."),await qr(I,s.version,M,X),Ce){let D=await dt(X);await c(de,`${JSON.stringify(D,null," ")}
1664
- `)}if(_.stop("Baseline template stored."),!Ce){let D=await _p(de,X);D>0&&y.log.warn(`Rebuilt baseline differs from the original for ${D} 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(Ce){_.start("Computing baseline template hashes...");let D=await dt(X);await c(de,`${JSON.stringify(D,null," ")}
1665
- `),_.stop("Baseline hashes computed.")}await c(We(i,En),`${JSON.stringify({currentVersion:s.version,targetVersion:f.latest,changelog:se,stagedAt:new Date().toISOString(),...De.length>0?{newOptions:De}:{}},null," ")}
1666
- `),y.log.info(`Update staged: ${C.cyan(s.version)} \u2192 ${C.cyan(f.latest)}`),y.log.info(`Ask your AI coding assistant to ${C.cyan("'update my GenerateSaaS project'")}.`),s.desktop===!0&&cr(We(i,"apps/tauri"))&&y.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&&cr(We(i,"apps/electron"))&&y.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(f){_.stop("Failed."),y.cancel(`Update failed: ${j(f)}`),process.exit(1)}})}var Is="desktop-migration";function Ep(e,t){return t.push(e),t}function Sp(e){let t=new Set([Is,...Object.keys(Ts).map(n=>`retired:${n}`)]),r=new Map;for(let n of e){let i=n.indexOf("=");(i<=0||i===n.length-1)&&(y.cancel(`\`--answer ${n}\` is malformed. Use \`--answer <id>=<choice>\`.`),process.exit(1));let o=n.slice(0,i);t.has(o)||(y.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 Rs(e,t){let r=t.get(e.id);if(r!==void 0){let n=e.choices.find(i=>i.id===r);return n||(y.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 y.select({message:e.message,options:e.choices.map(o=>({value:o.id,label:o.label,...o.hint?{hint:o.hint}:{}}))});y.isCancel(n)&&(y.cancel("Update cancelled. Nothing was changed or staged."),process.exit(1));let i=e.choices.find(o=>o.id===n);return i||(y.cancel("Update cancelled. Nothing was changed or staged."),process.exit(1)),i}y.cancel(`${e.message}
1669
+ 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 v=JSON.stringify(Ne)!==xe;if(s=Ne,s.licenseToken)try{let D=await Tn(I,{currentToken:s.licenseToken,newVersion:f.latest});s.licenseToken=D.token,D.licenseKeyHash&&(s.licenseKeyHash=D.licenseKeyHash),await c(o,`${JSON.stringify(s,null," ")}
1670
+ `),v=!1,b.log.success("License refreshed.")}catch(D){let ht=Vt(D);ht&&(b.cancel(ht.message),process.exit(1)),b.log.warn("License refresh skipped.")}v&&await c(o,`${JSON.stringify(s,null," ")}
1671
+ `);let M=rs(s,i),G=qe(i,Sn);_.start(`Staging v${f.latest} (shaped for your config)...`),await Xr(I,f.latest,M,G),_.stop("Template staged.");let{text:se,title:N}=await Op(I,f,s.version);se&&b.note(se,N);let de=qe(i,Mt),X=qe(i,Ft),ue=!cr(X),Ce=!cr(de);if(ue){if(_.start("Building baseline template (one-time migration)..."),await Xr(I,s.version,M,X),Ce){let D=await dt(X);await c(de,`${JSON.stringify(D,null," ")}
1672
+ `)}if(_.stop("Baseline template stored."),!Ce){let D=await xp(de,X);D>0&&b.log.warn(`Rebuilt baseline differs from the original for ${D} 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(Ce){_.start("Computing baseline template hashes...");let D=await dt(X);await c(de,`${JSON.stringify(D,null," ")}
1673
+ `),_.stop("Baseline hashes computed.")}await c(qe(i,Pn),`${JSON.stringify({currentVersion:s.version,targetVersion:f.latest,changelog:se,stagedAt:new Date().toISOString(),...De.length>0?{newOptions:De}:{}},null," ")}
1674
+ `),b.log.info(`Update staged: ${C.cyan(s.version)} \u2192 ${C.cyan(f.latest)}`),b.log.info(`Ask your AI coding assistant to ${C.cyan("'update my GenerateSaaS project'")}.`),s.desktop===!0&&cr(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&&cr(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(f){_.stop("Failed."),b.cancel(`Update failed: ${j(f)}`),process.exit(1)}})}var Is="desktop-migration";function Pp(e,t){return t.push(e),t}function Ap(e){let t=new Set([Is,...Object.keys(Ts).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 Rs(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}
1667
1675
 
1668
1676
  This update is running without an interactive terminal, so it cannot ask you directly. Answer the question \`${e.id}\` and re-run, for example:
1669
1677
 
@@ -1671,24 +1679,24 @@ This update is running without an interactive terminal, so it cannot ask you dir
1671
1679
 
1672
1680
  Choices:
1673
1681
  ${e.choices.map(n=>` - ${n.id}: ${n.label}${n.hint?` (${n.hint})`:""}`).join(`
1674
- `)}`),process.exit(1)}async function Pp(e,t,r){if(t.kind==="none")return;let n=Rp[t.kind];(await Rs({id:Is,message:n.message,choices:n.choices},r)).apply(e)}var Ts={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 Ap(e,t){let r=[];for(let n of e){let i=n.severity==="ask"?Ts[n.key]:void 0;if(!i){y.log.warn(n.message);continue}r.push({notice:n,answers:i})}for(let{notice:n,answers:i}of r)(await Rs({id:`retired:${n.key}`,message:n.message,choices:i.map(s=>({id:s.value,label:s.label,hint:s.hint}))},t)).id==="stop"&&(y.cancel("Update cancelled. Nothing was changed or staged."),process.exit(1))}function Ip(e){e.desktop=!1}var Rp={"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, and this also drops the web runner - it requires AI",apply:e=>{e.ai=!1,e.runner=!1}},{id:"drop-desktop",label:"Drop the desktop app",hint:"your website keeps its AI surface exactly as it is today",apply:Ip}]}};async function Tp(e,t,r){let n=t.latest,i=t.versions.filter(d=>_e(d.version,r)>0&&_e(d.version,n)<=0).sort((d,m)=>_e(d.version,m.version)),o=async d=>{try{return await Sn(e,d)}catch{return null}};if(i.length<=1)return{text:await o(n),title:`Changelog v${n}`};let s=await Promise.all(i.map(d=>o(d.version)));return{text:i.map((d,m)=>{let w=d.date?` (${d.date.slice(0,10)})`:"",b=s[m]??"_No changelog available for this release._";return`# v${d.version}${w}
1682
+ `)}`),process.exit(1)}async function Ip(e,t,r){if(t.kind==="none")return;let n=_p[t.kind];(await Rs({id:Is,message:n.message,choices:n.choices},r)).apply(e)}var Ts={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 Rp(e,t){let r=[];for(let n of e){let i=n.severity==="ask"?Ts[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 Rs({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 Tp(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, and this also drops the web runner - it requires AI",apply:e=>{e.ai=!1,e.runner=!1}},{id:"drop-desktop",label:"Drop the desktop app",hint:"your website keeps its AI surface exactly as it is today",apply:Tp}]}};async function Op(e,t,r){let n=t.latest,i=t.versions.filter(d=>_e(d.version,r)>0&&_e(d.version,n)<=0).sort((d,u)=>_e(d.version,u.version)),o=async d=>{try{return await An(e,d)}catch{return null}};if(i.length<=1)return{text:await o(n),title:`Changelog v${n}`};let s=await Promise.all(i.map(d=>o(d.version)));return{text:i.map((d,u)=>{let w=d.date?` (${d.date.slice(0,10)})`:"",y=s[u]??"_No changelog available for this release._";return`# v${d.version}${w}
1675
1683
 
1676
- ${b}`}).join(`
1684
+ ${y}`}).join(`
1677
1685
 
1678
- `),title:`Changelog v${r} \u2192 v${n}`}}async function _p(e,t){let r=JSON.parse(await Ps(e,"utf-8")),n=await dt(t),i=0;for(let[o,s]of Object.entries(r))st(o)||n[o]!==s&&i++;for(let o of Object.keys(n))o in r||i++;return i}import*as z from"@clack/prompts";import Pe from"picocolors";import{readFile as Op}from"fs/promises";import{join as xp,resolve as Dp}from"path";function _s(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=Dp(t.cwd??process.cwd()),n=xp(r,we),i;try{i=JSON.parse(await Op(n,"utf-8"))}catch{z.cancel(".generatesaas/manifest.json not found. Run this from a GenerateSaaS project."),process.exit(1)}let o=[`Version: ${Pe.cyan(i.version)}`,i.deploymentTarget?`Deploy target: ${Pe.cyan(i.deploymentTarget)}`:null,i.databaseProvider?`Database: ${Pe.cyan(i.databaseProvider)}`:null,i.cacheProvider?`Cache: ${Pe.cyan(i.cacheProvider)}`:null].filter(Boolean).join(`
1679
- `);z.note(o,Pe.bold("Project Status"));let s=z.spinner();s.start("Checking for updates...");try{let a=await it(),d=ke(a),w=(await Te(d)).latest;i.version===w?(s.stop("Up to date."),z.log.success(`Already on the latest version (${Pe.green(w)})`)):(s.stop("Update available."),z.log.warning(`Update available: ${Pe.yellow(i.version)} \u2192 ${Pe.green(w)}`),z.log.info(`Open this project in your AI coding agent and ask it to ${Pe.cyan("update my GenerateSaaS project")} - it fetches and applies the update for you.`))}catch(a){s.stop("Check failed."),a instanceof F&&a.status===401?z.log.warning("Invalid API key. Run `generatesaas auth` to update it, or set GENERATESAAS_API_KEY."):z.log.warning(`Could not check for updates: ${j(a)}`)}})}import{Buffer as Np}from"buffer";import{readFile as Cp}from"fs/promises";import*as $ from"@clack/prompts";import L from"picocolors";function Lp(){return process.env.GENERATESAAS_API_KEY??vt()}function $p(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 jp(e){return{verdict:e.verdict??"unknown",ejectedAt:e.ejectedAt??null}}function Up(e){switch(e.verdict){case"licensed":return $.log.success(`${L.green("LICENSED")} - resolves to an account with an active${e.plan?` ${e.plan}`:""} license.`),!0;case"ejected":return $.log.success(`${L.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 $.log.error(`${L.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 $.log.error(`${L.red("LEAKED TOKEN")} - this license belongs to a different deployment${e.mismatchDomain?` (${L.cyan(e.mismatchDomain)})`:""}, not this site. The token was copied from a licensed project.`),!1;case"no_license_history":return $.log.error(`${L.red("NO LICENSE HISTORY")} - no license has ever been associated with this site. If it runs GenerateSaaS, treat it as unlicensed.`),!1;default:return $.log.warn(`${L.yellow("UNKNOWN")} - could not cross-reference the records right now. Try again shortly.`),!1}}async function Os(e,t){let r=process.env.GENERATESAAS_API_URL??wt,n=Lp();e.start("Cross-referencing license records...");try{let i=n?$p(await Rn(r,n,{lkh:t.lkh,nid:t.nid,domain:t.domain})):jp(await Er(r,{token:t.token,domain:t.domain}));return e.stop(`${L.green("Checked")} - records cross-referenced`),Up(i)}catch(i){return e.stop(`${L.yellow("Skipped")} - ${j(i)}`),null}}function Mp(e){let t=e.split(".");if(t.length!==3||!t[1])throw new Error("Invalid JWT format");let r=Np.from(t[1],"base64url").toString("utf-8");return JSON.parse(r)}function Xr(e){return typeof e!="number"?"unknown":new Date(e*1e3).toISOString().split("T")[0]}function xs(e){$.note([`License ID: ${L.cyan(String(e.lid??"unknown"))}`,`Version: ${L.cyan(String(e.ver??"unknown"))}`,`Init version: ${String(e.iver??"unknown")}`,`Frontend: ${String(e.fe??"unknown")}`,`Created: ${Xr(e.pat)}`,`Last updated: ${Xr(e.uat)}`,`Expires: ${Xr(e.exp)}`,`Install ID: ${String(e.nid??"unknown")}`].join(`
1680
- `),L.yellow("License Details"))}function Fp(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 Ds(e){let t=$.spinner(),r=null,n="no candidates";for(let s of Fp(e)){t.start(`Checking ${s}...`);try{let a=await fetch(s);if(!a.ok){n=`${s} returned ${a.status}`,t.stop(`${L.yellow("Not here")} - ${n}`);continue}let d=(await a.text()).trim();if(!d||d.split(".").length!==3){n=`${s} did not return a JWT`,t.stop(`${L.yellow("Not here")} - ${n}`);continue}r=d,t.stop(`${L.green("Found")} - license endpoint responded`);break}catch(a){n=`${s}: ${j(a)}`,t.stop(`${L.yellow("Unreachable")} - ${n}`)}}if(r===null){$.log.warn(`No license endpoint found (last: ${n}). The site may be ejected, not a GenerateSaaS app, or serving its API elsewhere.`);let s=Ns(e);return s?await Os(t,{domain:s})??!1:!1}let i;try{i=Mp(r)}catch{return $.log.error("Could not decode JWT payload."),!1}t.start("Verifying signature...");try{let s=process.env.GENERATESAAS_API_URL??wt,a=await Er(s,{token:r});if(a.valid)t.stop(`${L.green("Valid")} - signature verified`);else return t.stop(`${L.red("Invalid")} - ${a.reason}`),!1}catch{return t.stop(`${L.yellow("Skipped")} - could not reach verification service`),$.log.warn("Signature not verified. Displaying unverified claims:"),xs(i),!1}return xs(i),await Os(t,{token:r,lkh:typeof i.lkh=="string"?i.lkh:void 0,nid:typeof i.nid=="string"?i.nid:void 0,domain:Ns(e)})??!0}function Ns(e){try{return new URL(/^https?:\/\//i.test(e)?e:`https://${e}`).hostname}catch{return}}function Cs(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&&($.cancel("Provide a URL or --file <path>."),process.exit(1)),r.file){let i=(await Cp(r.file,"utf-8")).split(`
1681
- `).map(s=>s.trim()).filter(s=>s&&!s.startsWith("#"));i.length===0&&($.cancel("No URLs found in file."),process.exit(1));let o=0;for(let s of i)await Ds(s)&&o++,$.log.info("");$.log.success(`${o}/${i.length} sites verified.`)}else await Ds(t)||process.exit(1)})}import{existsSync as Vp,rmSync as Bp}from"fs";import*as ie from"@clack/prompts";function Ls(e){e.command("auth").description("Set or update your GenerateSaaS API key").option("--clear","remove saved API key").action(async t=>{if(t.clear){Vp(ve)?(Bp(ve),ie.log.success("API key removed.")):ie.log.info("No API key configured.");return}let r=vt();r?ie.log.info(`Current API key: ****${r.slice(-4)}`):ie.log.info("No API key configured.");let n=await kt(),i=ke(n),o=ie.spinner();o.start("Verifying API key...");try{await Te(i),o.stop("API key verified."),Ve(n),ie.log.success("API key saved.")}catch(s){o.stop("Verification failed."),s instanceof F&&s.status===401?ie.cancel("Invalid API key."):ie.cancel(j(s)),process.exit(1)}})}import{existsSync as lr,readFileSync as Qr,rmSync as Gp,writeFileSync as $s}from"fs";import{join as ze}from"path";import*as B from"@clack/prompts";var Kp=["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"],Hp=[{file:"packages/api/src/routes/inngest.ts",removals:[`import { licenseHeartbeatFunction } from "../functions/maintenance/license-heartbeat";
1686
+ `),title:`Changelog v${r} \u2192 v${n}`}}async function xp(e,t){let r=JSON.parse(await Ps(e,"utf-8")),n=await dt(t),i=0;for(let[o,s]of Object.entries(r))at(o)||n[o]!==s&&i++;for(let o of Object.keys(n))o in r||i++;return i}import*as z from"@clack/prompts";import Pe from"picocolors";import{readFile as Dp}from"fs/promises";import{join as Np,resolve as Cp}from"path";function _s(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=Cp(t.cwd??process.cwd()),n=Np(r,we),i;try{i=JSON.parse(await Dp(n,"utf-8"))}catch{z.cancel(".generatesaas/manifest.json not found. Run this from a GenerateSaaS project."),process.exit(1)}let o=[`Version: ${Pe.cyan(i.version)}`,i.deploymentTarget?`Deploy target: ${Pe.cyan(i.deploymentTarget)}`:null,i.databaseProvider?`Database: ${Pe.cyan(i.databaseProvider)}`:null,i.cacheProvider?`Cache: ${Pe.cyan(i.cacheProvider)}`:null].filter(Boolean).join(`
1687
+ `);z.note(o,Pe.bold("Project Status"));let s=z.spinner();s.start("Checking for updates...");try{let a=await ot(),d=ke(a),w=(await Te(d)).latest;i.version===w?(s.stop("Up to date."),z.log.success(`Already on the latest version (${Pe.green(w)})`)):(s.stop("Update available."),z.log.warning(`Update available: ${Pe.yellow(i.version)} \u2192 ${Pe.green(w)}`),z.log.info(`Open this project in your AI coding agent and ask it to ${Pe.cyan("update my GenerateSaaS project")} - it fetches and applies the update for you.`))}catch(a){s.stop("Check failed."),a instanceof F&&a.status===401?z.log.warning("Invalid API key. Run `generatesaas auth` to update it, or set GENERATESAAS_API_KEY."):z.log.warning(`Could not check for updates: ${j(a)}`)}})}import{Buffer as Lp}from"buffer";import{readFile as $p}from"fs/promises";import*as $ from"@clack/prompts";import L from"picocolors";function jp(){return process.env.GENERATESAAS_API_KEY??vt()}function Up(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 Mp(e){return{verdict:e.verdict??"unknown",ejectedAt:e.ejectedAt??null}}function Fp(e){switch(e.verdict){case"licensed":return $.log.success(`${L.green("LICENSED")} - resolves to an account with an active${e.plan?` ${e.plan}`:""} license.`),!0;case"ejected":return $.log.success(`${L.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 $.log.error(`${L.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 $.log.error(`${L.red("LEAKED TOKEN")} - this license belongs to a different deployment${e.mismatchDomain?` (${L.cyan(e.mismatchDomain)})`:""}, not this site. The token was copied from a licensed project.`),!1;case"no_license_history":return $.log.error(`${L.red("NO LICENSE HISTORY")} - no license has ever been associated with this site. If it runs GenerateSaaS, treat it as unlicensed.`),!1;default:return $.log.warn(`${L.yellow("UNKNOWN")} - could not cross-reference the records right now. Try again shortly.`),!1}}async function Os(e,t){let r=process.env.GENERATESAAS_API_URL??wt,n=jp();e.start("Cross-referencing license records...");try{let i=n?Up(await _n(r,n,{lkh:t.lkh,nid:t.nid,domain:t.domain})):Mp(await Er(r,{token:t.token,domain:t.domain}));return e.stop(`${L.green("Checked")} - records cross-referenced`),Fp(i)}catch(i){return e.stop(`${L.yellow("Skipped")} - ${j(i)}`),null}}function Vp(e){let t=e.split(".");if(t.length!==3||!t[1])throw new Error("Invalid JWT format");let r=Lp.from(t[1],"base64url").toString("utf-8");return JSON.parse(r)}function Qr(e){return typeof e!="number"?"unknown":new Date(e*1e3).toISOString().split("T")[0]}function xs(e){$.note([`License ID: ${L.cyan(String(e.lid??"unknown"))}`,`Version: ${L.cyan(String(e.ver??"unknown"))}`,`Init version: ${String(e.iver??"unknown")}`,`Frontend: ${String(e.fe??"unknown")}`,`Created: ${Qr(e.pat)}`,`Last updated: ${Qr(e.uat)}`,`Expires: ${Qr(e.exp)}`,`Install ID: ${String(e.nid??"unknown")}`].join(`
1688
+ `),L.yellow("License Details"))}function Bp(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 Ds(e){let t=$.spinner(),r=null,n="no candidates";for(let s of Bp(e)){t.start(`Checking ${s}...`);try{let a=await fetch(s);if(!a.ok){n=`${s} returned ${a.status}`,t.stop(`${L.yellow("Not here")} - ${n}`);continue}let d=(await a.text()).trim();if(!d||d.split(".").length!==3){n=`${s} did not return a JWT`,t.stop(`${L.yellow("Not here")} - ${n}`);continue}r=d,t.stop(`${L.green("Found")} - license endpoint responded`);break}catch(a){n=`${s}: ${j(a)}`,t.stop(`${L.yellow("Unreachable")} - ${n}`)}}if(r===null){$.log.warn(`No license endpoint found (last: ${n}). The site may be ejected, not a GenerateSaaS app, or serving its API elsewhere.`);let s=Ns(e);return s?await Os(t,{domain:s})??!1:!1}let i;try{i=Vp(r)}catch{return $.log.error("Could not decode JWT payload."),!1}t.start("Verifying signature...");try{let s=process.env.GENERATESAAS_API_URL??wt,a=await Er(s,{token:r});if(a.valid)t.stop(`${L.green("Valid")} - signature verified`);else return t.stop(`${L.red("Invalid")} - ${a.reason}`),!1}catch{return t.stop(`${L.yellow("Skipped")} - could not reach verification service`),$.log.warn("Signature not verified. Displaying unverified claims:"),xs(i),!1}return xs(i),await Os(t,{token:r,lkh:typeof i.lkh=="string"?i.lkh:void 0,nid:typeof i.nid=="string"?i.nid:void 0,domain:Ns(e)})??!0}function Ns(e){try{return new URL(/^https?:\/\//i.test(e)?e:`https://${e}`).hostname}catch{return}}function Cs(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&&($.cancel("Provide a URL or --file <path>."),process.exit(1)),r.file){let i=(await $p(r.file,"utf-8")).split(`
1689
+ `).map(s=>s.trim()).filter(s=>s&&!s.startsWith("#"));i.length===0&&($.cancel("No URLs found in file."),process.exit(1));let o=0;for(let s of i)await Ds(s)&&o++,$.log.info("");$.log.success(`${o}/${i.length} sites verified.`)}else await Ds(t)||process.exit(1)})}import{existsSync as Gp,rmSync as Kp}from"fs";import*as ie from"@clack/prompts";function Ls(e){e.command("auth").description("Set or update your GenerateSaaS API key").option("--clear","remove saved API key").action(async t=>{if(t.clear){Gp(ve)?(Kp(ve),ie.log.success("API key removed.")):ie.log.info("No API key configured.");return}let r=vt();r?ie.log.info(`Current API key: ****${r.slice(-4)}`):ie.log.info("No API key configured.");let n=await kt(),i=ke(n),o=ie.spinner();o.start("Verifying API key...");try{await Te(i),o.stop("API key verified."),Ve(n),ie.log.success("API key saved.")}catch(s){o.stop("Verification failed."),s instanceof F&&s.status===401?ie.cancel("Invalid API key."):ie.cancel(j(s)),process.exit(1)}})}import{existsSync as lr,readFileSync as tn,rmSync as Hp,writeFileSync as $s}from"fs";import{join as Je}from"path";import*as B from"@clack/prompts";var Yp=["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"],Wp=[{file:"packages/api/src/routes/inngest.ts",removals:[`import { licenseHeartbeatFunction } from "../functions/maintenance/license-heartbeat";
1682
1690
  `,` licenseHeartbeatFunction,
1683
1691
  `]},{file:"packages/api/src/routes/internal/index.ts",removals:[`import licenseRoutes from "./license";
1684
1692
  `,` .route("/license", licenseRoutes)
1685
1693
  `]},{file:"packages/api/src/routes/public/v1/health.ts",removals:[`import { manifest } from "../../../lib/manifest";
1686
- `],replacements:[{from:'c.json({ status: "success" as const, version: manifest?.version })',to:'c.json({ status: "success" as const })'}]}];function Yp(){return Ge.flatMap(e=>Yr.map(t=>ze(e,t)))}function Zr(e){return lr(e)?(Gp(e,{recursive:!0}),!0):!1}function Wp(e,t,r=[]){if(!lr(e))return!1;let n=Qr(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:($s(e,i,"utf-8"),!0)}function zp(e){let t=ze(e,".gitignore");if(!lr(t))return!1;let r=Qr(t,"utf-8"),n=r.split(`
1694
+ `],replacements:[{from:'c.json({ status: "success" as const, version: manifest?.version })',to:'c.json({ status: "success" as const })'}]}];function zp(){return He.flatMap(e=>zr.map(t=>Je(e,t)))}function en(e){return lr(e)?(Hp(e,{recursive:!0}),!0):!1}function qp(e,t,r=[]){if(!lr(e))return!1;let n=tn(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:($s(e,i,"utf-8"),!0)}function Jp(e){let t=Je(e,".gitignore");if(!lr(t))return!1;let r=tn(t,"utf-8"),n=r.split(`
1687
1695
  `).filter(i=>!i.includes(".generatesaas")).join(`
1688
- `);return n===r?!1:($s(t,n,"utf-8"),!0)}function js(e){e.command("eject").description("Remove all GenerateSaaS ties - manifest, license, heartbeat, skills").action(async()=>{let t=process.cwd(),r=ze(t,we),n;try{n=JSON.parse(Qr(r,"utf-8"))}catch{B.cancel("No GenerateSaaS project found in this directory."),process.exit(1)}let i=await B.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(B.isCancel(i)&&(B.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)}),B.log.info("Recorded the opt-out with generatesaas.com (final event - nothing is sent after this).")}catch{B.log.warn("Could not reach generatesaas.com to record the opt-out. Ejecting anyway.")}let o=[],s=[];for(let a of Yp())Zr(ze(t,a))&&o.push(a);for(let a of Kp)Zr(ze(t,a))&&o.push(a);Zr(ze(t,Q))&&o.push(`${Q}/`);for(let a of Hp){let d=ze(t,a.file);Wp(d,a.removals,a.replacements)?s.push(a.file):lr(d)&&B.log.warn(`Could not auto-modify ${a.file} - manually remove license/heartbeat references.`)}zp(t)&&s.push(".gitignore");for(let a of o)B.log.info(`Deleted ${a}`);for(let a of s)B.log.info(`Modified ${a}`);B.log.success("Ejected successfully. This project is now fully standalone.")})}var qe=new qp().name("generatesaas").description("CLI for scaffolding and managing GenerateSaaS projects").version("3.10.0").addHelpText("after",`
1696
+ `);return n===r?!1:($s(t,n,"utf-8"),!0)}function js(e){e.command("eject").description("Remove all GenerateSaaS ties - manifest, license, heartbeat, skills").action(async()=>{let t=process.cwd(),r=Je(t,we),n;try{n=JSON.parse(tn(r,"utf-8"))}catch{B.cancel("No GenerateSaaS project found in this directory."),process.exit(1)}let i=await B.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(B.isCancel(i)&&(B.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)}),B.log.info("Recorded the opt-out with generatesaas.com (final event - nothing is sent after this).")}catch{B.log.warn("Could not reach generatesaas.com to record the opt-out. Ejecting anyway.")}let o=[],s=[];for(let a of zp())en(Je(t,a))&&o.push(a);for(let a of Yp)en(Je(t,a))&&o.push(a);en(Je(t,Q))&&o.push(`${Q}/`);for(let a of Wp){let d=Je(t,a.file);qp(d,a.removals,a.replacements)?s.push(a.file):lr(d)&&B.log.warn(`Could not auto-modify ${a.file} - manually remove license/heartbeat references.`)}Jp(t)&&s.push(".gitignore");for(let a of o)B.log.info(`Deleted ${a}`);for(let a of s)B.log.info(`Modified ${a}`);B.log.success("Ejected successfully. This project is now fully standalone.")})}var Xe=new Xp().name("generatesaas").description("CLI for scaffolding and managing GenerateSaaS projects").version("3.11.0").addHelpText("after",`
1689
1697
  Examples:
1690
1698
  $ generatesaas init Interactive setup
1691
1699
  $ generatesaas init -n my-app -y Quick setup with defaults
1692
1700
  $ generatesaas status Check for updates
1693
1701
  $ generatesaas auth Set or update API key
1694
- `);bs(qe);As(qe);_s(qe);Cs(qe);Ls(qe);js(qe);qe.parseAsync().catch(e=>{Us.cancel("An unexpected error occurred."),console.error(e),process.exit(1)});
1702
+ `);bs(Xe);As(Xe);_s(Xe);Cs(Xe);Ls(Xe);js(Xe);Xe.parseAsync().catch(e=>{Us.cancel("An unexpected error occurred."),console.error(e),process.exit(1)});